@pgxsinkit/client 0.1.49 → 0.1.51
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.
- package/dist/boot-report.d.ts +76 -0
- package/dist/boot-report.d.ts.map +1 -1
- package/dist/index.d.ts +56 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1106 -312
- package/dist/index.js.map +19 -18
- package/dist/local-store.d.ts +58 -0
- package/dist/local-store.d.ts.map +1 -1
- package/dist/local-tables.d.ts +340 -0
- package/dist/local-tables.d.ts.map +1 -1
- package/dist/mutation.d.ts +36 -0
- package/dist/mutation.d.ts.map +1 -1
- package/dist/mutations-api.d.ts +82 -0
- package/dist/mutations-api.d.ts.map +1 -0
- package/dist/schema.d.ts +80 -1
- package/dist/schema.d.ts.map +1 -1
- package/dist/shape-sync.d.ts +6 -0
- package/dist/shape-sync.d.ts.map +1 -1
- package/dist/sync/index.d.ts +1 -1
- package/dist/sync/index.d.ts.map +1 -1
- package/dist/sync/metadata-tables.d.ts +16 -0
- package/dist/sync/metadata-tables.d.ts.map +1 -1
- package/dist/sync/subscription-state.d.ts +10 -2
- package/dist/sync/subscription-state.d.ts.map +1 -1
- package/dist/sync/tags.d.ts +16 -4
- package/dist/sync/tags.d.ts.map +1 -1
- package/dist/sync/types.d.ts +12 -0
- package/dist/sync/types.d.ts.map +1 -1
- package/dist/worker/attach-sync-client.d.ts.map +1 -1
- package/dist/worker/define-sync-worker.d.ts.map +1 -1
- package/dist/worker/protocol.d.ts +44 -1
- package/dist/worker/protocol.d.ts.map +1 -1
- package/package.json +2 -2
- package/skills/core/SKILL.md +1 -1
- package/skills/operating/SKILL.md +1 -1
- package/src/boot-report.ts +108 -0
- package/src/index.ts +555 -136
- package/src/local-store.ts +150 -3
- package/src/local-tables.ts +49 -1
- package/src/mutation.ts +256 -15
- package/src/mutations-api.ts +310 -0
- package/src/schema.ts +428 -197
- package/src/shape-sync.ts +11 -0
- package/src/sync/index.ts +14 -1
- package/src/sync/metadata-tables.ts +41 -0
- package/src/sync/subscription-state.ts +29 -4
- package/src/sync/tags.ts +34 -9
- package/src/sync/types.ts +12 -0
- package/src/worker/attach-sync-client.ts +114 -5
- package/src/worker/define-sync-worker.ts +65 -4
- package/src/worker/protocol.ts +38 -1
package/dist/index.js.map
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["../src/index.ts", "../src/debug.ts", "../src/boot-report.ts", "../src/convergence.ts", "../src/export-dump.ts", "../src/export-store.ts", "../src/store-path.ts", "../src/export-data.ts", "../src/lazy-guard.ts", "../src/lifecycle-slot.ts", "../src/live-rows-sql.ts", "../src/local-store.ts", "../src/local-tables.ts", "../src/schema.ts", "../src/sync/tags.ts", "../src/sync/apply.ts", "../src/sync/copy.ts", "../src/sync/drizzle-executor.ts", "../src/sync/metadata-tables.ts", "../src/mutation.ts", "../src/mutation-state.ts", "../src/sync-auth.ts", "../src/shape-sync.ts", "../src/sync/index.ts", "../src/sync/nudge.ts", "../src/sync/shape-inbox.ts", "../src/sync/subscription-state.ts", "../src/sync/types.ts", "../src/worker/live-diff.ts", "../src/worker/live-query-fingerprint.ts", "../src/worker/live-query-manager.ts", "../src/worker/protocol.ts", "../src/worker/attach-sync-client.ts", "../src/worker/token-cache.ts", "../src/worker/define-sync-worker.ts"],
|
|
3
|
+
"sources": ["../src/index.ts", "../src/debug.ts", "../src/boot-report.ts", "../src/convergence.ts", "../src/export-dump.ts", "../src/export-store.ts", "../src/store-path.ts", "../src/export-data.ts", "../src/lazy-guard.ts", "../src/lifecycle-slot.ts", "../src/live-rows-sql.ts", "../src/local-store.ts", "../src/local-tables.ts", "../src/schema.ts", "../src/sync/tags.ts", "../src/sync/apply.ts", "../src/sync/copy.ts", "../src/sync/drizzle-executor.ts", "../src/sync/metadata-tables.ts", "../src/mutation.ts", "../src/mutation-state.ts", "../src/mutations-api.ts", "../src/sync-auth.ts", "../src/shape-sync.ts", "../src/sync/index.ts", "../src/sync/nudge.ts", "../src/sync/shape-inbox.ts", "../src/sync/subscription-state.ts", "../src/sync/types.ts", "../src/worker/live-diff.ts", "../src/worker/live-query-fingerprint.ts", "../src/worker/live-query-manager.ts", "../src/worker/protocol.ts", "../src/worker/attach-sync-client.ts", "../src/worker/token-cache.ts", "../src/worker/define-sync-worker.ts"],
|
|
4
4
|
"sourcesContent": [
|
|
5
|
-
"import { PGlite, type Results } from \"@electric-sql/pglite\";\nimport { live, type PGliteWithLive } from \"@electric-sql/pglite/live\";\nimport type { PgliteDatabase } from \"drizzle-orm/pglite\";\nimport { drizzle } from \"drizzle-orm/pglite\";\nimport { defineRelations } from \"drizzle-orm/relations\";\n\nimport type {\n MutationAck,\n MutationDiagnostics,\n RegistryRelations,\n RegistryTables,\n RegistryViews,\n SyncConfigInput,\n SyncRuntimeStatus,\n SyncTableCreateInput,\n SyncTableEntry,\n SyncTableName,\n SyncTableRegistry,\n SyncTableUpdateInput,\n WriteMode,\n} from \"@pgxsinkit/contracts\";\nimport { fingerprintRegistry, getSyncRegistrySchema, isClaimsDependentRowFilter } from \"@pgxsinkit/contracts\";\n\nimport { type BootReport, type BootReportBuilder, createBootReportBuilder } from \"./boot-report\";\nimport { type ConvergenceDriver, type ConvergenceTrigger, createConvergenceDriver } from \"./convergence\";\nimport { syncDebug, timeAsync } from \"./debug\";\nimport { type DataExportOptions, type DataExportResult, performDataExport } from \"./export-data\";\nimport { type DiagnosticExportOptions, type DiagnosticExportResult, performDiagnosticExport } from \"./export-dump\";\nimport { performStoreExport, type StoreExportOptions, type StoreExportResult } from \"./export-store\";\nimport {\n assertLazyRefsActivated,\n buildLazyGuardIndex,\n findReferencedLazyKeysInSql,\n findReferencedSyncedKeysInSql,\n} from \"./lazy-guard\";\nimport { createLifecycleSlot } from \"./lifecycle-slot\";\nimport { wrapLiveQueryForMaterialization } from \"./live-rows-sql\";\nimport {\n type LocalStoreVersionEvent,\n clearLazyGroupActivation,\n readActivatedLazyGroups,\n reconcileLocalStoreVersion,\n writeLazyGroupActivation,\n} from \"./local-store\";\nimport {\n createMutationRuntime,\n type MutationBatchItem,\n type MutationDetail,\n type MutationKind,\n type WriteUnit,\n} from \"./mutation\";\nimport {\n buildDataExportCloneCleanupSql,\n buildDataExportEnumHeaderSql,\n buildDesyncTableSql,\n buildDropReadCacheSql,\n buildWipeLocalStoreSql,\n collectDataExportSyncedTableNames,\n generateLocalSchemaSql,\n} from \"./schema\";\nimport { startConfiguredSync } from \"./shape-sync\";\nimport {\n classifyNonPersistentDataDir,\n NonPersistentStoreError,\n normaliseStorePathInput,\n readTestStoreMarker,\n resolveStoreDataDir,\n RestoreTargetExistsError,\n storeTargetExists,\n type StorePathInput,\n} from \"./store-path\";\nimport { createSyncEngine, type SyncEngine } from \"./sync\";\nimport { buildShapeHeaders } from \"./sync-auth\";\nimport { LiveRowsMaterializer } from \"./worker/live-diff\";\nimport {\n createLiveQueryManager,\n type LiveQueryDiagnostics,\n type LiveQueryManager,\n validateLiveQueryPolicy,\n} from \"./worker/live-query-manager\";\n\nexport { generateLocalSchemaSql };\nexport { wrapLiveQueryForMaterialization } from \"./live-rows-sql\";\nexport type { BootReport } from \"./boot-report\";\nexport {\n type CloneDumpPhases,\n type CloneDumpResult,\n type DiagnosticExportDeps,\n type DiagnosticExportOptions,\n type DiagnosticExportResult,\n performDiagnosticExport,\n runThrowawayCloneDump,\n} from \"./export-dump\";\nexport {\n type DataExportDeps,\n DataExportDrainError,\n type DataExportOptions,\n type DataExportResult,\n DEFAULT_DRAIN_TIMEOUT_MS,\n type DrainJournalOption,\n type DrainJournalOptions,\n performDataExport,\n} from \"./export-data\";\nexport {\n type DataExportReport,\n deriveStoreId,\n type DiagnosticDumpReport,\n type ExportReport,\n type ExportReportCommon,\n performDatadirDump,\n performStoreExport,\n type StoreBackupReport,\n type StoreExportDeps,\n type StoreExportOptions,\n type StoreExportResult,\n} from \"./export-store\";\nexport { createLifecycleSlot, LifecycleBusyError, type LifecycleSlot } from \"./lifecycle-slot\";\nexport {\n InvalidStorePathError,\n NonPersistentStoreError,\n resolveStoreDataDir,\n RestoreTargetExistsError,\n storeIndexedDbDatabaseName,\n storeTargetExists,\n} from \"./store-path\";\nexport {\n type ConvergenceClient,\n type ConvergenceDriver,\n type ConvergenceDriverOptions,\n type ConvergenceTrigger,\n createBrowserConvergenceTrigger,\n createConvergenceDriver,\n createIntervalConvergenceTrigger,\n} from \"./convergence\";\nexport { instrumentShapeFetch, setSyncDebugSink, syncDebug, timeAsync } from \"./debug\";\nexport {\n type AttachedSyncClient,\n attachSyncClient,\n type AttachSyncClientOptions,\n provisionSyncWorker,\n} from \"./worker/attach-sync-client\";\nexport { defineSyncWorker, type DefineSyncWorkerOptions, type SyncWorkerHost } from \"./worker/define-sync-worker\";\nexport {\n computeLiveDiff,\n type LiveDiffState,\n LiveRowsMaterializer,\n rowKey,\n seedLiveDiffState,\n} from \"./worker/live-diff\";\nexport type { LiveQueryDiagnostics };\nexport { createWorkerTokenCache, type WorkerTokenCache } from \"./worker/token-cache\";\nexport {\n type AttachAckPayload,\n type AttachPayload,\n type AuthTokenSnapshot,\n BRIDGE_CHANNEL,\n BRIDGE_PROTOCOL_VERSION,\n type BridgeCodec,\n type BridgeEnvelope,\n type BridgeEvent,\n type BridgeMessageType,\n type BridgePort,\n encodeEnvelope,\n type ExportArtefactWire,\n identityCodec,\n isBridgeEnvelope,\n type LiveDiffPayload,\n type LiveInitialPayload,\n postBridgeMessage,\n type ProvisionAckPayload,\n type ProvisionPayload,\n type RpcOp,\n type RpcPayload,\n type RpcResultPayload,\n type SetOnlinePayload,\n type SubscribePayload,\n type TokenRequestPayload,\n type TokenResponsePayload,\n type WakePayload,\n} from \"./worker/protocol\";\nexport {\n assertLazyRefsActivated,\n buildLazyGuardIndex,\n findReferencedLazyKeysInSql,\n findReferencedSyncedKeysInSql,\n type LazyGuardIndex,\n LazyRelationNotActivatedError,\n} from \"./lazy-guard\";\nexport {\n getJournalTable,\n getLocalMetaTable,\n getOverlayTable,\n getReadModelView,\n getSyncedLocalTable,\n getSyncStateView,\n type JournalTable,\n type LocalMetaTable,\n type OverlayTable,\n type ReadModelView,\n type SyncStateView,\n} from \"./local-tables\";\nexport type { LocalStoreVersionEvent };\n\n// The store carries PGlite's own `live` extension (a genuine create-time extension) plus the pgxsinkit\n// sync engine's namespace, attached post-create by `createSyncClient` as the `electric` property (ADR-0032\n// S1) — no longer a create-time extension. The `electric` part is derived from `createSyncEngine`'s real\n// return so the type follows the attached object.\nexport type ClientPGlite = PGliteWithLive & { electric: SyncEngine[\"namespace\"] };\n\n/**\n * The pre-warmed PGlite boot assets (the WASM modules + filesystem bundle), consumed by\n * {@link createClientPGlite} / {@link CreateSyncClientOptions.pgliteBootAssets}. The host fetches +\n * compiles these on an earlier screen and hands the promise in, so `PGlite.create` skips its own lazy\n * asset load — see the field's JSDoc for the accelerator geometry.\n */\nexport interface PgliteBootAssets {\n pgliteWasmModule?: WebAssembly.Module;\n initdbWasmModule?: WebAssembly.Module;\n fsBundle?: Blob;\n}\n\n/** Options for {@link createClientPGlite}. */\nexport interface CreateClientPGliteOptions {\n /**\n * Pre-warmed PGlite boot assets (see {@link CreateSyncClientOptions.pgliteBootAssets}). Awaited and\n * passed into `PGlite.create`; a rejected warm is caught to `undefined` (falls back to PGlite's own\n * asset load), so it never fails the create.\n */\n bootAssets?: Promise<PgliteBootAssets>;\n /**\n * @internal Test-only storage-backend override (ADR-0036). `\"memory\"` resolves the store to a\n * scheme-selected in-memory store — the sanctioned unit-test/ephemeral lane. Never a product\n * configuration: reached only through `@pgxsinkit/client/testing`, never consumer-facing.\n */\n backendOverride?: \"memory\";\n /**\n * A store-backup tarball to seed the new store from (ADR-0035 decision 6, restore) — a `File`/`Blob` as\n * produced by {@link SyncClient.exportStore}. Passed straight to PGlite's `loadDataDir`, so the created\n * store boots ON the backup's datadir. Restore is a CREATION-path feature: the caller (`createSyncClient`)\n * has already proven the target does not yet exist ({@link storeTargetExists}); this option carries no\n * freshness check of its own. A corrupt/foreign tarball surfaces as a PGlite boot failure here.\n */\n restoreFrom?: File | Blob;\n}\n\n/**\n * Create the raw local PGlite store the sync client runs on — the SAME `PGlite.create` call\n * {@link createSyncClient} makes internally (the `electric` + `live` extensions, pre-warmed boot-asset\n * consumption, and the `boot pglite.create` rail stamp), extracted so exactly one implementation exists\n * and a host can create the store EAGERLY on an earlier screen. Hand the returned (still-pending)\n * instance to {@link CreateSyncClientOptions.precreatedPglite}: the client then owns schema exec, prepare\n * hooks, journal recovery and store-version reconcile, exactly as its own `storePath` path does.\n *\n * Takes a plain store path (ADR-0036), never a storage URL — the backend is DERIVED (IndexedDB in a\n * browser/worker, the filesystem on Bun/Node); a scheme-bearing path throws {@link InvalidStorePathError}.\n * Also accepts the testing helper's output (`createClientPGlite(memoryStoreForTests(\"x\"))`) so a test can\n * mint a memory store without naming a backend.\n *\n * The instance is deliberately **schemaless** — the registry-derived local schema is role/registry\n * dependent, so it is applied post-create by `createSyncClient`. The eager create buys only the expensive\n * initdb (+ IDBFS open), which is the dominant cold-boot cost once the WASM is pre-warmed.\n *\n * `bootAssets` is the pre-warmed WASM/fs bundle (see {@link CreateSyncClientOptions.pgliteBootAssets}); a\n * rejected warm is caught to `undefined`, so PGlite falls back to loading its own assets — never a failure.\n */\nexport async function createClientPGlite(\n store: StorePathInput,\n options?: CreateClientPGliteOptions,\n): Promise<ClientPGlite> {\n // Normalise the store argument to a plain path (+ any internal memory override the testing helper carried),\n // then derive the concrete PGlite dataDir URL (ADR-0036) — the single resolution point. A scheme-bearing/\n // empty storePath throws here, so the old dataDir-URL contract fails loudly, never silently re-interpreted.\n const normalised = normaliseStorePathInput(store);\n const dataDir = resolveStoreDataDir(normalised.storePath, options?.backendOverride ?? normalised.backendOverride);\n // Stamp only the storage scheme (e.g. \"idb:\" / \"memory:\"), never the full path — the path can carry an\n // identity-specific store name, and the boot rail stays monotonic-and-scheme only.\n const dataDirScheme = dataDir.slice(0, dataDir.indexOf(\":\") + 1);\n // Resolve any pre-warmed boot assets BEFORE (and outside) the `boot pglite.create` stamp: the\n // fetch+compile was kicked off on an earlier screen, so this await just retrieves the already-settled\n // result and the stamp measures the create itself. A rejected warm is caught to `undefined` so a failed\n // pre-warm silently falls back to PGlite's own asset loading rather than failing the boot.\n const bootAssets = options?.bootAssets ? await options.bootAssets.catch(() => undefined) : undefined;\n return (await timeAsync(\n \"boot pglite.create\",\n () =>\n // Only PGlite's own `live` extension is a create-time extension; the pgxsinkit sync engine is NOT\n // (ADR-0032 S1) — it is a plain module `createSyncClient` attaches post-create as `pg.electric`. So\n // a store minted here is deliberately ENGINE-LESS by construction: a spare/pre-warmed store (e.g.\n // the board's login-screen mint) carries no engine, no shape streams, and no Electric connections\n // until it is claimed and handed to `createSyncClient`. The `as ClientPGlite` cast reflects that the\n // `electric` namespace is provisioned later, exactly as the registry-derived schema is.\n PGlite.create(dataDir, {\n ...(bootAssets ?? {}),\n // Restore (ADR-0035 decision 6): seed the brand-new store from the backup tarball. PGlite's\n // `loadDataDir` unpacks it into the datadir being created, so the store boots ON the backup's bytes —\n // the whole synced cache, Overlay, and Mutation journal that travelled inside it. Absent on a normal\n // create (the store initdbs empty).\n ...(options?.restoreFrom ? { loadDataDir: options.restoreFrom } : {}),\n extensions: {\n live,\n },\n }),\n { dataDir: dataDirScheme },\n // `as unknown as` because the raw store is deliberately engine-less here (only `live` is a create-time\n // extension); `createSyncClient` provisions the `electric` namespace post-create (ADR-0032 S1).\n )) as unknown as ClientPGlite;\n}\n\nexport interface CreateSyncClientOptions<TRegistry extends SyncTableRegistry> {\n registry: TRegistry;\n electricUrl: string;\n writeUrl: string;\n getAuthToken?: () => Promise<string | undefined>;\n /**\n * Static headers added to **every** read-shape and write request, alongside the per-request\n * `Authorization` (which always wins). The toolkit is agnostic about deployment-gateway\n * credentials, so this is the seam for them — e.g. a Supabase Cloud `apikey` header the platform\n * function gateway expects. Sent even when no `getAuthToken` is supplied.\n */\n requestHeaders?: Record<string, string>;\n /**\n * Extra static headers sent on the **write** path only (the mutation-flush POST), merged over\n * {@link requestHeaders} (`{...requestHeaders, ...writeRequestHeaders}`). Read/shape requests never\n * see these. The seam exists because the two ingress points have opposite geometry: the write\n * function is DB-bound, so pinning it to the database's region (e.g. an `x-region` header) keeps its\n * chatty function→DB protocol on a ~1ms loop; the read proxy's upstream is a globally-distributed\n * CDN (Electric Cloud), so pinning reads away from the caller pays intercontinental round trips per\n * catch-up hop. Put region/DB-affinity headers here; keep gateway credentials the reads also need\n * (e.g. `apikey`) in the shared {@link requestHeaders}.\n */\n writeRequestHeaders?: Record<string, string>;\n syncEnabled?: boolean;\n /**\n * The local store's name (ADR-0036) — a PLAIN path/name, never a PGlite storage URL. The storage backend\n * is DERIVED from the environment (IndexedDB in a browser/worker, the filesystem on Bun/Node); a\n * scheme-bearing string (anything containing `://`) is rejected with {@link InvalidStorePathError}\n * at boot. Defaults to a built-in overlay store name when omitted. A memory-backed store is not a product\n * configuration — for the test/ephemeral lane, spread `memoryStoreForTests(...)` from\n * `@pgxsinkit/client/testing` instead of naming one here.\n */\n storePath?: string;\n /**\n * Pre-warmed PGlite boot assets (the WASM modules + filesystem bundle), awaited and passed straight\n * into `PGlite.create`. The intent is to hide PGlite's ~2.5s cold `boot pglite.create` cost —\n * dominated by the WASM fetch+compile — behind user think-time: the host starts fetching/compiling\n * these on an earlier screen (e.g. the login/identity picker) and hands the still-pending promise\n * here, so by the time a store is opened the assets are already resolved and `PGlite.create` skips\n * its own lazy asset load. Ignored when {@link pgliteInstance} is supplied (the caller owns that\n * instance's boot). A rejected/failed warm is caught to `undefined` and never fails the boot — PGlite\n * falls back to loading its own assets, so this is a pure best-effort accelerator.\n */\n pgliteBootAssets?: Promise<PgliteBootAssets>;\n resetSubscriptionKeys?: string[];\n prepareLocalDbBeforeSchema?: (pglite: ClientPGlite) => Promise<void>;\n prepareLocalDb?: (pglite: ClientPGlite) => Promise<void>;\n onStatusChange?: (status: SyncRuntimeStatus) => void;\n onTableInitialSync?: (tableKey: string) => void;\n /**\n * A fully-provisioned PGlite instance the CALLER owns end-to-end. The client runs NONE of its\n * post-create boot steps against it — no schema exec, prepare hooks, or store-version reconcile\n * (journal recovery still runs, as it does on every path). Use it only when the caller has already\n * applied the registry schema itself. Contrast the three PGlite-provenance seams:\n * - {@link storePath} (default) — the client creates the store AND runs every post-create step.\n * - {@link precreatedPglite} — the caller creates the raw store (via {@link createClientPGlite}), but\n * the client still runs every post-create step (schema/prepare/reconcile), exactly as `storePath` does.\n * - `pgliteInstance` — the caller creates AND provisions the store; the client runs none of them.\n *\n * A caller-owned instance is REFUSED with {@link NonPersistentStoreError} if it is provably\n * non-persistent (a `new PGlite()` default, or an in-memory store) — pgxsinkit's durability semantics\n * assume a persisted store (ADR-0036). Acknowledge a deliberate test store by spreading\n * `testStoreAcknowledgment()` from `@pgxsinkit/client/testing`.\n *\n * Mutually exclusive with {@link precreatedPglite} (supplying both throws).\n */\n pgliteInstance?: ClientPGlite;\n /**\n * A raw PGlite instance the caller created EAGERLY (via {@link createClientPGlite}) — typically on an\n * earlier screen, to hide the ~1.9s cold `initdb`/IDBFS open behind user think-time — but for which the\n * client still owns EVERYTHING else: schema exec, prepare hooks, journal recovery, and store-version\n * reconcile all run exactly as on the {@link storePath} path. This is the difference from\n * {@link pgliteInstance} (which skips schema/prepare/reconcile because the caller owns them); see that\n * option's JSDoc for the three-way distinction.\n *\n * The promise form lets the still-pending eager create be handed straight in. Precedence/validation:\n * - Supplying both this and {@link pgliteInstance} throws — they claim different ownership.\n * - {@link storePath} is used ONLY as the fallback store name if this promise REJECTS: a failed eager\n * create is caught, logged on the boot rail, and the normal `storePath` create path runs instead (also\n * consuming {@link pgliteBootAssets} if provided). The pattern is a pure accelerator, never a boot\n * dependency.\n * - A successfully-adopted instance is subject to the same {@link NonPersistentStoreError} refusal as\n * {@link pgliteInstance} (checked after resolution, so the refusal propagates rather than being\n * swallowed by the reject-fallback).\n */\n precreatedPglite?: Promise<ClientPGlite>;\n /**\n * Restore the store from a **store backup** (ADR-0035 decision 6) — a `File`/`Blob` tarball as produced by\n * {@link SyncClient.exportStore}. The client creates its store with the backup handed to PGlite's\n * `loadDataDir`, so it boots ON the backup's datadir (synced cache + Overlay + Mutation journal, all the\n * bytes that travelled inside it). Three restore-only rules apply, none of them optional:\n *\n * - **Fresh target only.** Refused with {@link RestoreTargetExistsError} if a store already exists at the\n * resolved {@link storePath} — restore never overlays a live store (that would corrupt the datadir); the\n * remedy is a deliberate {@link SyncClient.destroy} of the existing store first.\n * - **Always boots offline.** The engine boots with sync OFF regardless of {@link syncEnabled}/{@link autoSync}\n * or anything captured in the backup — no shape streams, no read fetch, no flush, no convergence passes.\n * Restore wins over an explicit online option (a debug-rail warning notes the override). The app inspects\n * {@link SyncClient.diagnostics}, releases/discards the quarantined rows, then a subsequent NORMAL boot of\n * the (now-persisted) store brings sync online — `loadDataDir` happens exactly once, on this restore boot.\n * - **Journal quarantined.** Every non-terminal recovered row (`pending`/`sending`/`failed`) is moved to\n * `quarantined` — nothing recovered from a backup auto-flushes (the write path has no `mutationId` dedupe\n * ledger, so replay is unsafe on last-write-wins tables). Release (`retryFailed`) or discard\n * (`discardQuarantined`) them explicitly.\n *\n * Mutually exclusive with {@link pgliteInstance} AND {@link precreatedPglite} — restore owns the store's\n * creation (`loadDataDir` is a create-time seed), so a caller-supplied instance conflicts (supplying either\n * with `restoreFrom` throws).\n */\n restoreFrom?: File | Blob;\n /**\n * PROVABLY-fresh store hint (ADR-0032 S4 / backlog-0003): the caller guarantees this store is brand-new\n * and schemaless — no prior schema, no synced rows, no persisted subscription state. When set (and sync\n * is enabled, and the client owns schema exec — i.e. not the {@link pgliteInstance} path), the shape\n * catch-up is started BEFORE the local boot phases (schema exec, journal recovery, store-version\n * reconcile) and buffered in memory, with commits gated until those phases finish — so the network\n * catch-up overlaps them instead of running strictly after. On a far-from-database caller this collapses\n * boot from `local-phases + catch-up` toward `max(local-phases, catch-up)`.\n *\n * MUST be set only when freshness is proven, never derived by probing — a claimed schemaless spare (the\n * board's claim path knows: a claimed spare is always fresh; a mapped/returning store never is). A wrong\n * `true` on a warm store would start the streams from offset 0 and skip the subscription-state read,\n * re-snapshotting instead of resuming. Absent/false → the exact sequential path (the default, correct for\n * every warm store).\n */\n freshStore?: boolean;\n /**\n * Hard cap on send attempts before a still-failing mutation is quarantined\n * (ADR-0005 congestion policy). Defaults to the library's built-in cap.\n */\n maxMutationAttempts?: number;\n /**\n * Invoked when mutations are quarantined (permanently rejected by the server, terminal). The library\n * surfaces them here rather than silently dropping or retry-looping (ADR-0006). Surface, then either\n * re-author + resubmit or roll back via {@link SyncClient.discardQuarantined} — which clears the kept\n * overlay + quarantined journal rows so the entity accepts new mutations again.\n */\n onQuarantine?: (quarantined: MutationDetail[]) => void | Promise<void>;\n /**\n * Invoked when mutations are `conflicted` — a stale write the server declined under the\n * `reject-if-stale` Conflict policy (ADR-0015). The optimistic Overlay is kept, so the app shows a\n * resolution/diff UI and resolves each as a new write (`mutate.update`) or `discardConflict`s it.\n */\n onConflict?: (conflicted: MutationDetail[]) => void | Promise<void>;\n /**\n * Invoked when a pessimistic write-unit is `rejected` (ADR-0022) — a business decline from the\n * authoritative endpoint (capacity/quota/uniqueness). The inverse of `onConflict`: the optimistic Overlay\n * was auto-discarded for the whole unit, so the app surfaces the typed reason rather than a resolve UI.\n */\n onReject?: (rejected: MutationDetail[]) => void | Promise<void>;\n /**\n * Invoked on boot when the registry fingerprint differs from the one the local store was\n * provisioned under (ADR-0006). `rebuilt` = the read cache was dropped and rebuilt at the\n * new shape; `deferred` = un-flushed/quarantined writes are still owed, so the rebuild is\n * postponed (and retried on a later boot) rather than dropping owed data.\n */\n onSchemaChange?: (event: LocalStoreVersionEvent) => void | Promise<void>;\n /**\n * Opt-in convergence driver (ADR-0005). Supply a {@link ConvergenceTrigger} (e.g.\n * `createBrowserConvergenceTrigger()`) and the client drives `flush`/`reconcile`/`retryFailed`\n * on the trigger's schedule, started once sync is ready and stopped on `stop()`/`destroy()`.\n * Omit it for fully-manual convergence (the mechanism primitives stay public either way).\n */\n autoSync?: ConvergenceTrigger;\n /** Invoked after each automatic convergence pass with its error, or `null` on success (only when `autoSync` is set). */\n onConvergencePass?: (error: unknown) => void;\n /**\n * Invoked when a read-path sync commit fails after exhausting its retries (ADR-0009 decision 5).\n * The runtime enters the `degraded` phase and holds the read cache at the last applied commit\n * instead of silently diverging from the server; recovery is a later commit or a restart/refetch.\n */\n onSyncError?: (error: Error) => void;\n /**\n * Boot observability (ADR-0034): invoked exactly once, at boot completion, with the finalized\n * {@link BootReport}. The push counterpart of {@link SyncClient.bootReport} (the pull) for consumers that\n * want the numbers without polling — dashboards, CI budget gates. Never fired before initial sync; a\n * `stop()`/`destroy()` before then means it never fires.\n */\n onBootReport?: (report: BootReport) => void;\n /**\n * @internal Boot mode stamped into the {@link BootReport} (ADR-0034). `defineSyncWorker` sets `\"worker\"`;\n * absent → `\"in-process\"`. Not a behavior knob — it only labels the report.\n */\n bootMode?: BootReport[\"mode\"];\n /**\n * @internal Provision timing for a boot that ADOPTS a pre-provisioned store (ADR-0034). When the store was\n * minted ahead of boot (a spare's off-thread initdb), the provisioner stamps its create cost and ready\n * time here; the boot reports them as {@link BootReport.provision} and sets `phases.pgliteCreateMs = null`.\n * A promise because the stamp settles with the spare's `create`. Only honoured on the {@link precreatedPglite}\n * adoption path (ignored on a fallback create). `provisionReadyAt` must share this process's monotonic clock.\n */\n provisionStamp?: Promise<{ initdbMs: number; provisionReadyAt: number }>;\n /**\n * Bounded zero-subscriber keep-alive for the live-query manager (ADR-0040 decision 4) — same block as\n * {@link DefineSyncWorkerOptions.liveQueries}. Takes effect in BOTH client forms: the in-process client\n * now owns its own manager (decision 6), so this policy governs its live-query dedup and retention just as\n * it does the worker's. Defaults: `defaultKeepAliveMs` 0 (tear a query down the instant its last consumer\n * leaves), `maxRetainedQueries` 16, `maxRetainedRows` 50_000.\n */\n liveQueries?: {\n defaultKeepAliveMs?: number;\n maxRetainedQueries?: number;\n maxRetainedRows?: number;\n };\n}\n\nexport interface SyncClientTableHandle<TRegistry extends SyncTableRegistry, TKey extends SyncTableName<TRegistry>> {\n key: TKey;\n mode: TRegistry[TKey][\"mode\"];\n create: (input: SyncTableCreateInput<TRegistry, TKey>) => Promise<void>;\n update: (entityKey: Record<string, string>, patch: SyncTableUpdateInput<TRegistry, TKey>) => Promise<void>;\n delete: (entityKey: Record<string, string>) => Promise<void>;\n}\n\n/**\n * A table handle inside a {@link SyncClient.transaction} block (ADR-0022 §2). It *collects* mutations into\n * the open write-unit rather than enqueuing each immediately; the whole set is enqueued atomically when the\n * block's callback returns. The calls are synchronous (collection only) — no per-call await needed.\n */\nexport interface SyncTransactionTableHandle<\n TRegistry extends SyncTableRegistry,\n TKey extends SyncTableName<TRegistry>,\n> {\n create: (input: SyncTableCreateInput<TRegistry, TKey>) => void;\n update: (entityKey: Record<string, string>, patch: SyncTableUpdateInput<TRegistry, TKey>) => void;\n delete: (entityKey: Record<string, string>) => void;\n /**\n * An **update-by-key with no local base row** (ADR-0022 addendum). Ordinary `update` requires the entity\n * to be present in the actor's local read model (it seeds the optimistic overlay and captures the base\n * server version); `updateBlind` skips that presence check and writes NO overlay — nothing appears in the\n * read model. Use it when the write target is deliberately EXCLUDED from your read shape (a write-only\n * flow, or an anonymity-scoped moderation write whose row streams only to a different projection), so there\n * is no local row to update and nothing to show optimistically.\n *\n * **Pessimistic-only.** The /unit expander is authoritative for the outcome, so a blind write is meaningful\n * only inside a `transaction({ mode: \"pessimistic\" })` block (or over a statically-pessimistic table). An\n * optimistic-routed blind write has nothing to converge and THROWS at enqueue.\n *\n * The acked journal row **retires without a synced echo** (no visible row ever converges for it), so it does\n * not linger — unlike the seed-a-phantom-row workaround this replaces, whose acked row + overlay lingered\n * forever behind the echo barrier. A `conflicted` blind write stays dischargeable via `discardConflict`; a\n * `rejected` one is surfaced via `onReject`, both with no overlay to clean up.\n */\n updateBlind: (entityKey: Record<string, string>, patch: SyncTableUpdateInput<TRegistry, TKey>) => void;\n}\n\n/** The handle passed to a {@link SyncClient.transaction} callback: collecting table handles for the unit. */\nexport interface SyncTransaction<TRegistry extends SyncTableRegistry> {\n tables: { [TKey in SyncTableName<TRegistry>]: SyncTransactionTableHandle<TRegistry, TKey> };\n}\n\n/**\n * The result of a {@link SyncClient.transaction}. A `pessimistic` block carries the authoritative server\n * `acks` (each `acked` / `conflicted` / `rejected`); an `optimistic` block enqueues atomically and flushes\n * in the background, so its `acks` are empty.\n */\nexport interface SyncTransactionResult {\n acks: MutationAck[];\n}\n\n/** Minimal shape of a Drizzle select builder: inspectable via `.toSQL()` and awaitable for its rows. */\nexport interface DrizzleQueryBuilder<TRows extends readonly unknown[]> extends PromiseLike<TRows> {\n toSQL(): { sql: string; params: unknown[] };\n}\n\n/**\n * The builder callback for a guarded read (ADR-0021): it receives the client and returns a Drizzle\n * select builder. Reach relations through `c.views` / `c.drizzle` / a directly-imported synced table.\n */\nexport type GuardedQueryFn<TRegistry extends SyncTableRegistry, TRows extends readonly unknown[]> = (\n client: SyncClient<TRegistry>,\n) => DrizzleQueryBuilder<TRows>;\n\n/**\n * A guarded query whose builder MAY embed a raw `sql` template fragment (ADR-0021). A raw fragment can\n * name a lazy relation as a bare/unquoted identifier the compiled-SQL scan cannot see, so declare those\n * relations in `use` — they are activated and awaited before the query runs. Pure-Drizzle reads need no\n * `use` (the scan detects every relation): pass the builder callback directly to `client.query`.\n */\nexport interface GuardedRawQuerySpec<TRegistry extends SyncTableRegistry, TRows extends readonly unknown[]> {\n use?: readonly SyncTableName<TRegistry>[];\n build: GuardedQueryFn<TRegistry, TRows>;\n}\n\n/**\n * Inputs to the read-path safety seam {@link SyncClient.prepareQuery}. The lazy relations a query reads\n * are detected by scanning the compiled `sql` (union with the optional explicit `use`), then activated.\n * Shared by the live React hooks and the non-live facade.\n */\nexport interface PrepareQueryInput<TRegistry extends SyncTableRegistry> {\n /** The compiled (parameterised) Drizzle SQL the query will run — the scan's ground-truth target. */\n sql: string;\n /** Lazy relations to also activate, beyond those scanned from `sql` — a pre-activation hint, not required. */\n use?: readonly SyncTableName<TRegistry>[];\n}\n\n/**\n * The narrow live-rows seam (ADR-0032 S2 §4) both client modes implement so the `@pgxsinkit/react` hooks\n * work against either. Input for a reactive subscription: the compiled SQL + params (from a Drizzle\n * builder's `.toSQL()` or a raw string) and the result's `pkColumns` (drives worker-side diff keying;\n * omit for a keyless query). The in-process client runs it directly over `pglite.live`; the worker-attached\n * client runs the live query in the worker and streams DIFFs across the bridge.\n */\nexport interface SubscribeLiveRowsInput {\n sql: string;\n params: readonly unknown[];\n /**\n * The unique output aliases to render the query's columns under so it is SAFE TO MATERIALISE, in the\n * compiled SQL's column order (one per output column). Drizzle emits no output aliases, so a JOIN whose\n * tables share a column name compiles to duplicate output names — which PGlite's `live` extension\n * refuses to materialise (`column \"title\" specified more than once`) and which silently collapse\n * same-named columns even in a plain query. When supplied, the seam wraps the query so every output\n * column gets its alias and rows come back KEYED BY THESE ALIASES; the consumer's row-mapper must read\n * by alias (the `@pgxsinkit/react` hooks do). Omit for a raw or non-colliding query — the seam then\n * leaves the SQL untouched and rows stay keyed by the underlying column names (backward-compatible).\n */\n fields?: readonly string[];\n /**\n * The result's PK columns — the diff-keying identity across the bridge (§4). Omit for a keyless query.\n * When {@link fields} is supplied the result columns are the aliases, so a PK column here must be named\n * by its ALIAS (the aliased result column), not the underlying source column.\n */\n pkColumns?: readonly string[];\n /**\n * Lazy relations (ADR-0021) to activate before the query runs — forwarded to the worker so it can\n * `prepareQuery` before registering the live query (the tab's own `prepareQuery` is a no-op against the\n * worker bridge). Ignored by the in-process client, whose `prepareQuery` already ran on the tab.\n */\n use?: readonly string[];\n /**\n * Per-subscription keep-alive hint (ms) for the live-query manager (ADR-0040 decision 4): retain this\n * query's shared registration for the grace period after its last consumer leaves, so a re-mount reuses it\n * verbatim (no re-materialization). Honoured in BOTH modes — the worker manager and the in-process manager\n * (decision 6). Bounded by the `liveQueries` policy budgets. Absent → no hint.\n */\n keepAliveMs?: number;\n}\n\n/** A handle to a live-rows subscription: the initial ordered snapshot plus an idempotent unsubscribe. */\nexport interface LiveRowsSubscription<TRow> {\n initialRows: TRow[];\n unsubscribe: () => void;\n /**\n * The `lazy` relations the query reads (the guard's scan) — the relations held out of the eager boot\n * set. Activation (stream start) completed before the subscription registered. Informational only:\n * {@link hydrated} — not this — reflects catch-up completion, and it now spans eager groups too.\n */\n lazyTables?: readonly string[];\n /**\n * Present when the query reads ANY consistency group (eager OR lazy) that was NOT YET caught up at\n * subscribe time: resolves once every such group has completed its initial catch-up AND this\n * subscription has already delivered rows reflecting it (the seam refreshes the live query after\n * catch-up, then resolves — rows-before-signal is guaranteed, so flipping a UI out of its loading state\n * on this promise can never flash a false \"empty\"). Absent when every referenced group is already ready\n * at subscribe time (the steady-state fast path — no extra refresh) or sync is disabled. Offline note:\n * stays pending until the catch-up truly completes — gate empty-state COPY on it, not data access (rows\n * flow regardless).\n */\n hydrated?: Promise<void>;\n}\n\n/**\n * Result of {@link SyncClient.prepareQuery}: the `lazy` relations the guard scanned out of the SQL\n * (∪ the explicit `use`) and activated. Activation means the group's STREAM IS STARTED — reads are\n * safe from the tripwire — not that its initial catch-up has completed; await\n * {@link SyncClient.groupReady} per key for that (see ADR-0021 / ADR-0032 decision 6).\n *\n * Parameterized by the TABLE-NAME UNION, not the registry: `keyof TRegistry` in an output position\n * would make the registry parameter contravariant, and `SyncClient<ConcreteRegistry>` would stop\n * being assignable to bare-`SyncTableRegistry` supertypes — the erasure pattern consumer seams rely\n * on. A name union in output position keeps the whole client covariant in its registry.\n */\nexport interface PreparedQueryResult<TTable extends string = string> {\n lazyTables: readonly TTable[];\n}\n\nexport interface SyncClient<TRegistry extends SyncTableRegistry> {\n drizzle: PgliteDatabase<RegistryRelations<TRegistry>>;\n pglite: ClientPGlite;\n views: RegistryViews<TRegistry>;\n tables: {\n [TKey in SyncTableName<TRegistry>]: SyncClientTableHandle<TRegistry, TKey>;\n };\n ready: Promise<void>;\n status: SyncRuntimeStatus;\n start: () => Promise<void>;\n stop: () => Promise<void>;\n /**\n * Wipe the entire local store (synced cache + overlay + journal) and close the handle\n * (ADR-0005). Refuses if mutations are still owed to the server unless `force` is set, so\n * it never silently drops un-flushed writes. Distinct from `stop()`, which only halts sync.\n * Runs under the single lifecycle slot (ADR-0035 decision 4): a concurrent export — or another\n * `destroy`/`discardEphemeral`/`dropReadCache` — rejects with a {@link LifecycleBusyError} rather\n * than interleaving the wipe with a running export.\n */\n destroy: (options?: { force?: boolean }) => Promise<void>;\n /**\n * Drop and rebuild the reconstructible synced read cache, preserving the overlay and\n * mutation journal (ADR-0006). The next sync refills it. Use to recover from a corrupt or\n * stale read cache without losing un-flushed writes. Runs under the single lifecycle slot\n * (ADR-0035 decision 4) — it drops and rebuilds the synced tables, so an export must not capture a\n * half-rebuilt cache; a concurrent export (or `destroy`/`discardEphemeral`) rejects with a\n * {@link LifecycleBusyError}.\n */\n dropReadCache: () => Promise<void>;\n flush: (table?: SyncTableName<TRegistry>) => Promise<void>;\n reconcile: (table?: SyncTableName<TRegistry>) => Promise<void>;\n retryFailed: (table?: SyncTableName<TRegistry>) => Promise<void>;\n recoverSending: (table?: SyncTableName<TRegistry>) => Promise<void>;\n readMutationDetails: (table?: SyncTableName<TRegistry>) => Promise<MutationDetail[]>;\n mutate: {\n create: <TKey extends SyncTableName<TRegistry>>(\n table: TKey,\n input: SyncTableCreateInput<TRegistry, TKey>,\n ) => Promise<void>;\n update: <TKey extends SyncTableName<TRegistry>>(\n table: TKey,\n entityKey: Record<string, string>,\n patch: SyncTableUpdateInput<TRegistry, TKey>,\n ) => Promise<void>;\n delete: <TKey extends SyncTableName<TRegistry>>(table: TKey, entityKey: Record<string, string>) => Promise<void>;\n batch: (items: ReadonlyArray<MutationBatchItem<TRegistry>>) => Promise<void>;\n };\n /**\n * Discard a `conflicted` entity (ADR-0015): clear its conflicted journal entry and kept optimistic\n * Overlay, so the Read model falls back to the synced (server) value. Use when the user abandons a\n * stale edit instead of resolving it as a new write.\n */\n discardConflict: <TKey extends SyncTableName<TRegistry>>(\n table: TKey,\n entityKey: Record<string, string>,\n ) => Promise<void>;\n /**\n * Discard a `quarantined` entity (ADR-0006): clear its quarantined journal entry and kept optimistic\n * Overlay, so the Read model falls back to the synced (server) value. The rollback path for a write\n * the server permanently rejected — e.g. an RLS policy denial (42501) routed to quarantine. After the\n * discard the phantom optimistic row is gone and the entity accepts new mutations again (no longer\n * blocked behind the quarantined head). Symmetric to {@link SyncClient.discardConflict}; the overlay\n * is kept when another still-owed write depends on it. No-op for an entity with no quarantined entry.\n */\n discardQuarantined: <TKey extends SyncTableName<TRegistry>>(\n table: TKey,\n entityKey: Record<string, string>,\n ) => Promise<void>;\n diagnostics: (table?: SyncTableName<TRegistry>) => Promise<{ mutation: MutationDiagnostics }>;\n /**\n * The INSPECTION read surface (debug pages, REPLs, ad-hoc counts) — identical on the in-process and\n * worker-attached client (on the latter the statement runs in the worker). The statement runs raw\n * against the local store: it BYPASSES the mutation journal and optimistic overlay, and any write it\n * issues stays local and will NOT converge. For app data reads prefer the live-rows hooks /\n * {@link subscribeLiveRows} (or the guarded {@link query} family); reach for this only to look at the\n * store, not to read app state or mutate it.\n */\n rawQuery: (sql: string, params?: unknown[], options?: RawQueryOptions) => Promise<Results>;\n /** {@link rawQuery} for multi-statement SQL, returning one {@link Results} per statement. */\n rawExec: (sql: string, options?: RawQueryOptions) => Promise<Results[]>;\n /**\n * Run a one-shot (non-live) typed **pure-Drizzle** query with the lazy-relation safety net (ADR-0021).\n * Pass the builder callback directly — pgxsinkit scans the compiled SQL and activates + awaits every\n * lazy relation it reads (FROM, JOIN, subquery, WHERE) before it runs, and the tripwire rejects any\n * lazy relation the SQL still references but that is not active, so the result is never silently\n * empty/stale. The guaranteed-safe alternative to a bare `client.drizzle` read. If the builder embeds\n * a raw `sql` template fragment, use {@link queryRaw} and declare the lazy relations in `use`.\n */\n query: <TRows extends readonly unknown[]>(build: GuardedQueryFn<TRegistry, TRows>) => Promise<TRows>;\n /** {@link query} returning the first row, or null when empty. */\n queryRow: <TRows extends readonly unknown[]>(\n build: GuardedQueryFn<TRegistry, TRows>,\n ) => Promise<TRows[number] | null>;\n /**\n * {@link query} for a builder that embeds a raw `sql` template fragment (ADR-0021). The compiled-SQL\n * scan can miss a lazy relation named as a bare/unquoted identifier inside raw SQL, so declare those\n * in `use` — they are activated and awaited before the query runs. Pure-Drizzle reads should use\n * {@link query} instead (no `use` needed).\n */\n queryRaw: <TRows extends readonly unknown[]>(spec: GuardedRawQuerySpec<TRegistry, TRows>) => Promise<TRows>;\n /** {@link queryRaw} returning the first row, or null when empty. */\n queryRawRow: <TRows extends readonly unknown[]>(\n spec: GuardedRawQuerySpec<TRegistry, TRows>,\n ) => Promise<TRows[number] | null>;\n /**\n * Activate one or more lazy relations (ADR-0021): open their consistency-group subscription if held\n * out of the eager boot, resolving once each group's STREAM IS STARTED — reads are then tripwire-safe,\n * but the initial catch-up may still be in flight (local rows can be legitimately empty/stale until it\n * lands; await {@link groupReady} per relation for catch-up completion — deliberately separate so an\n * offline client still reads its persisted local rows instead of hanging on the network). Idempotent —\n * eager or already-started relations resolve immediately. Use to pre-activate before a\n * raw/`client.drizzle` read, or as the manual escape hatch the tripwire points to.\n */\n ensureSynced: (keys: readonly SyncTableName<TRegistry>[]) => Promise<void>;\n /**\n * Whether a relation's group has started and hydrated (ADR-0021). False for a still-dormant `lazy`\n * relation; true for eager relations once boot completes (and always when sync is disabled).\n */\n isSynced: (key: SyncTableName<TRegistry>) => boolean;\n /**\n * Revert a `lazy` relation to dormant (ADR-0021 §2) — the inverse of on-demand activation: stop its\n * consistency group's stream, clear any persisted `lazy + persistent` activation (so the next boot\n * holds it dormant again), and clean-truncate its local read cache. A later reference re-activates it\n * from scratch. Refuses when the relation is `eager` (always-on, would immediately re-sync) or owes\n * the server unsettled writes (the truncate would drop them — flush or discard first). The reclaim\n * primitive a host wires to navigation/idle for a rarely-opened lazy view; for an `ephemeral`\n * relation, idle-eviction is otherwise automatic at session end.\n */\n desync: (key: SyncTableName<TRegistry>) => Promise<void>;\n /**\n * Drop an **ephemeral** relation's local rows and revert it to dormant (ADR-0021) — the narrow,\n * scoped twin of {@link desync}. It runs the identical group-teardown machinery (stop the group stream,\n * clear the persisted lazy activation, reset the persisted subscription, clean-truncate every member),\n * but under a STRICTER gate: EVERY member of the relation's consistency group must be `retention:\n * \"ephemeral\"` — it refuses (naming the offender) if any member is persistent. Where a `desync` from one\n * tab reverts the shared group for every attached tab (the SharedWorker footgun), `discardEphemeral` is\n * safe under multi-tab because an ephemeral window is per-delivery-session and inherently single-consumer\n * — nothing durable, and no other tab, depends on it. Refuses an `eager` relation (always-on, would\n * immediately re-sync) and a group that owes the server unsettled writes, exactly as `desync` does. The\n * finalize primitive for a secure-delivery window: drop the local rows at session end without touching a\n * durable relation. Note the drop is local-lifecycle only: a later re-subscription re-activates the lazy\n * group and re-streams whatever the SERVER still serves — post-finalize non-redelivery is the server\n * gate's guarantee (e.g. a consumed server-owned cursor), not this method's. Runs under the single\n * lifecycle slot (ADR-0035 decision 4): a concurrent export (or `destroy`/`dropReadCache`) rejects with a\n * {@link LifecycleBusyError} rather than interleaving the cache truncate with a running export.\n */\n discardEphemeral: (key: SyncTableName<TRegistry>) => Promise<void>;\n /**\n * The read-path safety seam (ADR-0021): scan the compiled `sql` for the lazy relations it reads\n * (∪ the optional `use`) and activate them — so a lazy relation auto-activates on *any* reference\n * (FROM, JOIN, subquery, WHERE). Resolves once it is safe to run the query (streams started, tripwire\n * satisfied) and returns the activated keys ({@link PreparedQueryResult}) so a consumer can further\n * await {@link groupReady} per key for catch-up completion — the React hooks drive `hydrating` off\n * exactly that. A backstop throws {@link LazyRelationNotActivatedError} only if a referenced relation\n * could not be activated. Exposed for the React live hooks (which own their query build);\n * `query`/`queryRow` are the higher-level non-live wrappers. Raw, non-Drizzle SQL is out of scope —\n * pass `use`, or `ensureSynced` first.\n */\n prepareQuery: (input: PrepareQueryInput<TRegistry>) => Promise<PreparedQueryResult<SyncTableName<TRegistry>>>;\n /**\n * Author an atomic write-**unit** (ADR-0022 §2). The callback receives collecting table handles; every\n * mutation it issues is tagged into one unit and enqueued atomically when the callback returns.\n *\n * - `mode: \"pessimistic\"` — **server-authoritative**: the unit flush-routes to the authoritative endpoint\n * and this call resolves only once the server has decided. The result's `acks` carry each member's\n * outcome — `acked`, `conflicted` (overlay kept, ADR-0015), or `rejected` (overlay auto-discarded for\n * the whole unit, surfaced via `onReject`, ADR-0022 §4). Throws on transport failure (overlay kept). A\n * pessimistic block may also issue {@link SyncTransactionTableHandle.updateBlind} — an update-by-key with\n * no local base row and no overlay, for a write target excluded from the actor's read shape.\n * - `mode: \"optimistic\"` — an atomic batch enqueue that flushes in the background (empty `acks`).\n */\n transaction: (\n options: { mode: WriteMode },\n run: (tx: SyncTransaction<TRegistry>) => void | Promise<void>,\n ) => Promise<SyncTransactionResult>;\n /**\n * Per-group readiness (ADR-0032 decision 6): a promise resolving the moment the given table's\n * consistency group is up-to-date. Resolves immediately for an already-ready (or sync-disabled)\n * group; stays pending for a still-dormant `lazy` relation until it is activated and caught up. The\n * opt-in progressive-paint signal beside the all-eager-groups `ready` gate. `status.groups` carries the\n * same readiness as a synchronous snapshot.\n */\n groupReady: (table: SyncTableName<TRegistry>) => Promise<void>;\n /**\n * The referenced consistency groups' member tables that are NOT YET caught up at call time (ADR-0021 /\n * ADR-0032 decision 6): scan the compiled SQL for every synced relation the query reads (∪ `use`), map\n * each to its consistency group, and return those whose group has not completed its initial catch-up.\n * Empty when sync is disabled OR every referenced group is already ready — the steady-state fast path in\n * which the live-rows seam builds no `hydrated` promise. The seam (and the worker bridge) use this to gate\n * `hydrating` uniformly across eager AND lazy groups; ACTIVATION is separate and stays lazy-only. Returns\n * plain table-name strings (not `keyof TRegistry`) to keep the client covariant in its registry.\n */\n hydratingTablesFor: (query: { sql: string; use?: readonly string[] }) => readonly string[];\n /**\n * The live-rows seam (ADR-0032 S2 §4): register a reactive query and receive its initial ordered\n * snapshot plus subsequent updates via `onRows`. The React live hooks consume THIS (not `pglite.live`\n * directly), so they run unchanged against both the in-process client (which implements it over\n * `pglite.live`) and the worker-attached client (which implements it over the bridge). Prefer the\n * higher-level `@pgxsinkit/react` hooks; this is the lower-level primitive they build on.\n */\n subscribeLiveRows: <TRow extends Record<string, unknown> = Record<string, unknown>>(\n input: SubscribeLiveRowsInput,\n onRows: (rows: TRow[]) => void,\n ) => Promise<LiveRowsSubscription<TRow>>;\n /**\n * Boot observability (ADR-0034): the engine's most recent COMPLETED boot report, or `null` before the\n * first boot finalizes (and after a `stop()`/`destroy()` that preceded initial sync). Pull — so a\n * late-attaching tab can read a boot that predates it; in worker mode it round-trips to the worker's\n * stored report. The push counterpart is the `onBootReport` client option.\n */\n bootReport: () => Promise<BootReport | null>;\n /**\n * Live-query diagnostics (ADR-0040 decision 5): a point-in-time snapshot of the live-query manager's\n * entries — opaque fingerprint digests plus counts/timings only, NEVER SQL, params, or row values. Both\n * client forms return the real snapshot: in WORKER mode this pulls the worker manager's snapshot over the\n * bridge; the IN-PROCESS client returns its own manager's snapshot directly.\n */\n liveQueryDiagnostics: () => Promise<LiveQueryDiagnostics[]>;\n /**\n * Take a **store backup** (ADR-0035): a full-fidelity, PGlite-restorable tarball of the whole local\n * store — synced cache, Overlay, and Mutation journal (unflushed writes included) — via PGlite's\n * `dumpDataDir`. Taken LIVE (a `CHECKPOINT` serialised behind engine work, then the dump; no engine\n * suspension, no tab disruption), so it never blocks and is the only lossless export an offline device\n * with unflushed writes can take. Awaits engine-ready rather than rejecting during boot, then runs under\n * the single lifecycle slot: a second export (or, later, `destroy`/`discardEphemeral`) attempted while\n * one is in flight rejects immediately with a {@link LifecycleBusyError} — retry once it settles.\n * Resolves to the artefact `File` plus an {@link ExportReport} (phase timings + a diagnostics snapshot).\n */\n exportStore: (options?: StoreExportOptions) => Promise<StoreExportResult>;\n /**\n * Take a **diagnostic dump** (ADR-0035): human-readable SQL of EVERYTHING the store holds — synced tables,\n * the `_overlay`/`_mutations` journal (unflushed writes included — the evidence a diagnostic exists for),\n * the `pgxsinkit` metadata schema, the read-model views, and the reconcile functions/triggers — via\n * `pg_dump`. To keep `pg_dump`'s `DEALLOCATE ALL` away from the live engine, the dump runs against a\n * memory-backed THROWAWAY clone booted from a live datadir dump (ADR-0035 addendum): the running store is\n * never suspended and no tab is disrupted. Awaits engine-ready rather than rejecting during boot, then\n * runs under the single lifecycle slot — a concurrent export (or `destroy`/`discardEphemeral`) rejects\n * immediately with a {@link LifecycleBusyError}. Resolves to the SQL `File` (`application/sql`) plus a\n * {@link DiagnosticDumpReport} (phase timings + a diagnostics snapshot). Active ephemeral (`pg_temp`)\n * clusters are absent by construction (ADR-0035 decision 5 — `pg_dump` ignores temp objects).\n */\n exportDiagnostics: (options?: DiagnosticExportOptions) => Promise<DiagnosticExportResult>;\n /**\n * Take a **data export** (ADR-0035): the PORTABLE artefact — the synced tables and the enum types they\n * depend on, schema + data, nothing of pgxsinkit's machinery — as SQL loadable into a vanilla Postgres. It\n * is a generated enum DDL header concatenated ahead of `pg_dump -t <table> ... --no-owner` (one `-t` per\n * physical synced table; ephemeral/read-projection entries excluded by construction), run against the same\n * memory-backed THROWAWAY clone the diagnostic dump uses — so the live engine is never touched.\n *\n * Unlike the other two exports it GUARDS the journal (decision 3): a strict export requires a DRAINED\n * journal — all mutation counts zero, including `acked` writes whose synced echo has not landed (they live\n * only in the Overlay). The drain flushes drainable rows and awaits convergence up to\n * `drainJournal.timeoutMs` (default `15_000`); non-drainable states (`failed`/`quarantined`/`conflicted`)\n * fail FAST with a {@link DataExportDrainError} carrying the diagnostics. `drainJournal: false` is the\n * escape hatch — export synced state as-is (unflushed writes absent; `report.escapeHatch` records it). An\n * offline device with a clean journal exports strictly and instantly; one with a dirty journal cannot\n * produce a strict export (its lossless option is `exportStore`).\n *\n * Awaits engine-ready rather than rejecting during boot, then runs the whole drain+dump under the single\n * lifecycle slot — a concurrent export (or `destroy`/`discardEphemeral`) rejects with a\n * {@link LifecycleBusyError}. Resolves to the SQL `File` (`application/sql`) plus a {@link DataExportReport}\n * (drain + clone-pipeline phase timings, the applied `-t` table list, and the escape-hatch flag).\n */\n exportData: (options?: DataExportOptions) => Promise<DataExportResult>;\n}\n\nexport type { MutationBatchItem, MutationDetail, MutationDiagnostics, MutationKind };\n\n/**\n * The structured-clone-safe subset of PGlite's `QueryOptions` the inspection surface carries. Kept\n * narrow ON PURPOSE: on a worker-attached client the options object crosses the bridge via\n * `postMessage`, so function-valued options (`parsers`, `serializers`, `onNotice`) can never be part\n * of this contract. `rowMode: \"array\"` is what `@electric-sql/pglite-repl` asks for on every exec.\n */\nexport interface RawQueryOptions {\n rowMode?: \"object\" | \"array\";\n}\n\n/** The `{ query, exec }` duck `@electric-sql/pglite-repl` drives, backed by a client's inspection surface. */\nexport interface ReplInspectionSurface {\n query: (sql: string, params?: unknown[], options?: RawQueryOptions) => Promise<Results>;\n exec: (sql: string, options?: RawQueryOptions) => Promise<Results[]>;\n}\n\n/**\n * Shape a {@link SyncClient}'s inspection surface (`rawQuery`/`rawExec`) as the `{ query, exec }` duck\n * `@electric-sql/pglite-repl` needs. Identical on the in-process and worker-attached client — on the latter\n * each statement routes through the worker bridge, so the REPL works even though `client.pglite` is\n * unavailable. Cast the result at the `<Repl pg={...}>` prop (the REPL types the prop as a full `PGlite`).\n * The surface is registry-independent, so it accepts any client's `rawQuery`/`rawExec` pair.\n */\nexport function replAdapter(\n client: Pick<SyncClient<SyncTableRegistry>, \"rawQuery\" | \"rawExec\">,\n): ReplInspectionSurface {\n return {\n // Thread the options through UNMODIFIED — the REPL execs with `{ rowMode: \"array\" }` and renders\n // each row with `row.map`, so dropping the options here breaks every REPL statement.\n query: (sql, params, options) => client.rawQuery(sql, params, options),\n exec: (sql, options) => client.rawExec(sql, options),\n };\n}\n\nexport async function createSyncClient<const TRegistry extends SyncTableRegistry>(\n options: CreateSyncClientOptions<TRegistry>,\n): Promise<SyncClient<TRegistry>> {\n // Fail fast on a bad keep-alive policy — before any PGlite boot work (ADR-0040 decision 4 — bounded).\n validateLiveQueryPolicy(options.liveQueries);\n const status: SyncRuntimeStatus = {\n phase: \"booting\",\n isRunning: false,\n };\n\n let resolveReady!: () => void;\n const ready = new Promise<void>((resolve) => {\n resolveReady = resolve;\n });\n\n if (options.pgliteInstance && options.precreatedPglite) {\n throw new Error(\n \"createSyncClient: pass at most one of `pgliteInstance` or `precreatedPglite` — they claim different ownership of the post-create boot steps (schema exec, prepare hooks, store-version reconcile).\",\n );\n }\n\n // Restore (ADR-0035 decision 6) owns the store's CREATION — the backup tarball is a `loadDataDir` seed on\n // the fresh store — so it cannot coexist with a caller-supplied instance (which claims the store already\n // exists and is provisioned). Fail loudly rather than silently ignore one.\n const restoreBoot = options.restoreFrom != null;\n if (restoreBoot && (options.pgliteInstance || options.precreatedPglite)) {\n throw new Error(\n \"createSyncClient: `restoreFrom` is mutually exclusive with `pgliteInstance` / `precreatedPglite` — restore boots a brand-new store from the backup (a create-time `loadDataDir` seed), so it cannot adopt a caller-owned instance. Drop the instance option, or drop `restoreFrom` (ADR-0035).\",\n );\n }\n\n // Restore ALWAYS boots offline (ADR-0035 decision 6), regardless of `syncEnabled`/`autoSync` or anything\n // captured in the backup: no shape streams, no read fetch, no flush, no convergence passes. The app deals\n // with the quarantined journal, then a subsequent NORMAL boot brings sync online. Restore wins over an\n // explicit online option — warn on the debug rail so the override is visible rather than silent.\n if (restoreBoot && (options.syncEnabled === true || options.autoSync != null)) {\n syncDebug(\"boot restore forces offline — ignoring the online sync option for this restore boot\", {\n syncEnabled: options.syncEnabled === true,\n autoSync: options.autoSync != null,\n });\n }\n const syncEnabled = restoreBoot ? false : (options.syncEnabled ?? true);\n // ADR-0032 S4 overlap flag, computed once up front so the boot report and the prefetch gate agree.\n const overlapPrefetch = syncEnabled && options.freshStore === true && !options.pgliteInstance;\n\n // Boot observability (ADR-0034): build a structured report across the boot, finalized once at initial\n // sync. Created FIRST so its monotonic anchor precedes every timed phase (including the PGlite create).\n const bootReportBuilder: BootReportBuilder = createBootReportBuilder({\n mode: options.bootMode ?? \"in-process\",\n freshStore: options.freshStore === true,\n overlapPrefetch,\n registryFingerprint: fingerprintRegistry(options.registry),\n });\n // The single engine lifecycle slot (ADR-0035 decision 4). The three exports plus the destructive\n // lifecycle ops — `destroy()`, `discardEphemeral()`, and `dropReadCache()` — all serialise through it,\n // so a wipe/rebuild can never interleave a running export (nor vice versa): the slot rejects the second\n // entrant with a typed LifecycleBusyError in either direction.\n const lifecycleSlot = createLifecycleSlot();\n\n let finalizedBootReport: BootReport | null = null;\n const finalizeBootReport = () => {\n if (finalizedBootReport) return;\n finalizedBootReport = bootReportBuilder.finalize();\n options.onBootReport?.(finalizedBootReport);\n };\n\n // The testing marker (ADR-0036 decision 3), read once off the options object: `\"memory\"` selects the\n // memory backend for a client-owned create AND acknowledges the BYO seam; `\"acknowledged\"` only unlocks\n // the BYO refusal. Absent for every production consumer — the marker rides in only via\n // `@pgxsinkit/client/testing`, never named in a public type.\n const testStoreMarker = readTestStoreMarker(options);\n const backendOverride = testStoreMarker === \"memory\" ? (\"memory\" as const) : undefined;\n\n // Bind the create options once for the two client-owned create paths (fresh `storePath`, and the\n // `precreatedPglite` reject-fallback), so both consume the same pre-warm + resolve the same backend.\n const createClientOptions: CreateClientPGliteOptions = {\n ...(options.pgliteBootAssets ? { bootAssets: options.pgliteBootAssets } : {}),\n ...(backendOverride ? { backendOverride } : {}),\n // Restore (ADR-0035 decision 6): seed the fresh store from the backup via `loadDataDir`. Restore is\n // mutually exclusive with the BYO instance seams (checked above), so it only ever rides a client-owned\n // create — never the adopt paths, which leave `restoreFrom` unread.\n ...(restoreBoot ? { restoreFrom: options.restoreFrom } : {}),\n };\n const fallbackStorePath = options.storePath ?? \"pgxsinkit-overlay-v1\";\n\n // Fresh-target gate (ADR-0035 decision 6): restore refuses a store that already exists — it boots a\n // brand-new store and never overlays a live one. Checked BEFORE the create so we never touch (let alone\n // half-write) an existing datadir; the memory test lane is fresh by construction, so this is a no-op there.\n if (restoreBoot) {\n if (await storeTargetExists(fallbackStorePath, backendOverride)) {\n throw new RestoreTargetExistsError(fallbackStorePath);\n }\n }\n // Time a client-owned `createClientPGlite` into `phases.pgliteCreateMs`; an ADOPTED store (spare or\n // caller-supplied) leaves it `null` (create ran elsewhere — see the provision block below).\n const timedCreate = async (): Promise<ClientPGlite> => {\n const startedAt = performance.now();\n const created = await createClientPGlite(fallbackStorePath, createClientOptions);\n bootReportBuilder.setPgliteCreateMs(performance.now() - startedAt);\n return created;\n };\n\n // Refuse a caller-owned instance that is PROVABLY non-persistent (ADR-0036 decision 4), unless a testing\n // acknowledgment is present. `classifyNonPersistentDataDir` inspects the instance's own dataDir (the\n // `ClientPGlite` interface hides it, so via a narrow cast) — the two provably-non-persistent shapes are\n // an undefined dataDir (PGlite's in-memory default) and an explicit memory store. Checked AFTER a\n // successful resolution of the BYO promise, so the refusal PROPAGATES rather than being swallowed by the\n // `precreatedPglite` reject-fallback below (which only catches a create that never produced a store).\n const refuseIfNonPersistent = (instance: ClientPGlite): void => {\n if (testStoreMarker !== undefined) return; // a deliberate test store — acknowledged.\n const observed = classifyNonPersistentDataDir((instance as { dataDir?: string }).dataDir);\n if (observed !== null) throw new NonPersistentStoreError(observed);\n };\n\n let pglite: ClientPGlite;\n // Whether the boot adopted the caller's `precreatedPglite` (vs. falling back to a fresh create) — gates\n // whether the provision stamp is honoured (ADR-0034).\n let adoptedPrecreated = false;\n if (options.pgliteInstance) {\n // The caller created AND provisioned this store; the client runs NONE of the post-create boot steps\n // (schema/prepare/reconcile) — see the `pgliteInstance` JSDoc. No create here → `pgliteCreateMs` null.\n refuseIfNonPersistent(options.pgliteInstance);\n pglite = options.pgliteInstance;\n } else if (options.precreatedPglite) {\n // The caller created the raw store eagerly via `createClientPGlite`; the client still owns every\n // post-create step below. A REJECTED eager create must never fail the boot: fall back to the normal\n // `storePath` create, so the pattern stays a pure accelerator. Reify the promise's outcome first, THEN\n // branch — so the {@link NonPersistentStoreError} refusal runs on a SUCCESSFULLY resolved instance,\n // outside any catch, and PROPAGATES (never swallowed by the reject-fallback, which is only for a create\n // that never produced a store).\n const outcome = await options.precreatedPglite.then(\n (instance) => ({ ok: true as const, instance }),\n (error: unknown) => ({ ok: false as const, error }),\n );\n if (outcome.ok) {\n refuseIfNonPersistent(outcome.instance);\n pglite = outcome.instance;\n adoptedPrecreated = true;\n } else {\n syncDebug(\"boot precreated pglite rejected — falling back to storePath create\", {\n error: outcome.error instanceof Error ? outcome.error.message : String(outcome.error),\n });\n pglite = await timedCreate();\n }\n } else {\n pglite = await timedCreate();\n }\n\n // Provision block (ADR-0034): when the boot adopted a pre-provisioned store and the provisioner stamped\n // its create timing, report the spare's initdb cost + how long it sat ready, and leave `pgliteCreateMs`\n // null (the create was paid at provision time, off this boot's clock).\n if (adoptedPrecreated && options.provisionStamp) {\n const stamp = await options.provisionStamp.catch(() => null);\n if (stamp) {\n bootReportBuilder.setProvision({\n initdbMs: stamp.initdbMs,\n provisionedMsBeforeBoot: Math.max(0, bootReportBuilder.bootStartPerf - stamp.provisionReadyAt),\n });\n }\n }\n\n // Attach the sync engine explicitly, over the already-created instance, on ALL three provenance paths\n // (pgliteInstance, precreatedPglite, storePath) — ADR-0032 S1. The engine is no longer a create-time\n // extension, so the raw store (a `createClientPGlite` mint, or a caller's own instance) carries no\n // `electric` namespace until this point; the property assignment gives `ClientPGlite` its exact former\n // structural shape (live + electric) so every `pglite.electric.…` call site is unchanged. It is attached\n // BEFORE the schema/prepare steps below so a `prepareLocalDb` hook sees the same `.electric` it did when\n // the extension provided it at create time. `engine.close` (the former extension close hook — abort every\n // shape stream) is kept private to this client and run explicitly by `stop`/`destroy` at the same moment\n // `pglite.close()` used to trigger it.\n const engine: SyncEngine = await createSyncEngine(pglite);\n (pglite as { electric: SyncEngine[\"namespace\"] }).electric = engine.namespace;\n\n // Whether the read path's first initial sync has completed, so a recovery from `auth-needed` returns to\n // the right steady-state phase (`ready` if already caught up, else `syncing`).\n let initialSyncCompleted = false;\n // Why the runtime is `degraded` (#4). A read-stream error degraded clears on the next successful batch; a\n // commit-failure degraded is sticky (a fetch can succeed while applies still fail), so a bare\n // `onSyncActivity` must not clear it.\n let degradedReason: \"stream\" | \"commit\" | null = null;\n\n // ─── Fresh-store prefetch overlap (ADR-0032 S4 / backlog-0003) ─────────────────────────────────────\n // On a PROVABLY-FRESH store (the caller's `freshStore` hint — a claimed schemaless spare) the shape\n // catch-up needs none of the local boot phases, so start it NOW and gate its commits on `dbReady`, which\n // we resolve once schema exec + journal recovery + store-version reconcile complete. The network then\n // overlaps those phases instead of running strictly after them. Gated to the schema-owning paths (the\n // `pgliteInstance` path runs no schema step, so it has nothing to hide); warm stores keep the exact\n // sequential path. See the `freshStore` option's JSDoc for who sets the hint (the board's claim path).\n // (`overlapPrefetch` is computed once up front — see the boot-report builder above.)\n let openDbGate: () => void = () => {};\n const dbReady = overlapPrefetch\n ? new Promise<void>((resolve) => {\n openDbGate = resolve;\n })\n : null;\n\n // The sync-start options, built once and used by BOTH the overlap early-start and the sequential start —\n // the only per-call difference is the promoted-lazy set (empty on a fresh store) and the overlap gate.\n const buildStartOptions = (promotedGroups: ReadonlySet<string>): Parameters<typeof startConfiguredSync>[1] => ({\n syncConfig: buildSyncConfigFromRegistry(options.registry, options.electricUrl),\n registry: options.registry,\n promotedGroups,\n ...(dbReady ? { dbReady } : {}),\n // Boot observability (ADR-0034): the collector opens a per-boot-group accumulator (rows/requests/fetch/\n // apply wall) for the eager + promoted groups; lazy on-demand starts get none, so they never enter the report.\n bootCollector: bootReportBuilder,\n // Persist a durable lazy group's activation on first on-demand start, so the next boot promotes it.\n onLazyActivated: (groupKey) => {\n void writeLazyGroupActivation(pglite, options.registry, groupKey);\n },\n // The read path resolves the token per request (ADR-0013), not frozen at boot — so a long-lived session\n // never wedges on JWT expiry. Read and write share one token lifecycle.\n ...(options.getAuthToken || options.requestHeaders\n ? {\n shapeHeaders: buildShapeHeaders({\n ...(options.getAuthToken ? { getAuthToken: options.getAuthToken } : {}),\n ...(options.requestHeaders ? { requestHeaders: options.requestHeaders } : {}),\n }),\n }\n : {}),\n ...(options.onTableInitialSync ? { onTableInitialSync: options.onTableInitialSync } : {}),\n // Per-group readiness (ADR-0032 decision 6): mirror each group's catch-up into `status.groups` and\n // re-emit, so an app can drive progressive per-group paint off `status` (and `client.groupReady`).\n onGroupReady: (groupKey) => {\n status.groups = { ...(status.groups ?? {}), [groupKey]: true };\n options.onStatusChange?.(status);\n },\n onInitialSync: () => {\n initialSyncCompleted = true;\n status.phase = \"ready\";\n options.onStatusChange?.(status);\n // Boot complete: the first initial sync landed and `ready` is about to resolve. One monotonic stamp\n // closes the boot rail opened by `boot pglite.create` (the stamp itself is the number).\n syncDebug(\"boot client ready\");\n // Boot observability (ADR-0034): finalize the report at exactly this moment — the `boot client ready`\n // rail line — and fire the one-shot `onBootReport` push. Idempotent, so the sync-disabled path's own\n // finalize below never double-fires it.\n finalizeBootReport();\n resolveReady();\n },\n onSyncError: (error) => {\n // A sync commit exhausted its retries (ADR-0009 decision 5): go degraded and surface it, rather than\n // letting the read cache silently diverge from the server. Sticky (see below).\n status.phase = \"degraded\";\n degradedReason = \"commit\";\n status.lastError = error.message;\n options.onStatusChange?.(status);\n options.onSyncError?.(error);\n },\n // #4: a terminal/transient NON-auth read-stream error → `degraded`, so the runtime never keeps reporting\n // healthy while the read stream has stalled. Does not override the more-actionable `auth-needed`, nor a\n // commit-failure degraded. Cleared on the next successful batch below.\n onReadStreamError: (error) => {\n // Never mask the more-actionable auth-needed, nor a sticky commit-failure degraded (its lastError is\n // the more serious signal — a stream blip must not overwrite it).\n if (status.phase === \"auth-needed\") return;\n if (status.phase === \"degraded\" && degradedReason === \"commit\") return;\n // Enter, or refresh, a stream-degraded status. Refreshing keeps `lastError` pointing at the most\n // recent stream fault (and re-emits) rather than freezing on the first one, so a stream that fails one\n // way then another reports the current cause (observability).\n status.phase = \"degraded\";\n degradedReason = \"stream\";\n status.lastError = error.message;\n options.onStatusChange?.(status);\n },\n // Clear a recoverable status (auth-needed, or a read-stream degraded) the moment a batch is delivered\n // again. A commit-failure degraded is NOT cleared here — a fetch can succeed while applies keep failing,\n // so only `onSyncError` clearing (a clean commit) would lift it.\n onSyncActivity: () => {\n if (status.phase === \"auth-needed\" || (status.phase === \"degraded\" && degradedReason === \"stream\")) {\n degradedReason = null;\n status.phase = initialSyncCompleted ? \"ready\" : \"syncing\";\n options.onStatusChange?.(status);\n }\n },\n // ADR-0013 Phase 3: surface a persistent read-path auth failure as a distinct `auth-needed` status (the\n // app prompts re-login) while the stream keeps retrying for a fresh token. Only wired when a token\n // provider exists — without one there is no auth lifecycle to track.\n ...(options.getAuthToken\n ? {\n onAuthError: () => {\n if (status.phase !== \"auth-needed\") {\n status.phase = \"auth-needed\";\n options.onStatusChange?.(status);\n }\n },\n }\n : {}),\n });\n\n // Overlap: kick the shape streams off BEFORE schema exec (they buffer catch-up into the memory inbox,\n // commits gated on `dbReady`). A fresh store has no persisted lazy activations and no subscriptions to\n // reset, so both DB reads the sequential path makes first are skipped here.\n let earlySync: ReturnType<typeof startConfiguredSync> | null = null;\n let earlySyncStartedAt = 0;\n if (overlapPrefetch) {\n status.isRunning = true;\n status.phase = \"syncing\";\n options.onStatusChange?.(status);\n earlySyncStartedAt = performance.now();\n earlySync = startConfiguredSync(\n pglite as unknown as Parameters<typeof startConfiguredSync>[0],\n buildStartOptions(new Set()),\n );\n }\n\n if (!options.pgliteInstance) {\n if (options.prepareLocalDbBeforeSchema) {\n const prepareBeforeSchema = options.prepareLocalDbBeforeSchema;\n await bootReportBuilder.phase(\"prepare\", \"boot prepare(before-schema)\", () => prepareBeforeSchema(pglite));\n }\n\n const schemaSql = generateLocalSchemaSql(options.registry);\n await bootReportBuilder.phase(\"schemaExec\", \"boot local schema\", () => pglite.exec(schemaSql));\n\n if (options.prepareLocalDb) {\n const prepareLocalDb = options.prepareLocalDb;\n await bootReportBuilder.phase(\"prepare\", \"boot prepare(local-db)\", () => prepareLocalDb(pglite));\n }\n }\n\n // The write path's headers are the shared base plus the write-only overrides (region/DB-affinity):\n // `{...requestHeaders, ...writeRequestHeaders}`. The read/shape path keeps `requestHeaders` alone\n // (below), so `writeRequestHeaders` never reach reads — the two ingress points pin independently.\n const writePathHeaders =\n options.requestHeaders || options.writeRequestHeaders\n ? { ...(options.requestHeaders ?? {}), ...(options.writeRequestHeaders ?? {}) }\n : undefined;\n\n // ADR-0039: an ordinary optimistic write activates its target's lazy consistency group (a write is a\n // reference, and a reference activates — the read path already does this). The runtime reports the\n // non-blind table keys per enqueue; this indirection is assigned once `ensureSynced`/`lazyGuardIndex`\n // exist below (a write never fires during boot, so it is a harmless no-op until then).\n let activateOrdinaryWriteTables: ((tables: readonly string[]) => void) | null = null;\n const mutationRuntime = createMutationRuntime({\n db: pglite,\n registry: options.registry,\n writeUrl: options.writeUrl,\n onOrdinaryEnqueue: (tables) => activateOrdinaryWriteTables?.(tables),\n ...(options.getAuthToken ? { getAuthToken: options.getAuthToken } : {}),\n ...(writePathHeaders ? { requestHeaders: writePathHeaders } : {}),\n ...(options.maxMutationAttempts != null ? { maxMutationAttempts: options.maxMutationAttempts } : {}),\n ...(options.onQuarantine ? { onQuarantine: options.onQuarantine } : {}),\n ...(options.onConflict ? { onConflict: options.onConflict } : {}),\n ...(options.onReject ? { onReject: options.onReject } : {}),\n });\n\n // Reclaim any in-flight mutations interrupted by a previous shutdown (ADR-0005), then\n // reconcile the local store against the current registry fingerprint before sync starts\n // (ADR-0006). Skipped when the caller supplies their own pglite (they own its schema).\n await bootReportBuilder.phase(\"journalRecovery\", \"boot journal recovery\", () => mutationRuntime.recoverSending());\n\n // Restore-boot quarantine (ADR-0035 decision 6): the moment a store is booted FROM a backup, every\n // non-terminal recovered journal row (`pending`/`sending`/`failed`) is parked in `quarantined` so nothing\n // recovered auto-flushes — the write path has no `mutationId` dedupe ledger, making replay unsafe on\n // last-write-wins tables (silent stale reverts) and colliding on a recreated PK. Runs ONLY on the restore\n // boot (loadDataDir happens exactly once); a subsequent normal boot of the persisted store never re-runs\n // it. Placed AFTER `recoverSending` (which lifts any `sending` back to `pending`) so a single pass over\n // pending/sending/failed catches the lot. The app then inspects `diagnostics()` and releases/discards them.\n if (restoreBoot) {\n await mutationRuntime.quarantineRecovered();\n }\n\n let versionEvent: LocalStoreVersionEvent | null = null;\n\n // Registry-fingerprint mismatch on restore (ADR-0035 decision 6): an old backup restored against a NEWER\n // registry needs NO special handling — the existing local-schema-evolution path (ADR-0006) owns it, and\n // restore composes with it for free. On this restore boot the quarantine above ran FIRST, so every\n // recovered row now counts toward `owedMutations` (pending+sending+failed+quarantined) inside\n // `rebuildReadCacheOrDefer`: a stale fingerprint therefore DEFERS the read-cache rebuild rather than\n // dropping the quarantined writes, exactly as it would for any store that owes work. The rebuild completes\n // on a later boot once the app has released/discarded the quarantine and drained the journal.\n if (!options.pgliteInstance) {\n versionEvent = await bootReportBuilder.phase(\"storeVersionReconcile\", \"boot store-version reconcile\", () =>\n reconcileLocalStoreVersion({\n db: pglite,\n registry: options.registry,\n runtime: mutationRuntime,\n ...(options.onSchemaChange ? { onSchemaChange: options.onSchemaChange } : {}),\n }),\n );\n }\n\n const drizzleDb = createDrizzleDatabase(pglite, buildSchema(options.registry));\n // Static index of the registry's lazy relations (ADR-0021), driving the read-path safety net.\n const lazyGuardIndex = buildLazyGuardIndex(options.registry);\n\n let sync: Awaited<ReturnType<typeof startConfiguredSync>> | null = null;\n let convergenceDriver: ConvergenceDriver | null = null;\n\n status.isRunning = true;\n\n // Open the overlap commit gate now the local store is ready (schema exec + journal recovery + reconcile\n // done): the catch-up the streams prefetched during those phases now drains in one commit train. A no-op\n // on the sequential path (`openDbGate` is the empty default there).\n openDbGate();\n\n if (syncEnabled) {\n if (earlySync) {\n // Overlap path: the shape streams have been prefetching since before schema exec; adopt the handle\n // (it resolves as soon as the streams are subscribed — catch-up drains via the gate just lifted, and\n // `onInitialSync` still gates `ready` on a fully-consistent first paint). The construction was kicked\n // off before schema exec, so time it here (concurrent-segment wall) into `phases.syncStartMs`.\n sync = await earlySync;\n bootReportBuilder.setSyncStartMs(performance.now() - earlySyncStartedAt);\n bootReportBuilder.markSyncStartDone();\n } else {\n // Sequential path (warm store / no fresh hint): the exact pre-S4 ordering — reset any rebuilt\n // subscriptions, promote durable lazy groups, then start (catch-up strictly after the local phases).\n // After a read-cache rebuild the Electric subscription bookkeeping is stale (it would believe the\n // dropped shapes are still caught up and never backfill), so reset every shape subscription to force a\n // fresh re-stream (ADR-0006).\n const resetKeys =\n versionEvent?.status === \"rebuilt\"\n ? [...(options.resetSubscriptionKeys ?? []), ...allGroupSubscriptionKeys(options.registry)]\n : options.resetSubscriptionKeys;\n await resetSubscriptionsIfRequested(pglite, resetKeys);\n\n status.phase = \"syncing\";\n options.onStatusChange?.(status);\n\n // Promote any `lazy + persistent` group activated on a previous boot back into the eager set\n // (ADR-0021 §2); the sync engine does no DB read of its own.\n const promotedGroups = await readActivatedLazyGroups(pglite, options.registry);\n\n sync = await bootReportBuilder.phase(\"syncStart\", \"boot sync start\", () =>\n startConfiguredSync(\n pglite as unknown as Parameters<typeof startConfiguredSync>[0],\n buildStartOptions(promotedGroups),\n ),\n );\n bootReportBuilder.markSyncStartDone();\n }\n } else {\n status.phase = \"ready\";\n options.onStatusChange?.(status);\n // Sync disabled: there is no `onInitialSync` gate, but boot IS complete — finalize the report at the\n // same moment `ready` resolves (ADR-0034). Idempotent with the sync path's finalize.\n finalizeBootReport();\n resolveReady();\n }\n\n // Restore boots offline (ADR-0035 decision 6): never stand up the convergence driver on a restore boot,\n // so an `autoSync` trigger the caller passed (even an online one) drives NO flush/reconcile passes — the\n // recovered journal is quarantined and must stay put until the app releases it and a normal boot goes\n // online. On every other boot the driver behaves exactly as before.\n if (options.autoSync && !restoreBoot) {\n convergenceDriver = createConvergenceDriver({\n client: {\n flush: () => mutationRuntime.flush(),\n reconcile: () => mutationRuntime.reconcile(),\n },\n trigger: options.autoSync,\n ...(options.onConvergencePass ? { onPass: options.onConvergencePass } : {}),\n });\n\n // Start driving convergence once the initial sync is ready, so a pass never races the\n // first shape load. stop()/destroy() halt it.\n void ready.then(() => convergenceDriver?.start());\n }\n\n // Event-driven convergence: the moment a mutation is enqueued, ask the driver to run a pass so the\n // write flushes immediately rather than waiting for the trigger's next interval tick. This is what\n // lets the interval be a rare fallback (and so run far less often). No-op when `autoSync` is off — the\n // caller drives `flush`/`reconcile` itself.\n const requestConvergence = () => convergenceDriver?.requestPass();\n const mutate: SyncClient<TRegistry>[\"mutate\"] = {\n create: async (table, input) => {\n await mutationRuntime.create(table, input);\n requestConvergence();\n },\n update: async (table, entityKey, patch) => {\n await mutationRuntime.update(table, entityKey, patch);\n requestConvergence();\n },\n delete: async (table, entityKey) => {\n await mutationRuntime.delete(table, entityKey);\n requestConvergence();\n },\n batch: async (items) => {\n await mutationRuntime.batch(items);\n requestConvergence();\n },\n };\n\n // ─── Anonymous-activation diagnostic (ADR-0039) ────────────────────────────────────────────────\n // Per group key, whether ANY member's row filter denies (or cannot serve) an unauthenticated caller,\n // plus its member registry keys (for the warning). The registry is static and the group→member map is\n // fixed once sync is running, so it is computed once and cached.\n type GroupClaimsInfo = { claimsDependent: boolean; memberKeys: string[] };\n let groupClaimsInfoCache: Map<string, GroupClaimsInfo> | null = null;\n const groupClaimsInfoFor = (activeSync: NonNullable<typeof sync>): Map<string, GroupClaimsInfo> => {\n if (groupClaimsInfoCache != null) return groupClaimsInfoCache;\n const map = new Map<string, GroupClaimsInfo>();\n for (const key of Object.keys(options.registry) as SyncTableName<TRegistry>[]) {\n const groupKey = activeSync.groupKeyForTable(key as string);\n if (groupKey == null) continue;\n const entry = options.registry[key] as SyncTableEntry;\n const info = map.get(groupKey) ?? { claimsDependent: false, memberKeys: [] };\n info.memberKeys.push(key as string);\n if (isClaimsDependentRowFilter(entry.shape?.rowFilter)) info.claimsDependent = true;\n map.set(groupKey, info);\n }\n groupClaimsInfoCache = map;\n return map;\n };\n // One warning per group key, ever (a claims-denied group activated with no token opens an empty\n // subscription by construction, so repeated activations must not spam).\n const anonymousActivationWarned = new Set<string>();\n const warnIfAnonymousClaimsDependentActivation = (activeSync: NonNullable<typeof sync>, groupKey: string) => {\n if (anonymousActivationWarned.has(groupKey)) return;\n const info = groupClaimsInfoFor(activeSync).get(groupKey);\n if (info == null || !info.claimsDependent) return;\n // Fire-and-forget: activation never blocks or fails on the token probe (a rejected `getAuthToken`\n // is swallowed into a syncDebug line). The dedupe Set is checked+set synchronously around the warn,\n // so concurrent activations still emit at most one console.warn.\n void (async () => {\n try {\n const token = options.getAuthToken ? await options.getAuthToken() : undefined;\n if (token != null && token !== \"\") return;\n if (anonymousActivationWarned.has(groupKey)) return;\n anonymousActivationWarned.add(groupKey);\n console.warn(\n `pgxsinkit: activating the lazy group [${info.memberKeys.join(\", \")}] with no auth token — its ` +\n `row filter denies unauthenticated callers, so this opens an empty subscription. Gate the first ` +\n `query on auth (e.g. the React hooks' \\`ready\\` option) so the group activates with real claims.`,\n );\n syncDebug(\"anonymous activation of a claims-dependent lazy group\", {\n groupKey,\n tables: info.memberKeys,\n });\n } catch (error) {\n syncDebug(\"anonymous-activation auth probe failed\", { groupKey, error });\n }\n })();\n };\n\n // ─── Lazy-relation activation + the declared-safe query facade (ADR-0021) ──────────────────────\n const ensureSynced: SyncClient<TRegistry>[\"ensureSynced\"] = async (keys) => {\n const activeSync = sync;\n if (activeSync == null || keys.length === 0) return;\n const groupKeys = new Set<string>();\n for (const key of keys) {\n const groupKey = activeSync.groupKeyForTable(key);\n if (groupKey == null) continue;\n // Diagnostic at the activation choke point (ADR-0039): only for a group not yet started — an\n // already-active group has already paid (or dodged) this check. Write-triggered activation flows\n // through here too, so the warning fires for writes as well as reads.\n if (!activeSync.isTableStarted(key)) {\n warnIfAnonymousClaimsDependentActivation(activeSync, groupKey);\n }\n groupKeys.add(groupKey);\n }\n await Promise.all([...groupKeys].map((groupKey) => activeSync.ensureGroupStarted(groupKey)));\n };\n\n // ADR-0039: now `ensureSynced` + `lazyGuardIndex` exist, wire the ordinary-write activation. Filter the\n // reported tables to the lazy ones, then fire-and-forget `ensureSynced` — enqueue never blocks on the\n // network, and a failed start self-heals on the group's next activation (a `.catch` keeps the rejection\n // off the unhandled-rejection path).\n activateOrdinaryWriteTables = (tables) => {\n const lazyTables = tables.filter((table) => lazyGuardIndex.lazyKeys.has(table)) as SyncTableName<TRegistry>[];\n if (lazyTables.length === 0) return;\n void ensureSynced(lazyTables).catch((error) => {\n syncDebug(\"write-triggered lazy activation failed\", { tables: lazyTables, error });\n });\n };\n\n // Per-table catch-up completion (ADR-0032 decision 6) — the body of `client.groupReady`, hoisted so the\n // live-rows seam can also await it when building a subscription's `hydrated` promise.\n const groupReadyForTable = async (table: SyncTableName<TRegistry>): Promise<void> => {\n const activeSync = sync;\n // Sync disabled → local-only: every relation is trivially \"ready\" (nothing to await).\n if (activeSync == null) return;\n const groupKey = activeSync.groupKeyForTable(table as string);\n if (groupKey == null) return;\n await activeSync.groupReady(groupKey);\n };\n\n // Synchronous peek at a table's consistency-group catch-up (ADR-0032 decision 6) — the counterpart of\n // `groupReadyForTable`, hoisted so the live-rows seam can compute the STEADY-STATE fast path: when every\n // referenced group is already ready at subscribe time, no `hydrated` promise is built (no extra refresh).\n const isGroupReadyForTable = (table: string): boolean => {\n const activeSync = sync;\n // Sync disabled → local-only: reads hit whatever is local, so a group is trivially \"ready\".\n if (activeSync == null) return true;\n const groupKey = activeSync.groupKeyForTable(table);\n // No consistency group (unknown/writeonly) → nothing to await; treat as ready.\n if (groupKey == null) return true;\n return activeSync.isGroupReady(groupKey);\n };\n\n // The referenced synced tables whose consistency group is NOT YET caught up (ADR-0021/0032): scan the\n // compiled SQL for every synced relation the query reads (∪ the explicit `use`), then keep only those\n // whose group is still catching up. Empty when sync is disabled OR every referenced group is already\n // ready — the steady-state fast path, where the live-rows seam builds no `hydrated` promise. Eager and\n // lazy groups are treated identically here; only ACTIVATION (elsewhere) stays lazy-only.\n const hydratingTablesFor = (query: { sql: string; use?: readonly string[] }): string[] => {\n if (sync == null) return [];\n const referenced = new Set<string>(query.use ?? []);\n for (const key of findReferencedSyncedKeysInSql(query.sql, lazyGuardIndex)) referenced.add(key);\n return [...referenced].filter((table) => !isGroupReadyForTable(table));\n };\n\n const isSynced: SyncClient<TRegistry>[\"isSynced\"] = (key) => {\n const activeSync = sync;\n // Sync disabled → local-only: reads hit whatever is in the local store, so nothing is \"dormant\".\n if (activeSync == null) return true;\n return activeSync.isTableStarted(key);\n };\n\n // ADR-0021 §2/§4: the tables of `entry`'s consistency GROUP — a group is one subscription / one\n // transaction frontier, so reverting one member to dormant reverts them all (a table with no\n // `consistencyGroup` is its own singleton group).\n const groupTableKeysFor = (key: SyncTableName<TRegistry>, entry: SyncTableEntry): SyncTableName<TRegistry>[] => {\n const targetGroup = entry.consistencyGroup;\n return (\n targetGroup == null\n ? [key]\n : (Object.keys(options.registry) as SyncTableName<TRegistry>[]).filter(\n (candidate) => options.registry[candidate]!.consistencyGroup === targetGroup,\n )\n ) as SyncTableName<TRegistry>[];\n };\n\n // The shared group-teardown body of {@link desync} and {@link discardEphemeral} (ADR-0021 §2/§4). Both\n // revert a lazy relation's whole consistency group to dormant: refuse if any writable member owes\n // unsettled writes, stop the group stream, clear the persisted lazy activation, delete the persisted\n // Electric subscription (so re-activation re-streams from scratch), then clean-truncate every member's\n // local cluster. `label` names the calling primitive in the owed-writes refusal so each keeps its own\n // diagnostic (desync stays byte-identical). Callers apply their own lazy/retention gates BEFORE this.\n const tearDownLazyGroup = async (key: SyncTableName<TRegistry>, entry: SyncTableEntry, label: string) => {\n const groupTableKeys = groupTableKeysFor(key, entry);\n\n // Refuse if ANY writable member owes the server unsent/unsettled writes: the truncate clears the\n // journal, so dropping un-acked local intent would be silent data loss. Flush (or discard) those first.\n let owed = 0;\n for (const member of groupTableKeys) {\n if (options.registry[member]!.mode === \"readonly\") continue;\n const stats = await mutationRuntime.readMutationStats(member);\n owed +=\n stats.pendingCount + stats.sendingCount + stats.failedCount + stats.quarantinedCount + stats.conflictedCount;\n }\n if (owed > 0) {\n throw new Error(\n `${label}('${String(key)}') refused: ${owed} unsettled mutation(s) in the group's local journal. Flush or discard them first.`,\n );\n }\n\n const activeSync = sync;\n // The group key IS the Electric subscription key (`consistencyGroup ?? shapeKey`); fall back to the\n // registry derivation when sync is disabled.\n const groupKey = activeSync?.groupKeyForTable(key) ?? entry.consistencyGroup ?? entry.shape?.shapeKey;\n // Stop the stream BEFORE truncating so a live shape can't re-populate the rows we just cleared, and\n // revert the durable promotion (a no-op for ephemeral, which never persisted a flag) so the next boot\n // holds the relation dormant again.\n if (activeSync != null && groupKey != null) activeSync.stopGroup(groupKey);\n if (groupKey != null) await clearLazyGroupActivation(pglite, options.registry, groupKey);\n // CRITICAL: delete the group's persisted Electric subscription so a later re-activation re-streams the\n // shape from scratch. Without this it would resume from the old cursor and never re-send the rows we\n // truncate below — leaving the relation permanently missing its pre-desync data.\n if (groupKey != null) await resetSubscriptionsIfRequested(pglite, [groupKey]);\n // Clean-truncate every member's local cluster.\n for (const member of groupTableKeys) {\n await pglite.exec(buildDesyncTableSql(options.registry, member as string));\n }\n };\n\n const desync: SyncClient<TRegistry>[\"desync\"] = async (key) => {\n const entry = options.registry[key];\n if (entry == null) throw new Error(`desync: unknown table ${String(key)}`);\n if (entry.subscription !== \"lazy\") {\n throw new Error(\n `desync('${String(key)}') refused: only a lazy relation can be desynced — an eager relation is always-on and would immediately re-sync.`,\n );\n }\n await tearDownLazyGroup(key, entry, \"desync\");\n };\n\n const discardEphemeral: SyncClient<TRegistry>[\"discardEphemeral\"] = (key) =>\n // Run inside the SAME lifecycle slot the exports use (ADR-0035 decision 4): discardEphemeral\n // clean-truncates an ephemeral group's local cache, so an export must never interleave it (nor it an\n // export) — the slot's typed LifecycleBusyError fires in both directions. The existing lazy/ephemeral\n // gates below stay EXACTLY as they were, now inside the slot run. (`desync` is deliberately NOT slotted:\n // only the ADR-0035-named destructive ops — destroy/discardEphemeral/dropReadCache — serialise here.)\n lifecycleSlot.run(\"discardEphemeral\", async () => {\n const entry = options.registry[key];\n if (entry == null) throw new Error(`discardEphemeral: unknown table ${String(key)}`);\n // Keep the lazy gate desync has: eager+ephemeral is NOT forbidden by the type system (retention and\n // subscription are independent scalars on the entry — see contracts config.ts / registry.ts), and an\n // eager relation would immediately re-stream, so the same refusal applies here.\n if (entry.subscription !== \"lazy\") {\n throw new Error(\n `discardEphemeral('${String(key)}') refused: only a lazy relation can be discarded — an eager relation is always-on and would immediately re-sync.`,\n );\n }\n // STRICTER gate than desync: every member of the consistency group must be ephemeral. Retention is read\n // as `entry.retention ?? \"persistent\"` (absent → persistent, matching validateRegistryLifecycleGroups and\n // the schema generator); a read PROJECTION surfaces its declared retention on the same `retention` field\n // (withRetention/asEphemeral/defineReadProjection all set it), so this one read covers tables and\n // projections alike. Refuse (naming the offender) if any member is persistent — discardEphemeral is the\n // multi-tab-safe primitive for per-delivery-session windows, and truncating a persistent member's cache\n // would drop durable local data; use desync for a persistent lazy relation.\n for (const member of groupTableKeysFor(key, entry)) {\n if ((options.registry[member]!.retention ?? \"persistent\") !== \"ephemeral\") {\n throw new Error(\n `discardEphemeral('${String(key)}') refused: group member '${String(member)}' is persistent — ` +\n `discardEphemeral only drops an ephemeral relation's local rows. Use desync for a persistent lazy relation.`,\n );\n }\n }\n await tearDownLazyGroup(key, entry, \"discardEphemeral\");\n });\n\n const transaction: SyncClient<TRegistry>[\"transaction\"] = async ({ mode }, run) => {\n // The block's table handles only COLLECT mutations; the whole set is enqueued atomically as one unit.\n const collected: MutationBatchItem<TRegistry>[] = [];\n const txTables = Object.fromEntries(\n Object.keys(options.registry).map((tableKey) => [\n tableKey,\n {\n create: (input: unknown) => {\n collected.push({ table: tableKey, kind: \"create\", input } as MutationBatchItem<TRegistry>);\n },\n update: (entityKey: Record<string, string>, patch: unknown) => {\n collected.push({ table: tableKey, kind: \"update\", entityKey, patch } as MutationBatchItem<TRegistry>);\n },\n updateBlind: (entityKey: Record<string, string>, patch: unknown) => {\n collected.push({\n table: tableKey,\n kind: \"update\",\n entityKey,\n patch,\n blind: true,\n } as MutationBatchItem<TRegistry>);\n },\n delete: (entityKey: Record<string, string>) => {\n collected.push({ table: tableKey, kind: \"delete\", entityKey } as MutationBatchItem<TRegistry>);\n },\n },\n ]),\n ) as SyncTransaction<TRegistry>[\"tables\"];\n\n await run({ tables: txTables });\n\n if (collected.length === 0) {\n return { acks: [] };\n }\n\n const unit: WriteUnit = { id: globalThis.crypto.randomUUID(), mode };\n await mutationRuntime.batch(collected, unit);\n\n if (mode === \"optimistic\") {\n // An atomic batch enqueue; the background convergence loop flushes it (no foreground answer).\n void mutationRuntime.flush();\n return { acks: [] };\n }\n\n // Pessimistic: flush-route this unit to the authoritative endpoint and await the per-mutation result.\n return await mutationRuntime.flushUnit(unit.id);\n };\n\n const prepareQuery: SyncClient<TRegistry>[\"prepareQuery\"] = async ({ sql, use }) => {\n // Scan the compiled SQL for the lazy relations it reads (∪ the explicit `use`) and activate them.\n // The compiled SQL is ground truth and Drizzle quotes every relation, so any reference — FROM, JOIN,\n // subquery, WHERE — is caught; over-matching is bounded and harmless (one spurious persistent\n // subscription at worst, never a wrong result). Detection and activation are one step (ADR-0021).\n const toActivate = new Set<string>(use ?? []);\n for (const key of findReferencedLazyKeysInSql(sql, lazyGuardIndex)) toActivate.add(key);\n const lazyTables = [...toActivate] as SyncTableName<TRegistry>[];\n await ensureSynced(lazyTables);\n // Backstop: if a referenced lazy relation is somehow still not active (a failed start, or no group),\n // throw rather than let the query read empty/stale. In the normal path everything scanned was just\n // activated, so this passes.\n assertLazyRefsActivated({\n sql,\n index: lazyGuardIndex,\n isActive: (key) => isSynced(key as SyncTableName<TRegistry>),\n });\n // Activated = streams started, NOT caught up. Hand back the keys so consumers (the React hooks'\n // `hydrating`) can await `groupReady` per key without blocking the read on the network.\n return { lazyTables };\n };\n\n const runGuardedQuery = async <TRows extends readonly unknown[]>(\n build: GuardedQueryFn<TRegistry, TRows>,\n use?: readonly SyncTableName<TRegistry>[],\n ): Promise<TRows> => {\n const builder = build(client);\n await prepareQuery({ sql: builder.toSQL().sql, ...(use ? { use } : {}) });\n return builder;\n };\n\n // The live-query manager (ADR-0040) — the SAME module the worker uses (decision 6), so the in-process\n // client gets one lifecycle contract: dedup of identical concurrent subscriptions within this client,\n // bounded zero-subscriber keep-alive (`options.liveQueries`), and awaited teardown (decision 1 — `dispose()`\n // settles every un-awaited unsubscribe before `pglite.close()`, subsuming the old pending-teardowns set).\n // It cannot dedup across tabs (that is the worker's job) but keeps the contract identical across both forms.\n const liveManager: LiveQueryManager = createLiveQueryManager({\n live: pglite.live,\n ...(options.liveQueries ? { policy: options.liveQueries } : {}),\n });\n\n const client: SyncClient<TRegistry> = {\n drizzle: drizzleDb,\n pglite,\n views: buildViews(options.registry),\n tables: Object.fromEntries(\n Object.keys(options.registry).map((tableKey) => [\n tableKey,\n {\n key: tableKey,\n mode: options.registry[tableKey as SyncTableName<TRegistry>]!.mode,\n create: (input: SyncTableCreateInput<TRegistry, typeof tableKey>) =>\n mutate.create(tableKey as SyncTableName<TRegistry>, input),\n update: (entityKey: Record<string, string>, patch: SyncTableUpdateInput<TRegistry, typeof tableKey>) =>\n mutate.update(tableKey as SyncTableName<TRegistry>, entityKey, patch),\n delete: (entityKey: Record<string, string>) => mutate.delete(tableKey as SyncTableName<TRegistry>, entityKey),\n },\n ]),\n ) as SyncClient<TRegistry>[\"tables\"],\n ready,\n status,\n start: async () => {\n await ready;\n },\n stop: async () => {\n // Await any in-flight convergence pass before closing PGlite, so a pass never queries a\n // closed handle.\n await convergenceDriver?.stop();\n sync?.unsubscribe();\n status.isRunning = false;\n options.onStatusChange?.(status);\n // Tear the engine down (abort every shape stream) immediately before closing the DB — the exact\n // point PGlite's own close used to invoke the former extension's close hook (ADR-0032 S1). Order\n // preserved: convergence stop → sync unsubscribe → status → engine close → pglite close.\n await engine.close();\n // Dispose the live-query manager before closing PGlite (ADR-0040 decisions 1 & 6): it cancels any\n // keep-alive timers and awaits every in-flight live `unsubscribe()`, so none races `pglite.close()`.\n await liveManager.dispose();\n await pglite.close();\n },\n destroy: (destroyOptions) =>\n // Run inside the SAME lifecycle slot the exports use (ADR-0035 decision 4), so a destructive wipe can\n // never interleave a running export (nor an export interleave this wipe) — the slot's typed\n // LifecycleBusyError fires in both directions. The refuse-if-owed guard stays EXACTLY as it was, now\n // inside the slot run.\n lifecycleSlot.run(\"destroy\", async () => {\n if (!destroyOptions?.force) {\n const stats = await mutationRuntime.readMutationStats();\n const owed =\n stats.pendingCount +\n stats.sendingCount +\n stats.failedCount +\n stats.quarantinedCount +\n stats.conflictedCount;\n\n if (owed > 0) {\n throw new Error(\n `destroy() refused: ${owed} mutation(s) still owed to the server. Flush them first or call destroy({ force: true }).`,\n );\n }\n }\n\n // Drain any in-flight convergence pass before wiping, so a pass never writes into a store\n // being torn down underneath it.\n await convergenceDriver?.stop();\n sync?.unsubscribe();\n status.isRunning = false;\n options.onStatusChange?.(status);\n await pglite.exec(buildWipeLocalStoreSql(options.registry));\n // Same teardown ordering as `stop`: abort the engine's streams before closing the DB, the moment\n // the former extension close hook fired during `pglite.close()` (ADR-0032 S1).\n await engine.close();\n // Dispose the live-query manager before closing PGlite — same close-vs-unsubscribe hang guard as\n // `stop()` (ADR-0040 decisions 1 & 6).\n await liveManager.dispose();\n await pglite.close();\n }),\n dropReadCache: () =>\n // Under the SAME lifecycle slot as the exports (ADR-0035 decision 4). WHY dropReadCache is slotted and\n // not just destroy/discardEphemeral: it DROPS and rebuilds the synced read-cache tables, so an export\n // racing it would capture a half-rebuilt cache in the artefact (some tables dropped, some re-created,\n // none re-streamed yet). The slot makes the drop+rebuild atomic against any concurrent export.\n lifecycleSlot.run(\"dropReadCache\", async () => {\n await pglite.exec(buildDropReadCacheSql(options.registry));\n await pglite.exec(generateLocalSchemaSql(options.registry));\n // Reset the Electric subscriptions so the rebuilt synced tables re-stream from scratch\n // rather than the bookkeeping believing they are already caught up (ADR-0006).\n await resetSubscriptionsIfRequested(pglite, allGroupSubscriptionKeys(options.registry));\n }),\n flush: (table) => mutationRuntime.flush(table),\n reconcile: (table) => mutationRuntime.reconcile(table),\n retryFailed: (table) => mutationRuntime.retryFailed(table),\n recoverSending: (table) => mutationRuntime.recoverSending(table),\n readMutationDetails: (table) => mutationRuntime.readMutationDetails(table),\n mutate,\n discardConflict: (table, entityKey) => mutationRuntime.discardConflict(table, entityKey),\n discardQuarantined: (table, entityKey) => mutationRuntime.discardQuarantined(table, entityKey),\n diagnostics: async (table) => ({\n mutation: await mutationRuntime.readMutationStats(table),\n }),\n // Inspection surface (see the interface doc): straight through to the underlying store, no journal /\n // overlay involvement. The worker facade runs the identical call inside the worker's own client.\n rawQuery: (sql, params, options) => pglite.query(sql, params as unknown[] | undefined, options),\n rawExec: (sql, options) => pglite.exec(sql, options),\n query: (build) => runGuardedQuery(build),\n queryRow: async (build) => {\n const rows = await runGuardedQuery(build);\n return rows[0] ?? null;\n },\n queryRaw: (spec) => runGuardedQuery(spec.build, spec.use),\n queryRawRow: async (spec) => {\n const rows = await runGuardedQuery(spec.build, spec.use);\n return rows[0] ?? null;\n },\n ensureSynced,\n isSynced,\n desync,\n discardEphemeral,\n prepareQuery,\n transaction,\n groupReady: groupReadyForTable,\n hydratingTablesFor,\n // The live-rows seam, now delegated to the shared `LiveQueryManager` (ADR-0040 decision 6) — identical\n // contract to the pre-adoption inline `pglite.live.query` seam, but with dedup of identical concurrent\n // subscriptions, keep-alive (`keepAliveMs`), and awaited teardown for free. The manager delivers a diff\n // stream (`deliverInitial` + `deliverDiff`); we fold it back into FULL ordered row arrays with a\n // per-subscription `LiveRowsMaterializer` (the SAME piece `attachSyncClient` uses tab-side), so the\n // public `onRows(rows)` / `initialRows` contract is byte-unchanged — and unchanged rows now keep `===`\n // identity across diffs (a bonus the raw `results.rows` path did not give). Keyless (no `pkColumns`)\n // exactly as the inline seam was: PGlite's `live.query` + the manager's value-identity diff.\n subscribeLiveRows: async ({ sql, params, fields, use, keepAliveMs }, onRows) => {\n // Render the query safe to materialise: a JOIN with same-named columns fails `live.query`'s\n // temp-view creation (`column \"title\" specified more than once`) unless every output column has a\n // unique alias. No `fields` → SQL unchanged (backward-compatible name-keyed rows). The wrap stays\n // caller-side (ADR-0040 decision 3): the manager receives POST-WRAP SQL.\n const materialSql = wrapLiveQueryForMaterialization(sql, fields);\n // Keyless materializer (matches the inline seam, which never passed pkColumns): initial rows seed it;\n // each diff folds into a fresh ordered array whose unchanged rows keep their object identity.\n const materializer = new LiveRowsMaterializer<Record<string, unknown>>(undefined);\n const subscription = await liveManager.subscribe(\n { materialSql, params: params as unknown[] },\n {\n // The initial snapshot is returned via `initialRows`, NOT `onRows` (which fires on CHANGES only) —\n // so `deliverInitial` just seeds the materializer; `initialRows` is read from it below.\n deliverInitial: (rows) => {\n materializer.seed(rows);\n },\n deliverDiff: (diff) => {\n onRows(materializer.apply(diff) as never);\n },\n },\n keepAliveMs != null ? { keepAliveMs } : undefined,\n );\n // Seeded synchronously by `deliverInitial` during `subscribe` above.\n const initialRows = materializer.current();\n let unsubscribed = false;\n // The query's lazy relations (guard scan ∪ `use`; the caller's `prepareQuery` already activated them)\n // are surfaced as `lazyTables` for observability — the relations held out of the eager boot set.\n const lazySet = new Set<string>(use ?? []);\n for (const key of findReferencedLazyKeysInSql(sql, lazyGuardIndex)) lazySet.add(key);\n const lazyTables = [...lazySet];\n // Hydration spans EVERY referenced consistency group (eager AND lazy): the tables whose group is not\n // yet caught up at subscribe time. Empty (steady state / sync disabled) → NO `hydrated` promise, so a\n // post-boot subscription pays no extra refresh (exactly today's eager-only behaviour). Otherwise build\n // `hydrated` with rows-before-signal ordering: await the pending groups' catch-up, refresh the live\n // query (the manager's coalesced refresh; its listener delivers the caught-up rows as a diff → onRows,\n // synchronously inside the refresh), THEN resolve — so a UI flipping out of its loading state on this\n // promise can never flash a false empty.\n const hydratingTables = hydratingTablesFor({ sql, ...(use ? { use } : {}) });\n const hydrated =\n hydratingTables.length > 0\n ? Promise.all(hydratingTables.map((table) => groupReadyForTable(table as SyncTableName<TRegistry>)))\n .then(async () => {\n if (!unsubscribed) await subscription.refresh();\n })\n .catch(() => undefined)\n : undefined;\n return {\n initialRows: initialRows as never,\n unsubscribe: () => {\n unsubscribed = true;\n // Non-blocking for the caller; the manager retains the teardown promise so `dispose()` (called by\n // `stop()`/`destroy()`) awaits it before closing PGlite (ADR-0040 decision 1 — the close race).\n void subscription.unsubscribe();\n },\n ...(lazyTables.length > 0 ? { lazyTables } : {}),\n ...(hydrated ? { hydrated } : {}),\n };\n },\n // Boot observability (ADR-0034): the finalized report (null before initial sync completes / after an\n // early stop). Resolves from the builder-owned ref this client holds — no round trip in-process.\n bootReport: async () => finalizedBootReport,\n // Live-query diagnostics (ADR-0040 decisions 5 & 6): the in-process client now owns a real manager, so\n // this returns its live snapshot (digests + counts/timings only — never SQL/params/rows).\n liveQueryDiagnostics: async () => liveManager.snapshot(),\n exportStore: async (exportOptions) => {\n // Await engine-ready first (ADR-0035: exports wait out a boot rather than rejecting during it), THEN\n // take the lifecycle slot — a concurrent export/lifecycle op is refused with a typed busy error.\n await ready;\n // Name the backup from the configured plain store PATH (ADR-0036), never the PGlite instance's\n // resolved dataDir URL — a resolved URL is internal plumbing and must not leak into an artefact name\n // as something to imitate. The store id is the path's last segment (see `deriveStoreId`).\n return lifecycleSlot.run(\"exportStore\", () =>\n performStoreExport(\n {\n pglite,\n readMutationStats: () => mutationRuntime.readMutationStats(),\n ...(options.storePath != null ? { storePath: options.storePath } : {}),\n },\n exportOptions,\n ),\n );\n },\n exportDiagnostics: async (exportOptions) => {\n // Same lifecycle discipline as `exportStore` (ADR-0035): await engine-ready first (wait out a boot\n // rather than reject during it), THEN take the single slot so a concurrent export/lifecycle op is\n // refused with a typed busy error. The diagnostic dump runs the live datadir dump on `pglite`, then\n // clones it in memory — the live engine every reference here holds is never closed (the addendum's\n // whole reason for the throwaway clone over the abandoned suspend/reopen seam).\n await ready;\n return lifecycleSlot.run(\"exportDiagnostics\", () =>\n performDiagnosticExport(\n {\n pglite,\n readMutationStats: () => mutationRuntime.readMutationStats(),\n ...(options.storePath != null ? { storePath: options.storePath } : {}),\n },\n exportOptions,\n ),\n );\n },\n exportData: async (exportOptions) => {\n // Same lifecycle discipline (ADR-0035): await engine-ready first (wait out a boot rather than reject),\n // THEN take the single slot. The DRAIN runs inside the slot (the caller-side placement decision 3\n // makes): flush needs the running engine and is not lifecycle-exclusive, but the artefact must be\n // taken right after the drain, so export owns the store's lifecycle for the whole drain+dump. The\n // `-t` allowlist + enum header are resolved from the registry through the SAME projection the DDL\n // generator uses — never re-derived by string convention.\n await ready;\n return lifecycleSlot.run(\"exportData\", () =>\n performDataExport(\n {\n pglite,\n readMutationStats: () => mutationRuntime.readMutationStats(),\n flush: () => mutationRuntime.flush(),\n syncedTableNames: collectDataExportSyncedTableNames(options.registry),\n enumHeaderSql: buildDataExportEnumHeaderSql(options.registry),\n cloneCleanupSql: buildDataExportCloneCleanupSql(options.registry),\n ...(options.storePath != null ? { storePath: options.storePath } : {}),\n },\n exportOptions,\n ),\n );\n },\n };\n\n return client;\n}\n\n/**\n * Every persisted subscription key declared by the registry — one per consistency group (ADR-0009\n * decision 2), not per table. Grouped tables share a subscription-state row keyed by their group;\n * ungrouped tables are singleton groups keyed by their own `shapeKey`. Deduped, since several tables\n * collapse onto one group key.\n */\nfunction allGroupSubscriptionKeys<TRegistry extends SyncTableRegistry>(registry: TRegistry): string[] {\n const keys = Object.values(registry)\n .filter((entry) => typeof entry.shape?.shapeKey === \"string\" && entry.shape.shapeKey.length > 0)\n .map((entry) => entry.consistencyGroup ?? entry.shape!.shapeKey);\n return [...new Set(keys)];\n}\n\nasync function resetSubscriptionsIfRequested(pglite: ClientPGlite, keys: string[] | undefined) {\n if (!keys || keys.length === 0) {\n return;\n }\n\n const uniqueKeys = [...new Set(keys.map((key) => key.trim()).filter((key) => key.length > 0))];\n\n if (uniqueKeys.length === 0) {\n return;\n }\n\n await pglite.electric.initMetadataTables();\n await Promise.all(uniqueKeys.map((key) => pglite.electric.deleteSubscription(key)));\n}\n\nfunction createDrizzleDatabase<TRegistry extends SyncTableRegistry>(\n client: ClientPGlite,\n schema: RegistryTables<TRegistry>,\n) {\n const relations = defineRelations(schema) as RegistryRelations<TRegistry>;\n\n const createDatabase = drizzle as unknown as (config: {\n client: ClientPGlite;\n relations: RegistryRelations<TRegistry>;\n }) => PgliteDatabase<RegistryRelations<TRegistry>>;\n\n return createDatabase({ client, relations });\n}\n\nfunction buildSchema<TRegistry extends SyncTableRegistry>(registry: TRegistry) {\n return Object.fromEntries(\n Object.entries(registry).map(([key, entry]) => [key, entry.table]),\n ) as RegistryTables<TRegistry>;\n}\n\nfunction buildViews<TRegistry extends SyncTableRegistry>(registry: TRegistry) {\n return Object.fromEntries(\n Object.entries(registry).flatMap(([key, entry]) => (entry.view != null ? [[key, entry.view]] : [])),\n ) as RegistryViews<TRegistry>;\n}\n\n/**\n * The tab-side READ handles a worker-attached client exposes (ADR-0032 S2): a build-only Drizzle instance\n * plus the registry views. On the attach client, Drizzle is used only to COMPILE queries to SQL\n * (`.toSQL()`) on the tab — execution happens in the worker via the live-rows bridge / RPC — so it is\n * constructed over a stub client that is never invoked (`construct` stores the client without calling it).\n * The same builders `createSyncClient` uses, so a query built on either client compiles identically.\n */\nexport function buildRegistryReadHandles<TRegistry extends SyncTableRegistry>(\n registry: TRegistry,\n): { drizzle: PgliteDatabase<RegistryRelations<TRegistry>>; views: RegistryViews<TRegistry> } {\n const stubClient = {} as ClientPGlite;\n return {\n drizzle: createDrizzleDatabase(stubClient, buildSchema(registry)),\n views: buildViews(registry),\n };\n}\n\nfunction buildSyncConfigFromRegistry<TRegistry extends SyncTableRegistry>(\n registry: TRegistry,\n electricUrl: string,\n): SyncConfigInput {\n return {\n electricUrl,\n localSchema: getSyncRegistrySchema(registry),\n tables: Object.fromEntries(Object.entries(registry).map(([key, entry]) => [key, buildSyncTableInput(entry, key)])),\n };\n}\n\nfunction buildSyncTableInput(entry: SyncTableEntry, tableKey: string) {\n const clientProjection = getClientProjection(entry, tableKey);\n\n return {\n name: tableKey,\n mode: entry.mode,\n primaryKey: entry.primaryKey,\n ...(entry.shape !== undefined ? { shape: entry.shape } : {}),\n clientProjection,\n // The read-path apply ladder (strategy + json casts) is resolved by the engine directly from the\n // registry entry via `resolveApplyTarget` (ADR-0029 D1/D2) — `deriveSyncColumnTypes` /\n // `classifyTableApplyStrategy` on the model, never carried through this config surface.\n // Carry the consistency group (ADR-0009 decision 2) so the sync starter buckets grouped tables\n // onto one MultiShapeStream; absent → singleton group.\n ...(entry.consistencyGroup ? { consistencyGroup: entry.consistencyGroup } : {}),\n // Carry the lifecycle axes (ADR-0021) so the sync starter can hold lazy groups out of the eager\n // boot set and provision ephemeral clusters as TEMP; absent → eager/persistent (today's path).\n ...(entry.subscription ? { subscription: entry.subscription } : {}),\n ...(entry.retention ? { retention: entry.retention } : {}),\n };\n}\n\nfunction getClientProjection(entry: SyncTableEntry, tableKey: string) {\n if (!entry.clientProjection) {\n throw new Error(`clientProjection is required for client table ${tableKey}`);\n }\n\n return entry.clientProjection;\n}\n",
|
|
5
|
+
"import { PGlite, type Results } from \"@electric-sql/pglite\";\nimport { live, type PGliteWithLive } from \"@electric-sql/pglite/live\";\nimport type { PgliteDatabase } from \"drizzle-orm/pglite\";\nimport { drizzle } from \"drizzle-orm/pglite\";\nimport { defineRelations } from \"drizzle-orm/relations\";\n\nimport type {\n MutationAck,\n MutationDiagnostics,\n MutationSummary,\n RegistryRelations,\n RegistryTables,\n RegistryViews,\n SyncConfigInput,\n SyncRuntimeStatus,\n SyncTableCreateInput,\n SyncTableEntry,\n SyncTableName,\n SyncTableRegistry,\n SyncTableUpdateInput,\n WriteMode,\n} from \"@pgxsinkit/contracts\";\nimport { fingerprintRegistry, getSyncRegistrySchema, isClaimsDependentRowFilter } from \"@pgxsinkit/contracts\";\n\nimport { type BootReport, type BootReportBuilder, createBootReportBuilder } from \"./boot-report\";\nimport { type ConvergenceDriver, type ConvergenceTrigger, createConvergenceDriver } from \"./convergence\";\nimport { syncDebug, timeAsync } from \"./debug\";\nimport { type DataExportOptions, type DataExportResult, performDataExport } from \"./export-data\";\nimport { type DiagnosticExportOptions, type DiagnosticExportResult, performDiagnosticExport } from \"./export-dump\";\nimport { performStoreExport, type StoreExportOptions, type StoreExportResult } from \"./export-store\";\nimport {\n assertLazyRefsActivated,\n buildLazyGuardIndex,\n findReferencedLazyKeysInSql,\n findReferencedSyncedKeysInSql,\n} from \"./lazy-guard\";\nimport { createLifecycleSlot } from \"./lifecycle-slot\";\nimport { wrapLiveQueryForMaterialization } from \"./live-rows-sql\";\nimport {\n type LocalStoreVersionEvent,\n clearLazyGroupActivation,\n readActivatedLazyGroups,\n readStoredLocalSchemaFingerprint,\n reconcileLocalStoreVersion,\n writeLazyGroupActivation,\n writeStoredLocalSchemaFingerprint,\n} from \"./local-store\";\nimport {\n createMutationRuntime,\n type MutationBatchItem,\n type MutationDetail,\n type MutationKind,\n type WriteUnit,\n} from \"./mutation\";\nimport { createMutationsApi, type MutationsApi } from \"./mutations-api\";\nimport {\n buildDataExportCloneCleanupSql,\n buildDataExportEnumHeaderSql,\n buildDesyncTableSql,\n buildDropReadCacheSql,\n buildLocalMetaBootstrapSql,\n buildWipeLocalStoreSql,\n collectDataExportSyncedTableNames,\n computeLocalSchemaFingerprint,\n generateDurableLocalSchemaSql,\n generateEphemeralLocalSchemaSql,\n generateLocalSchemaSql,\n} from \"./schema\";\nimport { startConfiguredSync } from \"./shape-sync\";\nimport {\n classifyNonPersistentDataDir,\n NonPersistentStoreError,\n normaliseStorePathInput,\n readTestStoreMarker,\n resolveStoreDataDir,\n RestoreTargetExistsError,\n storeTargetExists,\n type StorePathInput,\n} from \"./store-path\";\nimport { createSyncEngine, type SyncEngine } from \"./sync\";\nimport { buildShapeHeaders } from \"./sync-auth\";\nimport { LiveRowsMaterializer } from \"./worker/live-diff\";\nimport {\n createLiveQueryManager,\n type LiveQueryDiagnostics,\n type LiveQueryManager,\n validateLiveQueryPolicy,\n} from \"./worker/live-query-manager\";\n\nexport { generateLocalSchemaSql };\nexport { wrapLiveQueryForMaterialization } from \"./live-rows-sql\";\nexport type { BootReport } from \"./boot-report\";\nexport {\n type CloneDumpPhases,\n type CloneDumpResult,\n type DiagnosticExportDeps,\n type DiagnosticExportOptions,\n type DiagnosticExportResult,\n performDiagnosticExport,\n runThrowawayCloneDump,\n} from \"./export-dump\";\nexport {\n type DataExportDeps,\n DataExportDrainError,\n type DataExportOptions,\n type DataExportResult,\n DEFAULT_DRAIN_TIMEOUT_MS,\n type DrainJournalOption,\n type DrainJournalOptions,\n performDataExport,\n} from \"./export-data\";\nexport {\n type DataExportReport,\n deriveStoreId,\n type DiagnosticDumpReport,\n type ExportReport,\n type ExportReportCommon,\n performDatadirDump,\n performStoreExport,\n type StoreBackupReport,\n type StoreExportDeps,\n type StoreExportOptions,\n type StoreExportResult,\n} from \"./export-store\";\nexport { createLifecycleSlot, LifecycleBusyError, type LifecycleSlot } from \"./lifecycle-slot\";\nexport {\n InvalidStorePathError,\n NonPersistentStoreError,\n resolveStoreDataDir,\n RestoreTargetExistsError,\n storeIndexedDbDatabaseName,\n storeTargetExists,\n} from \"./store-path\";\nexport {\n type ConvergenceClient,\n type ConvergenceDriver,\n type ConvergenceDriverOptions,\n type ConvergenceTrigger,\n createBrowserConvergenceTrigger,\n createConvergenceDriver,\n createIntervalConvergenceTrigger,\n} from \"./convergence\";\nexport { instrumentShapeFetch, setSyncDebugSink, syncDebug, timeAsync } from \"./debug\";\nexport {\n type AttachedSyncClient,\n attachSyncClient,\n type AttachSyncClientOptions,\n provisionSyncWorker,\n} from \"./worker/attach-sync-client\";\nexport { defineSyncWorker, type DefineSyncWorkerOptions, type SyncWorkerHost } from \"./worker/define-sync-worker\";\nexport {\n computeLiveDiff,\n type LiveDiffState,\n LiveRowsMaterializer,\n rowKey,\n seedLiveDiffState,\n} from \"./worker/live-diff\";\nexport type { LiveQueryDiagnostics };\nexport { createWorkerTokenCache, type WorkerTokenCache } from \"./worker/token-cache\";\nexport {\n type AttachAckPayload,\n type AttachPayload,\n type AuthTokenSnapshot,\n BRIDGE_CHANNEL,\n BRIDGE_PROTOCOL_VERSION,\n type BridgeCodec,\n type BridgeEnvelope,\n type BridgeEvent,\n type BridgeMessageType,\n type BridgePort,\n encodeEnvelope,\n type ExportArtefactWire,\n identityCodec,\n isBridgeEnvelope,\n type LiveDiffPayload,\n type LiveInitialPayload,\n postBridgeMessage,\n type ProvisionAckPayload,\n type ProvisionPayload,\n type RpcOp,\n type RpcPayload,\n type RpcResultPayload,\n type SetOnlinePayload,\n type SubscribePayload,\n type TokenRequestPayload,\n type TokenResponsePayload,\n type WakePayload,\n} from \"./worker/protocol\";\nexport {\n assertLazyRefsActivated,\n buildLazyGuardIndex,\n findReferencedLazyKeysInSql,\n findReferencedSyncedKeysInSql,\n type LazyGuardIndex,\n LazyRelationNotActivatedError,\n} from \"./lazy-guard\";\nexport {\n type AllMutationsView,\n getAllMutationsView,\n getJournalTable,\n getLocalMetaTable,\n getOverlayTable,\n getReadModelView,\n getSyncedLocalTable,\n getSyncStateView,\n type JournalTable,\n type LocalMetaTable,\n type OverlayTable,\n type ReadModelView,\n type SyncStateView,\n} from \"./local-tables\";\nexport {\n createMutationsApi,\n type MutationListOptions,\n type MutationListSubscription,\n type MutationsApi,\n type MutationsApiDeps,\n type MutationSummaryDetail,\n type MutationSummarySubscription,\n} from \"./mutations-api\";\nexport type { LocalStoreVersionEvent };\n\n/**\n * A write-path method was invoked against a client whose `writeReady` stage has not resolved and the caller\n * opted out of awaiting it (ADR-0041). pgxsinkit's own write methods always `await writeReady` internally, so\n * this is NEVER thrown on the stage-1 default path. It is **reserved for the stage-2 opt-out surface** — the\n * ADR's typed pre-`writeReady` rejection for a consumer who chooses not to await — so a pre-`writeReady` write\n * fails loudly rather than silently no-oping. Exported now so that surface is a non-breaking addition later.\n */\nexport class WriteNotReadyError extends Error {\n constructor() {\n super(\n \"pgxsinkit: write attempted before `writeReady` resolved. Await `client.writeReady` (the default write \" +\n \"methods do this for you) before enqueuing, or gate the write on it.\",\n );\n this.name = \"WriteNotReadyError\";\n }\n}\n\n/**\n * The client was stopped/destroyed (or its worker attachment detached) before a boot stage it exposed could\n * resolve (ADR-0041 FIX 2). `stop()`/`destroy()` reject the still-pending `writeReady` and `ready` with this so\n * a parked mutation or an `await client.ready` / `client.start()` fails FAST rather than hanging forever after\n * teardown. `bootSettled` still RESOLVES (it means \"teardown completion\", not \"boot succeeded\").\n */\nexport class ClientDisposedError extends Error {\n constructor() {\n super(\"pgxsinkit: the client was stopped/destroyed before this readiness stage resolved.\");\n this.name = \"ClientDisposedError\";\n }\n}\n\n// The store carries PGlite's own `live` extension (a genuine create-time extension) plus the pgxsinkit\n// sync engine's namespace, attached post-create by `createSyncClient` as the `electric` property (ADR-0032\n// S1) — no longer a create-time extension. The `electric` part is derived from `createSyncEngine`'s real\n// return so the type follows the attached object.\nexport type ClientPGlite = PGliteWithLive & { electric: SyncEngine[\"namespace\"] };\n\n/**\n * The pre-warmed PGlite boot assets (the WASM modules + filesystem bundle), consumed by\n * {@link createClientPGlite} / {@link CreateSyncClientOptions.pgliteBootAssets}. The host fetches +\n * compiles these on an earlier screen and hands the promise in, so `PGlite.create` skips its own lazy\n * asset load — see the field's JSDoc for the accelerator geometry.\n */\nexport interface PgliteBootAssets {\n pgliteWasmModule?: WebAssembly.Module;\n initdbWasmModule?: WebAssembly.Module;\n fsBundle?: Blob;\n}\n\n/** Options for {@link createClientPGlite}. */\nexport interface CreateClientPGliteOptions {\n /**\n * Pre-warmed PGlite boot assets (see {@link CreateSyncClientOptions.pgliteBootAssets}). Awaited and\n * passed into `PGlite.create`; a rejected warm is caught to `undefined` (falls back to PGlite's own\n * asset load), so it never fails the create.\n */\n bootAssets?: Promise<PgliteBootAssets>;\n /**\n * @internal Test-only storage-backend override (ADR-0036). `\"memory\"` resolves the store to a\n * scheme-selected in-memory store — the sanctioned unit-test/ephemeral lane. Never a product\n * configuration: reached only through `@pgxsinkit/client/testing`, never consumer-facing.\n */\n backendOverride?: \"memory\";\n /**\n * A store-backup tarball to seed the new store from (ADR-0035 decision 6, restore) — a `File`/`Blob` as\n * produced by {@link SyncClient.exportStore}. Passed straight to PGlite's `loadDataDir`, so the created\n * store boots ON the backup's datadir. Restore is a CREATION-path feature: the caller (`createSyncClient`)\n * has already proven the target does not yet exist ({@link storeTargetExists}); this option carries no\n * freshness check of its own. A corrupt/foreign tarball surfaces as a PGlite boot failure here.\n */\n restoreFrom?: File | Blob;\n}\n\n/**\n * Create the raw local PGlite store the sync client runs on — the SAME `PGlite.create` call\n * {@link createSyncClient} makes internally (the `electric` + `live` extensions, pre-warmed boot-asset\n * consumption, and the `boot pglite.create` rail stamp), extracted so exactly one implementation exists\n * and a host can create the store EAGERLY on an earlier screen. Hand the returned (still-pending)\n * instance to {@link CreateSyncClientOptions.precreatedPglite}: the client then owns schema exec, prepare\n * hooks, journal recovery and store-version reconcile, exactly as its own `storePath` path does.\n *\n * Takes a plain store path (ADR-0036), never a storage URL — the backend is DERIVED (IndexedDB in a\n * browser/worker, the filesystem on Bun/Node); a scheme-bearing path throws {@link InvalidStorePathError}.\n * Also accepts the testing helper's output (`createClientPGlite(memoryStoreForTests(\"x\"))`) so a test can\n * mint a memory store without naming a backend.\n *\n * The instance is deliberately **schemaless** — the registry-derived local schema is role/registry\n * dependent, so it is applied post-create by `createSyncClient`. The eager create buys only the expensive\n * initdb (+ IDBFS open), which is the dominant cold-boot cost once the WASM is pre-warmed.\n *\n * `bootAssets` is the pre-warmed WASM/fs bundle (see {@link CreateSyncClientOptions.pgliteBootAssets}); a\n * rejected warm is caught to `undefined`, so PGlite falls back to loading its own assets — never a failure.\n */\nexport async function createClientPGlite(\n store: StorePathInput,\n options?: CreateClientPGliteOptions,\n): Promise<ClientPGlite> {\n // Normalise the store argument to a plain path (+ any internal memory override the testing helper carried),\n // then derive the concrete PGlite dataDir URL (ADR-0036) — the single resolution point. A scheme-bearing/\n // empty storePath throws here, so the old dataDir-URL contract fails loudly, never silently re-interpreted.\n const normalised = normaliseStorePathInput(store);\n const dataDir = resolveStoreDataDir(normalised.storePath, options?.backendOverride ?? normalised.backendOverride);\n // Stamp only the storage scheme (e.g. \"idb:\" / \"memory:\"), never the full path — the path can carry an\n // identity-specific store name, and the boot rail stays monotonic-and-scheme only.\n const dataDirScheme = dataDir.slice(0, dataDir.indexOf(\":\") + 1);\n // Resolve any pre-warmed boot assets BEFORE (and outside) the `boot pglite.create` stamp: the\n // fetch+compile was kicked off on an earlier screen, so this await just retrieves the already-settled\n // result and the stamp measures the create itself. A rejected warm is caught to `undefined` so a failed\n // pre-warm silently falls back to PGlite's own asset loading rather than failing the boot.\n const bootAssets = options?.bootAssets ? await options.bootAssets.catch(() => undefined) : undefined;\n return (await timeAsync(\n \"boot pglite.create\",\n () =>\n // Only PGlite's own `live` extension is a create-time extension; the pgxsinkit sync engine is NOT\n // (ADR-0032 S1) — it is a plain module `createSyncClient` attaches post-create as `pg.electric`. So\n // a store minted here is deliberately ENGINE-LESS by construction: a spare/pre-warmed store (e.g.\n // the board's login-screen mint) carries no engine, no shape streams, and no Electric connections\n // until it is claimed and handed to `createSyncClient`. The `as ClientPGlite` cast reflects that the\n // `electric` namespace is provisioned later, exactly as the registry-derived schema is.\n PGlite.create(dataDir, {\n ...(bootAssets ?? {}),\n // Restore (ADR-0035 decision 6): seed the brand-new store from the backup tarball. PGlite's\n // `loadDataDir` unpacks it into the datadir being created, so the store boots ON the backup's bytes —\n // the whole synced cache, Overlay, and Mutation journal that travelled inside it. Absent on a normal\n // create (the store initdbs empty).\n ...(options?.restoreFrom ? { loadDataDir: options.restoreFrom } : {}),\n extensions: {\n live,\n },\n }),\n { dataDir: dataDirScheme },\n // `as unknown as` because the raw store is deliberately engine-less here (only `live` is a create-time\n // extension); `createSyncClient` provisions the `electric` namespace post-create (ADR-0032 S1).\n )) as unknown as ClientPGlite;\n}\n\nexport interface CreateSyncClientOptions<TRegistry extends SyncTableRegistry> {\n registry: TRegistry;\n electricUrl: string;\n writeUrl: string;\n getAuthToken?: () => Promise<string | undefined>;\n /**\n * Static headers added to **every** read-shape and write request, alongside the per-request\n * `Authorization` (which always wins). The toolkit is agnostic about deployment-gateway\n * credentials, so this is the seam for them — e.g. a Supabase Cloud `apikey` header the platform\n * function gateway expects. Sent even when no `getAuthToken` is supplied.\n */\n requestHeaders?: Record<string, string>;\n /**\n * Extra static headers sent on the **write** path only (the mutation-flush POST), merged over\n * {@link requestHeaders} (`{...requestHeaders, ...writeRequestHeaders}`). Read/shape requests never\n * see these. The seam exists because the two ingress points have opposite geometry: the write\n * function is DB-bound, so pinning it to the database's region (e.g. an `x-region` header) keeps its\n * chatty function→DB protocol on a ~1ms loop; the read proxy's upstream is a globally-distributed\n * CDN (Electric Cloud), so pinning reads away from the caller pays intercontinental round trips per\n * catch-up hop. Put region/DB-affinity headers here; keep gateway credentials the reads also need\n * (e.g. `apikey`) in the shared {@link requestHeaders}.\n */\n writeRequestHeaders?: Record<string, string>;\n syncEnabled?: boolean;\n /**\n * The local store's name (ADR-0036) — a PLAIN path/name, never a PGlite storage URL. The storage backend\n * is DERIVED from the environment (IndexedDB in a browser/worker, the filesystem on Bun/Node); a\n * scheme-bearing string (anything containing `://`) is rejected with {@link InvalidStorePathError}\n * at boot. Defaults to a built-in overlay store name when omitted. A memory-backed store is not a product\n * configuration — for the test/ephemeral lane, spread `memoryStoreForTests(...)` from\n * `@pgxsinkit/client/testing` instead of naming one here.\n */\n storePath?: string;\n /**\n * Pre-warmed PGlite boot assets (the WASM modules + filesystem bundle), awaited and passed straight\n * into `PGlite.create`. The intent is to hide PGlite's ~2.5s cold `boot pglite.create` cost —\n * dominated by the WASM fetch+compile — behind user think-time: the host starts fetching/compiling\n * these on an earlier screen (e.g. the login/identity picker) and hands the still-pending promise\n * here, so by the time a store is opened the assets are already resolved and `PGlite.create` skips\n * its own lazy asset load. Ignored when {@link pgliteInstance} is supplied (the caller owns that\n * instance's boot). A rejected/failed warm is caught to `undefined` and never fails the boot — PGlite\n * falls back to loading its own assets, so this is a pure best-effort accelerator.\n */\n pgliteBootAssets?: Promise<PgliteBootAssets>;\n resetSubscriptionKeys?: string[];\n prepareLocalDbBeforeSchema?: (pglite: ClientPGlite) => Promise<void>;\n prepareLocalDb?: (pglite: ClientPGlite) => Promise<void>;\n onStatusChange?: (status: SyncRuntimeStatus) => void;\n onTableInitialSync?: (tableKey: string) => void;\n /**\n * A fully-provisioned PGlite instance the CALLER owns end-to-end. The client runs NONE of its\n * post-create boot steps against it — no schema exec, prepare hooks, or store-version reconcile\n * (journal recovery still runs, as it does on every path). Use it only when the caller has already\n * applied the registry schema itself. Contrast the three PGlite-provenance seams:\n * - {@link storePath} (default) — the client creates the store AND runs every post-create step.\n * - {@link precreatedPglite} — the caller creates the raw store (via {@link createClientPGlite}), but\n * the client still runs every post-create step (schema/prepare/reconcile), exactly as `storePath` does.\n * - `pgliteInstance` — the caller creates AND provisions the store; the client runs none of them.\n *\n * A caller-owned instance is REFUSED with {@link NonPersistentStoreError} if it is provably\n * non-persistent (a `new PGlite()` default, or an in-memory store) — pgxsinkit's durability semantics\n * assume a persisted store (ADR-0036). Acknowledge a deliberate test store by spreading\n * `testStoreAcknowledgment()` from `@pgxsinkit/client/testing`.\n *\n * Mutually exclusive with {@link precreatedPglite} (supplying both throws).\n */\n pgliteInstance?: ClientPGlite;\n /**\n * A raw PGlite instance the caller created EAGERLY (via {@link createClientPGlite}) — typically on an\n * earlier screen, to hide the ~1.9s cold `initdb`/IDBFS open behind user think-time — but for which the\n * client still owns EVERYTHING else: schema exec, prepare hooks, journal recovery, and store-version\n * reconcile all run exactly as on the {@link storePath} path. This is the difference from\n * {@link pgliteInstance} (which skips schema/prepare/reconcile because the caller owns them); see that\n * option's JSDoc for the three-way distinction.\n *\n * The promise form lets the still-pending eager create be handed straight in. Precedence/validation:\n * - Supplying both this and {@link pgliteInstance} throws — they claim different ownership.\n * - {@link storePath} is used ONLY as the fallback store name if this promise REJECTS: a failed eager\n * create is caught, logged on the boot rail, and the normal `storePath` create path runs instead (also\n * consuming {@link pgliteBootAssets} if provided). The pattern is a pure accelerator, never a boot\n * dependency.\n * - A successfully-adopted instance is subject to the same {@link NonPersistentStoreError} refusal as\n * {@link pgliteInstance} (checked after resolution, so the refusal propagates rather than being\n * swallowed by the reject-fallback).\n */\n precreatedPglite?: Promise<ClientPGlite>;\n /**\n * Restore the store from a **store backup** (ADR-0035 decision 6) — a `File`/`Blob` tarball as produced by\n * {@link SyncClient.exportStore}. The client creates its store with the backup handed to PGlite's\n * `loadDataDir`, so it boots ON the backup's datadir (synced cache + Overlay + Mutation journal, all the\n * bytes that travelled inside it). Three restore-only rules apply, none of them optional:\n *\n * - **Fresh target only.** Refused with {@link RestoreTargetExistsError} if a store already exists at the\n * resolved {@link storePath} — restore never overlays a live store (that would corrupt the datadir); the\n * remedy is a deliberate {@link SyncClient.destroy} of the existing store first.\n * - **Always boots offline.** The engine boots with sync OFF regardless of {@link syncEnabled}/{@link autoSync}\n * or anything captured in the backup — no shape streams, no read fetch, no flush, no convergence passes.\n * Restore wins over an explicit online option (a debug-rail warning notes the override). The app inspects\n * {@link SyncClient.diagnostics}, releases/discards the quarantined rows, then a subsequent NORMAL boot of\n * the (now-persisted) store brings sync online — `loadDataDir` happens exactly once, on this restore boot.\n * - **Journal quarantined.** Every non-terminal recovered row (`pending`/`sending`/`failed`) is moved to\n * `quarantined` — nothing recovered from a backup auto-flushes (the write path has no `mutationId` dedupe\n * ledger, so replay is unsafe on last-write-wins tables). Release (`retryFailed`) or discard\n * (`discardQuarantined`) them explicitly.\n *\n * Mutually exclusive with {@link pgliteInstance} AND {@link precreatedPglite} — restore owns the store's\n * creation (`loadDataDir` is a create-time seed), so a caller-supplied instance conflicts (supplying either\n * with `restoreFrom` throws).\n */\n restoreFrom?: File | Blob;\n /**\n * PROVABLY-fresh store hint (ADR-0032 S4 / backlog-0003): the caller guarantees this store is brand-new\n * and schemaless — no prior schema, no synced rows, no persisted subscription state. When set (and sync\n * is enabled, and the client owns schema exec — i.e. not the {@link pgliteInstance} path), the shape\n * catch-up is started BEFORE the local boot phases (schema exec, journal recovery, store-version\n * reconcile) and buffered in memory, with commits gated until those phases finish — so the network\n * catch-up overlaps them instead of running strictly after. On a far-from-database caller this collapses\n * boot from `local-phases + catch-up` toward `max(local-phases, catch-up)`.\n *\n * MUST be set only when freshness is proven, never derived by probing — a claimed schemaless spare (the\n * board's claim path knows: a claimed spare is always fresh; a mapped/returning store never is). A wrong\n * `true` on a warm store would start the streams from offset 0 and skip the subscription-state read,\n * re-snapshotting instead of resuming. Absent/false → the exact sequential path (the default, correct for\n * every warm store).\n */\n freshStore?: boolean;\n /**\n * Hard cap on send attempts before a still-failing mutation is quarantined\n * (ADR-0005 congestion policy). Defaults to the library's built-in cap.\n */\n maxMutationAttempts?: number;\n /**\n * Invoked when mutations are quarantined (permanently rejected by the server, terminal). The library\n * surfaces them here rather than silently dropping or retry-looping (ADR-0006). Surface, then either\n * re-author + resubmit or roll back via {@link SyncClient.discardQuarantined} — which clears the kept\n * overlay + quarantined journal rows so the entity accepts new mutations again.\n */\n onQuarantine?: (quarantined: MutationDetail[]) => void | Promise<void>;\n /**\n * Invoked when mutations are `conflicted` — a stale write the server declined under the\n * `reject-if-stale` Conflict policy (ADR-0015). The optimistic Overlay is kept, so the app shows a\n * resolution/diff UI and resolves each as a new write (`mutate.update`) or `discardConflict`s it.\n */\n onConflict?: (conflicted: MutationDetail[]) => void | Promise<void>;\n /**\n * Invoked when a pessimistic write-unit is `rejected` (ADR-0022) — a business decline from the\n * authoritative endpoint (capacity/quota/uniqueness). The inverse of `onConflict`: the optimistic Overlay\n * was auto-discarded for the whole unit, so the app surfaces the typed reason rather than a resolve UI.\n */\n onReject?: (rejected: MutationDetail[]) => void | Promise<void>;\n /**\n * Invoked on boot when the registry fingerprint differs from the one the local store was\n * provisioned under (ADR-0006). `rebuilt` = the read cache was dropped and rebuilt at the\n * new shape; `deferred` = un-flushed/quarantined writes are still owed, so the rebuild is\n * postponed (and retried on a later boot) rather than dropping owed data.\n */\n onSchemaChange?: (event: LocalStoreVersionEvent) => void | Promise<void>;\n /**\n * Opt-in convergence driver (ADR-0005). Supply a {@link ConvergenceTrigger} (e.g.\n * `createBrowserConvergenceTrigger()`) and the client drives `flush`/`reconcile`/`retryFailed`\n * on the trigger's schedule, started once sync is ready and stopped on `stop()`/`destroy()`.\n * Omit it for fully-manual convergence (the mechanism primitives stay public either way).\n */\n autoSync?: ConvergenceTrigger;\n /** Invoked after each automatic convergence pass with its error, or `null` on success (only when `autoSync` is set). */\n onConvergencePass?: (error: unknown) => void;\n /**\n * Invoked when a read-path sync commit fails after exhausting its retries (ADR-0009 decision 5).\n * The runtime enters the `degraded` phase and holds the read cache at the last applied commit\n * instead of silently diverging from the server; recovery is a later commit or a restart/refetch.\n */\n onSyncError?: (error: Error) => void;\n /**\n * Boot observability (ADR-0034): invoked exactly once, at boot completion, with the finalized\n * {@link BootReport}. The push counterpart of {@link SyncClient.bootReport} (the pull) for consumers that\n * want the numbers without polling — dashboards, CI budget gates. Never fired before initial sync; a\n * `stop()`/`destroy()` before then means it never fires.\n */\n onBootReport?: (report: BootReport) => void;\n /**\n * @internal Boot mode stamped into the {@link BootReport} (ADR-0034). `defineSyncWorker` sets `\"worker\"`;\n * absent → `\"in-process\"`. Not a behavior knob — it only labels the report.\n */\n bootMode?: BootReport[\"mode\"];\n /**\n * @internal Provision timing for a boot that ADOPTS a pre-provisioned store (ADR-0034). When the store was\n * minted ahead of boot (a spare's off-thread initdb), the provisioner stamps its create cost and ready\n * time here; the boot reports them as {@link BootReport.provision} and sets `phases.pgliteCreateMs = null`.\n * A promise because the stamp settles with the spare's `create`. Only honoured on the {@link precreatedPglite}\n * adoption path (ignored on a fallback create). `provisionReadyAt` must share this process's monotonic clock.\n */\n provisionStamp?: Promise<{ initdbMs: number; provisionReadyAt: number }>;\n /**\n * Bounded zero-subscriber keep-alive for the live-query manager (ADR-0040 decision 4) — same block as\n * {@link DefineSyncWorkerOptions.liveQueries}. Takes effect in BOTH client forms: the in-process client\n * now owns its own manager (decision 6), so this policy governs its live-query dedup and retention just as\n * it does the worker's. Defaults: `defaultKeepAliveMs` 0 (tear a query down the instant its last consumer\n * leaves), `maxRetainedQueries` 16, `maxRetainedRows` 50_000.\n */\n liveQueries?: {\n defaultKeepAliveMs?: number;\n maxRetainedQueries?: number;\n maxRetainedRows?: number;\n };\n}\n\nexport interface SyncClientTableHandle<TRegistry extends SyncTableRegistry, TKey extends SyncTableName<TRegistry>> {\n key: TKey;\n mode: TRegistry[TKey][\"mode\"];\n create: (input: SyncTableCreateInput<TRegistry, TKey>) => Promise<void>;\n update: (entityKey: Record<string, string>, patch: SyncTableUpdateInput<TRegistry, TKey>) => Promise<void>;\n delete: (entityKey: Record<string, string>) => Promise<void>;\n}\n\n/**\n * A table handle inside a {@link SyncClient.transaction} block (ADR-0022 §2). It *collects* mutations into\n * the open write-unit rather than enqueuing each immediately; the whole set is enqueued atomically when the\n * block's callback returns. The calls are synchronous (collection only) — no per-call await needed.\n */\nexport interface SyncTransactionTableHandle<\n TRegistry extends SyncTableRegistry,\n TKey extends SyncTableName<TRegistry>,\n> {\n create: (input: SyncTableCreateInput<TRegistry, TKey>) => void;\n update: (entityKey: Record<string, string>, patch: SyncTableUpdateInput<TRegistry, TKey>) => void;\n delete: (entityKey: Record<string, string>) => void;\n /**\n * An **update-by-key with no local base row** (ADR-0022 addendum). Ordinary `update` requires the entity\n * to be present in the actor's local read model (it seeds the optimistic overlay and captures the base\n * server version); `updateBlind` skips that presence check and writes NO overlay — nothing appears in the\n * read model. Use it when the write target is deliberately EXCLUDED from your read shape (a write-only\n * flow, or an anonymity-scoped moderation write whose row streams only to a different projection), so there\n * is no local row to update and nothing to show optimistically.\n *\n * **Pessimistic-only.** The /unit expander is authoritative for the outcome, so a blind write is meaningful\n * only inside a `transaction({ mode: \"pessimistic\" })` block (or over a statically-pessimistic table). An\n * optimistic-routed blind write has nothing to converge and THROWS at enqueue.\n *\n * The acked journal row **retires without a synced echo** (no visible row ever converges for it), so it does\n * not linger — unlike the seed-a-phantom-row workaround this replaces, whose acked row + overlay lingered\n * forever behind the echo barrier. A `conflicted` blind write stays dischargeable via `discardConflict`; a\n * `rejected` one is surfaced via `onReject`, both with no overlay to clean up.\n */\n updateBlind: (entityKey: Record<string, string>, patch: SyncTableUpdateInput<TRegistry, TKey>) => void;\n}\n\n/** The handle passed to a {@link SyncClient.transaction} callback: collecting table handles for the unit. */\nexport interface SyncTransaction<TRegistry extends SyncTableRegistry> {\n tables: { [TKey in SyncTableName<TRegistry>]: SyncTransactionTableHandle<TRegistry, TKey> };\n}\n\n/**\n * The result of a {@link SyncClient.transaction}. A `pessimistic` block carries the authoritative server\n * `acks` (each `acked` / `conflicted` / `rejected`); an `optimistic` block enqueues atomically and flushes\n * in the background, so its `acks` are empty.\n */\nexport interface SyncTransactionResult {\n acks: MutationAck[];\n}\n\n/** Minimal shape of a Drizzle select builder: inspectable via `.toSQL()` and awaitable for its rows. */\nexport interface DrizzleQueryBuilder<TRows extends readonly unknown[]> extends PromiseLike<TRows> {\n toSQL(): { sql: string; params: unknown[] };\n}\n\n/**\n * The builder callback for a guarded read (ADR-0021): it receives the client and returns a Drizzle\n * select builder. Reach relations through `c.views` / `c.drizzle` / a directly-imported synced table.\n */\nexport type GuardedQueryFn<TRegistry extends SyncTableRegistry, TRows extends readonly unknown[]> = (\n client: SyncClient<TRegistry>,\n) => DrizzleQueryBuilder<TRows>;\n\n/**\n * A guarded query whose builder MAY embed a raw `sql` template fragment (ADR-0021). A raw fragment can\n * name a lazy relation as a bare/unquoted identifier the compiled-SQL scan cannot see, so declare those\n * relations in `use` — they are activated and awaited before the query runs. Pure-Drizzle reads need no\n * `use` (the scan detects every relation): pass the builder callback directly to `client.query`.\n */\nexport interface GuardedRawQuerySpec<TRegistry extends SyncTableRegistry, TRows extends readonly unknown[]> {\n use?: readonly SyncTableName<TRegistry>[];\n build: GuardedQueryFn<TRegistry, TRows>;\n}\n\n/**\n * Inputs to the read-path safety seam {@link SyncClient.prepareQuery}. The lazy relations a query reads\n * are detected by scanning the compiled `sql` (union with the optional explicit `use`), then activated.\n * Shared by the live React hooks and the non-live facade.\n */\nexport interface PrepareQueryInput<TRegistry extends SyncTableRegistry> {\n /** The compiled (parameterised) Drizzle SQL the query will run — the scan's ground-truth target. */\n sql: string;\n /** Lazy relations to also activate, beyond those scanned from `sql` — a pre-activation hint, not required. */\n use?: readonly SyncTableName<TRegistry>[];\n}\n\n/**\n * The narrow live-rows seam (ADR-0032 S2 §4) both client modes implement so the `@pgxsinkit/react` hooks\n * work against either. Input for a reactive subscription: the compiled SQL + params (from a Drizzle\n * builder's `.toSQL()` or a raw string) and the result's `pkColumns` (drives worker-side diff keying;\n * omit for a keyless query). The in-process client runs it directly over `pglite.live`; the worker-attached\n * client runs the live query in the worker and streams DIFFs across the bridge.\n */\nexport interface SubscribeLiveRowsInput {\n sql: string;\n params: readonly unknown[];\n /**\n * The unique output aliases to render the query's columns under so it is SAFE TO MATERIALISE, in the\n * compiled SQL's column order (one per output column). Drizzle emits no output aliases, so a JOIN whose\n * tables share a column name compiles to duplicate output names — which PGlite's `live` extension\n * refuses to materialise (`column \"title\" specified more than once`) and which silently collapse\n * same-named columns even in a plain query. When supplied, the seam wraps the query so every output\n * column gets its alias and rows come back KEYED BY THESE ALIASES; the consumer's row-mapper must read\n * by alias (the `@pgxsinkit/react` hooks do). Omit for a raw or non-colliding query — the seam then\n * leaves the SQL untouched and rows stay keyed by the underlying column names (backward-compatible).\n */\n fields?: readonly string[];\n /**\n * The result's PK columns — the diff-keying identity across the bridge (§4). Omit for a keyless query.\n * When {@link fields} is supplied the result columns are the aliases, so a PK column here must be named\n * by its ALIAS (the aliased result column), not the underlying source column.\n */\n pkColumns?: readonly string[];\n /**\n * Lazy relations (ADR-0021) to activate before the query runs — forwarded to the worker so it can\n * `prepareQuery` before registering the live query (the tab's own `prepareQuery` is a no-op against the\n * worker bridge). Ignored by the in-process client, whose `prepareQuery` already ran on the tab.\n */\n use?: readonly string[];\n /**\n * Per-subscription keep-alive hint (ms) for the live-query manager (ADR-0040 decision 4): retain this\n * query's shared registration for the grace period after its last consumer leaves, so a re-mount reuses it\n * verbatim (no re-materialization). Honoured in BOTH modes — the worker manager and the in-process manager\n * (decision 6). Bounded by the `liveQueries` policy budgets. Absent → no hint.\n */\n keepAliveMs?: number;\n}\n\n/** A handle to a live-rows subscription: the initial ordered snapshot plus an idempotent unsubscribe. */\nexport interface LiveRowsSubscription<TRow> {\n initialRows: TRow[];\n unsubscribe: () => void;\n /**\n * The `lazy` relations the query reads (the guard's scan) — the relations held out of the eager boot\n * set. Activation (stream start) completed before the subscription registered. Informational only:\n * {@link hydrated} — not this — reflects catch-up completion, and it now spans eager groups too.\n */\n lazyTables?: readonly string[];\n /**\n * Present when the query reads ANY consistency group (eager OR lazy) that was NOT YET caught up at\n * subscribe time: resolves once every such group has completed its initial catch-up AND this\n * subscription has already delivered rows reflecting it (the seam refreshes the live query after\n * catch-up, then resolves — rows-before-signal is guaranteed, so flipping a UI out of its loading state\n * on this promise can never flash a false \"empty\"). Absent when every referenced group is already ready\n * at subscribe time (the steady-state fast path — no extra refresh) or sync is disabled. Offline note:\n * stays pending until the catch-up truly completes — gate empty-state COPY on it, not data access (rows\n * flow regardless).\n */\n hydrated?: Promise<void>;\n}\n\n/**\n * Result of {@link SyncClient.prepareQuery}: the `lazy` relations the guard scanned out of the SQL\n * (∪ the explicit `use`) and activated. Activation means the group's STREAM IS STARTED — reads are\n * safe from the tripwire — not that its initial catch-up has completed; await\n * {@link SyncClient.groupReady} per key for that (see ADR-0021 / ADR-0032 decision 6).\n *\n * Parameterized by the TABLE-NAME UNION, not the registry: `keyof TRegistry` in an output position\n * would make the registry parameter contravariant, and `SyncClient<ConcreteRegistry>` would stop\n * being assignable to bare-`SyncTableRegistry` supertypes — the erasure pattern consumer seams rely\n * on. A name union in output position keeps the whole client covariant in its registry.\n */\nexport interface PreparedQueryResult<TTable extends string = string> {\n lazyTables: readonly TTable[];\n}\n\nexport interface SyncClient<TRegistry extends SyncTableRegistry> {\n drizzle: PgliteDatabase<RegistryRelations<TRegistry>>;\n pglite: ClientPGlite;\n views: RegistryViews<TRegistry>;\n tables: {\n [TKey in SyncTableName<TRegistry>]: SyncClientTableHandle<TRegistry, TKey>;\n };\n /**\n * Local-read readiness (ADR-0041): resolves once PGlite is open, the durable schema is compatible\n * (fingerprint fast path or completed evolution), store-version reconcile has run, and the drizzle read\n * facade is built — so cached rows are queryable. Resolving this stage requires NO write runtime, NO sync\n * start, and NO network I/O, so an offline boot resolves it promptly. Under the ADR-0041 Option B contract\n * `createSyncClient()` (and, in stage 2, `attachSyncClient()`) resolves at exactly this stage; the write and\n * sync tail continues in the background. Monotonic and idempotent.\n */\n localReadReady: Promise<void>;\n /**\n * Write readiness (ADR-0041): resolves once the mutation runtime is constructed and boot recovery has\n * completed (plus restore quarantine on a restore boot) — enqueue is safe. Every write-path method awaits\n * this internally, so a write issued the instant `localReadReady` resolves completes once `writeReady`\n * lands rather than failing opaquely. Resolves with NO network I/O. Monotonic and idempotent.\n */\n writeReady: Promise<void>;\n /**\n * @internal Boot-settled signal (ADR-0041): resolves at today's full in-process resolution point — the\n * write runtime, boot recovery, and sync START have all run (initial catch-up is NOT awaited; that is\n * `ready`). The worker bridge awaits this before `attach-ack` so worker-mode external timing is unchanged\n * in stage 1; stage 2 replaces it with per-stage milestone messages. Not part of the supported public\n * surface — a diagnostics/bridge hook only.\n */\n bootSettled: Promise<void>;\n ready: Promise<void>;\n status: SyncRuntimeStatus;\n start: () => Promise<void>;\n stop: () => Promise<void>;\n /**\n * Wipe the entire local store (synced cache + overlay + journal) and close the handle\n * (ADR-0005). Refuses if mutations are still owed to the server unless `force` is set, so\n * it never silently drops un-flushed writes. Distinct from `stop()`, which only halts sync.\n * Runs under the single lifecycle slot (ADR-0035 decision 4): a concurrent export — or another\n * `destroy`/`discardEphemeral`/`dropReadCache` — rejects with a {@link LifecycleBusyError} rather\n * than interleaving the wipe with a running export.\n */\n destroy: (options?: { force?: boolean }) => Promise<void>;\n /**\n * Drop and rebuild the reconstructible synced read cache, preserving the overlay and\n * mutation journal (ADR-0006). The next sync refills it. Use to recover from a corrupt or\n * stale read cache without losing un-flushed writes. Runs under the single lifecycle slot\n * (ADR-0035 decision 4) — it drops and rebuilds the synced tables, so an export must not capture a\n * half-rebuilt cache; a concurrent export (or `destroy`/`discardEphemeral`) rejects with a\n * {@link LifecycleBusyError}.\n */\n dropReadCache: () => Promise<void>;\n flush: (table?: SyncTableName<TRegistry>) => Promise<void>;\n reconcile: (table?: SyncTableName<TRegistry>) => Promise<void>;\n retryFailed: (table?: SyncTableName<TRegistry>) => Promise<void>;\n recoverSending: (table?: SyncTableName<TRegistry>) => Promise<void>;\n readMutationDetails: (table?: SyncTableName<TRegistry>) => Promise<MutationDetail[]>;\n mutate: {\n create: <TKey extends SyncTableName<TRegistry>>(\n table: TKey,\n input: SyncTableCreateInput<TRegistry, TKey>,\n ) => Promise<void>;\n update: <TKey extends SyncTableName<TRegistry>>(\n table: TKey,\n entityKey: Record<string, string>,\n patch: SyncTableUpdateInput<TRegistry, TKey>,\n ) => Promise<void>;\n delete: <TKey extends SyncTableName<TRegistry>>(table: TKey, entityKey: Record<string, string>) => Promise<void>;\n batch: (items: ReadonlyArray<MutationBatchItem<TRegistry>>) => Promise<void>;\n };\n /**\n * Discard a `conflicted` entity (ADR-0015): clear its conflicted journal entry and kept optimistic\n * Overlay, so the Read model falls back to the synced (server) value. Use when the user abandons a\n * stale edit instead of resolving it as a new write.\n */\n discardConflict: <TKey extends SyncTableName<TRegistry>>(\n table: TKey,\n entityKey: Record<string, string>,\n ) => Promise<void>;\n /**\n * Discard a `quarantined` entity (ADR-0006): clear its quarantined journal entry and kept optimistic\n * Overlay, so the Read model falls back to the synced (server) value. The rollback path for a write\n * the server permanently rejected — e.g. an RLS policy denial (42501) routed to quarantine. After the\n * discard the phantom optimistic row is gone and the entity accepts new mutations again (no longer\n * blocked behind the quarantined head). Symmetric to {@link SyncClient.discardConflict}; the overlay\n * is kept when another still-owed write depends on it. No-op for an entity with no quarantined entry.\n */\n discardQuarantined: <TKey extends SyncTableName<TRegistry>>(\n table: TKey,\n entityKey: Record<string, string>,\n ) => Promise<void>;\n diagnostics: (table?: SyncTableName<TRegistry>) => Promise<{ mutation: MutationDiagnostics }>;\n /**\n * The registry-wide reactive mutation-status surface (proposal §5): a global per-status summary and a\n * filtered normalized detail list over EVERY writable journal, each available one-shot or as a live\n * subscription. Identical on the in-process and worker-attached client. Render a global sync indicator with\n * ONE `subscribeSummary` instead of one journal live query per writable table; consumers never touch the\n * generated journal relation names. See {@link MutationsApi}.\n */\n mutations: MutationsApi<TRegistry>;\n /**\n * The INSPECTION read surface (debug pages, REPLs, ad-hoc counts) — identical on the in-process and\n * worker-attached client (on the latter the statement runs in the worker). The statement runs raw\n * against the local store: it BYPASSES the mutation journal and optimistic overlay, and any write it\n * issues stays local and will NOT converge. For app data reads prefer the live-rows hooks /\n * {@link subscribeLiveRows} (or the guarded {@link query} family); reach for this only to look at the\n * store, not to read app state or mutate it.\n */\n rawQuery: (sql: string, params?: unknown[], options?: RawQueryOptions) => Promise<Results>;\n /** {@link rawQuery} for multi-statement SQL, returning one {@link Results} per statement. */\n rawExec: (sql: string, options?: RawQueryOptions) => Promise<Results[]>;\n /**\n * Run a one-shot (non-live) typed **pure-Drizzle** query with the lazy-relation safety net (ADR-0021).\n * Pass the builder callback directly — pgxsinkit scans the compiled SQL and activates + awaits every\n * lazy relation it reads (FROM, JOIN, subquery, WHERE) before it runs, and the tripwire rejects any\n * lazy relation the SQL still references but that is not active, so the result is never silently\n * empty/stale. The guaranteed-safe alternative to a bare `client.drizzle` read. If the builder embeds\n * a raw `sql` template fragment, use {@link queryRaw} and declare the lazy relations in `use`.\n */\n query: <TRows extends readonly unknown[]>(build: GuardedQueryFn<TRegistry, TRows>) => Promise<TRows>;\n /** {@link query} returning the first row, or null when empty. */\n queryRow: <TRows extends readonly unknown[]>(\n build: GuardedQueryFn<TRegistry, TRows>,\n ) => Promise<TRows[number] | null>;\n /**\n * {@link query} for a builder that embeds a raw `sql` template fragment (ADR-0021). The compiled-SQL\n * scan can miss a lazy relation named as a bare/unquoted identifier inside raw SQL, so declare those\n * in `use` — they are activated and awaited before the query runs. Pure-Drizzle reads should use\n * {@link query} instead (no `use` needed).\n */\n queryRaw: <TRows extends readonly unknown[]>(spec: GuardedRawQuerySpec<TRegistry, TRows>) => Promise<TRows>;\n /** {@link queryRaw} returning the first row, or null when empty. */\n queryRawRow: <TRows extends readonly unknown[]>(\n spec: GuardedRawQuerySpec<TRegistry, TRows>,\n ) => Promise<TRows[number] | null>;\n /**\n * Activate one or more lazy relations (ADR-0021): open their consistency-group subscription if held\n * out of the eager boot, resolving once each group's STREAM IS STARTED — reads are then tripwire-safe,\n * but the initial catch-up may still be in flight (local rows can be legitimately empty/stale until it\n * lands; await {@link groupReady} per relation for catch-up completion — deliberately separate so an\n * offline client still reads its persisted local rows instead of hanging on the network). Idempotent —\n * eager or already-started relations resolve immediately. Use to pre-activate before a\n * raw/`client.drizzle` read, or as the manual escape hatch the tripwire points to.\n */\n ensureSynced: (keys: readonly SyncTableName<TRegistry>[]) => Promise<void>;\n /**\n * Whether a relation's group has started and hydrated (ADR-0021). False for a still-dormant `lazy`\n * relation; true for eager relations once boot completes (and always when sync is disabled).\n */\n isSynced: (key: SyncTableName<TRegistry>) => boolean;\n /**\n * Revert a `lazy` relation to dormant (ADR-0021 §2) — the inverse of on-demand activation: stop its\n * consistency group's stream, clear any persisted `lazy + persistent` activation (so the next boot\n * holds it dormant again), and clean-truncate its local read cache. A later reference re-activates it\n * from scratch. Refuses when the relation is `eager` (always-on, would immediately re-sync) or owes\n * the server unsettled writes (the truncate would drop them — flush or discard first). The reclaim\n * primitive a host wires to navigation/idle for a rarely-opened lazy view; for an `ephemeral`\n * relation, idle-eviction is otherwise automatic at session end.\n */\n desync: (key: SyncTableName<TRegistry>) => Promise<void>;\n /**\n * Drop an **ephemeral** relation's local rows and revert it to dormant (ADR-0021) — the narrow,\n * scoped twin of {@link desync}. It runs the identical group-teardown machinery (stop the group stream,\n * clear the persisted lazy activation, reset the persisted subscription, clean-truncate every member),\n * but under a STRICTER gate: EVERY member of the relation's consistency group must be `retention:\n * \"ephemeral\"` — it refuses (naming the offender) if any member is persistent. Where a `desync` from one\n * tab reverts the shared group for every attached tab (the SharedWorker footgun), `discardEphemeral` is\n * safe under multi-tab because an ephemeral window is per-delivery-session and inherently single-consumer\n * — nothing durable, and no other tab, depends on it. Refuses an `eager` relation (always-on, would\n * immediately re-sync) and a group that owes the server unsettled writes, exactly as `desync` does. The\n * finalize primitive for a secure-delivery window: drop the local rows at session end without touching a\n * durable relation. Note the drop is local-lifecycle only: a later re-subscription re-activates the lazy\n * group and re-streams whatever the SERVER still serves — post-finalize non-redelivery is the server\n * gate's guarantee (e.g. a consumed server-owned cursor), not this method's. Runs under the single\n * lifecycle slot (ADR-0035 decision 4): a concurrent export (or `destroy`/`dropReadCache`) rejects with a\n * {@link LifecycleBusyError} rather than interleaving the cache truncate with a running export.\n */\n discardEphemeral: (key: SyncTableName<TRegistry>) => Promise<void>;\n /**\n * The read-path safety seam (ADR-0021): scan the compiled `sql` for the lazy relations it reads\n * (∪ the optional `use`) and activate them — so a lazy relation auto-activates on *any* reference\n * (FROM, JOIN, subquery, WHERE). Resolves once it is safe to run the query (streams started, tripwire\n * satisfied) and returns the activated keys ({@link PreparedQueryResult}) so a consumer can further\n * await {@link groupReady} per key for catch-up completion — the React hooks drive `hydrating` off\n * exactly that. A backstop throws {@link LazyRelationNotActivatedError} only if a referenced relation\n * could not be activated. Exposed for the React live hooks (which own their query build);\n * `query`/`queryRow` are the higher-level non-live wrappers. Raw, non-Drizzle SQL is out of scope —\n * pass `use`, or `ensureSynced` first.\n */\n prepareQuery: (input: PrepareQueryInput<TRegistry>) => Promise<PreparedQueryResult<SyncTableName<TRegistry>>>;\n /**\n * Author an atomic write-**unit** (ADR-0022 §2). The callback receives collecting table handles; every\n * mutation it issues is tagged into one unit and enqueued atomically when the callback returns.\n *\n * - `mode: \"pessimistic\"` — **server-authoritative**: the unit flush-routes to the authoritative endpoint\n * and this call resolves only once the server has decided. The result's `acks` carry each member's\n * outcome — `acked`, `conflicted` (overlay kept, ADR-0015), or `rejected` (overlay auto-discarded for\n * the whole unit, surfaced via `onReject`, ADR-0022 §4). Throws on transport failure (overlay kept). A\n * pessimistic block may also issue {@link SyncTransactionTableHandle.updateBlind} — an update-by-key with\n * no local base row and no overlay, for a write target excluded from the actor's read shape.\n * - `mode: \"optimistic\"` — an atomic batch enqueue that flushes in the background (empty `acks`).\n */\n transaction: (\n options: { mode: WriteMode },\n run: (tx: SyncTransaction<TRegistry>) => void | Promise<void>,\n ) => Promise<SyncTransactionResult>;\n /**\n * Per-group readiness (ADR-0032 decision 6): a promise resolving the moment the given table's\n * consistency group is up-to-date. Resolves immediately for an already-ready (or sync-disabled)\n * group; stays pending for a still-dormant `lazy` relation until it is activated and caught up. The\n * opt-in progressive-paint signal beside the all-eager-groups `ready` gate. `status.groups` carries the\n * same readiness as a synchronous snapshot.\n */\n groupReady: (table: SyncTableName<TRegistry>) => Promise<void>;\n /**\n * The referenced consistency groups' member tables that are NOT YET caught up at call time (ADR-0021 /\n * ADR-0032 decision 6): scan the compiled SQL for every synced relation the query reads (∪ `use`), map\n * each to its consistency group, and return those whose group has not completed its initial catch-up.\n * Empty when sync is disabled OR every referenced group is already ready — the steady-state fast path in\n * which the live-rows seam builds no `hydrated` promise. The seam (and the worker bridge) use this to gate\n * `hydrating` uniformly across eager AND lazy groups; ACTIVATION is separate and stays lazy-only. Returns\n * plain table-name strings (not `keyof TRegistry`) to keep the client covariant in its registry.\n */\n hydratingTablesFor: (query: { sql: string; use?: readonly string[] }) => readonly string[];\n /**\n * The live-rows seam (ADR-0032 S2 §4): register a reactive query and receive its initial ordered\n * snapshot plus subsequent updates via `onRows`. The React live hooks consume THIS (not `pglite.live`\n * directly), so they run unchanged against both the in-process client (which implements it over\n * `pglite.live`) and the worker-attached client (which implements it over the bridge). Prefer the\n * higher-level `@pgxsinkit/react` hooks; this is the lower-level primitive they build on.\n */\n subscribeLiveRows: <TRow extends Record<string, unknown> = Record<string, unknown>>(\n input: SubscribeLiveRowsInput,\n onRows: (rows: TRow[]) => void,\n ) => Promise<LiveRowsSubscription<TRow>>;\n /**\n * Boot observability (ADR-0034): the engine's most recent COMPLETED boot report, or `null` before the\n * first boot finalizes (and after a `stop()`/`destroy()` that preceded initial sync). Pull — so a\n * late-attaching tab can read a boot that predates it; in worker mode it round-trips to the worker's\n * stored report. The push counterpart is the `onBootReport` client option.\n */\n bootReport: () => Promise<BootReport | null>;\n /**\n * Live-query diagnostics (ADR-0040 decision 5): a point-in-time snapshot of the live-query manager's\n * entries — opaque fingerprint digests plus counts/timings only, NEVER SQL, params, or row values. Both\n * client forms return the real snapshot: in WORKER mode this pulls the worker manager's snapshot over the\n * bridge; the IN-PROCESS client returns its own manager's snapshot directly.\n */\n liveQueryDiagnostics: () => Promise<LiveQueryDiagnostics[]>;\n /**\n * Take a **store backup** (ADR-0035): a full-fidelity, PGlite-restorable tarball of the whole local\n * store — synced cache, Overlay, and Mutation journal (unflushed writes included) — via PGlite's\n * `dumpDataDir`. Taken LIVE (a `CHECKPOINT` serialised behind engine work, then the dump; no engine\n * suspension, no tab disruption), so it never blocks and is the only lossless export an offline device\n * with unflushed writes can take. Awaits engine-ready rather than rejecting during boot, then runs under\n * the single lifecycle slot: a second export (or, later, `destroy`/`discardEphemeral`) attempted while\n * one is in flight rejects immediately with a {@link LifecycleBusyError} — retry once it settles.\n * Resolves to the artefact `File` plus an {@link ExportReport} (phase timings + a diagnostics snapshot).\n */\n exportStore: (options?: StoreExportOptions) => Promise<StoreExportResult>;\n /**\n * Take a **diagnostic dump** (ADR-0035): human-readable SQL of EVERYTHING the store holds — synced tables,\n * the `_overlay`/`_mutations` journal (unflushed writes included — the evidence a diagnostic exists for),\n * the `pgxsinkit` metadata schema, the read-model views, and the reconcile functions/triggers — via\n * `pg_dump`. To keep `pg_dump`'s `DEALLOCATE ALL` away from the live engine, the dump runs against a\n * memory-backed THROWAWAY clone booted from a live datadir dump (ADR-0035 addendum): the running store is\n * never suspended and no tab is disrupted. Awaits engine-ready rather than rejecting during boot, then\n * runs under the single lifecycle slot — a concurrent export (or `destroy`/`discardEphemeral`) rejects\n * immediately with a {@link LifecycleBusyError}. Resolves to the SQL `File` (`application/sql`) plus a\n * {@link DiagnosticDumpReport} (phase timings + a diagnostics snapshot). Active ephemeral (`pg_temp`)\n * clusters are absent by construction (ADR-0035 decision 5 — `pg_dump` ignores temp objects).\n */\n exportDiagnostics: (options?: DiagnosticExportOptions) => Promise<DiagnosticExportResult>;\n /**\n * Take a **data export** (ADR-0035): the PORTABLE artefact — the synced tables and the enum types they\n * depend on, schema + data, nothing of pgxsinkit's machinery — as SQL loadable into a vanilla Postgres. It\n * is a generated enum DDL header concatenated ahead of `pg_dump -t <table> ... --no-owner` (one `-t` per\n * physical synced table; ephemeral/read-projection entries excluded by construction), run against the same\n * memory-backed THROWAWAY clone the diagnostic dump uses — so the live engine is never touched.\n *\n * Unlike the other two exports it GUARDS the journal (decision 3): a strict export requires a DRAINED\n * journal — all mutation counts zero, including `acked` writes whose synced echo has not landed (they live\n * only in the Overlay). The drain flushes drainable rows and awaits convergence up to\n * `drainJournal.timeoutMs` (default `15_000`); non-drainable states (`failed`/`quarantined`/`conflicted`)\n * fail FAST with a {@link DataExportDrainError} carrying the diagnostics. `drainJournal: false` is the\n * escape hatch — export synced state as-is (unflushed writes absent; `report.escapeHatch` records it). An\n * offline device with a clean journal exports strictly and instantly; one with a dirty journal cannot\n * produce a strict export (its lossless option is `exportStore`).\n *\n * Awaits engine-ready rather than rejecting during boot, then runs the whole drain+dump under the single\n * lifecycle slot — a concurrent export (or `destroy`/`discardEphemeral`) rejects with a\n * {@link LifecycleBusyError}. Resolves to the SQL `File` (`application/sql`) plus a {@link DataExportReport}\n * (drain + clone-pipeline phase timings, the applied `-t` table list, and the escape-hatch flag).\n */\n exportData: (options?: DataExportOptions) => Promise<DataExportResult>;\n}\n\nexport type { MutationBatchItem, MutationDetail, MutationDiagnostics, MutationKind, MutationSummary };\n\n/**\n * The structured-clone-safe subset of PGlite's `QueryOptions` the inspection surface carries. Kept\n * narrow ON PURPOSE: on a worker-attached client the options object crosses the bridge via\n * `postMessage`, so function-valued options (`parsers`, `serializers`, `onNotice`) can never be part\n * of this contract. `rowMode: \"array\"` is what `@electric-sql/pglite-repl` asks for on every exec.\n */\nexport interface RawQueryOptions {\n rowMode?: \"object\" | \"array\";\n}\n\n/** The `{ query, exec }` duck `@electric-sql/pglite-repl` drives, backed by a client's inspection surface. */\nexport interface ReplInspectionSurface {\n query: (sql: string, params?: unknown[], options?: RawQueryOptions) => Promise<Results>;\n exec: (sql: string, options?: RawQueryOptions) => Promise<Results[]>;\n}\n\n/**\n * Shape a {@link SyncClient}'s inspection surface (`rawQuery`/`rawExec`) as the `{ query, exec }` duck\n * `@electric-sql/pglite-repl` needs. Identical on the in-process and worker-attached client — on the latter\n * each statement routes through the worker bridge, so the REPL works even though `client.pglite` is\n * unavailable. Cast the result at the `<Repl pg={...}>` prop (the REPL types the prop as a full `PGlite`).\n * The surface is registry-independent, so it accepts any client's `rawQuery`/`rawExec` pair.\n */\nexport function replAdapter(\n client: Pick<SyncClient<SyncTableRegistry>, \"rawQuery\" | \"rawExec\">,\n): ReplInspectionSurface {\n return {\n // Thread the options through UNMODIFIED — the REPL execs with `{ rowMode: \"array\" }` and renders\n // each row with `row.map`, so dropping the options here breaks every REPL statement.\n query: (sql, params, options) => client.rawQuery(sql, params, options),\n exec: (sql, options) => client.rawExec(sql, options),\n };\n}\n\nexport async function createSyncClient<const TRegistry extends SyncTableRegistry>(\n options: CreateSyncClientOptions<TRegistry>,\n): Promise<SyncClient<TRegistry>> {\n // Fail fast on a bad keep-alive policy — before any PGlite boot work (ADR-0040 decision 4 — bounded).\n validateLiveQueryPolicy(options.liveQueries);\n const status: SyncRuntimeStatus = {\n phase: \"booting\",\n isRunning: false,\n };\n\n let resolveReady!: () => void;\n let rejectReady!: (error: unknown) => void;\n const ready = new Promise<void>((resolve, reject) => {\n resolveReady = resolve;\n rejectReady = reject;\n });\n\n // Staged boot readiness (ADR-0041). Three monotonic, idempotent stages resolved as the boot crosses them:\n // - `localReadReady`: local-read core done (schema compatible + reconcile + drizzle facade) — zero network.\n // - `writeReady`: mutation runtime + boot recovery (+ restore quarantine) done — enqueue is safe.\n // - `bootSettled`: today's full resolution point (sync START done). The worker bridge awaits it (stage 1).\n // Under the Option B contract this function RESOLVES at `localReadReady` and runs the write/sync tail in the\n // background, so a returning offline consumer gets a readable client without waiting on the network. Each\n // stage's rejection is guarded (below) so an unconsumed stage never surfaces as an unhandled rejection —\n // real awaiters still observe the failure.\n // `localReadReady` has no reject binding: a local-read-core failure throws straight out of this async\n // function (so the returned promise rejects, exactly as a pre-ADR-0041 boot failure did) before the client\n // is handed out, leaving `localReadReady` pending on a store nobody holds — no awaiter, no leak.\n let resolveLocalReadReady!: () => void;\n const localReadReady = new Promise<void>((resolve) => {\n resolveLocalReadReady = resolve;\n });\n let resolveWriteReady!: () => void;\n let rejectWriteReady!: (error: unknown) => void;\n const writeReady = new Promise<void>((resolve, reject) => {\n resolveWriteReady = resolve;\n rejectWriteReady = reject;\n });\n let resolveBootSettled!: () => void;\n let rejectBootSettled!: (error: unknown) => void;\n const bootSettled = new Promise<void>((resolve, reject) => {\n resolveBootSettled = resolve;\n rejectBootSettled = reject;\n });\n\n if (options.pgliteInstance && options.precreatedPglite) {\n throw new Error(\n \"createSyncClient: pass at most one of `pgliteInstance` or `precreatedPglite` — they claim different ownership of the post-create boot steps (schema exec, prepare hooks, store-version reconcile).\",\n );\n }\n\n // Restore (ADR-0035 decision 6) owns the store's CREATION — the backup tarball is a `loadDataDir` seed on\n // the fresh store — so it cannot coexist with a caller-supplied instance (which claims the store already\n // exists and is provisioned). Fail loudly rather than silently ignore one.\n const restoreBoot = options.restoreFrom != null;\n if (restoreBoot && (options.pgliteInstance || options.precreatedPglite)) {\n throw new Error(\n \"createSyncClient: `restoreFrom` is mutually exclusive with `pgliteInstance` / `precreatedPglite` — restore boots a brand-new store from the backup (a create-time `loadDataDir` seed), so it cannot adopt a caller-owned instance. Drop the instance option, or drop `restoreFrom` (ADR-0035).\",\n );\n }\n\n // Restore ALWAYS boots offline (ADR-0035 decision 6), regardless of `syncEnabled`/`autoSync` or anything\n // captured in the backup: no shape streams, no read fetch, no flush, no convergence passes. The app deals\n // with the quarantined journal, then a subsequent NORMAL boot brings sync online. Restore wins over an\n // explicit online option — warn on the debug rail so the override is visible rather than silent.\n if (restoreBoot && (options.syncEnabled === true || options.autoSync != null)) {\n syncDebug(\"boot restore forces offline — ignoring the online sync option for this restore boot\", {\n syncEnabled: options.syncEnabled === true,\n autoSync: options.autoSync != null,\n });\n }\n const syncEnabled = restoreBoot ? false : (options.syncEnabled ?? true);\n // ADR-0032 S4 overlap flag, computed once up front so the boot report and the prefetch gate agree.\n const overlapPrefetch = syncEnabled && options.freshStore === true && !options.pgliteInstance;\n // How the store presents at boot (ADR-0034 `storeKind`): a restore boot seeds a brand-new store from a\n // backup; otherwise the caller's fresh-store hint (the same signal as `freshStore`) marks a fresh spare;\n // everything else is a warm (existing persisted) store. Restore wins — a restore boot is never \"fresh\".\n const storeKind: BootReport[\"storeKind\"] = restoreBoot ? \"restored\" : options.freshStore === true ? \"fresh\" : \"warm\";\n\n // Boot observability (ADR-0034): build a structured report across the boot, finalized once at initial\n // sync. Created FIRST so its monotonic anchor precedes every timed phase (including the PGlite create).\n const bootReportBuilder: BootReportBuilder = createBootReportBuilder({\n mode: options.bootMode ?? \"in-process\",\n freshStore: options.freshStore === true,\n storeKind,\n overlapPrefetch,\n registryFingerprint: fingerprintRegistry(options.registry),\n });\n // The single engine lifecycle slot (ADR-0035 decision 4). The three exports plus the destructive\n // lifecycle ops — `destroy()`, `discardEphemeral()`, and `dropReadCache()` — all serialise through it,\n // so a wipe/rebuild can never interleave a running export (nor vice versa): the slot rejects the second\n // entrant with a typed LifecycleBusyError in either direction.\n const lifecycleSlot = createLifecycleSlot();\n\n let finalizedBootReport: BootReport | null = null;\n const finalizeBootReport = () => {\n if (finalizedBootReport) return;\n finalizedBootReport = bootReportBuilder.finalize();\n options.onBootReport?.(finalizedBootReport);\n };\n\n // The testing marker (ADR-0036 decision 3), read once off the options object: `\"memory\"` selects the\n // memory backend for a client-owned create AND acknowledges the BYO seam; `\"acknowledged\"` only unlocks\n // the BYO refusal. Absent for every production consumer — the marker rides in only via\n // `@pgxsinkit/client/testing`, never named in a public type.\n const testStoreMarker = readTestStoreMarker(options);\n const backendOverride = testStoreMarker === \"memory\" ? (\"memory\" as const) : undefined;\n\n // Bind the create options once for the two client-owned create paths (fresh `storePath`, and the\n // `precreatedPglite` reject-fallback), so both consume the same pre-warm + resolve the same backend.\n const createClientOptions: CreateClientPGliteOptions = {\n ...(options.pgliteBootAssets ? { bootAssets: options.pgliteBootAssets } : {}),\n ...(backendOverride ? { backendOverride } : {}),\n // Restore (ADR-0035 decision 6): seed the fresh store from the backup via `loadDataDir`. Restore is\n // mutually exclusive with the BYO instance seams (checked above), so it only ever rides a client-owned\n // create — never the adopt paths, which leave `restoreFrom` unread.\n ...(restoreBoot ? { restoreFrom: options.restoreFrom } : {}),\n };\n const fallbackStorePath = options.storePath ?? \"pgxsinkit-overlay-v1\";\n\n // Fresh-target gate (ADR-0035 decision 6): restore refuses a store that already exists — it boots a\n // brand-new store and never overlays a live one. Checked BEFORE the create so we never touch (let alone\n // half-write) an existing datadir; the memory test lane is fresh by construction, so this is a no-op there.\n if (restoreBoot) {\n if (await storeTargetExists(fallbackStorePath, backendOverride)) {\n throw new RestoreTargetExistsError(fallbackStorePath);\n }\n }\n // Time a client-owned `createClientPGlite` into `phases.pgliteCreateMs`; an ADOPTED store (spare or\n // caller-supplied) leaves it `null` (create ran elsewhere — see the provision block below).\n const timedCreate = async (): Promise<ClientPGlite> => {\n const startedAt = performance.now();\n const created = await createClientPGlite(fallbackStorePath, createClientOptions);\n bootReportBuilder.setPgliteCreateMs(performance.now() - startedAt);\n return created;\n };\n\n // Refuse a caller-owned instance that is PROVABLY non-persistent (ADR-0036 decision 4), unless a testing\n // acknowledgment is present. `classifyNonPersistentDataDir` inspects the instance's own dataDir (the\n // `ClientPGlite` interface hides it, so via a narrow cast) — the two provably-non-persistent shapes are\n // an undefined dataDir (PGlite's in-memory default) and an explicit memory store. Checked AFTER a\n // successful resolution of the BYO promise, so the refusal PROPAGATES rather than being swallowed by the\n // `precreatedPglite` reject-fallback below (which only catches a create that never produced a store).\n const refuseIfNonPersistent = (instance: ClientPGlite): void => {\n if (testStoreMarker !== undefined) return; // a deliberate test store — acknowledged.\n const observed = classifyNonPersistentDataDir((instance as { dataDir?: string }).dataDir);\n if (observed !== null) throw new NonPersistentStoreError(observed);\n };\n\n let pglite: ClientPGlite;\n // Whether the boot adopted the caller's `precreatedPglite` (vs. falling back to a fresh create) — gates\n // whether the provision stamp is honoured (ADR-0034).\n let adoptedPrecreated = false;\n if (options.pgliteInstance) {\n // The caller created AND provisioned this store; the client runs NONE of the post-create boot steps\n // (schema/prepare/reconcile) — see the `pgliteInstance` JSDoc. No create here → `pgliteCreateMs` null.\n refuseIfNonPersistent(options.pgliteInstance);\n pglite = options.pgliteInstance;\n } else if (options.precreatedPglite) {\n // The caller created the raw store eagerly via `createClientPGlite`; the client still owns every\n // post-create step below. A REJECTED eager create must never fail the boot: fall back to the normal\n // `storePath` create, so the pattern stays a pure accelerator. Reify the promise's outcome first, THEN\n // branch — so the {@link NonPersistentStoreError} refusal runs on a SUCCESSFULLY resolved instance,\n // outside any catch, and PROPAGATES (never swallowed by the reject-fallback, which is only for a create\n // that never produced a store).\n const outcome = await options.precreatedPglite.then(\n (instance) => ({ ok: true as const, instance }),\n (error: unknown) => ({ ok: false as const, error }),\n );\n if (outcome.ok) {\n refuseIfNonPersistent(outcome.instance);\n pglite = outcome.instance;\n adoptedPrecreated = true;\n } else {\n syncDebug(\"boot precreated pglite rejected — falling back to storePath create\", {\n error: outcome.error instanceof Error ? outcome.error.message : String(outcome.error),\n });\n pglite = await timedCreate();\n }\n } else {\n pglite = await timedCreate();\n }\n\n // Provision block (ADR-0034): when the boot adopted a pre-provisioned store and the provisioner stamped\n // its create timing, report the spare's initdb cost + how long it sat ready, and leave `pgliteCreateMs`\n // null (the create was paid at provision time, off this boot's clock).\n if (adoptedPrecreated && options.provisionStamp) {\n const stamp = await options.provisionStamp.catch(() => null);\n if (stamp) {\n bootReportBuilder.setProvision({\n initdbMs: stamp.initdbMs,\n provisionedMsBeforeBoot: Math.max(0, bootReportBuilder.bootStartPerf - stamp.provisionReadyAt),\n });\n }\n }\n\n // Attach the sync engine explicitly, over the already-created instance, on ALL three provenance paths\n // (pgliteInstance, precreatedPglite, storePath) — ADR-0032 S1. The engine is no longer a create-time\n // extension, so the raw store (a `createClientPGlite` mint, or a caller's own instance) carries no\n // `electric` namespace until this point; the property assignment gives `ClientPGlite` its exact former\n // structural shape (live + electric) so every `pglite.electric.…` call site is unchanged. It is attached\n // BEFORE the schema/prepare steps below so a `prepareLocalDb` hook sees the same `.electric` it did when\n // the extension provided it at create time. `engine.close` (the former extension close hook — abort every\n // shape stream) is kept private to this client and run explicitly by `stop`/`destroy` at the same moment\n // `pglite.close()` used to trigger it.\n const engine: SyncEngine = await createSyncEngine(pglite);\n (pglite as { electric: SyncEngine[\"namespace\"] }).electric = engine.namespace;\n\n // Whether the read path's first initial sync has completed, so a recovery from `auth-needed` returns to\n // the right steady-state phase (`ready` if already caught up, else `syncing`).\n let initialSyncCompleted = false;\n // Why the runtime is `degraded` (#4). A read-stream error degraded clears on the next successful batch; a\n // commit-failure degraded is sticky (a fetch can succeed while applies still fail), so a bare\n // `onSyncActivity` must not clear it.\n let degradedReason: \"stream\" | \"commit\" | null = null;\n\n // ─── Fresh-store prefetch overlap (ADR-0032 S4 / backlog-0003) ─────────────────────────────────────\n // On a PROVABLY-FRESH store (the caller's `freshStore` hint — a claimed schemaless spare) the shape\n // catch-up needs none of the local boot phases, so start it NOW and gate its commits on `dbReady`, which\n // we resolve once schema exec + journal recovery + store-version reconcile complete. The network then\n // overlaps those phases instead of running strictly after them. Gated to the schema-owning paths (the\n // `pgliteInstance` path runs no schema step, so it has nothing to hide); warm stores keep the exact\n // sequential path. See the `freshStore` option's JSDoc for who sets the hint (the board's claim path).\n // (`overlapPrefetch` is computed once up front — see the boot-report builder above.)\n let openDbGate: () => void = () => {};\n const dbReady = overlapPrefetch\n ? new Promise<void>((resolve) => {\n openDbGate = resolve;\n })\n : null;\n\n // The sync-start options, built once and used by BOTH the overlap early-start and the sequential start —\n // the only per-call difference is the promoted-lazy set (empty on a fresh store) and the overlap gate.\n const buildStartOptions = (promotedGroups: ReadonlySet<string>): Parameters<typeof startConfiguredSync>[1] => ({\n syncConfig: buildSyncConfigFromRegistry(options.registry, options.electricUrl),\n registry: options.registry,\n promotedGroups,\n ...(dbReady ? { dbReady } : {}),\n // Boot observability (ADR-0034): the collector opens a per-boot-group accumulator (rows/requests/fetch/\n // apply wall) for the eager + promoted groups; lazy on-demand starts get none, so they never enter the report.\n bootCollector: bootReportBuilder,\n // Persist a durable lazy group's activation on first on-demand start, so the next boot promotes it.\n onLazyActivated: (groupKey) => {\n void writeLazyGroupActivation(pglite, options.registry, groupKey);\n },\n // The read path resolves the token per request (ADR-0013), not frozen at boot — so a long-lived session\n // never wedges on JWT expiry. Read and write share one token lifecycle.\n ...(options.getAuthToken || options.requestHeaders\n ? {\n shapeHeaders: buildShapeHeaders({\n ...(options.getAuthToken ? { getAuthToken: options.getAuthToken } : {}),\n ...(options.requestHeaders ? { requestHeaders: options.requestHeaders } : {}),\n }),\n }\n : {}),\n ...(options.onTableInitialSync ? { onTableInitialSync: options.onTableInitialSync } : {}),\n // Per-group readiness (ADR-0032 decision 6): mirror each group's catch-up into `status.groups` and\n // re-emit, so an app can drive progressive per-group paint off `status` (and `client.groupReady`).\n onGroupReady: (groupKey) => {\n status.groups = { ...(status.groups ?? {}), [groupKey]: true };\n options.onStatusChange?.(status);\n },\n onInitialSync: () => {\n initialSyncCompleted = true;\n status.phase = \"ready\";\n options.onStatusChange?.(status);\n // Boot complete: the first initial sync landed and `ready` is about to resolve. One monotonic stamp\n // closes the boot rail opened by `boot pglite.create` (the stamp itself is the number).\n syncDebug(\"boot client ready\");\n // Boot observability (ADR-0034): finalize the report at exactly this moment — the `boot client ready`\n // rail line — and fire the one-shot `onBootReport` push. Idempotent, so the sync-disabled path's own\n // finalize below never double-fires it.\n finalizeBootReport();\n resolveReady();\n },\n onSyncError: (error) => {\n // A sync commit exhausted its retries (ADR-0009 decision 5): go degraded and surface it, rather than\n // letting the read cache silently diverge from the server. Sticky (see below).\n status.phase = \"degraded\";\n degradedReason = \"commit\";\n status.lastError = error.message;\n options.onStatusChange?.(status);\n options.onSyncError?.(error);\n },\n // #4: a terminal/transient NON-auth read-stream error → `degraded`, so the runtime never keeps reporting\n // healthy while the read stream has stalled. Does not override the more-actionable `auth-needed`, nor a\n // commit-failure degraded. Cleared on the next successful batch below.\n onReadStreamError: (error) => {\n // Never mask the more-actionable auth-needed, nor a sticky commit-failure degraded (its lastError is\n // the more serious signal — a stream blip must not overwrite it).\n if (status.phase === \"auth-needed\") return;\n if (status.phase === \"degraded\" && degradedReason === \"commit\") return;\n // Enter, or refresh, a stream-degraded status. Refreshing keeps `lastError` pointing at the most\n // recent stream fault (and re-emits) rather than freezing on the first one, so a stream that fails one\n // way then another reports the current cause (observability).\n status.phase = \"degraded\";\n degradedReason = \"stream\";\n status.lastError = error.message;\n options.onStatusChange?.(status);\n },\n // Clear a recoverable status (auth-needed, or a read-stream degraded) the moment a batch is delivered\n // again. A commit-failure degraded is NOT cleared here — a fetch can succeed while applies keep failing,\n // so only `onSyncError` clearing (a clean commit) would lift it.\n onSyncActivity: () => {\n if (status.phase === \"auth-needed\" || (status.phase === \"degraded\" && degradedReason === \"stream\")) {\n degradedReason = null;\n status.phase = initialSyncCompleted ? \"ready\" : \"syncing\";\n options.onStatusChange?.(status);\n }\n },\n // ADR-0013 Phase 3: surface a persistent read-path auth failure as a distinct `auth-needed` status (the\n // app prompts re-login) while the stream keeps retrying for a fresh token. Only wired when a token\n // provider exists — without one there is no auth lifecycle to track.\n ...(options.getAuthToken\n ? {\n onAuthError: () => {\n if (status.phase !== \"auth-needed\") {\n status.phase = \"auth-needed\";\n options.onStatusChange?.(status);\n }\n },\n }\n : {}),\n });\n\n // Overlap: kick the shape streams off BEFORE schema exec (they buffer catch-up into the memory inbox,\n // commits gated on `dbReady`). A fresh store has no persisted lazy activations and no subscriptions to\n // reset, so both DB reads the sequential path makes first are skipped here.\n let earlySync: ReturnType<typeof startConfiguredSync> | null = null;\n let earlySyncStartedAt = 0;\n if (overlapPrefetch) {\n status.isRunning = true;\n status.phase = \"syncing\";\n options.onStatusChange?.(status);\n earlySyncStartedAt = performance.now();\n earlySync = startConfiguredSync(\n pglite as unknown as Parameters<typeof startConfiguredSync>[0],\n buildStartOptions(new Set()),\n );\n }\n\n if (!options.pgliteInstance) {\n if (options.prepareLocalDbBeforeSchema) {\n const prepareBeforeSchema = options.prepareLocalDbBeforeSchema;\n await bootReportBuilder.phase(\"prepare\", \"boot prepare(before-schema)\", () => prepareBeforeSchema(pglite));\n }\n\n // Durable-schema fingerprint fast path (slice 3 / proposal §3). The whole block stays inside the\n // `schemaExec` phase so `schemaExecMs` remains comparable across the fast (skip) and full (replay) paths.\n await bootReportBuilder.phase(\"schemaExec\", \"boot local schema\", async () => {\n // (2) The minimal bootstrap first — one small crossing so the `local_schema_fingerprint` read/write\n // below has its `pgxsinkit_local_meta` table before the durable replay is decided.\n await pglite.exec(buildLocalMetaBootstrapSql(options.registry));\n\n // (3) Generate the durable SQL (JS-only) and hash it; compare with the stored fingerprint.\n const currentFingerprint = computeLocalSchemaFingerprint(options.registry);\n const storedFingerprint = await readStoredLocalSchemaFingerprint(pglite, options.registry);\n\n if (storedFingerprint === currentFingerprint) {\n // (4a) Match → SKIP the durable replay entirely; the persisted durable schema is already current.\n bootReportBuilder.setSchemaFastPath({ skipped: true, fingerprintMatch: true });\n } else {\n // (4b) Absent/mismatch → replay the durable schema, then stamp the fingerprint AFTER success only\n // (exec and stamp travel together — a throw here leaves the old/absent fingerprint for a retry).\n await pglite.exec(generateDurableLocalSchemaSql(options.registry));\n await writeStoredLocalSchemaFingerprint(pglite, options.registry, currentFingerprint);\n bootReportBuilder.setSchemaFastPath({ skipped: false, fingerprintMatch: false });\n }\n\n // (5) ALWAYS apply the ephemeral schema (TEMP relations die with the old engine), skipping the\n // crossing when the registry declares no ephemeral entry (the generator returns \"\").\n const ephemeralSql = generateEphemeralLocalSchemaSql(options.registry);\n if (ephemeralSql.length > 0) {\n await pglite.exec(ephemeralSql);\n }\n });\n\n if (options.prepareLocalDb) {\n const prepareLocalDb = options.prepareLocalDb;\n await bootReportBuilder.phase(\"prepare\", \"boot prepare(local-db)\", () => prepareLocalDb(pglite));\n }\n }\n\n // The write path's headers are the shared base plus the write-only overrides (region/DB-affinity):\n // `{...requestHeaders, ...writeRequestHeaders}`. The read/shape path keeps `requestHeaders` alone\n // (below), so `writeRequestHeaders` never reach reads — the two ingress points pin independently.\n const writePathHeaders =\n options.requestHeaders || options.writeRequestHeaders\n ? { ...(options.requestHeaders ?? {}), ...(options.writeRequestHeaders ?? {}) }\n : undefined;\n\n // ADR-0039: an ordinary optimistic write activates its target's lazy consistency group (a write is a\n // reference, and a reference activates — the read path already does this). The runtime reports the\n // non-blind table keys per enqueue; this indirection is assigned once `ensureSynced`/`lazyGuardIndex`\n // exist below (a write never fires during boot, so it is a harmless no-op until then).\n let activateOrdinaryWriteTables: ((tables: readonly string[]) => void) | null = null;\n const mutationRuntime = createMutationRuntime({\n db: pglite,\n registry: options.registry,\n writeUrl: options.writeUrl,\n // pgxsinkit owns the local schema (and the `pgxsinkit_local_meta` marker table) unless the caller\n // supplied their own PGlite — then the marker is never touched and recovery falls back to legacy always-recover.\n ownsMetaTable: !options.pgliteInstance,\n onOrdinaryEnqueue: (tables) => activateOrdinaryWriteTables?.(tables),\n ...(options.getAuthToken ? { getAuthToken: options.getAuthToken } : {}),\n ...(writePathHeaders ? { requestHeaders: writePathHeaders } : {}),\n ...(options.maxMutationAttempts != null ? { maxMutationAttempts: options.maxMutationAttempts } : {}),\n ...(options.onQuarantine ? { onQuarantine: options.onQuarantine } : {}),\n ...(options.onConflict ? { onConflict: options.onConflict } : {}),\n ...(options.onReject ? { onReject: options.onReject } : {}),\n });\n\n // Activation buffer (ADR-0041): a read (`ensureSynced`) OR a write (`onOrdinaryEnqueue`) can reference a\n // lazy group after `localReadReady` but BEFORE `sync` is wired (the Option B window). With a null `sync` the\n // seams cannot start a group, so BOTH feed this one buffer; the tail replays it once sync is wired, so the\n // activation is never LOST across the staged split (ADR-0039 semantics preserved). Null once replayed (or on\n // a tail failure — see the tail's rejection handler).\n let pendingActivations: Set<string> | null = new Set();\n\n let versionEvent: LocalStoreVersionEvent | null = null;\n\n // Boot recovery (ADR-0005) driven by the durable recovery marker (slice 2), PLUS the restore quarantine\n // (ADR-0035 decision 6, gated on `restoreBoot` inside `runBootRecovery`). Hoisted so the restore path runs\n // it BEFORE read exposure (the ADR-0041 invariant) and the normal path defers it to the background write\n // tail. `runBootRecovery` owns the full decision — marker read, skip/legacy/transactional-recover, restore\n // quarantine, marker clear — and returns the honest `warmBoot` outcome (ADR-0034).\n const runBootRecoveryStage = async (): Promise<void> => {\n const recoveryOutcome = await bootReportBuilder.phase(\"journalRecovery\", \"boot journal recovery\", () =>\n mutationRuntime.runBootRecovery({ ownsMetaTable: !options.pgliteInstance, restore: restoreBoot }),\n );\n bootReportBuilder.setJournalRecovery(recoveryOutcome);\n };\n\n // Store-version reconcile against the current registry fingerprint (ADR-0006). It reads the runtime's\n // journal stats to decide rebuild-vs-defer and `runtime.registryVersion` (static), so it needs only the\n // CONSTRUCTED runtime — not a completed recovery pass.\n const runReconcileStage = async (): Promise<void> => {\n if (options.pgliteInstance) return;\n versionEvent = await bootReportBuilder.phase(\"storeVersionReconcile\", \"boot store-version reconcile\", () =>\n reconcileLocalStoreVersion({\n db: pglite,\n registry: options.registry,\n runtime: mutationRuntime,\n ...(options.onSchemaChange ? { onSchemaChange: options.onSchemaChange } : {}),\n }),\n );\n };\n\n if (restoreBoot) {\n // Restore invariant (ADR-0041): the quarantine of every recovered write MUST complete before any read\n // facade is exposed, so recovery + quarantine run FIRST, then reconcile. Because the quarantine ran first,\n // every recovered row counts toward `owedMutations` (pending+sending+failed+quarantined) inside\n // `rebuildReadCacheOrDefer`, so a stale-fingerprint restore DEFERS the read-cache rebuild rather than\n // dropping the quarantined writes — unchanged from the pre-ADR-0041 recover→quarantine→reconcile order.\n // `localReadReady` and `writeReady` therefore coincide on a restore boot (both resolved after this point).\n await runBootRecoveryStage();\n await runReconcileStage();\n } else {\n // Normal boot (ADR-0041): reconcile is part of the local-read core and runs BEFORE recovery (which moves\n // to the write tail). The owed count already includes `sending`, so an UNRECOVERED crash journal defers a\n // rebuild exactly as a recovered one would (recovery only lifts `sending → pending`, both counted) — the\n // deferral outcome is byte-identical to the pre-ADR-0041 recover-then-reconcile order.\n await runReconcileStage();\n }\n\n const drizzleDb = createDrizzleDatabase(pglite, buildSchema(options.registry));\n // Static index of the registry's lazy relations (ADR-0021), driving the read-path safety net.\n const lazyGuardIndex = buildLazyGuardIndex(options.registry);\n\n let sync: Awaited<ReturnType<typeof startConfiguredSync>> | null = null;\n let convergenceDriver: ConvergenceDriver | null = null;\n\n // Lifecycle guard (ADR-0041): `stop()`/`destroy()` can now be called while the background write/sync tail is\n // still in flight (React StrictMode mount/unmount is the canonical case). `disposed` lets the tail bail at\n // each stage boundary — before setting `isRunning`, before starting sync — so no shape stream starts after a\n // stop; and `stop`/`destroy` await `bootSettled` before teardown so the tail can never exec against a\n // closing PGlite.\n let disposed = false;\n // Resolves the moment `sync` is wired (and the activation buffer replayed); rejects if the boot is disposed\n // or the tail fails before wiring — so a read seam awaiting it in the pre-wire window unblocks rather than\n // hanging. On a sync-DISABLED boot it resolves at tail end (reads short-circuit before awaiting it anyway).\n let resolveSyncWired!: () => void;\n let rejectSyncWired!: (error: unknown) => void;\n const syncWired = new Promise<void>((resolve, reject) => {\n resolveSyncWired = resolve;\n rejectSyncWired = reject;\n });\n void syncWired.catch(() => undefined);\n // True once `sync` is genuinely wired — the read seams use this (not just `sync != null`) plus `syncEnabled`\n // to tell \"sync disabled\" (trivially ready) apart from \"sync pending\" (not yet ready / hydrating).\n const isSyncPending = (): boolean => syncEnabled && sync == null && !disposed;\n\n // Quiesce the background write/sync tail before a teardown (ADR-0041 BLOCKER 2). `stop()`/`destroy()` can be\n // called while the tail is still in flight (React StrictMode mount/unmount). Flag disposal so the tail bails\n // at its next stage boundary (never starting sync after this), gracefully release any read seam parked on\n // `syncWired` (it then falls through to the local-only path), then AWAIT `bootSettled` — swallowing a tail\n // failure — so the tail has fully SETTLED before teardown touches the engine/PGlite. Any sync the tail did\n // manage to start is assigned to `sync` by the time this resolves, for the caller's `sync?.unsubscribe()`.\n const quiesceTailForTeardown = async (): Promise<void> => {\n disposed = true;\n // FIX 2: a stopped client can never reach `writeReady` / `ready`, so reject them (idempotent — a race with\n // the tail's own resolve is settled first-wins; a normal stop AFTER boot is a no-op on the already-resolved\n // promises) so a parked mutation or an `await ready` / `start()` fails FAST rather than hanging past\n // teardown. `bootSettled` still RESOLVES below as teardown completion. Both are guarded by the\n // `.catch(() => undefined)` at construction, so an unconsumed rejection never leaks.\n const disposedError = new ClientDisposedError();\n rejectWriteReady(disposedError);\n rejectReady(disposedError);\n resolveSyncWired();\n await bootSettled.catch(() => undefined);\n };\n\n // The write/sync activation tail (ADR-0041 decision 3). On a NORMAL boot this runs in the BACKGROUND after\n // `localReadReady` resolves, so `createSyncClient` resolves at `localReadReady` (the Option B contract). On a\n // restore boot recovery already ran in the core, so the tail only opens the (unused) gate and settles. It\n // resolves `bootSettled` — today's full resolution point (sync START done; initial catch-up is NOT awaited,\n // that is `ready`), which the worker bridge awaits so worker-mode external timing is unchanged in stage 1.\n const runWriteAndSyncTail = async (): Promise<void> => {\n // Bail if the client was stopped before the tail even started (StrictMode mount/unmount): no write runtime\n // activation, no sync start. `bootSettled` still resolves (this returns), unblocking `stop()`'s await.\n if (disposed) return;\n // Normal boot: recovery runs here (restore already ran it in the core, before read exposure).\n if (!restoreBoot) {\n await runBootRecoveryStage();\n }\n if (disposed) return;\n // Write runtime + boot recovery complete — enqueue is safe. Stamp + resolve `writeReady` (idempotent: on a\n // restore boot it already resolved in the core alongside `localReadReady`).\n bootReportBuilder.setWriteReadyMs(performance.now() - bootReportBuilder.bootStartPerf);\n resolveWriteReady();\n\n // Do NOT set `isRunning` / start sync after a stop (BLOCKER 2): bail here so no shape stream is ever\n // started once teardown has begun.\n if (disposed) return;\n status.isRunning = true;\n\n // Open the overlap commit gate now the local store is ready (schema exec + journal recovery + reconcile\n // done): the catch-up the streams prefetched during those phases now drains in one commit train. A no-op\n // on the sequential path (`openDbGate` is the empty default there).\n openDbGate();\n\n if (syncEnabled) {\n if (earlySync) {\n // Overlap path: the shape streams have been prefetching since before schema exec; adopt the handle\n // (it resolves as soon as the streams are subscribed — catch-up drains via the gate just lifted, and\n // `onInitialSync` still gates `ready` on a fully-consistent first paint). The construction was kicked\n // off before schema exec, so time it here (concurrent-segment wall) into `phases.syncStartMs`.\n sync = await earlySync;\n bootReportBuilder.setSyncStartMs(performance.now() - earlySyncStartedAt);\n bootReportBuilder.markSyncStartDone();\n } else {\n // Sequential path (warm store / no fresh hint): the exact pre-S4 ordering — reset any rebuilt\n // subscriptions, promote durable lazy groups, then start (catch-up strictly after the local phases).\n // After a read-cache rebuild the Electric subscription bookkeeping is stale (it would believe the\n // dropped shapes are still caught up and never backfill), so reset every shape subscription to force a\n // fresh re-stream (ADR-0006).\n const resetKeys =\n versionEvent?.status === \"rebuilt\"\n ? [...(options.resetSubscriptionKeys ?? []), ...allGroupSubscriptionKeys(options.registry)]\n : options.resetSubscriptionKeys;\n await resetSubscriptionsIfRequested(pglite, resetKeys);\n // Re-check after the awaited reset: a stop during it must still abort BEFORE the network shape streams\n // start (BLOCKER 2 — cannot start sync after stop).\n if (disposed) return;\n\n status.phase = \"syncing\";\n options.onStatusChange?.(status);\n\n // Promote any `lazy + persistent` group activated on a previous boot back into the eager set\n // (ADR-0021 §2); the sync engine does no DB read of its own.\n const promotedGroups = await readActivatedLazyGroups(pglite, options.registry);\n if (disposed) return;\n\n sync = await bootReportBuilder.phase(\"syncStart\", \"boot sync start\", () =>\n startConfiguredSync(\n pglite as unknown as Parameters<typeof startConfiguredSync>[0],\n buildStartOptions(promotedGroups),\n ),\n );\n bootReportBuilder.markSyncStartDone();\n }\n // If a stop landed DURING the sync-start await, unsubscribe the just-started streams here rather than\n // leaving them running (stop read `sync` as null before this assignment), then bail.\n if (disposed) {\n sync?.unsubscribe();\n sync = null;\n return;\n }\n } else {\n status.phase = \"ready\";\n options.onStatusChange?.(status);\n // Sync disabled: there is no `onInitialSync` gate, but boot IS complete — finalize the report at the\n // same moment `ready` resolves (ADR-0034). Idempotent with the sync path's finalize.\n finalizeBootReport();\n resolveReady();\n }\n\n // ADR-0039/0041: replay every activation (read via `ensureSynced` AND write via `onOrdinaryEnqueue`)\n // buffered while `sync` was still null. Now `sync` is wired, re-issuing them through `ensureSynced` starts\n // the referenced groups — the activation is preserved, never lost across the split. Awaited so the groups\n // are STARTED before `syncWired` resolves (a `ensureSynced`/`prepareQuery` awaiter then sees them active).\n const buffered = pendingActivations;\n pendingActivations = null;\n if (sync != null && buffered && buffered.size > 0) {\n await ensureSynced([...buffered] as SyncTableName<TRegistry>[]);\n }\n // Sync is wired (or disabled and boot complete): unblock any read seam that parked on `syncWired`.\n resolveSyncWired();\n };\n\n // Restore boots offline (ADR-0035 decision 6): never stand up the convergence driver on a restore boot,\n // so an `autoSync` trigger the caller passed (even an online one) drives NO flush/reconcile passes — the\n // recovered journal is quarantined and must stay put until the app releases it and a normal boot goes\n // online. On every other boot the driver behaves exactly as before.\n if (options.autoSync && !restoreBoot) {\n convergenceDriver = createConvergenceDriver({\n client: {\n flush: () => mutationRuntime.flush(),\n reconcile: () => mutationRuntime.reconcile(),\n },\n trigger: options.autoSync,\n ...(options.onConvergencePass ? { onPass: options.onConvergencePass } : {}),\n });\n\n // Start driving convergence once the initial sync is ready, so a pass never races the first shape load.\n // stop()/destroy() halt it. `ready` is now rejectable (ADR-0041: the background tail rejects it on\n // failure), so the rejection handler keeps the driver un-started and off the unhandled-rejection path.\n void ready.then(\n () => convergenceDriver?.start(),\n () => undefined,\n );\n }\n\n // Event-driven convergence: the moment a mutation is enqueued, ask the driver to run a pass so the\n // write flushes immediately rather than waiting for the trigger's next interval tick. This is what\n // lets the interval be a rare fallback (and so run far less often). No-op when `autoSync` is off — the\n // caller drives `flush`/`reconcile` itself.\n const requestConvergence = () => convergenceDriver?.requestPass();\n // Every write-path method gates on `writeReady` (ADR-0041): a write issued the instant `localReadReady`\n // resolves awaits the write runtime + boot recovery rather than racing an unfinished boot or failing\n // opaquely. `writeReady` is already resolved on the steady-state client, so this is a settled-promise await.\n const mutate: SyncClient<TRegistry>[\"mutate\"] = {\n create: async (table, input) => {\n await writeReady;\n await mutationRuntime.create(table, input);\n requestConvergence();\n },\n update: async (table, entityKey, patch) => {\n await writeReady;\n await mutationRuntime.update(table, entityKey, patch);\n requestConvergence();\n },\n delete: async (table, entityKey) => {\n await writeReady;\n await mutationRuntime.delete(table, entityKey);\n requestConvergence();\n },\n batch: async (items) => {\n await writeReady;\n await mutationRuntime.batch(items);\n requestConvergence();\n },\n };\n\n // ─── Anonymous-activation diagnostic (ADR-0039) ────────────────────────────────────────────────\n // Per group key, whether ANY member's row filter denies (or cannot serve) an unauthenticated caller,\n // plus its member registry keys (for the warning). The registry is static and the group→member map is\n // fixed once sync is running, so it is computed once and cached.\n type GroupClaimsInfo = { claimsDependent: boolean; memberKeys: string[] };\n let groupClaimsInfoCache: Map<string, GroupClaimsInfo> | null = null;\n const groupClaimsInfoFor = (activeSync: NonNullable<typeof sync>): Map<string, GroupClaimsInfo> => {\n if (groupClaimsInfoCache != null) return groupClaimsInfoCache;\n const map = new Map<string, GroupClaimsInfo>();\n for (const key of Object.keys(options.registry) as SyncTableName<TRegistry>[]) {\n const groupKey = activeSync.groupKeyForTable(key as string);\n if (groupKey == null) continue;\n const entry = options.registry[key] as SyncTableEntry;\n const info = map.get(groupKey) ?? { claimsDependent: false, memberKeys: [] };\n info.memberKeys.push(key as string);\n if (isClaimsDependentRowFilter(entry.shape?.rowFilter)) info.claimsDependent = true;\n map.set(groupKey, info);\n }\n groupClaimsInfoCache = map;\n return map;\n };\n // One warning per group key, ever (a claims-denied group activated with no token opens an empty\n // subscription by construction, so repeated activations must not spam).\n const anonymousActivationWarned = new Set<string>();\n const warnIfAnonymousClaimsDependentActivation = (activeSync: NonNullable<typeof sync>, groupKey: string) => {\n if (anonymousActivationWarned.has(groupKey)) return;\n const info = groupClaimsInfoFor(activeSync).get(groupKey);\n if (info == null || !info.claimsDependent) return;\n // Fire-and-forget: activation never blocks or fails on the token probe (a rejected `getAuthToken`\n // is swallowed into a syncDebug line). The dedupe Set is checked+set synchronously around the warn,\n // so concurrent activations still emit at most one console.warn.\n void (async () => {\n try {\n const token = options.getAuthToken ? await options.getAuthToken() : undefined;\n if (token != null && token !== \"\") return;\n if (anonymousActivationWarned.has(groupKey)) return;\n anonymousActivationWarned.add(groupKey);\n console.warn(\n `pgxsinkit: activating the lazy group [${info.memberKeys.join(\", \")}] with no auth token — its ` +\n `row filter denies unauthenticated callers, so this opens an empty subscription. Gate the first ` +\n `query on auth (e.g. the React hooks' \\`ready\\` option) so the group activates with real claims.`,\n );\n syncDebug(\"anonymous activation of a claims-dependent lazy group\", {\n groupKey,\n tables: info.memberKeys,\n });\n } catch (error) {\n syncDebug(\"anonymous-activation auth probe failed\", { groupKey, error });\n }\n })();\n };\n\n // ─── Lazy-relation activation + the declared-safe query facade (ADR-0021) ──────────────────────\n const ensureSynced: SyncClient<TRegistry>[\"ensureSynced\"] = async (keys) => {\n if (keys.length === 0) return;\n // Sync PENDING (ADR-0041 Option B window): `sync` is not yet wired but the boot IS syncing. Record the\n // keys in the shared buffer AND await `syncWired` — the tail replays the buffer and STARTS the groups\n // before resolving `syncWired`, so on return the relations are genuinely active (the tripwire passes).\n // Distinct from sync DISABLED, which falls through to the trivially-active local-only path below.\n if (sync == null && isSyncPending()) {\n if (pendingActivations != null) for (const key of keys) pendingActivations.add(key);\n await syncWired;\n }\n const activeSync = sync;\n // Sync disabled → local-only (or the client was disposed before wiring): every relation is trivially\n // \"synced\" — reads hit whatever is local, so there is nothing to start.\n if (activeSync == null) return;\n const groupKeys = new Set<string>();\n for (const key of keys) {\n const groupKey = activeSync.groupKeyForTable(key);\n if (groupKey == null) continue;\n // Diagnostic at the activation choke point (ADR-0039): only for a group not yet started — an\n // already-active group has already paid (or dodged) this check. Write-triggered activation flows\n // through here too, so the warning fires for writes as well as reads.\n if (!activeSync.isTableStarted(key)) {\n warnIfAnonymousClaimsDependentActivation(activeSync, groupKey);\n }\n groupKeys.add(groupKey);\n }\n await Promise.all([...groupKeys].map((groupKey) => activeSync.ensureGroupStarted(groupKey)));\n };\n\n // ADR-0039: now `ensureSynced` + `lazyGuardIndex` exist, wire the ordinary-write activation. Filter the\n // reported tables to the lazy ones, then fire-and-forget `ensureSynced` — enqueue never blocks on the\n // network, and a failed start self-heals on the group's next activation (a `.catch` keeps the rejection\n // off the unhandled-rejection path).\n activateOrdinaryWriteTables = (tables) => {\n // ADR-0041: a write can land after `writeReady` but before `sync` is wired. Buffer the reported tables\n // (the tail replays them once sync is up) so the activation is never lost — this seam is fire-and-forget\n // (`onOrdinaryEnqueue` has a sync signature), so it cannot await `syncWired` the way `ensureSynced` does.\n if (sync == null) {\n if (pendingActivations != null) for (const table of tables) pendingActivations.add(table);\n return;\n }\n const lazyTables = tables.filter((table) => lazyGuardIndex.lazyKeys.has(table)) as SyncTableName<TRegistry>[];\n if (lazyTables.length === 0) return;\n void ensureSynced(lazyTables).catch((error) => {\n syncDebug(\"write-triggered lazy activation failed\", { tables: lazyTables, error });\n });\n };\n\n // Per-table catch-up completion (ADR-0032 decision 6) — the body of `client.groupReady`, hoisted so the\n // live-rows seam can also await it when building a subscription's `hydrated` promise.\n const groupReadyForTable = async (table: SyncTableName<TRegistry>): Promise<void> => {\n // Sync PENDING (ADR-0041): wait for sync to wire before its catch-up can even be evaluated, so a group\n // referenced in the pre-wire window retains its catch-up meaning rather than resolving instantly.\n if (sync == null && isSyncPending()) {\n await syncWired;\n }\n const activeSync = sync;\n // Sync disabled → local-only (or disposed before wiring): every relation is trivially \"ready\".\n if (activeSync == null) return;\n const groupKey = activeSync.groupKeyForTable(table as string);\n if (groupKey == null) return;\n await activeSync.groupReady(groupKey);\n };\n\n // Synchronous peek at a table's consistency-group catch-up (ADR-0032 decision 6) — the counterpart of\n // `groupReadyForTable`, hoisted so the live-rows seam can compute the STEADY-STATE fast path: when every\n // referenced group is already ready at subscribe time, no `hydrated` promise is built (no extra refresh).\n const isGroupReadyForTable = (table: string): boolean => {\n const activeSync = sync;\n if (activeSync == null) {\n // Sync PENDING (ADR-0041): not yet wired → the group is NOT ready (its catch-up has not run). Sync\n // DISABLED → local-only, trivially ready.\n return !isSyncPending();\n }\n const groupKey = activeSync.groupKeyForTable(table);\n // No consistency group (unknown/writeonly) → nothing to await; treat as ready.\n if (groupKey == null) return true;\n return activeSync.isGroupReady(groupKey);\n };\n\n // The referenced synced tables whose consistency group is NOT YET caught up (ADR-0021/0032): scan the\n // compiled SQL for every synced relation the query reads (∪ the explicit `use`), then keep only those\n // whose group is still catching up. Empty when sync is DISABLED or every referenced group is already ready\n // — the steady-state fast path, where the live-rows seam builds no `hydrated` promise. When sync is PENDING\n // (ADR-0041 window) every referenced synced group is not-yet-ready, so all are returned as hydrating.\n const hydratingTablesFor = (query: { sql: string; use?: readonly string[] }): string[] => {\n // Sync disabled → nothing hydrates. Sync pending → every referenced synced group is hydrating (below).\n if (sync == null && !isSyncPending()) return [];\n const referenced = new Set<string>(query.use ?? []);\n for (const key of findReferencedSyncedKeysInSql(query.sql, lazyGuardIndex)) referenced.add(key);\n return [...referenced].filter((table) => !isGroupReadyForTable(table));\n };\n\n const isSynced: SyncClient<TRegistry>[\"isSynced\"] = (key) => {\n const activeSync = sync;\n if (activeSync == null) {\n // Sync PENDING (ADR-0041): not yet wired → the relation is not started (dormant). Sync DISABLED →\n // local-only, so nothing is \"dormant\".\n return !isSyncPending();\n }\n return activeSync.isTableStarted(key);\n };\n\n // ADR-0021 §2/§4: the tables of `entry`'s consistency GROUP — a group is one subscription / one\n // transaction frontier, so reverting one member to dormant reverts them all (a table with no\n // `consistencyGroup` is its own singleton group).\n const groupTableKeysFor = (key: SyncTableName<TRegistry>, entry: SyncTableEntry): SyncTableName<TRegistry>[] => {\n const targetGroup = entry.consistencyGroup;\n return (\n targetGroup == null\n ? [key]\n : (Object.keys(options.registry) as SyncTableName<TRegistry>[]).filter(\n (candidate) => options.registry[candidate]!.consistencyGroup === targetGroup,\n )\n ) as SyncTableName<TRegistry>[];\n };\n\n // The shared group-teardown body of {@link desync} and {@link discardEphemeral} (ADR-0021 §2/§4). Both\n // revert a lazy relation's whole consistency group to dormant: refuse if any writable member owes\n // unsettled writes, stop the group stream, clear the persisted lazy activation, delete the persisted\n // Electric subscription (so re-activation re-streams from scratch), then clean-truncate every member's\n // local cluster. `label` names the calling primitive in the owed-writes refusal so each keeps its own\n // diagnostic (desync stays byte-identical). Callers apply their own lazy/retention gates BEFORE this.\n const tearDownLazyGroup = async (key: SyncTableName<TRegistry>, entry: SyncTableEntry, label: string) => {\n const groupTableKeys = groupTableKeysFor(key, entry);\n\n // Refuse if ANY writable member owes the server unsent/unsettled writes: the truncate clears the\n // journal, so dropping un-acked local intent would be silent data loss. Flush (or discard) those first.\n let owed = 0;\n for (const member of groupTableKeys) {\n if (options.registry[member]!.mode === \"readonly\") continue;\n const stats = await mutationRuntime.readMutationStats(member);\n owed +=\n stats.pendingCount + stats.sendingCount + stats.failedCount + stats.quarantinedCount + stats.conflictedCount;\n }\n if (owed > 0) {\n throw new Error(\n `${label}('${String(key)}') refused: ${owed} unsettled mutation(s) in the group's local journal. Flush or discard them first.`,\n );\n }\n\n const activeSync = sync;\n // The group key IS the Electric subscription key (`consistencyGroup ?? shapeKey`); fall back to the\n // registry derivation when sync is disabled.\n const groupKey = activeSync?.groupKeyForTable(key) ?? entry.consistencyGroup ?? entry.shape?.shapeKey;\n // Stop the stream BEFORE truncating so a live shape can't re-populate the rows we just cleared, and\n // revert the durable promotion (a no-op for ephemeral, which never persisted a flag) so the next boot\n // holds the relation dormant again.\n if (activeSync != null && groupKey != null) activeSync.stopGroup(groupKey);\n if (groupKey != null) await clearLazyGroupActivation(pglite, options.registry, groupKey);\n // CRITICAL: delete the group's persisted Electric subscription so a later re-activation re-streams the\n // shape from scratch. Without this it would resume from the old cursor and never re-send the rows we\n // truncate below — leaving the relation permanently missing its pre-desync data.\n if (groupKey != null) await resetSubscriptionsIfRequested(pglite, [groupKey]);\n // Clean-truncate every member's local cluster.\n for (const member of groupTableKeys) {\n await pglite.exec(buildDesyncTableSql(options.registry, member as string));\n }\n };\n\n const desync: SyncClient<TRegistry>[\"desync\"] = async (key) => {\n // ADR-0041 (SHOULD-FIX 5): a destructive group-teardown reads the journal and stops a group's stream, so\n // it must not race the background tail's recovery updates / subscription reset / sync start. Gate on\n // `bootSettled` — these are rare admin ops, so the stronger gate is correct (a tail failure rejects here).\n await bootSettled;\n const entry = options.registry[key];\n if (entry == null) throw new Error(`desync: unknown table ${String(key)}`);\n if (entry.subscription !== \"lazy\") {\n throw new Error(\n `desync('${String(key)}') refused: only a lazy relation can be desynced — an eager relation is always-on and would immediately re-sync.`,\n );\n }\n await tearDownLazyGroup(key, entry, \"desync\");\n };\n\n const discardEphemeral: SyncClient<TRegistry>[\"discardEphemeral\"] = async (key) => {\n // ADR-0041 (SHOULD-FIX 5): gate the destructive teardown on `bootSettled` so it never races the tail.\n await bootSettled;\n return (\n // Run inside the SAME lifecycle slot the exports use (ADR-0035 decision 4): discardEphemeral\n // clean-truncates an ephemeral group's local cache, so an export must never interleave it (nor it an\n // export) — the slot's typed LifecycleBusyError fires in both directions. The existing lazy/ephemeral\n // gates below stay EXACTLY as they were, now inside the slot run. (`desync` is deliberately NOT slotted:\n // only the ADR-0035-named destructive ops — destroy/discardEphemeral/dropReadCache — serialise here.)\n lifecycleSlot.run(\"discardEphemeral\", async () => {\n const entry = options.registry[key];\n if (entry == null) throw new Error(`discardEphemeral: unknown table ${String(key)}`);\n // Keep the lazy gate desync has: eager+ephemeral is NOT forbidden by the type system (retention and\n // subscription are independent scalars on the entry — see contracts config.ts / registry.ts), and an\n // eager relation would immediately re-stream, so the same refusal applies here.\n if (entry.subscription !== \"lazy\") {\n throw new Error(\n `discardEphemeral('${String(key)}') refused: only a lazy relation can be discarded — an eager relation is always-on and would immediately re-sync.`,\n );\n }\n // STRICTER gate than desync: every member of the consistency group must be ephemeral. Retention is read\n // as `entry.retention ?? \"persistent\"` (absent → persistent, matching validateRegistryLifecycleGroups and\n // the schema generator); a read PROJECTION surfaces its declared retention on the same `retention` field\n // (withRetention/asEphemeral/defineReadProjection all set it), so this one read covers tables and\n // projections alike. Refuse (naming the offender) if any member is persistent — discardEphemeral is the\n // multi-tab-safe primitive for per-delivery-session windows, and truncating a persistent member's cache\n // would drop durable local data; use desync for a persistent lazy relation.\n for (const member of groupTableKeysFor(key, entry)) {\n if ((options.registry[member]!.retention ?? \"persistent\") !== \"ephemeral\") {\n throw new Error(\n `discardEphemeral('${String(key)}') refused: group member '${String(member)}' is persistent — ` +\n `discardEphemeral only drops an ephemeral relation's local rows. Use desync for a persistent lazy relation.`,\n );\n }\n }\n await tearDownLazyGroup(key, entry, \"discardEphemeral\");\n })\n );\n };\n\n const transaction: SyncClient<TRegistry>[\"transaction\"] = async ({ mode }, run) => {\n // Write-path gate (ADR-0041): the atomic unit enqueues + (pessimistic) flushes, so await `writeReady`.\n await writeReady;\n // The block's table handles only COLLECT mutations; the whole set is enqueued atomically as one unit.\n const collected: MutationBatchItem<TRegistry>[] = [];\n const txTables = Object.fromEntries(\n Object.keys(options.registry).map((tableKey) => [\n tableKey,\n {\n create: (input: unknown) => {\n collected.push({ table: tableKey, kind: \"create\", input } as MutationBatchItem<TRegistry>);\n },\n update: (entityKey: Record<string, string>, patch: unknown) => {\n collected.push({ table: tableKey, kind: \"update\", entityKey, patch } as MutationBatchItem<TRegistry>);\n },\n updateBlind: (entityKey: Record<string, string>, patch: unknown) => {\n collected.push({\n table: tableKey,\n kind: \"update\",\n entityKey,\n patch,\n blind: true,\n } as MutationBatchItem<TRegistry>);\n },\n delete: (entityKey: Record<string, string>) => {\n collected.push({ table: tableKey, kind: \"delete\", entityKey } as MutationBatchItem<TRegistry>);\n },\n },\n ]),\n ) as SyncTransaction<TRegistry>[\"tables\"];\n\n await run({ tables: txTables });\n\n if (collected.length === 0) {\n return { acks: [] };\n }\n\n const unit: WriteUnit = { id: globalThis.crypto.randomUUID(), mode };\n await mutationRuntime.batch(collected, unit);\n\n if (mode === \"optimistic\") {\n // An atomic batch enqueue; the background convergence loop flushes it (no foreground answer).\n void mutationRuntime.flush();\n return { acks: [] };\n }\n\n // Pessimistic: flush-route this unit to the authoritative endpoint and await the per-mutation result.\n return await mutationRuntime.flushUnit(unit.id);\n };\n\n const prepareQuery: SyncClient<TRegistry>[\"prepareQuery\"] = async ({ sql, use }) => {\n // Scan the compiled SQL for the lazy relations it reads (∪ the explicit `use`) and activate them.\n // The compiled SQL is ground truth and Drizzle quotes every relation, so any reference — FROM, JOIN,\n // subquery, WHERE — is caught; over-matching is bounded and harmless (one spurious persistent\n // subscription at worst, never a wrong result). Detection and activation are one step (ADR-0021).\n const toActivate = new Set<string>(use ?? []);\n for (const key of findReferencedLazyKeysInSql(sql, lazyGuardIndex)) toActivate.add(key);\n const lazyTables = [...toActivate] as SyncTableName<TRegistry>[];\n await ensureSynced(lazyTables);\n // Backstop: if a referenced lazy relation is somehow still not active (a failed start, or no group),\n // throw rather than let the query read empty/stale. In the normal path everything scanned was just\n // activated, so this passes.\n assertLazyRefsActivated({\n sql,\n index: lazyGuardIndex,\n isActive: (key) => isSynced(key as SyncTableName<TRegistry>),\n });\n // Activated = streams started, NOT caught up. Hand back the keys so consumers (the React hooks'\n // `hydrating`) can await `groupReady` per key without blocking the read on the network.\n return { lazyTables };\n };\n\n const runGuardedQuery = async <TRows extends readonly unknown[]>(\n build: GuardedQueryFn<TRegistry, TRows>,\n use?: readonly SyncTableName<TRegistry>[],\n ): Promise<TRows> => {\n // Read gate (ADR-0041): a query must not run against a store whose local-read core has not finished. On\n // the in-process client this is a settled-promise await (the client is handed out at `localReadReady`),\n // but it is cheap and keeps the read path safe if a caller retained a query builder across the boundary.\n await localReadReady;\n const builder = build(client);\n await prepareQuery({ sql: builder.toSQL().sql, ...(use ? { use } : {}) });\n return builder;\n };\n\n // The live-query manager (ADR-0040) — the SAME module the worker uses (decision 6), so the in-process\n // client gets one lifecycle contract: dedup of identical concurrent subscriptions within this client,\n // bounded zero-subscriber keep-alive (`options.liveQueries`), and awaited teardown (decision 1 — `dispose()`\n // settles every un-awaited unsubscribe before `pglite.close()`, subsuming the old pending-teardowns set).\n // It cannot dedup across tabs (that is the worker's job) but keeps the contract identical across both forms.\n const liveManager: LiveQueryManager = createLiveQueryManager({\n live: pglite.live,\n ...(options.liveQueries ? { policy: options.liveQueries } : {}),\n });\n\n const client: SyncClient<TRegistry> = {\n drizzle: drizzleDb,\n pglite,\n views: buildViews(options.registry),\n tables: Object.fromEntries(\n Object.keys(options.registry).map((tableKey) => [\n tableKey,\n {\n key: tableKey,\n mode: options.registry[tableKey as SyncTableName<TRegistry>]!.mode,\n create: (input: SyncTableCreateInput<TRegistry, typeof tableKey>) =>\n mutate.create(tableKey as SyncTableName<TRegistry>, input),\n update: (entityKey: Record<string, string>, patch: SyncTableUpdateInput<TRegistry, typeof tableKey>) =>\n mutate.update(tableKey as SyncTableName<TRegistry>, entityKey, patch),\n delete: (entityKey: Record<string, string>) => mutate.delete(tableKey as SyncTableName<TRegistry>, entityKey),\n },\n ]),\n ) as SyncClient<TRegistry>[\"tables\"],\n localReadReady,\n writeReady,\n bootSettled,\n ready,\n status,\n start: async () => {\n await ready;\n },\n stop: async () => {\n // ADR-0041: quiesce the background boot tail FIRST — flag disposal (so it never starts sync after this)\n // and await its settlement — so no shape stream is left running and nothing execs against the closing\n // PGlite. Any sync the tail started before disposal is now in `sync` for the unsubscribe below.\n await quiesceTailForTeardown();\n // Await any in-flight convergence pass before closing PGlite, so a pass never queries a\n // closed handle.\n await convergenceDriver?.stop();\n sync?.unsubscribe();\n status.isRunning = false;\n options.onStatusChange?.(status);\n // Tear the engine down (abort every shape stream) immediately before closing the DB — the exact\n // point PGlite's own close used to invoke the former extension's close hook (ADR-0032 S1). Order\n // preserved: convergence stop → sync unsubscribe → status → engine close → pglite close.\n await engine.close();\n // Dispose the live-query manager before closing PGlite (ADR-0040 decisions 1 & 6): it cancels any\n // keep-alive timers and awaits every in-flight live `unsubscribe()`, so none races `pglite.close()`.\n await liveManager.dispose();\n await pglite.close();\n },\n destroy: (destroyOptions) =>\n // Run inside the SAME lifecycle slot the exports use (ADR-0035 decision 4), so a destructive wipe can\n // never interleave a running export (nor an export interleave this wipe) — the slot's typed\n // LifecycleBusyError fires in both directions. The refuse-if-owed guard stays EXACTLY as it was, now\n // inside the slot run.\n lifecycleSlot.run(\"destroy\", async () => {\n // ADR-0041: quiesce the background boot tail BEFORE the owed-mutations read and the wipe, so neither\n // races the tail's recovery journal updates / sync start (BLOCKER 2). After this the tail has settled.\n await quiesceTailForTeardown();\n if (!destroyOptions?.force) {\n const stats = await mutationRuntime.readMutationStats();\n const owed =\n stats.pendingCount +\n stats.sendingCount +\n stats.failedCount +\n stats.quarantinedCount +\n stats.conflictedCount;\n\n if (owed > 0) {\n throw new Error(\n `destroy() refused: ${owed} mutation(s) still owed to the server. Flush them first or call destroy({ force: true }).`,\n );\n }\n }\n\n // Drain any in-flight convergence pass before wiping, so a pass never writes into a store\n // being torn down underneath it.\n await convergenceDriver?.stop();\n sync?.unsubscribe();\n status.isRunning = false;\n options.onStatusChange?.(status);\n await pglite.exec(buildWipeLocalStoreSql(options.registry));\n // Same teardown ordering as `stop`: abort the engine's streams before closing the DB, the moment\n // the former extension close hook fired during `pglite.close()` (ADR-0032 S1).\n await engine.close();\n // Dispose the live-query manager before closing PGlite — same close-vs-unsubscribe hang guard as\n // `stop()` (ADR-0040 decisions 1 & 6).\n await liveManager.dispose();\n await pglite.close();\n }),\n dropReadCache: async () => {\n // ADR-0041 (SHOULD-FIX 5): the drop+rebuild resets subscriptions and rewrites the read cache, so it must\n // not race the background tail's sync start / subscription reset. Gate on `bootSettled` first.\n await bootSettled;\n return (\n // Under the SAME lifecycle slot as the exports (ADR-0035 decision 4). WHY dropReadCache is slotted and\n // not just destroy/discardEphemeral: it DROPS and rebuilds the synced read-cache tables, so an export\n // racing it would capture a half-rebuilt cache in the artefact (some tables dropped, some re-created,\n // none re-streamed yet). The slot makes the drop+rebuild atomic against any concurrent export.\n lifecycleSlot.run(\"dropReadCache\", async () => {\n await pglite.exec(buildDropReadCacheSql(options.registry));\n await pglite.exec(generateLocalSchemaSql(options.registry));\n // A full durable-schema exec re-stamps the durable-schema fingerprint (slice 3): exec and stamp\n // travel together so the next boot's fast path can trust the rebuilt cache's fingerprint.\n await writeStoredLocalSchemaFingerprint(\n pglite,\n options.registry,\n computeLocalSchemaFingerprint(options.registry),\n );\n // Reset the Electric subscriptions so the rebuilt synced tables re-stream from scratch\n // rather than the bookkeeping believing they are already caught up (ADR-0006).\n await resetSubscriptionsIfRequested(pglite, allGroupSubscriptionKeys(options.registry));\n })\n );\n },\n // Write-path methods gate on `writeReady` (ADR-0041): each enqueues, drains, or mutates a journal, so\n // none may run before the write runtime + boot recovery have completed. `writeReady` is already resolved\n // on the steady-state client, so these are settled-promise awaits.\n flush: async (table) => {\n await writeReady;\n return mutationRuntime.flush(table);\n },\n reconcile: async (table) => {\n await writeReady;\n return mutationRuntime.reconcile(table);\n },\n retryFailed: async (table) => {\n await writeReady;\n return mutationRuntime.retryFailed(table);\n },\n recoverSending: async (table) => {\n await writeReady;\n return mutationRuntime.recoverSending(table);\n },\n // NIT 7 (ADR-0041): these are READ diagnostics, deliberately UNGATED so they work at `localReadReady`. In\n // the narrow pre-`writeReady` window they may observe pre-recovery `sending` rows (boot recovery lifts\n // `sending → pending`), i.e. the honest current journal state before recovery has run — not a bug.\n readMutationDetails: (table) => mutationRuntime.readMutationDetails(table),\n mutate,\n discardConflict: async (table, entityKey) => {\n await writeReady;\n return mutationRuntime.discardConflict(table, entityKey);\n },\n discardQuarantined: async (table, entityKey) => {\n await writeReady;\n return mutationRuntime.discardQuarantined(table, entityKey);\n },\n // See the `readMutationDetails` note: a read, ungated, so pre-`writeReady` it may show pre-recovery counts.\n diagnostics: async (table) => ({\n mutation: await mutationRuntime.readMutationStats(table),\n }),\n // The registry-wide mutation-status API (slice 4). Assigned just below the object so it can close over\n // this client's own `subscribeLiveRows` + `pglite.query` seams — the SAME factory the worker facade uses.\n mutations: undefined as unknown as MutationsApi<TRegistry>,\n // Inspection surface (see the interface doc): straight through to the underlying store, no journal /\n // overlay involvement. The worker facade runs the identical call inside the worker's own client.\n rawQuery: (sql, params, options) => pglite.query(sql, params as unknown[] | undefined, options),\n rawExec: (sql, options) => pglite.exec(sql, options),\n query: (build) => runGuardedQuery(build),\n queryRow: async (build) => {\n const rows = await runGuardedQuery(build);\n return rows[0] ?? null;\n },\n queryRaw: (spec) => runGuardedQuery(spec.build, spec.use),\n queryRawRow: async (spec) => {\n const rows = await runGuardedQuery(spec.build, spec.use);\n return rows[0] ?? null;\n },\n ensureSynced,\n isSynced,\n desync,\n discardEphemeral,\n prepareQuery,\n transaction,\n groupReady: groupReadyForTable,\n hydratingTablesFor,\n // The live-rows seam, now delegated to the shared `LiveQueryManager` (ADR-0040 decision 6) — identical\n // contract to the pre-adoption inline `pglite.live.query` seam, but with dedup of identical concurrent\n // subscriptions, keep-alive (`keepAliveMs`), and awaited teardown for free. The manager delivers a diff\n // stream (`deliverInitial` + `deliverDiff`); we fold it back into FULL ordered row arrays with a\n // per-subscription `LiveRowsMaterializer` (the SAME piece `attachSyncClient` uses tab-side), so the\n // public `onRows(rows)` / `initialRows` contract is byte-unchanged — and unchanged rows now keep `===`\n // identity across diffs (a bonus the raw `results.rows` path did not give). Keyless (no `pkColumns`)\n // exactly as the inline seam was: PGlite's `live.query` + the manager's value-identity diff.\n subscribeLiveRows: async ({ sql, params, fields, use, keepAliveMs }, onRows) => {\n // Read gate (ADR-0041): do not register a live query before the local-read core has finished (a\n // settled-promise await on the steady-state client — cheap, and stage-2-safe).\n await localReadReady;\n // Render the query safe to materialise: a JOIN with same-named columns fails `live.query`'s\n // temp-view creation (`column \"title\" specified more than once`) unless every output column has a\n // unique alias. No `fields` → SQL unchanged (backward-compatible name-keyed rows). The wrap stays\n // caller-side (ADR-0040 decision 3): the manager receives POST-WRAP SQL.\n const materialSql = wrapLiveQueryForMaterialization(sql, fields);\n // Keyless materializer (matches the inline seam, which never passed pkColumns): initial rows seed it;\n // each diff folds into a fresh ordered array whose unchanged rows keep their object identity.\n const materializer = new LiveRowsMaterializer<Record<string, unknown>>(undefined);\n const subscription = await liveManager.subscribe(\n { materialSql, params: params as unknown[] },\n {\n // The initial snapshot is returned via `initialRows`, NOT `onRows` (which fires on CHANGES only) —\n // so `deliverInitial` just seeds the materializer; `initialRows` is read from it below.\n deliverInitial: (rows) => {\n materializer.seed(rows);\n },\n deliverDiff: (diff) => {\n onRows(materializer.apply(diff) as never);\n },\n },\n keepAliveMs != null ? { keepAliveMs } : undefined,\n );\n // Seeded synchronously by `deliverInitial` during `subscribe` above.\n const initialRows = materializer.current();\n let unsubscribed = false;\n // The query's lazy relations (guard scan ∪ `use`; the caller's `prepareQuery` already activated them)\n // are surfaced as `lazyTables` for observability — the relations held out of the eager boot set.\n const lazySet = new Set<string>(use ?? []);\n for (const key of findReferencedLazyKeysInSql(sql, lazyGuardIndex)) lazySet.add(key);\n const lazyTables = [...lazySet];\n // Hydration spans EVERY referenced consistency group (eager AND lazy): the tables whose group is not\n // yet caught up at subscribe time. Empty (steady state / sync disabled) → NO `hydrated` promise, so a\n // post-boot subscription pays no extra refresh (exactly today's eager-only behaviour). Otherwise build\n // `hydrated` with rows-before-signal ordering: await the pending groups' catch-up, refresh the live\n // query (the manager's coalesced refresh; its listener delivers the caught-up rows as a diff → onRows,\n // synchronously inside the refresh), THEN resolve — so a UI flipping out of its loading state on this\n // promise can never flash a false empty.\n const hydratingTables = hydratingTablesFor({ sql, ...(use ? { use } : {}) });\n const hydrated =\n hydratingTables.length > 0\n ? Promise.all(hydratingTables.map((table) => groupReadyForTable(table as SyncTableName<TRegistry>)))\n .then(async () => {\n if (!unsubscribed) await subscription.refresh();\n })\n .catch(() => undefined)\n : undefined;\n return {\n initialRows: initialRows as never,\n unsubscribe: () => {\n unsubscribed = true;\n // Non-blocking for the caller; the manager retains the teardown promise so `dispose()` (called by\n // `stop()`/`destroy()`) awaits it before closing PGlite (ADR-0040 decision 1 — the close race).\n void subscription.unsubscribe();\n },\n ...(lazyTables.length > 0 ? { lazyTables } : {}),\n ...(hydrated ? { hydrated } : {}),\n };\n },\n // Boot observability (ADR-0034): the finalized report (null before initial sync completes / after an\n // early stop). Resolves from the builder-owned ref this client holds — no round trip in-process.\n bootReport: async () => finalizedBootReport,\n // Live-query diagnostics (ADR-0040 decisions 5 & 6): the in-process client now owns a real manager, so\n // this returns its live snapshot (digests + counts/timings only — never SQL/params/rows).\n liveQueryDiagnostics: async () => liveManager.snapshot(),\n exportStore: async (exportOptions) => {\n // Await engine-ready first (ADR-0035: exports wait out a boot rather than rejecting during it), THEN\n // take the lifecycle slot — a concurrent export/lifecycle op is refused with a typed busy error.\n await ready;\n // Name the backup from the configured plain store PATH (ADR-0036), never the PGlite instance's\n // resolved dataDir URL — a resolved URL is internal plumbing and must not leak into an artefact name\n // as something to imitate. The store id is the path's last segment (see `deriveStoreId`).\n return lifecycleSlot.run(\"exportStore\", () =>\n performStoreExport(\n {\n pglite,\n readMutationStats: () => mutationRuntime.readMutationStats(),\n ...(options.storePath != null ? { storePath: options.storePath } : {}),\n },\n exportOptions,\n ),\n );\n },\n exportDiagnostics: async (exportOptions) => {\n // Same lifecycle discipline as `exportStore` (ADR-0035): await engine-ready first (wait out a boot\n // rather than reject during it), THEN take the single slot so a concurrent export/lifecycle op is\n // refused with a typed busy error. The diagnostic dump runs the live datadir dump on `pglite`, then\n // clones it in memory — the live engine every reference here holds is never closed (the addendum's\n // whole reason for the throwaway clone over the abandoned suspend/reopen seam).\n await ready;\n return lifecycleSlot.run(\"exportDiagnostics\", () =>\n performDiagnosticExport(\n {\n pglite,\n readMutationStats: () => mutationRuntime.readMutationStats(),\n ...(options.storePath != null ? { storePath: options.storePath } : {}),\n },\n exportOptions,\n ),\n );\n },\n exportData: async (exportOptions) => {\n // Same lifecycle discipline (ADR-0035): await engine-ready first (wait out a boot rather than reject),\n // THEN take the single slot. The DRAIN runs inside the slot (the caller-side placement decision 3\n // makes): flush needs the running engine and is not lifecycle-exclusive, but the artefact must be\n // taken right after the drain, so export owns the store's lifecycle for the whole drain+dump. The\n // `-t` allowlist + enum header are resolved from the registry through the SAME projection the DDL\n // generator uses — never re-derived by string convention.\n await ready;\n return lifecycleSlot.run(\"exportData\", () =>\n performDataExport(\n {\n pglite,\n readMutationStats: () => mutationRuntime.readMutationStats(),\n flush: () => mutationRuntime.flush(),\n syncedTableNames: collectDataExportSyncedTableNames(options.registry),\n enumHeaderSql: buildDataExportEnumHeaderSql(options.registry),\n cloneCleanupSql: buildDataExportCloneCleanupSql(options.registry),\n ...(options.storePath != null ? { storePath: options.storePath } : {}),\n },\n exportOptions,\n ),\n );\n },\n };\n\n // Wire the mutation-status API over this client's shared seams (slice 4): its live-rows seam (over\n // `pglite.live` via the manager) and its one-shot `pglite.query`. The worker facade wires the SAME factory\n // over the bridge, so `client.mutations` behaves identically in both modes.\n client.mutations = createMutationsApi({\n registry: options.registry,\n subscribeLiveRows: client.subscribeLiveRows,\n query: (sql, params) => pglite.query<Record<string, unknown>>(sql, params),\n });\n\n // ─── Local-read core complete → resolve `localReadReady`, then run the write/sync tail in the background ──\n // (ADR-0041 Option B.) The durable schema is compatible, store-version reconcile has run, and the drizzle\n // read facade + client are built — cached reads are safe now, with ZERO network. Stamp + resolve\n // `localReadReady`; on a restore boot `writeReady` coincides (recovery + quarantine already ran in the core,\n // before this read exposure — the ADR-0041 invariant). This function then RESOLVES at `localReadReady`.\n bootReportBuilder.setLocalReadReadyMs(performance.now() - bootReportBuilder.bootStartPerf);\n resolveLocalReadReady();\n if (restoreBoot) {\n bootReportBuilder.setWriteReadyMs(performance.now() - bootReportBuilder.bootStartPerf);\n resolveWriteReady();\n }\n\n // Guard the downstream stages so a tail failure on an UNCONSUMED stage (e.g. `bootSettled` in-process, where\n // only the worker awaits it) never surfaces as an unhandled rejection — a real awaiter still observes it.\n void writeReady.catch(() => undefined);\n void bootSettled.catch(() => undefined);\n void ready.catch(() => undefined);\n\n // Kick the write/sync tail (background). Its completion is today's full resolution point → `bootSettled`. A\n // tail failure lands AFTER `localReadReady` resolved, so it can no longer reject this function's returned\n // promise (as a pre-ADR-0041 boot failure would); surface it on every still-pending downstream stage instead\n // so their awaiters (a gated write, `ready`, the worker's `bootSettled`) fail loudly rather than hang.\n void runWriteAndSyncTail().then(\n () => {\n resolveBootSettled();\n // Belt-and-braces: if a `disposed` bail returned before the replay, drop the buffer so it cannot leak or\n // keep collecting (steady-state activations go straight through `ensureSynced` once `sync` is wired).\n pendingActivations = null;\n resolveSyncWired();\n },\n (error: unknown) => {\n syncDebug(\"boot write/sync tail failed after localReadReady\", { error });\n // SHOULD-FIX 4: the tail failed at/before sync start, so buffered activations can never be replayed —\n // null the buffer (bounded, no unbounded growth) and name the loss on the debug rail.\n if (pendingActivations != null && pendingActivations.size > 0) {\n syncDebug(\"boot tail failure dropped buffered activations\", { tables: [...pendingActivations] });\n }\n pendingActivations = null;\n // NIT 8: surface a signal beyond the stage rejections — move the runtime to `degraded` so a consumer\n // watching `status`/`onStatusChange` sees the boot failed, not just an awaiter of a stage promise.\n status.phase = \"degraded\";\n status.lastError = error instanceof Error ? error.message : String(error);\n options.onStatusChange?.(status);\n rejectWriteReady(error);\n rejectReady(error);\n rejectBootSettled(error);\n // Unblock any read seam parked on `syncWired` — it will see `sync == null` and fall back to local-only.\n rejectSyncWired(error);\n },\n );\n\n return client;\n}\n\n/**\n * Every persisted subscription key declared by the registry — one per consistency group (ADR-0009\n * decision 2), not per table. Grouped tables share a subscription-state row keyed by their group;\n * ungrouped tables are singleton groups keyed by their own `shapeKey`. Deduped, since several tables\n * collapse onto one group key.\n */\nfunction allGroupSubscriptionKeys<TRegistry extends SyncTableRegistry>(registry: TRegistry): string[] {\n const keys = Object.values(registry)\n .filter((entry) => typeof entry.shape?.shapeKey === \"string\" && entry.shape.shapeKey.length > 0)\n .map((entry) => entry.consistencyGroup ?? entry.shape!.shapeKey);\n return [...new Set(keys)];\n}\n\nasync function resetSubscriptionsIfRequested(pglite: ClientPGlite, keys: string[] | undefined) {\n if (!keys || keys.length === 0) {\n return;\n }\n\n const uniqueKeys = [...new Set(keys.map((key) => key.trim()).filter((key) => key.length > 0))];\n\n if (uniqueKeys.length === 0) {\n return;\n }\n\n await pglite.electric.initMetadataTables();\n await Promise.all(uniqueKeys.map((key) => pglite.electric.deleteSubscription(key)));\n}\n\nfunction createDrizzleDatabase<TRegistry extends SyncTableRegistry>(\n client: ClientPGlite,\n schema: RegistryTables<TRegistry>,\n) {\n const relations = defineRelations(schema) as RegistryRelations<TRegistry>;\n\n const createDatabase = drizzle as unknown as (config: {\n client: ClientPGlite;\n relations: RegistryRelations<TRegistry>;\n }) => PgliteDatabase<RegistryRelations<TRegistry>>;\n\n return createDatabase({ client, relations });\n}\n\nfunction buildSchema<TRegistry extends SyncTableRegistry>(registry: TRegistry) {\n return Object.fromEntries(\n Object.entries(registry).map(([key, entry]) => [key, entry.table]),\n ) as RegistryTables<TRegistry>;\n}\n\nfunction buildViews<TRegistry extends SyncTableRegistry>(registry: TRegistry) {\n return Object.fromEntries(\n Object.entries(registry).flatMap(([key, entry]) => (entry.view != null ? [[key, entry.view]] : [])),\n ) as RegistryViews<TRegistry>;\n}\n\n/**\n * The tab-side READ handles a worker-attached client exposes (ADR-0032 S2): a build-only Drizzle instance\n * plus the registry views. On the attach client, Drizzle is used only to COMPILE queries to SQL\n * (`.toSQL()`) on the tab — execution happens in the worker via the live-rows bridge / RPC — so it is\n * constructed over a stub client that is never invoked (`construct` stores the client without calling it).\n * The same builders `createSyncClient` uses, so a query built on either client compiles identically.\n */\nexport function buildRegistryReadHandles<TRegistry extends SyncTableRegistry>(\n registry: TRegistry,\n): { drizzle: PgliteDatabase<RegistryRelations<TRegistry>>; views: RegistryViews<TRegistry> } {\n const stubClient = {} as ClientPGlite;\n return {\n drizzle: createDrizzleDatabase(stubClient, buildSchema(registry)),\n views: buildViews(registry),\n };\n}\n\nfunction buildSyncConfigFromRegistry<TRegistry extends SyncTableRegistry>(\n registry: TRegistry,\n electricUrl: string,\n): SyncConfigInput {\n return {\n electricUrl,\n localSchema: getSyncRegistrySchema(registry),\n tables: Object.fromEntries(Object.entries(registry).map(([key, entry]) => [key, buildSyncTableInput(entry, key)])),\n };\n}\n\nfunction buildSyncTableInput(entry: SyncTableEntry, tableKey: string) {\n const clientProjection = getClientProjection(entry, tableKey);\n\n return {\n name: tableKey,\n mode: entry.mode,\n primaryKey: entry.primaryKey,\n ...(entry.shape !== undefined ? { shape: entry.shape } : {}),\n clientProjection,\n // The read-path apply ladder (strategy + json casts) is resolved by the engine directly from the\n // registry entry via `resolveApplyTarget` (ADR-0029 D1/D2) — `deriveSyncColumnTypes` /\n // `classifyTableApplyStrategy` on the model, never carried through this config surface.\n // Carry the consistency group (ADR-0009 decision 2) so the sync starter buckets grouped tables\n // onto one MultiShapeStream; absent → singleton group.\n ...(entry.consistencyGroup ? { consistencyGroup: entry.consistencyGroup } : {}),\n // Carry the lifecycle axes (ADR-0021) so the sync starter can hold lazy groups out of the eager\n // boot set and provision ephemeral clusters as TEMP; absent → eager/persistent (today's path).\n ...(entry.subscription ? { subscription: entry.subscription } : {}),\n ...(entry.retention ? { retention: entry.retention } : {}),\n };\n}\n\nfunction getClientProjection(entry: SyncTableEntry, tableKey: string) {\n if (!entry.clientProjection) {\n throw new Error(`clientProjection is required for client table ${tableKey}`);\n }\n\n return entry.clientProjection;\n}\n",
|
|
6
6
|
"// Opt-in runtime instrumentation for diagnosing convergence / sync latency in a live app (e.g. the\n// board demo). It is OFF by default and adds nothing to a normal run: every call early-returns unless\n// `globalThis.__pgxsinkitDebug` is truthy, so it is safe to leave the call sites in shipping code.\n//\n// Enable it from the browser console (`globalThis.__pgxsinkitDebug = true`) — or set it before the\n// client boots; the board's dev build turns it on automatically. Each line is stamped with a monotonic\n// millisecond clock so the gaps between phases (enqueue → flush → server ack → Electric echo →\n// overlay clear → live-query render) can be read straight off the console.\n\ninterface DebugGlobal {\n __pgxsinkitDebug?: boolean;\n}\n\nconst isEnabled = (): boolean => (globalThis as DebugGlobal).__pgxsinkitDebug === true;\n\nconst now = (): number => (typeof performance !== \"undefined\" ? performance.now() : Date.now());\n\n/**\n * A sink that receives every `syncDebug` line (event, the worker's monotonic stamp, optional data),\n * INDEPENDENT of the local `__pgxsinkitDebug` console gate. This is the seam `defineSyncWorker` installs\n * to forward the debug rail to tabs (ADR-0032 decision 7): a SharedWorker's own console is invisible\n * (`chrome://inspect`), so lines must cross the bridge and each tab re-prints them gated on ITS OWN flag.\n * Unset by default → no forwarding and zero cost on the in-process path.\n */\ntype SyncDebugSink = (event: string, stamp: number, data?: Record<string, unknown>) => void;\nlet syncDebugSink: SyncDebugSink | undefined;\n\n/** Install (or clear, with `undefined`) the debug-rail sink. Idempotent; `defineSyncWorker` owns it. */\nexport function setSyncDebugSink(sink: SyncDebugSink | undefined): void {\n syncDebugSink = sink;\n}\n\n/**\n * Log one timestamped event. Prints to the console only when `globalThis.__pgxsinkitDebug` is on, but ALSO\n * feeds any installed {@link setSyncDebugSink} sink (so the worker can forward the rail to tabs even when the\n * worker's own console gate is off). No sink AND not enabled → an early return, so the off-path pays nothing.\n */\nexport function syncDebug(event: string, data?: Record<string, unknown>): void {\n const enabled = isEnabled();\n if (!enabled && syncDebugSink === undefined) return;\n const stamp = now();\n if (enabled) {\n const prefix = `[pgxsinkit ${stamp.toFixed(0)}ms]`;\n if (data) {\n console.debug(`${prefix} ${event}`, data);\n } else {\n console.debug(`${prefix} ${event}`);\n }\n }\n syncDebugSink?.(event, stamp, data);\n}\n\n/** The request URL of a `fetch` first argument, in any of its accepted forms; undefined if unreadable. */\nfunction fetchInputUrl(input: Parameters<typeof fetch>[0]): string | undefined {\n if (typeof input === \"string\") return input;\n if (input instanceof URL) return input.toString();\n if (typeof input === \"object\" && input !== null && \"url\" in input) {\n return (input as { url: string }).url;\n }\n return undefined;\n}\n\n/**\n * Wrap a `fetch` so every ShapeStream request (the Electric read-path long-poll/catch-up) emits a start\n * line (shape/table, offset, live — derived from the request URL params) and a completion line (status,\n * ms, and whether the response is up-to-date). Passthrough when instrumentation is off: the early return\n * runs before any URL parsing, so the off-path pays nothing per request beyond this closure itself.\n *\n * Inject it as a ShapeStream `fetchClient`; pass the stream's existing `fetchClient` (if any) as the base\n * so the instrumentation composes rather than replaces.\n */\nexport function instrumentShapeFetch(baseFetch: typeof fetch = fetch): typeof fetch {\n const wrapped = (input: Parameters<typeof fetch>[0], init?: Parameters<typeof fetch>[1]): Promise<Response> => {\n if (!isEnabled()) return baseFetch(input, init);\n const url = fetchInputUrl(input);\n const params = url ? new URL(url).searchParams : undefined;\n // Derive the shape identity ONCE and name it on BOTH the start and done lines, so a start/done pair\n // is readable without cross-referencing timing (multiple shapes' requests interleave on the rail).\n const shape = params?.get(\"table\") ?? undefined;\n const live = params?.get(\"live\") === \"true\";\n const offset = params?.get(\"offset\") ?? undefined;\n // The handle chain is the backlog-0001 forensic: WHICH handle each request carried, which one the\n // response minted, and whether the stale-cache ladder's params were on the wire — so a\n // dead-handle-served-N-times storm reads straight off the rail (same responseHandle across busted\n // attempts) instead of needing a network-tab capture at the moment of recurrence.\n const requestHandle = params?.get(\"handle\") ?? undefined;\n const cacheBuster = params?.has(\"cache-buster\") ?? false;\n const expiredHandle = params?.get(\"expired_handle\") ?? undefined;\n // The whole request identity rides in ONE compact string field: Chrome's console preview truncates\n // object previews at ~5 properties, and a captured log (the only artifact of a live recurrence) keeps\n // just the preview — separate fields silently vanish exactly when they matter (backlog 0001).\n const cursor = params?.get(\"cursor\") ?? undefined;\n const req = [\n `${shape ?? \"?\"}@${offset ?? \"?\"}`,\n live ? \"live\" : \"catchup\",\n requestHandle ? `h=${requestHandle}` : \"no-handle\",\n // The live-cycle cursor is Electric's CDN-collapse defense — its absence or non-advancement on\n // live polls is itself a finding (backlog 0001).\n cursor ? `c=${cursor}` : live ? \"NO-CURSOR\" : \"\",\n cacheBuster ? \"BUSTED\" : \"\",\n expiredHandle ? `expired=${expiredHandle}` : \"\",\n ]\n .filter(Boolean)\n .join(\" \");\n syncDebug(\"shape request start\", { req });\n const startedAt = now();\n return baseFetch(input, init).then((response) => {\n // Same single-string discipline for the response half: status/ms stay first-class (they are what\n // rail readers scan), the forensic chain (up-to-date, minted handle, end offset) folds into `resp`.\n const responseHandle = response.headers.get(\"electric-handle\");\n const responseOffset = response.headers.get(\"electric-offset\");\n const responseCursor = response.headers.get(\"electric-cursor\");\n const age = response.headers.get(\"age\");\n const resp = [\n response.headers.has(\"electric-up-to-date\") ? \"up-to-date\" : \"\",\n responseHandle && responseHandle !== requestHandle ? `minted h=${responseHandle}` : \"\",\n responseOffset ? `end=${responseOffset}` : \"\",\n responseCursor ? `c=${responseCursor}` : \"\",\n age ? `age=${age}` : \"\",\n ]\n .filter(Boolean)\n .join(\" \");\n syncDebug(\"shape request done\", {\n req,\n status: response.status,\n ms: Math.round(now() - startedAt),\n ...(resp ? { resp } : {}),\n });\n return response;\n });\n };\n // `typeof fetch` (Bun's global) carries a `preconnect` member the wrapper neither has nor needs — the\n // ShapeStream only ever invokes fetchClient as a plain fetch — so the shape-compatible cast is safe.\n return wrapped as typeof fetch;\n}\n\n/**\n * Run `fn`, logging `<event> done` with its wall-clock duration (and any extra `data`). When\n * instrumentation is off this is a thin pass-through with no logging and no timing overhead beyond the\n * call itself. Returns whatever `fn` returns.\n */\nexport async function timeAsync<T>(event: string, fn: () => Promise<T>, data?: Record<string, unknown>): Promise<T> {\n if (!isEnabled()) return fn();\n const startedAt = now();\n syncDebug(`${event} start`, data);\n try {\n return await fn();\n } finally {\n syncDebug(`${event} done`, { ms: Math.round(now() - startedAt) });\n }\n}\n",
|
|
7
|
-
"// Boot observability (ADR-0034). Every client boot builds a structured, versioned {@link BootReport} as it\n// runs and finalizes it exactly once at `onInitialSync` (the moment the `boot client ready` rail line fires\n// and `ready` resolves). The report is a plain, allocation-light object — no class instance leaks out — so\n// it structured-clones across the worker bridge unchanged.\n//\n// The numbers are captured INDEPENDENTLY of the debug rail: `timeAsync` only measures when\n// `__pgxsinkitDebug` is on, but the report must exist on every boot, so the builder always measures. It\n// still emits the SAME rail lines `timeAsync` would (`<event> start` / `<event> done {ms}`), gated by\n// `syncDebug`'s own console/sink gate, so the log text tools and tests match is unchanged.\n\nimport { syncDebug } from \"./debug\";\n\n/** Monotonic clock (ms) — `performance.now()` where available, else `Date.now()`. */\nconst nowMs = (): number => (typeof performance !== \"undefined\" ? performance.now() : Date.now());\n\n/**\n * A structured, versioned record of one client boot (ADR-0034). `reportVersion` is a contract number:\n * additive fields keep it, a breaking reshape bumps it. All durations are milliseconds; all `*AtMs` are\n * offsets from boot start (the `startedAt` epoch anchor is the only wall-clock value).\n */\nexport interface BootReport {\n reportVersion: 1;\n /** How the engine booted: the in-process client (bun/Node/fallback) or inside `defineSyncWorker`. */\n mode: \"in-process\" | \"worker\";\n /** Whether the caller proved the store a schemaless spare (the ADR-0032 S4 fresh-store hint). */\n freshStore: boolean;\n /** Whether the ADR-0032 S4 fetch/schema overlap was active for this boot. */\n overlapPrefetch: boolean;\n /** The registry fingerprint the store is provisioned under — the same value store-version reconcile stamps. */\n registryFingerprint: string;\n /** Epoch anchor (`Date.now()`) at boot start; every other duration/offset is monotonic relative to it. */\n startedAt: number;\n /** Boot start → `onInitialSync` (all eager groups caught up). */\n totalMs: number;\n /**\n * Present only when the store was pre-provisioned (a spare's initdb ran off-thread before this boot\n * adopted it); `null` otherwise. When present, `phases.pgliteCreateMs` is `null` — the create cost is\n * reported here instead.\n */\n provision: {\n /** The spare's PGlite create (initdb) cost, paid at provision time. */\n initdbMs: number;\n /** How long the provisioned store sat ready before this boot adopted it. */\n provisionedMsBeforeBoot: number;\n } | null;\n phases: {\n /** PGlite create cost, or `null` when the store was adopted from a spare (see {@link BootReport.provision}). */\n pgliteCreateMs: number | null;\n schemaExecMs: number;\n journalRecoveryMs: number;\n storeVersionReconcileMs: number;\n /**\n * `startConfiguredSync`: stream/group construction wall. On an overlap boot (ADR-0032 S4,\n * {@link BootReport.overlapPrefetch}) the early-started segment runs concurrently with schema/journal/\n * reconcile, so this includes that shared wall. Structurally 0 when the boot is ready inside the\n * sync-start call itself (zero eager groups / instant catch-up) — finalize runs before the phase closes.\n */\n syncStartMs: number;\n /** Sync-start done → last eager boot group ready. */\n catchupMs: number;\n /**\n * Cumulative time in configured prepare hooks (`prepareLocalDbBeforeSchema` + `prepareLocalDb`), present\n * only when at least one hook is configured. Not part of the required v1 shape (ADR-0034).\n */\n prepareMs?: number;\n };\n /**\n * Per consistency GROUP, for the eager + promoted boot groups only (a lazily-activated-later group never\n * appears — nor mutates a finalized report). Groups run concurrently, so `fetchMs`/`applyMs` are per-group\n * wall SEGMENTS, not a partition of `totalMs`.\n */\n groups: Array<{\n groupKey: string;\n /** Number of member tables (shapes) in the group. */\n tables: number;\n /** Offset from boot start when the group's streams started. */\n startedAtMs: number;\n /** Offset from boot start when the group reached its initial sync. */\n readyAtMs: number;\n /** Number of batch deliveries the group's stream chain received during boot catch-up. */\n requests: number;\n /** Number of change rows ingested during boot catch-up. */\n rows: number;\n /**\n * Settle→next-delivery wall within this group's chain. On the single-threaded WASM host this absorbs\n * OTHER groups' apply transactions and main-thread work between deliveries — read it as \"time this\n * group spent not applying\", an upper bound on its network wait, not pure network cost.\n */\n fetchMs: number;\n /**\n * Wall around this group's batch commits into PGlite. Includes waiting behind another group's\n * transaction on the shared connection (single writer), so concurrent groups' `applyMs` can overlap.\n */\n applyMs: number;\n }>;\n}\n\n/** The phase durations the builder captures by key; `catchupMs` is derived, not a captured phase. */\ntype PhaseKey = \"schemaExec\" | \"journalRecovery\" | \"storeVersionReconcile\" | \"syncStart\";\n\n/**\n * The per-group accumulator the engine stamps as a boot group's stream chain delivers and applies (ADR-0034).\n * One per consistency group (one `syncShapesToTables` call). Frozen at the group's ready edge so later live\n * traffic never mutates a finalized report.\n */\nexport interface GroupBootStamp {\n /** A batch was delivered to the group's subscribe callback (one response). `changeCount` = its change rows. */\n onBatchDelivered: (changeCount: number) => void;\n /** A commit transaction applied `ms` of work into PGlite for this group. */\n onApply: (ms: number) => void;\n /** The group reached its initial sync — stamp `readyAtMs` and freeze accumulation. */\n markReady: () => void;\n}\n\n/** The seam `startConfiguredSync` uses to open a boot group's accumulator (implemented by the builder). */\nexport interface BootStampCollector {\n beginGroup: (groupKey: string, tables: number) => GroupBootStamp;\n}\n\ninterface GroupAccumulator extends GroupBootStamp {\n snapshot: () => BootReport[\"groups\"][number];\n}\n\nfunction createGroupAccumulator(groupKey: string, tables: number, bootStartPerf: number): GroupAccumulator {\n const startedAtMs = nowMs() - bootStartPerf;\n let requests = 0;\n let rows = 0;\n let fetchMs = 0;\n let applyMs = 0;\n let readyAtMs: number | null = null;\n // `markReady` fires from INSIDE the ready-causing commit (before that delivery's `onApply` runs), so we\n // must record that commit's apply before freezing. So `markReady` only flags ready; the freeze snaps shut\n // at the START of the NEXT delivery — the first that is genuinely post-boot live traffic.\n let readyReached = false;\n let frozen = false;\n // Marks the last settle point; the gap to the next delivery is fetch (network) wait. Seeded at creation so\n // the first delivery's gap is the initial catch-up wait.\n let lastMark = nowMs();\n\n return {\n onBatchDelivered: (changeCount) => {\n // A delivery arriving after the group is ready is post-boot live traffic — freeze here so it (and its\n // apply) is excluded, leaving the ready-causing batch fully recorded.\n if (readyReached) frozen = true;\n if (frozen) return;\n const now = nowMs();\n fetchMs += Math.max(0, now - lastMark);\n lastMark = now;\n requests += 1;\n rows += changeCount;\n },\n onApply: (ms) => {\n if (frozen) return;\n applyMs += ms;\n // Exclude the apply wall from the NEXT fetch gap (the apply happens inside the delivery callback).\n lastMark = nowMs();\n },\n markReady: () => {\n if (readyAtMs != null) return;\n readyAtMs = nowMs() - bootStartPerf;\n readyReached = true;\n },\n snapshot: () => ({\n groupKey,\n tables,\n startedAtMs,\n readyAtMs: readyAtMs ?? nowMs() - bootStartPerf,\n requests,\n rows,\n fetchMs,\n applyMs,\n }),\n };\n}\n\n/** Builds a {@link BootReport} across a boot and finalizes it exactly once. Owned by `createSyncClient`. */\nexport interface BootReportBuilder extends BootStampCollector {\n /** The monotonic anchor (`performance.now()` at boot start) every offset is relative to. */\n readonly bootStartPerf: number;\n /**\n * Time `fn`, always measuring (unlike `timeAsync`, which only measures when the rail is on) and capturing\n * the duration into the report, while emitting the SAME rail lines `timeAsync` would. `key` is `null` for\n * a prepare hook (folded into the optional `prepareMs`).\n */\n phase: <T>(\n key: PhaseKey | \"prepare\",\n event: string,\n fn: () => Promise<T>,\n data?: Record<string, unknown>,\n ) => Promise<T>;\n setPgliteCreateMs: (ms: number | null) => void;\n setProvision: (provision: BootReport[\"provision\"]) => void;\n /**\n * Record `phases.syncStartMs` directly — for the ADR-0032 S4 overlap path, where sync construction is\n * kicked off before schema exec (not wrapped in {@link BootReportBuilder.phase}) and has no rail line.\n */\n setSyncStartMs: (ms: number) => void;\n /** Capture the offset at which sync construction completed — the base for `catchupMs`. */\n markSyncStartDone: () => void;\n /** Build + store the report once (idempotent). Returns the report, or the already-built one on a re-call. */\n finalize: () => BootReport;\n /** The finalized report, or `null` before the first boot completes / after an early stop. */\n report: () => BootReport | null;\n}\n\n/** Inputs known at boot start — the flags and identity the report carries verbatim. */\nexport interface BootReportInit {\n mode: BootReport[\"mode\"];\n freshStore: boolean;\n overlapPrefetch: boolean;\n registryFingerprint: string;\n}\n\nexport function createBootReportBuilder(init: BootReportInit): BootReportBuilder {\n const startedAt = Date.now();\n const bootStartPerf = nowMs();\n const durations = new Map<PhaseKey, number>();\n let prepareMs: number | null = null;\n let pgliteCreateMs: number | null = null;\n let provision: BootReport[\"provision\"] = null;\n let syncStartDoneOffset: number | null = null;\n const groups: GroupAccumulator[] = [];\n let built: BootReport | null = null;\n\n const duration = (key: PhaseKey): number => durations.get(key) ?? 0;\n\n return {\n bootStartPerf,\n phase: async (key, event, fn, data) => {\n const startedAtPerf = nowMs();\n // Mirror `timeAsync`'s rail lines exactly (text tools/tests match); `syncDebug` self-gates the console.\n syncDebug(`${event} start`, data);\n try {\n return await fn();\n } finally {\n const ms = nowMs() - startedAtPerf;\n syncDebug(`${event} done`, { ms: Math.round(ms) });\n if (key === \"prepare\") prepareMs = (prepareMs ?? 0) + ms;\n else durations.set(key, ms);\n }\n },\n setPgliteCreateMs: (ms) => {\n pgliteCreateMs = ms;\n },\n setProvision: (value) => {\n provision = value;\n },\n setSyncStartMs: (ms) => {\n durations.set(\"syncStart\", ms);\n },\n markSyncStartDone: () => {\n syncStartDoneOffset = nowMs() - bootStartPerf;\n },\n beginGroup: (groupKey, tables) => {\n const accumulator = createGroupAccumulator(groupKey, tables, bootStartPerf);\n groups.push(accumulator);\n return accumulator;\n },\n finalize: () => {\n if (built) return built;\n const totalMs = nowMs() - bootStartPerf;\n const syncStartBase = syncStartDoneOffset ?? totalMs;\n built = {\n reportVersion: 1,\n mode: init.mode,\n freshStore: init.freshStore,\n overlapPrefetch: init.overlapPrefetch,\n registryFingerprint: init.registryFingerprint,\n startedAt,\n totalMs,\n provision,\n phases: {\n pgliteCreateMs,\n schemaExecMs: duration(\"schemaExec\"),\n journalRecoveryMs: duration(\"journalRecovery\"),\n storeVersionReconcileMs: duration(\"storeVersionReconcile\"),\n syncStartMs: duration(\"syncStart\"),\n catchupMs: Math.max(0, totalMs - syncStartBase),\n ...(prepareMs != null ? { prepareMs } : {}),\n },\n groups: groups.map((group) => group.snapshot()),\n };\n return built;\n },\n report: () => built,\n };\n}\n",
|
|
7
|
+
"// Boot observability (ADR-0034). Every client boot builds a structured, versioned {@link BootReport} as it\n// runs and finalizes it exactly once at `onInitialSync` (the moment the `boot client ready` rail line fires\n// and `ready` resolves). The report is a plain, allocation-light object — no class instance leaks out — so\n// it structured-clones across the worker bridge unchanged.\n//\n// The numbers are captured INDEPENDENTLY of the debug rail: `timeAsync` only measures when\n// `__pgxsinkitDebug` is on, but the report must exist on every boot, so the builder always measures. It\n// still emits the SAME rail lines `timeAsync` would (`<event> start` / `<event> done {ms}`), gated by\n// `syncDebug`'s own console/sink gate, so the log text tools and tests match is unchanged.\n\nimport { syncDebug } from \"./debug\";\n\n/** Monotonic clock (ms) — `performance.now()` where available, else `Date.now()`. */\nconst nowMs = (): number => (typeof performance !== \"undefined\" ? performance.now() : Date.now());\n\n/**\n * A structured, versioned record of one client boot (ADR-0034). `reportVersion` is a contract number:\n * additive fields keep it, a breaking reshape bumps it. All durations are milliseconds; all `*AtMs` are\n * offsets from boot start (the `startedAt` epoch anchor is the only wall-clock value).\n */\nexport interface BootReport {\n reportVersion: 1;\n /** How the engine booted: the in-process client (bun/Node/fallback) or inside `defineSyncWorker`. */\n mode: \"in-process\" | \"worker\";\n /** Whether the caller proved the store a schemaless spare (the ADR-0032 S4 fresh-store hint). */\n freshStore: boolean;\n /**\n * How this store presented at boot: `\"restored\"` when the boot seeded a brand-new store from a backup\n * (ADR-0035 `restoreFrom`); `\"fresh\"` when the caller proved it a schemaless spare (the SAME signal as\n * {@link BootReport.freshStore}); `\"warm\"` otherwise (an existing persisted store — the common case).\n * Distinct from `freshStore`, which stays a bare boolean: `storeKind` additionally names the restore case,\n * which a boolean cannot express.\n */\n storeKind: \"fresh\" | \"warm\" | \"restored\";\n /** Whether the ADR-0032 S4 fetch/schema overlap was active for this boot. */\n overlapPrefetch: boolean;\n /** The registry fingerprint the store is provisioned under — the same value store-version reconcile stamps. */\n registryFingerprint: string;\n /** Epoch anchor (`Date.now()`) at boot start; every other duration/offset is monotonic relative to it. */\n startedAt: number;\n /** Boot start → `onInitialSync` (all eager groups caught up). */\n totalMs: number;\n /**\n * Boot start → `localReadReady` resolved (ADR-0041): PGlite open, durable schema compatible, store-version\n * reconcile complete, and the drizzle read facade built — cached reads are safe with ZERO network. `null`\n * when the boot rejected before the stage. Additive field; `reportVersion` stays `1`.\n */\n localReadReadyMs: number | null;\n /**\n * Boot start → `writeReady` resolved (ADR-0041): the mutation runtime is constructed and boot recovery\n * (plus restore quarantine on a restore boot) has completed — enqueue is safe. `null` when the boot\n * rejected before the stage. Additive field; `reportVersion` stays `1`.\n */\n writeReadyMs: number | null;\n /**\n * Present only when the store was pre-provisioned (a spare's initdb ran off-thread before this boot\n * adopted it); `null` otherwise. When present, `phases.pgliteCreateMs` is `null` — the create cost is\n * reported here instead.\n */\n provision: {\n /** The spare's PGlite create (initdb) cost, paid at provision time. */\n initdbMs: number;\n /** How long the provisioned store sat ready before this boot adopted it. */\n provisionedMsBeforeBoot: number;\n } | null;\n phases: {\n /** PGlite create cost, or `null` when the store was adopted from a spare (see {@link BootReport.provision}). */\n pgliteCreateMs: number | null;\n schemaExecMs: number;\n journalRecoveryMs: number;\n storeVersionReconcileMs: number;\n /**\n * `startConfiguredSync`: stream/group construction wall. On an overlap boot (ADR-0032 S4,\n * {@link BootReport.overlapPrefetch}) the early-started segment runs concurrently with schema/journal/\n * reconcile, so this includes that shared wall. Structurally 0 when the boot is ready inside the\n * sync-start call itself (zero eager groups / instant catch-up) — finalize runs before the phase closes.\n */\n syncStartMs: number;\n /** Sync-start done → last eager boot group ready. */\n catchupMs: number;\n /**\n * Cumulative time in configured prepare hooks (`prepareLocalDbBeforeSchema` + `prepareLocalDb`), present\n * only when at least one hook is configured. Not part of the required v1 shape (ADR-0034).\n */\n prepareMs?: number;\n };\n /**\n * Warm-persisted-store-startup observability (the schema-replay + journal-recovery fast-path lane). Every\n * field carries the honest CURRENT truth so the report never lies mid-lane: the durable-schema-fingerprint\n * slice sets the `schema*` flags and the recovery-marker slice the `journal*` flags as those optimizations\n * land. Grouped like {@link BootReport.phases} so the flags structured-clone across the worker bridge as one\n * unit.\n */\n warmBoot: {\n /** Whether durable-schema replay was skipped this boot (a fingerprint match). `false` today — replay is unconditional. */\n schemaSkipped: boolean;\n /** Whether the stored durable-schema fingerprint matched the generated schema. `false` today — not yet computed. */\n schemaFingerprintMatch: boolean;\n /** Whether the boot-time `recoverSending` journal pass was skipped this boot. `false` today — the pass is unconditional. */\n journalRecoverySkipped: boolean;\n /**\n * Whether journal recovery was required this boot. `true` today under pre-marker legacy semantics: with no\n * durable recovery marker, recovery is ALWAYS treated as required. The recovery-marker slice will set this\n * from the durable marker instead (a clean shutdown clears the marker → `false`, skipping recovery).\n */\n journalRecoveryRequired: boolean;\n /** How many writable table journals the boot-time `recoverSending` pass visited (the registry's writable-entry count). */\n journalTablesVisited: number;\n /** Rows lifted `sending → pending` by recovery. `null` = not yet instrumented; populated by the recovery-marker slice. */\n journalRowsRecovered: number | null;\n };\n /**\n * Per consistency GROUP, for the eager + promoted boot groups only (a lazily-activated-later group never\n * appears — nor mutates a finalized report). Groups run concurrently, so `fetchMs`/`applyMs` are per-group\n * wall SEGMENTS, not a partition of `totalMs`.\n */\n groups: Array<{\n groupKey: string;\n /** Number of member tables (shapes) in the group. */\n tables: number;\n /** Offset from boot start when the group's streams started. */\n startedAtMs: number;\n /** Offset from boot start when the group reached its initial sync. */\n readyAtMs: number;\n /** Number of batch deliveries the group's stream chain received during boot catch-up. */\n requests: number;\n /** Number of change rows ingested during boot catch-up. */\n rows: number;\n /**\n * Settle→next-delivery wall within this group's chain. On the single-threaded WASM host this absorbs\n * OTHER groups' apply transactions and main-thread work between deliveries — read it as \"time this\n * group spent not applying\", an upper bound on its network wait, not pure network cost.\n */\n fetchMs: number;\n /**\n * Wall around this group's batch commits into PGlite. Includes waiting behind another group's\n * transaction on the shared connection (single writer), so concurrent groups' `applyMs` can overlap.\n */\n applyMs: number;\n }>;\n}\n\n/** The phase durations the builder captures by key; `catchupMs` is derived, not a captured phase. */\ntype PhaseKey = \"schemaExec\" | \"journalRecovery\" | \"storeVersionReconcile\" | \"syncStart\";\n\n/**\n * The per-group accumulator the engine stamps as a boot group's stream chain delivers and applies (ADR-0034).\n * One per consistency group (one `syncShapesToTables` call). Frozen at the group's ready edge so later live\n * traffic never mutates a finalized report.\n */\nexport interface GroupBootStamp {\n /** A batch was delivered to the group's subscribe callback (one response). `changeCount` = its change rows. */\n onBatchDelivered: (changeCount: number) => void;\n /** A commit transaction applied `ms` of work into PGlite for this group. */\n onApply: (ms: number) => void;\n /** The group reached its initial sync — stamp `readyAtMs` and freeze accumulation. */\n markReady: () => void;\n}\n\n/** The seam `startConfiguredSync` uses to open a boot group's accumulator (implemented by the builder). */\nexport interface BootStampCollector {\n beginGroup: (groupKey: string, tables: number) => GroupBootStamp;\n}\n\ninterface GroupAccumulator extends GroupBootStamp {\n snapshot: () => BootReport[\"groups\"][number];\n}\n\nfunction createGroupAccumulator(groupKey: string, tables: number, bootStartPerf: number): GroupAccumulator {\n const startedAtMs = nowMs() - bootStartPerf;\n let requests = 0;\n let rows = 0;\n let fetchMs = 0;\n let applyMs = 0;\n let readyAtMs: number | null = null;\n // `markReady` fires from INSIDE the ready-causing commit (before that delivery's `onApply` runs), so we\n // must record that commit's apply before freezing. So `markReady` only flags ready; the freeze snaps shut\n // at the START of the NEXT delivery — the first that is genuinely post-boot live traffic.\n let readyReached = false;\n let frozen = false;\n // Marks the last settle point; the gap to the next delivery is fetch (network) wait. Seeded at creation so\n // the first delivery's gap is the initial catch-up wait.\n let lastMark = nowMs();\n\n return {\n onBatchDelivered: (changeCount) => {\n // A delivery arriving after the group is ready is post-boot live traffic — freeze here so it (and its\n // apply) is excluded, leaving the ready-causing batch fully recorded.\n if (readyReached) frozen = true;\n if (frozen) return;\n const now = nowMs();\n fetchMs += Math.max(0, now - lastMark);\n lastMark = now;\n requests += 1;\n rows += changeCount;\n },\n onApply: (ms) => {\n if (frozen) return;\n applyMs += ms;\n // Exclude the apply wall from the NEXT fetch gap (the apply happens inside the delivery callback).\n lastMark = nowMs();\n },\n markReady: () => {\n if (readyAtMs != null) return;\n readyAtMs = nowMs() - bootStartPerf;\n readyReached = true;\n },\n snapshot: () => ({\n groupKey,\n tables,\n startedAtMs,\n readyAtMs: readyAtMs ?? nowMs() - bootStartPerf,\n requests,\n rows,\n fetchMs,\n applyMs,\n }),\n };\n}\n\n/** Builds a {@link BootReport} across a boot and finalizes it exactly once. Owned by `createSyncClient`. */\nexport interface BootReportBuilder extends BootStampCollector {\n /** The monotonic anchor (`performance.now()` at boot start) every offset is relative to. */\n readonly bootStartPerf: number;\n /**\n * Time `fn`, always measuring (unlike `timeAsync`, which only measures when the rail is on) and capturing\n * the duration into the report, while emitting the SAME rail lines `timeAsync` would. `key` is `null` for\n * a prepare hook (folded into the optional `prepareMs`).\n */\n phase: <T>(\n key: PhaseKey | \"prepare\",\n event: string,\n fn: () => Promise<T>,\n data?: Record<string, unknown>,\n ) => Promise<T>;\n setPgliteCreateMs: (ms: number | null) => void;\n setProvision: (provision: BootReport[\"provision\"]) => void;\n /**\n * Record the durable-schema fast-path outcome (the durable-schema-fingerprint slice): whether replay was\n * skipped and whether the stored fingerprint matched. Both default to the current truth (`false`), so this\n * need not be called until that slice lands.\n */\n setSchemaFastPath: (info: { skipped: boolean; fingerprintMatch: boolean }) => void;\n /**\n * Record the boot-time journal-recovery outcome (the recovery-marker slice): whether the pass was skipped,\n * whether it was required, how many writable journals it visited, and how many rows it lifted (`null` until\n * instrumented). `tablesVisited` is wired from boot today; the rest default to current-truth values.\n */\n setJournalRecovery: (info: {\n skipped: boolean;\n required: boolean;\n tablesVisited: number;\n rowsRecovered: number | null;\n }) => void;\n /**\n * Stamp `localReadReadyMs` at the moment the staged local-read core resolves `localReadReady` (ADR-0041).\n * Idempotent — the first stamp wins.\n */\n setLocalReadReadyMs: (ms: number) => void;\n /**\n * Stamp `writeReadyMs` at the moment the write/recovery tail resolves `writeReady` (ADR-0041). Idempotent —\n * the first stamp wins.\n */\n setWriteReadyMs: (ms: number) => void;\n /**\n * Record `phases.syncStartMs` directly — for the ADR-0032 S4 overlap path, where sync construction is\n * kicked off before schema exec (not wrapped in {@link BootReportBuilder.phase}) and has no rail line.\n */\n setSyncStartMs: (ms: number) => void;\n /** Capture the offset at which sync construction completed — the base for `catchupMs`. */\n markSyncStartDone: () => void;\n /** Build + store the report once (idempotent). Returns the report, or the already-built one on a re-call. */\n finalize: () => BootReport;\n /** The finalized report, or `null` before the first boot completes / after an early stop. */\n report: () => BootReport | null;\n}\n\n/** Inputs known at boot start — the flags and identity the report carries verbatim. */\nexport interface BootReportInit {\n mode: BootReport[\"mode\"];\n freshStore: boolean;\n storeKind: BootReport[\"storeKind\"];\n overlapPrefetch: boolean;\n registryFingerprint: string;\n}\n\nexport function createBootReportBuilder(init: BootReportInit): BootReportBuilder {\n const startedAt = Date.now();\n const bootStartPerf = nowMs();\n const durations = new Map<PhaseKey, number>();\n let prepareMs: number | null = null;\n let pgliteCreateMs: number | null = null;\n let provision: BootReport[\"provision\"] = null;\n // Current-truth defaults (this slice's honest baseline): durable schema replay + journal recovery are both\n // unconditional today, and recovery is always treated as required pre-marker. Later slices flip these via\n // the setters below.\n let warmBoot: BootReport[\"warmBoot\"] = {\n schemaSkipped: false,\n schemaFingerprintMatch: false,\n journalRecoverySkipped: false,\n journalRecoveryRequired: true,\n journalTablesVisited: 0,\n journalRowsRecovered: null,\n };\n let syncStartDoneOffset: number | null = null;\n let localReadReadyMs: number | null = null;\n let writeReadyMs: number | null = null;\n const groups: GroupAccumulator[] = [];\n let built: BootReport | null = null;\n\n const duration = (key: PhaseKey): number => durations.get(key) ?? 0;\n\n return {\n bootStartPerf,\n phase: async (key, event, fn, data) => {\n const startedAtPerf = nowMs();\n // Mirror `timeAsync`'s rail lines exactly (text tools/tests match); `syncDebug` self-gates the console.\n syncDebug(`${event} start`, data);\n try {\n return await fn();\n } finally {\n const ms = nowMs() - startedAtPerf;\n syncDebug(`${event} done`, { ms: Math.round(ms) });\n if (key === \"prepare\") prepareMs = (prepareMs ?? 0) + ms;\n else durations.set(key, ms);\n }\n },\n setPgliteCreateMs: (ms) => {\n pgliteCreateMs = ms;\n },\n setProvision: (value) => {\n provision = value;\n },\n setSchemaFastPath: (info) => {\n warmBoot = { ...warmBoot, schemaSkipped: info.skipped, schemaFingerprintMatch: info.fingerprintMatch };\n },\n setJournalRecovery: (info) => {\n warmBoot = {\n ...warmBoot,\n journalRecoverySkipped: info.skipped,\n journalRecoveryRequired: info.required,\n journalTablesVisited: info.tablesVisited,\n journalRowsRecovered: info.rowsRecovered,\n };\n },\n setLocalReadReadyMs: (ms) => {\n if (localReadReadyMs == null) localReadReadyMs = ms;\n },\n setWriteReadyMs: (ms) => {\n if (writeReadyMs == null) writeReadyMs = ms;\n },\n setSyncStartMs: (ms) => {\n durations.set(\"syncStart\", ms);\n },\n markSyncStartDone: () => {\n syncStartDoneOffset = nowMs() - bootStartPerf;\n },\n beginGroup: (groupKey, tables) => {\n const accumulator = createGroupAccumulator(groupKey, tables, bootStartPerf);\n groups.push(accumulator);\n return accumulator;\n },\n finalize: () => {\n if (built) return built;\n const totalMs = nowMs() - bootStartPerf;\n const syncStartBase = syncStartDoneOffset ?? totalMs;\n built = {\n reportVersion: 1,\n mode: init.mode,\n freshStore: init.freshStore,\n storeKind: init.storeKind,\n overlapPrefetch: init.overlapPrefetch,\n registryFingerprint: init.registryFingerprint,\n startedAt,\n totalMs,\n localReadReadyMs,\n writeReadyMs,\n provision,\n warmBoot,\n phases: {\n pgliteCreateMs,\n schemaExecMs: duration(\"schemaExec\"),\n journalRecoveryMs: duration(\"journalRecovery\"),\n storeVersionReconcileMs: duration(\"storeVersionReconcile\"),\n syncStartMs: duration(\"syncStart\"),\n catchupMs: Math.max(0, totalMs - syncStartBase),\n ...(prepareMs != null ? { prepareMs } : {}),\n },\n groups: groups.map((group) => group.snapshot()),\n };\n return built;\n },\n report: () => built,\n };\n}\n",
|
|
8
8
|
"/**\n * The opt-in convergence driver (ADR-0005 decision 3).\n *\n * The mechanism primitives (`flush` / `reconcile` / `retryFailed`) stay public and manual.\n * This driver is the *scheduling-policy seam*: the app decides WHEN to converge (online?\n * foregrounded? on power?) and how it learns those conditions, while the library owns the\n * convergence pass and the congestion policy (jittered backoff + attempt cap, already in the\n * mutation runtime). Pass nothing to `createSyncClient` → fully manual, today's behaviour.\n *\n * A pass is `flush` → `reconcile`. It deliberately does NOT call `retryFailed`: `flush`\n * already re-attempts `failed` mutations whose `next_retry_at_us` backoff has elapsed, so a\n * pass leaves the jittered backoff intact. Calling `retryFailed` on every pass would reset\n * every failed mutation to \"due now\" and, under a short trigger interval, burn the whole\n * attempt budget during a transient outage and quarantine writes prematurely. `retryFailed`\n * stays a manual, user-initiated primitive (\"retry my failed writes now\").\n */\n\nimport { syncDebug, timeAsync } from \"./debug\";\n\n/** The mechanism primitives a convergence pass schedules. */\nexport interface ConvergenceClient {\n flush: () => Promise<void>;\n reconcile: () => Promise<void>;\n}\n\n/**\n * The scheduling-policy seam. Browser (`online` / `visibilitychange`) and React Native\n * (`AppState` / `NetInfo`) are two genuine adapters — which is what earns this its place as a\n * seam rather than being inlined.\n */\nexport interface ConvergenceTrigger {\n /** Register a callback fired whenever the app wants a convergence attempt; returns an unsubscribe. */\n subscribe: (onSignal: () => void) => () => void;\n /** Whether a convergence pass should run right now (e.g. online and foregrounded). */\n shouldConverge: () => boolean;\n}\n\nexport interface ConvergenceDriverOptions {\n client: ConvergenceClient;\n trigger: ConvergenceTrigger;\n /** Invoked after each convergence pass with the error it raised, or `null` on success. */\n onPass?: (error: unknown) => void;\n}\n\nexport interface ConvergenceDriver {\n start: () => void;\n /**\n * Stop scheduling and **await any in-flight pass** before resolving, so a caller can then\n * safely close or wipe the underlying database without a pass racing against it. Idempotent.\n */\n stop: () => Promise<void>;\n /**\n * Request a convergence pass now — the event-driven path. The client calls this the moment a\n * mutation is enqueued, so a local write flushes immediately instead of waiting for the trigger's\n * next interval tick. Coalesced exactly like a trigger signal (one pass at a time; a request mid-pass\n * queues a single follow-up) and still gated by `shouldConverge()`, so a write made while offline\n * stages without flushing. With this, the trigger's interval is only a fallback (retries/recovery),\n * which lets it run far less often — the interval, not real convergence, is what costs idle CPU.\n */\n requestPass: () => void;\n}\n\n/**\n * Drive convergence from a {@link ConvergenceTrigger}. Each signal runs at most one pass at a\n * time (`flush` → `reconcile`); a signal arriving mid-pass coalesces into a single follow-up\n * pass, so a burst of triggers never stampedes the server (the per-mutation backoff in the\n * runtime handles the rest).\n */\nexport function createConvergenceDriver(options: ConvergenceDriverOptions): ConvergenceDriver {\n let unsubscribe: (() => void) | null = null;\n let running = false;\n let queued = false;\n let disposed = false;\n // The promise of the pass currently in flight, so stop() can await it before teardown.\n let currentPass: Promise<void> | null = null;\n\n const runPass = async (): Promise<void> => {\n if (disposed || running) {\n if (!disposed) {\n queued = true;\n }\n // The signal that mattered most for latency: a write asked to converge but a pass was already\n // running, so this one coalesces and waits for the current pass to finish before it flushes.\n syncDebug(\"convergence pass coalesced (one already running)\", { disposed, queued });\n return;\n }\n\n if (!options.trigger.shouldConverge()) {\n syncDebug(\"convergence pass skipped (shouldConverge=false: offline or backgrounded)\");\n return;\n }\n\n running = true;\n let error: unknown = null;\n const pass = (async () => {\n try {\n await timeAsync(\"convergence flush\", () => options.client.flush());\n await timeAsync(\"convergence reconcile\", () => options.client.reconcile());\n } catch (passError) {\n error = passError;\n }\n })();\n currentPass = pass;\n await pass;\n running = false;\n currentPass = null;\n options.onPass?.(error);\n\n if (queued && !disposed) {\n queued = false;\n void runPass();\n }\n };\n\n return {\n start: () => {\n if (unsubscribe || disposed) {\n return;\n }\n\n unsubscribe = options.trigger.subscribe(() => {\n void runPass();\n });\n void runPass();\n },\n stop: async () => {\n disposed = true;\n queued = false;\n unsubscribe?.();\n unsubscribe = null;\n // Await the in-flight pass (if any) so the DB is quiescent before the caller closes/wipes it.\n await currentPass;\n },\n requestPass: () => {\n syncDebug(\"convergence pass requested (event-driven, e.g. local write enqueued)\");\n void runPass();\n },\n };\n}\n\n/** Minimal browser globals the trigger needs, read off `globalThis` so the library carries no DOM lib dependency. */\ninterface EventTargetLike {\n addEventListener: (type: string, handler: () => void) => void;\n removeEventListener: (type: string, handler: () => void) => void;\n}\ninterface BrowserEnv {\n window?: EventTargetLike;\n document?: EventTargetLike & { visibilityState?: string };\n navigator?: { onLine?: boolean };\n}\n\n/**\n * Browser convergence trigger: fires on `online`, `visibilitychange`, and a fallback interval,\n * and converges only while online and not backgrounded. The adapter most apps use.\n */\nexport function createBrowserConvergenceTrigger(options: { intervalMs?: number } = {}): ConvergenceTrigger {\n const intervalMs = options.intervalMs ?? 1500;\n const env = globalThis as unknown as BrowserEnv;\n\n return {\n subscribe: (onSignal) => {\n const handler = () => {\n onSignal();\n };\n env.window?.addEventListener(\"online\", handler);\n env.document?.addEventListener(\"visibilitychange\", handler);\n const timer = setInterval(handler, intervalMs);\n\n return () => {\n env.window?.removeEventListener(\"online\", handler);\n env.document?.removeEventListener(\"visibilitychange\", handler);\n clearInterval(timer);\n };\n },\n shouldConverge: () => env.navigator?.onLine !== false && env.document?.visibilityState !== \"hidden\",\n };\n}\n\n/**\n * Interval convergence trigger: fires on a fixed cadence and always converges. The minimal\n * non-browser adapter — usable directly in tests/servers and the base a React Native\n * `AppState`/`NetInfo` adapter builds on — which is the second adapter that proves the seam.\n */\nexport function createIntervalConvergenceTrigger(intervalMs: number): ConvergenceTrigger {\n return {\n subscribe: (onSignal) => {\n const timer = setInterval(() => {\n onSignal();\n }, intervalMs);\n\n return () => {\n clearInterval(timer);\n };\n },\n shouldConverge: () => true,\n };\n}\n",
|
|
9
9
|
"// Diagnostic dump (ADR-0035, via the throwaway clone of the addendum). Where a store backup keeps the\n// datadir tarball as its artefact, a diagnostic dump turns the store into human-readable SQL — every table\n// (synced + the `_overlay`/`_mutations` journal), the `pgxsinkit` metadata schema, the read-model views,\n// and the reconcile functions/triggers — so a support engineer sees the misbehaving store EXACTLY as it\n// holds it, unflushed writes and all.\n//\n// The mechanism is the addendum's throwaway clone, NOT the abandoned suspend/reopen seam: (1) take a LIVE\n// datadir dump of the running store (the SAME checkpoint + `dumpDataDir` core the store backup uses, but\n// uncompressed — the clone consumes it immediately, so the gzip+gunzip round trip is pure waste); (2) boot\n// a memory-backed THROWAWAY PGlite from that dump via `loadDataDir` — engine-less, no `live` extension,\n// nothing `pg_dump`'s `DEALLOCATE ALL` can corrupt; (3) run `pg_dump` against the throwaway; (4) discard\n// it. The live engine is never touched — the addendum's whole point — so tabs never notice beyond the\n// lifecycle slot reporting busy.\n//\n// `@electric-sql/pglite-tools` is loaded ONLY via the dynamic `import()` below (ADR-0035 decision 7): its\n// ~700 kB `pg_dump.wasm` (+ ~100 kB JS) stays off boot and off every non-exporting bundle, fetched on first\n// `exportDiagnostics`.\n\nimport { PGlite } from \"@electric-sql/pglite\";\n\nimport type { MutationDiagnostics } from \"@pgxsinkit/contracts\";\n\nimport { compactTimestamp, type DiagnosticDumpReport, deriveStoreId, nowMs, performDatadirDump } from \"./export-store\";\nimport type { ClientPGlite } from \"./index\";\nimport { resolveStoreDataDir } from \"./store-path\";\n\n/** Options for {@link SyncClient.exportDiagnostics}. */\nexport interface DiagnosticExportOptions {\n /**\n * Override the generated artefact file name. When omitted, the name is\n * `<storeId>-<timestamp>-diagnostics.sql`, where `storeId` is a filesystem-safe derivation of the store\n * path (see `deriveStoreId`).\n */\n fileName?: string;\n}\n\n/** The SQL artefact + its report — the resolved value of {@link SyncClient.exportDiagnostics}. */\nexport interface DiagnosticExportResult {\n /** The `pg_dump` output as a named `File` (`application/sql`), loadable into a vanilla Postgres. */\n file: File;\n /** The structured record of the export (ADR-0035). */\n report: DiagnosticDumpReport;\n}\n\n/** The dependencies {@link performDiagnosticExport} needs from the owning client — narrow, so it is unit-testable. */\nexport interface DiagnosticExportDeps {\n /** The live store to checkpoint and dump (the clone source; the live engine is never suspended). */\n pglite: Pick<ClientPGlite, \"exec\" | \"dumpDataDir\">;\n /** The Mutation diagnostics seam (`client.diagnostics().mutation` / `readMutationStats`). */\n readMutationStats: () => Promise<MutationDiagnostics>;\n /**\n * The store's configured plain store PATH (ADR-0036) — reduced to the `storeId` in the default artefact\n * file name. The resolved PGlite dataDir URL is deliberately NOT used: it is internal plumbing and must\n * not leak into an artefact name as something to imitate.\n */\n storePath?: string;\n}\n\n/**\n * The shape of `@electric-sql/pglite-tools/pg_dump` — declared locally so the dynamic `import()` stays\n * typed without a static top-level dependency on the module (which would pull its WASM into the boot\n * bundle). `pgDump` runs the WASM `pg_dump` on the given instance's single connection and returns the SQL\n * as a `File`. We run it against the THROWAWAY clone only, never the live engine.\n */\ninterface PgliteToolsModule {\n pgDump: (opts: { pg: PGlite; args?: string[]; fileName?: string }) => Promise<File>;\n}\n\n/**\n * A process-unique suffix source for the throwaway clone's store name. The clone is memory-backed and\n * closed in a `finally`, so a collision would only matter if two dumps overlapped — the lifecycle slot\n * already forbids that — but a monotonic counter plus a random token makes the name collision-free by\n * construction regardless, so a stray second clone can never adopt a live one's memory namespace.\n */\nlet cloneCounter = 0;\nconst nextCloneStorePath = (): string =>\n `pgxsinkit-export-clone-${++cloneCounter}-${Math.random().toString(36).slice(2, 10)}`;\n\n/** The four extra phase walls the throwaway-clone pipeline adds on top of the shared checkpoint/dump pair. */\nexport interface CloneDumpPhases {\n /** Offset from `startPerf` when the internal `dumpDataDir` (the clone's source) began. */\n dumpStartedAtMs: number;\n /** `dumpDataDir` wall — the uncompressed internal tarball the throwaway clone boots from (`compression: \"none\"`). */\n dumpMs: number;\n /** Offset from `startPerf` when the `CHECKPOINT` began. */\n checkpointStartedAtMs: number;\n /** `CHECKPOINT` wall — flushing dirty buffers before the internal datadir dump the clone consumes. */\n checkpointMs: number;\n /** Offset from `startPerf` when the throwaway clone's `PGlite.create({ loadDataDir })` began. */\n cloneBootStartedAtMs: number;\n /** Clone boot wall — booting the memory-backed throwaway from the internal dump. */\n cloneBootMs: number;\n /** Offset from `startPerf` when `pg_dump` began running against the clone. */\n pgDumpStartedAtMs: number;\n /** `pg_dump` wall — the WASM `pg_dump` reading the clone out to SQL. */\n pgDumpMs: number;\n}\n\n/** The raw SQL bytes plus the pipeline phase walls — {@link runThrowawayCloneDump}'s result. */\nexport interface CloneDumpResult {\n /** The `pg_dump` output bytes (unwrapped from pglite-tools' `File` polyfill). */\n sqlBytes: Uint8Array<ArrayBuffer>;\n /** The pipeline phase timings, all offset from the caller's `startPerf` anchor. */\n phases: CloneDumpPhases;\n}\n\n/**\n * The throwaway-clone dump core shared by BOTH `pgDump` exports (ADR-0035 addendum): (1) a LIVE datadir dump\n * of the running store (`compression: \"none\"` — the clone consumes the bytes immediately, so gzip+gunzip is\n * pure waste); (2) a memory-backed THROWAWAY PGlite booted from it via `loadDataDir` — engine-less, no\n * `live` extension, nothing `pg_dump`'s `DEALLOCATE ALL` can corrupt; (3) `pg_dump` against the throwaway\n * with the caller's `args` (none for a diagnostic dump; the `-t` allowlist + `--no-owner` for a data\n * export); (4) discard the clone in a `finally`. Factored out so `performDiagnosticExport` and\n * `performDataExport` cannot drift on the clone plumbing, the memory-scheme selection, or the timing house\n * style — the ONLY differences between the two dumps are the `pg_dump` args and the artefact assembly.\n *\n * `@electric-sql/pglite-tools` is loaded ONLY via the dynamic `import()` here (ADR-0035 decision 7): its\n * ~700 kB `pg_dump.wasm` (+ ~100 kB JS) stays off boot and off every non-exporting bundle.\n */\nexport interface CloneDumpOptions {\n /** The `pg_dump` args (none for a diagnostic dump; `-t` allowlist + `--no-owner` for a data export). */\n pgDumpArgs?: string[];\n /**\n * A hook run on the throwaway clone AFTER boot, BEFORE `pg_dump` — its one legitimate window to mutate the\n * clone (which is fully owned and discarded straight after). The data export uses it to drop the reconcile\n * triggers `pg_dump -t` would otherwise pull into the artefact (see `buildDataExportCloneCleanupSql`); a\n * diagnostic dump passes none (it wants the store verbatim).\n */\n prepareClone?: (clone: PGlite) => Promise<void>;\n}\n\nexport async function runThrowawayCloneDump(\n pglite: Pick<ClientPGlite, \"exec\" | \"dumpDataDir\">,\n startPerf: number,\n options: CloneDumpOptions = {},\n): Promise<CloneDumpResult> {\n // Step 1 — the LIVE datadir dump the clone boots from (checkpoint → `dumpDataDir`, the shared core).\n const { dumped, checkpointStartedAtMs, checkpointMs, dumpStartedAtMs, dumpMs } = await performDatadirDump(\n pglite,\n \"none\",\n startPerf,\n );\n\n // Step 2 — boot the throwaway. Memory-backed via the resolution module's SCHEME selection (ADR-0036\n // decision 5: NEVER PGlite's explicit `fs: new MemoryFS()` — on 0.5.4 a `dumpDataDir` from an explicit-fs\n // instance silently omits post-initdb relation files). No extensions, no `electric` engine, no `live`:\n // the clone exists only to be read out by `pg_dump`, and `DEALLOCATE ALL` has nothing here to corrupt.\n const cloneDataDir = resolveStoreDataDir(nextCloneStorePath(), \"memory\");\n const cloneBootStartedAtMs = nowMs() - startPerf;\n const cloneBootStartPerf = nowMs();\n const throwaway = await PGlite.create({ dataDir: cloneDataDir, loadDataDir: dumped });\n const cloneBootMs = nowMs() - cloneBootStartPerf;\n\n let sqlBytes: Uint8Array<ArrayBuffer>;\n let pgDumpStartedAtMs: number;\n let pgDumpMs: number;\n try {\n // Between boot and dump — the clone's one mutation window (owned, discarded next) — run the caller's\n // prepare hook. The data export drops the reconcile triggers `-t` would otherwise capture; timed inside\n // the pgDump-prep gap, it is a couple of tiny DROPs, so it is not given its own report phase.\n if (options.prepareClone) {\n await options.prepareClone(throwaway);\n }\n\n // Step 3 — the lazy `pg_dump`. The subpath specifier (its export map's `./pg_dump` entry) keeps the\n // main pglite-tools entry — and its WASM — off this import. The caller rebuilds the artefact `File`\n // from the returned bytes, so `fileName` here is cosmetic only.\n pgDumpStartedAtMs = nowMs() - startPerf;\n const pgDumpStartPerf = nowMs();\n const { pgDump } = (await import(\"@electric-sql/pglite-tools/pg_dump\")) as PgliteToolsModule;\n const dumpFile = await pgDump({\n pg: throwaway,\n ...(options.pgDumpArgs != null ? { args: options.pgDumpArgs } : {}),\n fileName: \"pgxsinkit-export.sql\",\n });\n pgDumpMs = nowMs() - pgDumpStartPerf;\n sqlBytes = new Uint8Array(await dumpFile.arrayBuffer());\n } finally {\n // Step 4 — discard the throwaway in a `finally`, so a THROWING `pg_dump` never leaks the clone (its\n // memory is co-resident with the live engine for the export's duration; leaking one is a real cost).\n await throwaway.close();\n }\n\n return {\n sqlBytes,\n phases: {\n checkpointStartedAtMs,\n checkpointMs,\n dumpStartedAtMs,\n dumpMs,\n cloneBootStartedAtMs,\n cloneBootMs,\n pgDumpStartedAtMs,\n pgDumpMs,\n },\n };\n}\n\n/**\n * Run a diagnostic dump (ADR-0035): live datadir dump → memory-backed throwaway clone → `pg_dump` → discard\n * the clone → assemble the report. The caller (`createSyncClient`) awaits engine-ready and enters the\n * lifecycle slot BEFORE calling this, exactly as it does for the store backup — kept out of here so the\n * helper stays a pure \"do the dump\" unit.\n */\nexport async function performDiagnosticExport(\n deps: DiagnosticExportDeps,\n options: DiagnosticExportOptions = {},\n): Promise<DiagnosticExportResult> {\n const startedAt = Date.now();\n const startPerf = nowMs();\n\n // A diagnostic dump takes the WHOLE store (no `-t`): synced + overlay + journal + metadata + views +\n // functions — everything a support engineer needs to read a misbehaving store.\n const { sqlBytes, phases } = await runThrowawayCloneDump(deps.pglite, startPerf);\n\n const storeId = deriveStoreId(deps.storePath);\n const fileName = options.fileName ?? `${storeId}-${compactTimestamp()}-diagnostics.sql`;\n // Build the artefact `File` from the raw bytes, NOT by re-wrapping pglite-tools' `File`: it is a polyfill\n // in non-browser hosts, and `new File([polyfillFile], name)` keeps the polyfill's own name (the same bun\n // quirk the store backup hit) — the bytes-first path guarantees the store-scoped name/mime stick.\n const file = new File([sqlBytes], fileName, { type: \"application/sql\" });\n\n // Snapshot diagnostics of the LIVE store (the clone is already closed) — the journal state whose rows the\n // SQL also carries, so the report and the artefact agree on what was unflushed at dump time.\n const diagnostics = await deps.readMutationStats();\n\n const report: DiagnosticDumpReport = {\n reportVersion: 1,\n kind: \"diagnostic-dump\",\n scope: \"everything\",\n startedAt,\n totalMs: nowMs() - startPerf,\n byteLength: file.size,\n phases,\n diagnostics,\n };\n\n return { file, report };\n}\n",
|
|
10
10
|
"// Local store export (ADR-0035). Slice 1 ships the **store backup**: a full-fidelity, PGlite-restorable\n// tarball of the whole local store, taken LIVE (no engine suspension). It is a `CHECKPOINT` — run through\n// the engine's normal query serialisation so it orders behind in-flight engine work — followed by\n// PGlite's `dumpDataDir`. Because the dump is of the datadir itself, the Mutation journal and Overlay\n// travel INSIDE the artefact: a store backup is the lossless option, the only export an offline device\n// with unflushed writes can take (CONTEXT.md → Store backup).\n//\n// Every export resolves to an {@link ExportReport} alongside the artefact, extending the ADR-0034\n// observability rule (the BootReport house style) to exports: a versioned, allocation-light plain object\n// (structured-clones across the worker bridge unchanged) carrying phase timings, a {@link MutationDiagnostics}\n// snapshot, and a `startedAt` epoch anchor with every other value a monotonic offset/duration relative to it.\n\nimport type { MutationDiagnostics } from \"@pgxsinkit/contracts\";\n\nimport type { ClientPGlite } from \"./index\";\n\n/**\n * Monotonic clock (ms) — `performance.now()` where available, else `Date.now()` (mirrors BootReport).\n * Exported so the sibling diagnostic-dump path ({@link file://./export-dump.ts}) times its extra phases\n * (clone boot, pg_dump) on the SAME clock as this module's checkpoint/dump pair.\n */\nexport const nowMs = (): number => (typeof performance !== \"undefined\" ? performance.now() : Date.now());\n\n/** Options for {@link SyncClient.exportStore}. */\nexport interface StoreExportOptions {\n /**\n * How to compress the tarball, forwarded to PGlite's `dumpDataDir`. `\"auto\"` (the default) gzips when a\n * `CompressionStream` is available and falls back to an uncompressed tar otherwise; `\"gzip\"` forces\n * compression; `\"none\"` skips it. The report's `compression` records the compression that was actually\n * applied (which, under `\"auto\"`, is resolved at runtime).\n */\n compression?: \"auto\" | \"gzip\" | \"none\";\n /**\n * Override the generated artefact file name. When omitted, the name is\n * `<storeId>-<timestamp>.pgdata.tar[.gz]`, where `storeId` is a filesystem-safe derivation of the store\n * path and the extension reflects the applied compression.\n */\n fileName?: string;\n}\n\n/**\n * The fields EVERY export report carries, whatever its kind — built in the BootReport house style\n * (ADR-0034): `reportVersion` is a contract number (additive fields keep it, a breaking reshape bumps it);\n * all `*Ms` are milliseconds; `startedAt` is the only wall-clock value and every `*AtMs` is a monotonic\n * offset from it. The per-kind interfaces below add their `kind`/`scope`/`phases` discriminant on top.\n */\nexport interface ExportReportCommon {\n reportVersion: 1;\n /** Epoch anchor (`Date.now()`) at export start; every other duration/offset is monotonic relative to it. */\n startedAt: number;\n /** Export start → artefact ready. */\n totalMs: number;\n /** The artefact's byte length — the size the caller downloads / persists. */\n byteLength: number;\n /**\n * The {@link MutationDiagnostics} snapshot at export time — the journal state captured alongside the\n * artefact (for the store backup, the very journal that travels INSIDE the tarball; for the diagnostic\n * dump, the live store's journal at dump time, whose rows the SQL also carries).\n */\n diagnostics: MutationDiagnostics;\n}\n\n/**\n * A live **store backup** (ADR-0035): the whole datadir as a PGlite-restorable tarball, journal and overlay\n * included. `checkpoint`/`dump` are the only phases — a store backup is a `CHECKPOINT` + `dumpDataDir`, no\n * clone. Slice-1 shape, kept unchanged (the union is additive).\n */\nexport interface StoreBackupReport extends ExportReportCommon {\n /** Which export produced this artefact. */\n kind: \"store-backup\";\n /** What the artefact covers. A store backup is always the whole store, journal and overlay included. */\n scope: \"whole-store\";\n /** The compression actually applied to the tarball (resolved from `\"auto\"` at dump time). */\n compression: \"gzip\" | \"none\";\n phases: {\n /** Offset from export start when the `CHECKPOINT` began. */\n checkpointStartedAtMs: number;\n /** `CHECKPOINT` wall — flushing dirty buffers to the datadir before it is tarred, serialised behind engine work. */\n checkpointMs: number;\n /** Offset from export start when `dumpDataDir` began. */\n dumpStartedAtMs: number;\n /** `dumpDataDir` wall — reading the datadir out and assembling (optionally compressing) the tarball. */\n dumpMs: number;\n };\n}\n\n/**\n * A **diagnostic dump** (ADR-0035, via the throwaway clone of the addendum): human-readable SQL of\n * EVERYTHING the store holds — synced tables, the `_overlay`/`_mutations` journal, the `pgxsinkit` metadata\n * schema, the read-model views, and the reconcile functions/triggers. It is a live datadir dump (checkpoint\n * + `dumpDataDir`) fed into a memory-backed throwaway PGlite via `loadDataDir`, against which `pg_dump` runs\n * — so the live engine is never touched (the addendum's whole point). Its phases add the clone boot and the\n * `pg_dump` walls to the shared checkpoint/dump pair.\n */\nexport interface DiagnosticDumpReport extends ExportReportCommon {\n kind: \"diagnostic-dump\";\n /** A diagnostic dump covers everything the store holds — synced data, journal, metadata, views, functions. */\n scope: \"everything\";\n phases: {\n /** Offset from export start when the `CHECKPOINT` began. */\n checkpointStartedAtMs: number;\n /** `CHECKPOINT` wall — flushing dirty buffers before the internal datadir dump the clone consumes. */\n checkpointMs: number;\n /** Offset from export start when the internal `dumpDataDir` began. */\n dumpStartedAtMs: number;\n /** `dumpDataDir` wall — the uncompressed internal tarball the throwaway clone boots from (`compression: \"none\"`). */\n dumpMs: number;\n /** Offset from export start when the throwaway clone's `PGlite.create({ loadDataDir })` began. */\n cloneBootStartedAtMs: number;\n /** Clone boot wall — booting the memory-backed throwaway from the internal dump. */\n cloneBootMs: number;\n /** Offset from export start when `pg_dump` began running against the clone. */\n pgDumpStartedAtMs: number;\n /** `pg_dump` wall — the WASM `pg_dump` reading the clone out to SQL. */\n pgDumpMs: number;\n };\n}\n\n/**\n * A **data export** (ADR-0035 decision 1, via the throwaway clone of the addendum): the PORTABLE artefact —\n * the synced tables and the enum types they depend on, schema + data, nothing of pgxsinkit's machinery,\n * loadable into a vanilla Postgres. It is a generated enum DDL header concatenated ahead of a `pg_dump -t`\n * (per synced table) `--no-owner` run against the same memory-backed throwaway clone the diagnostic dump\n * uses. Unlike the other two exports it GUARDS: it requires a drained Mutation journal (or the explicit\n * `drainJournal: false` escape hatch), so its phases add the drain wall ahead of the clone pipeline, and it\n * records its provenance (`tables` = the `-t` allowlist actually applied, `escapeHatch` = whether the drain\n * was skipped).\n */\nexport interface DataExportReport extends ExportReportCommon {\n kind: \"data-export\";\n /** A data export covers the synced tables + their enum types only — never pgxsinkit's overlay/journal/metadata. */\n scope: \"synced-tables\";\n /**\n * The schema-qualified physical synced tables the `-t` allowlist targeted, in registry order — the\n * self-describing provenance of exactly what the artefact carries (ephemeral/read-projection entries\n * excluded by construction). May be empty when the registry declares no owning persistent table.\n */\n tables: string[];\n /**\n * `true` when `drainJournal: false` skipped the drain and the artefact reflects the SYNCED state as-is\n * (unflushed local writes silently absent). `false` on the strict path (a drained or empty journal).\n */\n escapeHatch: boolean;\n phases: {\n /** Offset from export start when the drain guard began (`0` when the escape hatch skipped it). */\n drainStartedAtMs: number;\n /** Drain wall — flushing + awaiting the journal reach fully-drained (`0` under the escape hatch). */\n drainMs: number;\n /** Offset from export start when the `CHECKPOINT` began. */\n checkpointStartedAtMs: number;\n /** `CHECKPOINT` wall — flushing dirty buffers before the internal datadir dump the clone consumes. */\n checkpointMs: number;\n /** Offset from export start when the internal `dumpDataDir` began. */\n dumpStartedAtMs: number;\n /** `dumpDataDir` wall — the uncompressed internal tarball the throwaway clone boots from (`compression: \"none\"`). */\n dumpMs: number;\n /** Offset from export start when the throwaway clone's `PGlite.create({ loadDataDir })` began. */\n cloneBootStartedAtMs: number;\n /** Clone boot wall — booting the memory-backed throwaway from the internal dump. */\n cloneBootMs: number;\n /** Offset from export start when `pg_dump -t` began running against the clone. */\n pgDumpStartedAtMs: number;\n /** `pg_dump -t` wall — the WASM `pg_dump` reading the allowlisted tables out to SQL. */\n pgDumpMs: number;\n };\n}\n\n/**\n * A structured, versioned record of one local-store export (ADR-0035) — a discriminated union on `kind`.\n * Every member shares {@link ExportReportCommon}; the `kind`/`scope`/`phases` discriminant tells the three\n * exports apart. `exportStore` resolves a {@link StoreBackupReport}; `exportDiagnostics` a\n * {@link DiagnosticDumpReport}; `exportData` a {@link DataExportReport}.\n */\nexport type ExportReport = StoreBackupReport | DiagnosticDumpReport | DataExportReport;\n\n/** The artefact + its report — the resolved value of {@link SyncClient.exportStore}. */\nexport interface StoreExportResult {\n /** The store-backup tarball as a named `File` (PGlite-restorable via `loadDataDir`, a later slice). */\n file: File;\n /** The structured record of the export (ADR-0035). */\n report: StoreBackupReport;\n}\n\n/**\n * Reduce a plain store PATH (ADR-0036) to a filesystem-safe token for the backup file name. Takes the\n * path's LAST segment (as PGlite's own `dumpDataDir` does when it names the inner db), then keeps only\n * `[A-Za-z0-9._-]`. No scheme stripping — the store path is a plain name, never a storage URL. Falls back\n * to a fixed token for an empty path so the name is always well formed.\n */\nexport function deriveStoreId(storePath: string | undefined): string {\n if (!storePath) return \"pgxsinkit-store\";\n const lastSegment = storePath.split(\"/\").filter(Boolean).pop() ?? storePath;\n const safe = lastSegment.replace(/[^A-Za-z0-9._-]/g, \"-\").replace(/^-+|-+$/g, \"\");\n return safe.length > 0 ? safe : \"pgxsinkit-store\";\n}\n\n/**\n * An ISO-ish, filesystem-safe timestamp (colons/dots → hyphens) for a default artefact file name. Exported\n * so the diagnostic-dump path names its `.sql` artefact with the identical timestamp shape.\n */\nexport const compactTimestamp = (): string => new Date().toISOString().replace(/[:.]/g, \"-\");\n\n/**\n * The datadir dump both exports share (ADR-0035): a `CHECKPOINT` through the store's normal query path,\n * then `dumpDataDir`. The store backup keeps its bytes as the artefact; the diagnostic dump feeds them to a\n * throwaway clone. Factored out so exactly one implementation of \"flush + tar the live datadir\" exists —\n * `performStoreExport` and `performDiagnosticExport` cannot drift on the checkpoint ordering or the timing\n * house style. Returns the raw `dumpDataDir` output plus the two phase walls, both offset from `startPerf`\n * (the caller's export-start monotonic anchor) so the timings compose into either report.\n *\n * The `CHECKPOINT` is a utility statement — Drizzle has no builder for it, so a raw `exec` is the justified\n * tier-③ form here. Running it via `pglite.exec` serialises it behind any in-flight engine work on PGlite's\n * single connection, flushing dirty buffers to the datadir the dump then reads — so the tarball reflects\n * committed state, not a torn mid-write datadir.\n */\nexport async function performDatadirDump(\n pglite: Pick<ClientPGlite, \"exec\" | \"dumpDataDir\">,\n compression: \"auto\" | \"gzip\" | \"none\",\n startPerf: number,\n): Promise<{\n dumped: Awaited<ReturnType<ClientPGlite[\"dumpDataDir\"]>>;\n checkpointStartedAtMs: number;\n checkpointMs: number;\n dumpStartedAtMs: number;\n dumpMs: number;\n}> {\n const checkpointStartedAtMs = nowMs() - startPerf;\n const checkpointStartPerf = nowMs();\n await pglite.exec(\"CHECKPOINT\");\n const checkpointMs = nowMs() - checkpointStartPerf;\n\n const dumpStartedAtMs = nowMs() - startPerf;\n const dumpStartPerf = nowMs();\n const dumped = await pglite.dumpDataDir(compression);\n const dumpMs = nowMs() - dumpStartPerf;\n\n return { dumped, checkpointStartedAtMs, checkpointMs, dumpStartedAtMs, dumpMs };\n}\n\n/** The dependencies {@link performStoreExport} needs from the owning client — narrow, so it is unit-testable. */\nexport interface StoreExportDeps {\n /** The live store to checkpoint and dump. */\n pglite: Pick<ClientPGlite, \"exec\" | \"dumpDataDir\">;\n /** The Mutation diagnostics seam (`client.diagnostics().mutation` / `readMutationStats`). */\n readMutationStats: () => Promise<MutationDiagnostics>;\n /**\n * The store's configured plain store PATH (ADR-0036) — reduced to the `storeId` in the default backup\n * file name (`deriveStoreId`). The resolved PGlite dataDir URL is deliberately NOT used here: it is\n * internal plumbing and must not leak into an artefact name as something to imitate.\n */\n storePath?: string;\n}\n\n/**\n * Run a live store backup (ADR-0035): checkpoint → dump → snapshot diagnostics → assemble the report. The\n * caller (`createSyncClient`) is responsible for awaiting engine-ready and entering the lifecycle slot\n * BEFORE calling this — kept out of here so the helper stays a pure \"do the dump\" unit. No engine\n * suspension: the backup is live by design.\n */\nexport async function performStoreExport(\n deps: StoreExportDeps,\n options: StoreExportOptions = {},\n): Promise<StoreExportResult> {\n const startedAt = Date.now();\n const startPerf = nowMs();\n const compression = options.compression ?? \"auto\";\n\n // Live dump of the whole datadir (checkpoint → `dumpDataDir`, the shared core) — the journal and overlay\n // ride inside it (the lossless backup, ADR-0035).\n const { dumped, checkpointStartedAtMs, checkpointMs, dumpStartedAtMs, dumpMs } = await performDatadirDump(\n deps.pglite,\n compression,\n startPerf,\n );\n\n // PGlite names its dump `<db>.tar.gz` (type `application/x-gzip`) when it compressed, `<db>.tar`\n // (`application/x-tar`) otherwise — so the RESULT, not the requested option, tells us what `\"auto\"`\n // resolved to. Detect from whichever of name/type the runtime populated (its `File` is a polyfill in\n // non-browser hosts, so trust both).\n const dumpedName = dumped instanceof File ? dumped.name : \"\";\n const gzipped = dumpedName.endsWith(\".gz\") || dumped.type.includes(\"gzip\");\n const appliedCompression: \"gzip\" | \"none\" = gzipped ? \"gzip\" : \"none\";\n const extension = gzipped ? \".pgdata.tar.gz\" : \".pgdata.tar\";\n const mimeType = gzipped ? \"application/x-gzip\" : \"application/x-tar\";\n const storeId = deriveStoreId(deps.storePath);\n const fileName = options.fileName ?? `${storeId}-${compactTimestamp()}${extension}`;\n // Build the artefact `File` from the raw bytes, NOT by re-wrapping `dumped`: PGlite's dump is a File\n // polyfill in non-browser hosts, and `new File([polyfillFile], name)` keeps the polyfill's own name\n // rather than the one we pass. Extracting the bytes first guarantees the store-scoped name sticks.\n const bytes = new Uint8Array(await dumped.arrayBuffer());\n const file = new File([bytes], fileName, { type: mimeType });\n\n // Snapshot diagnostics AFTER the dump so it describes the journal state the artefact actually holds.\n const diagnostics = await deps.readMutationStats();\n\n const report: StoreBackupReport = {\n reportVersion: 1,\n kind: \"store-backup\",\n scope: \"whole-store\",\n compression: appliedCompression,\n startedAt,\n totalMs: nowMs() - startPerf,\n byteLength: file.size,\n phases: { checkpointStartedAtMs, checkpointMs, dumpStartedAtMs, dumpMs },\n diagnostics,\n };\n\n return { file, report };\n}\n",
|
|
@@ -13,32 +13,33 @@
|
|
|
13
13
|
"import { getTableConfig, getViewConfig } from \"drizzle-orm/pg-core\";\n\nimport type { SyncTableRegistry } from \"@pgxsinkit/contracts\";\n\n/**\n * Lazy-relation safety (ADR-0021).\n *\n * A `lazy` relation is held out of the eager boot and only subscribed on first reference. The hazard is\n * a query reading it *before* it is hydrated — which silently returns empty/stale rows. This pure,\n * React-free core detects which lazy relations a query reads by scanning its **compiled** SQL, so the\n * caller can activate them (and hydrate-then-run) before the query executes.\n *\n * Why a single SQL scan is sufficient (and why there is no Proxy / builder-AST walk): Drizzle compiles\n * a query to parameterised SQL — values are bound (`$1`, `$2`), never inlined — and emits every relation\n * as a **quoted** identifier (`\"name\"`, or `\"schema\".\"name\"` when it carries a schema). So the compiled\n * SQL is ground truth: a relation the query reads must appear there by name, and the only things in the\n * text are quoted identifiers, keywords and `$n` placeholders. The index is built from the *same* Drizzle\n * objects that emit the SQL (`getTableConfig`/`getViewConfig`), so a token matches emission by\n * construction — schema and all. See \"Known limitations\" in ADR-0021 for the residual edges.\n */\n\n/** Static index of a registry's synced relations and the exact quoted tokens their reads compile to. */\nexport interface LazyGuardIndex {\n /** Registry keys whose subscription timing is `lazy`. */\n readonly lazyKeys: ReadonlySet<string>;\n /**\n * Per lazy key, the exact quoted reference token(s) the compiled SQL emits when reading it: the synced\n * table (and, for readwrite, its read-model view) as `\"name\"` or `\"schema\".\"name\"` — or, for a read\n * PROJECTION (ADR-0025), its DISTINCT local identity (`localTable`, the `as` name) rather than the\n * owner's physical table. Schema-qualified when the Drizzle object carries a schema — which makes the\n * token collision-proof against bare aliases/CTEs.\n */\n readonly lazyTokens: ReadonlyMap<string, readonly string[]>;\n /**\n * EVERY synced relation key (eager AND lazy). {@link lazyKeys} is a subset. Drives the hydration\n * guarantee (ADR-0021/0032): a live subscription must gate `hydrating` on every consistency group it\n * reads, not only the lazy ones — an eager group can still be catching up on a cold boot.\n */\n readonly allKeys: ReadonlySet<string>;\n /**\n * Per synced key (eager AND lazy), the exact quoted reference token(s) its reads compile to — the same\n * token rules as {@link lazyTokens}, just spanning every subscription timing. {@link lazyTokens} is a\n * subset restricted to the lazy keys (activation stays lazy-only; hydration spans all).\n */\n readonly allTokens: ReadonlyMap<string, readonly string[]>;\n}\n\n/**\n * The exact quoted reference token(s) a compiled read of `entry` emits — the synced base table (and, for\n * readwrite, its read-model view), or a read PROJECTION's (ADR-0025) DISTINCT local identity. Shared by\n * the lazy-only and all-relations index builds so a token matches emission by construction.\n */\nfunction tokensForEntry(entry: SyncTableRegistry[string]): string[] {\n const tokens: string[] = [];\n if (entry.readProjection) {\n // A read PROJECTION (defineReadProjection, ADR-0025) owns no physical table: its `entry.table` is the\n // OWNER's physical table, but a consumer reads it ONLY through its DISTINCT local identity\n // `entry.localTable` (the `as` name — where Electric syncs the projection's rows). Token that, NOT the\n // owner's physical name: a read of the projection's own local table then resolves to it, while a read of\n // the owner's table resolves the OWNER entry (which carries the owner token) without falsely resolving\n // this projection. (A projection is always readonly and has no read-model view.)\n const localTable = getTableConfig(entry.localTable);\n tokens.push(quotedRef(localTable.name, localTable.schema));\n } else {\n // A regular entry is read through the synced base table (and, for readwrite, its read-model view);\n // `entry.localTable` shares the base table's name here, so no extra token is needed.\n const table = getTableConfig(entry.table);\n tokens.push(quotedRef(table.name, table.schema));\n if (entry.view != null) {\n const view = getViewConfig(entry.view);\n tokens.push(quotedRef(view.name, view.schema));\n }\n }\n return tokens;\n}\n\n/** Build the {@link LazyGuardIndex} for a registry. Cheap and pure — cache it per client. */\nexport function buildLazyGuardIndex(registry: SyncTableRegistry): LazyGuardIndex {\n const lazyKeys = new Set<string>();\n const lazyTokens = new Map<string, readonly string[]>();\n const allKeys = new Set<string>();\n const allTokens = new Map<string, readonly string[]>();\n\n for (const [key, entry] of Object.entries(registry)) {\n const tokens = tokensForEntry(entry);\n allKeys.add(key);\n allTokens.set(key, tokens);\n // ACTIVATION stays lazy-only (ADR-0021): eager groups start at boot, so only lazy keys enter the lazy\n // maps the `prepareQuery`/`ensureSynced` guard scans. Hydration (all keys) is a superset.\n if (entry.subscription === \"lazy\") {\n lazyKeys.add(key);\n lazyTokens.set(key, tokens);\n }\n }\n\n return { lazyKeys, lazyTokens, allKeys, allTokens };\n}\n\n/** The quoted identifier Drizzle emits for a relation: `\"schema\".\"name\"` when schema-qualified, else `\"name\"`. */\nfunction quotedRef(name: string, schema: string | undefined): string {\n return schema != null && schema.length > 0 ? `\"${schema}\".\"${name}\"` : `\"${name}\"`;\n}\n\n/**\n * The compiled-SQL scan: the lazy registry keys whose quoted reference token appears in `sql`. Because\n * the token is fully quoted it is self-delimiting (`\"a\"` cannot match inside `\"ab\"`), so a substring test\n * is exact. A *bare* token sitting in alias position (`… as \"name\"`, which Drizzle emits for `.as(\"name\")`)\n * is excluded — the one realistic collision for a schema-less relation; a schema-qualified token cannot be\n * aliased and so needs no such guard.\n */\nexport function findReferencedLazyKeysInSql(sql: string, index: LazyGuardIndex): Set<string> {\n const found = new Set<string>();\n for (const [key, tokens] of index.lazyTokens) {\n if (tokens.some((token) => sqlReferencesToken(sql, token))) found.add(key);\n }\n return found;\n}\n\n/**\n * The compiled-SQL scan across EVERY synced relation (eager AND lazy): the registry keys whose quoted\n * reference token appears in `sql`. Same exact-token matching as {@link findReferencedLazyKeysInSql}, just\n * over {@link LazyGuardIndex.allTokens}. Drives the hydration guarantee — the caller maps each key to its\n * consistency group and gates a live subscription's `hydrating` on every group still catching up.\n */\nexport function findReferencedSyncedKeysInSql(sql: string, index: LazyGuardIndex): Set<string> {\n const found = new Set<string>();\n for (const [key, tokens] of index.allTokens) {\n if (tokens.some((token) => sqlReferencesToken(sql, token))) found.add(key);\n }\n return found;\n}\n\nfunction sqlReferencesToken(sql: string, token: string): boolean {\n for (let from = 0; ;) {\n const at = sql.indexOf(token, from);\n if (at === -1) return false;\n // Exclude an alias occurrence: `<expr> as \"token\"`. Only a bare token can be an alias, so this never\n // rejects a real (schema-qualified or FROM/JOIN) reference. Window comfortably covers Drizzle's ` as `.\n if (!/\\bas\\s+$/i.test(sql.slice(Math.max(0, at - 16), at))) return true;\n from = at + token.length;\n }\n}\n\n/**\n * The activation backstop (ADR-0021): throw if a query references a lazy relation that is still not\n * active. Called *after* the referenced lazy relations have been activated, so in the normal path every\n * scanned relation is now active and this passes. It fires only when activation could not make a\n * referenced relation active (a start that failed, or a lazy relation with no consistency group) —\n * converting a would-be silent empty/stale read into a loud error.\n */\nexport function assertLazyRefsActivated(args: {\n sql: string;\n index: LazyGuardIndex;\n isActive: (key: string) => boolean;\n}): void {\n const referenced = findReferencedLazyKeysInSql(args.sql, args.index);\n const missing = [...referenced].filter((key) => !args.isActive(key));\n if (missing.length > 0) throw new LazyRelationNotActivatedError(missing);\n}\n\n/** Thrown by the backstop ({@link assertLazyRefsActivated}) when a referenced lazy relation could not be activated. */\nexport class LazyRelationNotActivatedError extends Error {\n /** The lazy registry keys that were referenced but could not be activated. */\n readonly relations: readonly string[];\n\n constructor(relations: readonly string[]) {\n const quoted = relations.map((r) => `\"${r}\"`).join(\", \");\n super(\n `[pgxsinkit] query references lazy-synced relation(s) ${quoted} that could not be activated (ADR-0021), ` +\n `so it would read empty/stale data. This is usually a failed initial sync or a lazy relation with no ` +\n `consistency group. Activate it explicitly — client.ensureSynced([${quoted}]) — or check the sync ` +\n `status. See \"Known limitations\" in ADR-0021.`,\n );\n this.name = \"LazyRelationNotActivatedError\";\n this.relations = relations;\n }\n}\n",
|
|
14
14
|
"// The engine lifecycle slot (ADR-0035 decision 4). A store holds ONE in-flight lifecycle operation at a\n// time — the three exports plus the destructive ops `destroy()`/`discardEphemeral()`/`dropReadCache()` — so\n// two blackout-class operations can never overlap and corrupt each other's view of the store. The slot does\n// NOT queue: a\n// second entrant while one is running is rejected immediately with a typed {@link LifecycleBusyError}\n// (the ADR's deliberate choice — a fresh artefact is better served by the caller retrying than by\n// stacking back-to-back operations the second could get fresher after the first settles).\n\n/**\n * Thrown when a lifecycle operation is attempted while another already holds the slot (ADR-0035). Carries\n * the running operation's `label` so a caller (or a retry policy) can report exactly what it collided with.\n * A distinct error type — not a bare `Error` — so callers can `instanceof`-branch a busy collision from a\n * genuine operation failure.\n */\nexport class LifecycleBusyError extends Error {\n /** The label of the lifecycle operation currently holding the slot. */\n readonly runningLabel: string;\n /** The label of the operation that was refused. */\n readonly attemptedLabel: string;\n\n constructor(attemptedLabel: string, runningLabel: string) {\n super(\n `[pgxsinkit] lifecycle busy: \"${attemptedLabel}\" refused while \"${runningLabel}\" is running (ADR-0035; retry once it settles).`,\n );\n this.name = \"LifecycleBusyError\";\n this.attemptedLabel = attemptedLabel;\n this.runningLabel = runningLabel;\n }\n}\n\n/** A single-occupancy lifecycle slot. One owner per store (`createSyncClient`); one operation at a time. */\nexport interface LifecycleSlot {\n /**\n * Run `fn` under the slot's exclusion. Rejects with a {@link LifecycleBusyError} — without invoking `fn`\n * — if the slot is already occupied; otherwise holds the slot for `fn`'s lifetime and releases it in a\n * `finally`, so a throwing operation never leaves the slot stuck. The occupancy check + claim run\n * synchronously on entry (before the first `await`), so two calls issued in the same tick resolve\n * deterministically: the first claims, the second is refused.\n */\n run: <T>(label: string, fn: () => Promise<T>) => Promise<T>;\n /** Whether an operation currently holds the slot. */\n isBusy: () => boolean;\n /** The label of the operation currently holding the slot, or `null` when free. */\n runningLabel: () => string | null;\n}\n\n/** Create an empty lifecycle slot (ADR-0035 decision 4). */\nexport function createLifecycleSlot(): LifecycleSlot {\n let running: string | null = null;\n\n return {\n run: async (label, fn) => {\n // Refuse before touching `fn` — a busy collision must have zero side effects on the running operation.\n if (running !== null) throw new LifecycleBusyError(label, running);\n // Claim synchronously (before the first `await` below) so a same-tick second entrant sees us busy.\n running = label;\n try {\n return await fn();\n } finally {\n running = null;\n }\n },\n isBusy: () => running !== null,\n runningLabel: () => running,\n };\n}\n",
|
|
15
15
|
"import { quoteIdentifier } from \"@pgxsinkit/contracts\";\n\n// ─── Live-read materialization safety (ADR-0032 S2 §4) ───────────────────────────────────────────────\n//\n// The live-rows seam feeds the compiled SQL of a Drizzle-built select into PGlite's `live` extension,\n// which MATERIALISES the query (a temp view + state table it diffs against). Drizzle emits no output\n// aliases — it maps result columns positionally — so a JOIN whose tables share a column name (two\n// `title`) compiles to a SELECT with duplicate OUTPUT column names. That is legal as a plain one-shot\n// query, but the live materialisation fails hard:\n//\n// column \"title\" specified more than once\n//\n// and even the plain query silently COLLAPSES the same-named columns into one value (the last one wins),\n// because rows are keyed by column name. The compiled SQL cannot dedupe itself, so the seam must render\n// it into a form that is safe to materialise.\n\n/** The derived-table alias the live-rows seam wraps a materialised query under. Kept unlikely to collide. */\nconst LIVE_QUERY_TABLE_ALIAS = \"__pgx_live\";\n\n/**\n * Make a live-read SQL statement SAFE TO MATERIALISE by giving every output column a UNIQUE explicit name.\n *\n * `fields` is the ordered list of unique output aliases — one per output column, in the compiled SQL's\n * column order (Drizzle emits columns depth-first over the select's field keys, which are unique by\n * construction). The statement is wrapped in a derived table with a POSITIONAL column-alias-list:\n *\n * SELECT * FROM (<sql>) \"__pgx_live\" (\"<a0>\", \"<a1>\", …)\n *\n * A plain `SELECT * FROM (<sql>)` does NOT dedupe — the inner duplicate names survive — so the\n * column-alias-list is what renames every output column POSITIONALLY to a distinct name. The wrapped\n * query materialises cleanly, and its rows come back keyed by the aliases (so same-named source columns\n * keep DISTINCT values). `SELECT *` from the aliased derived table is safe precisely because the alias\n * list has already made the names unique.\n *\n * Returns the SQL UNCHANGED when `fields` is absent or empty — the backward-compatible path for existing\n * callers (raw SQL strings, or non-colliding queries that pass no `fields`): they keep name-keyed rows\n * exactly as before. Only a caller that supplies `fields` opts into alias-keyed rows.\n */\nexport function wrapLiveQueryForMaterialization(sql: string, fields: readonly string[] | undefined): string {\n if (fields == null || fields.length === 0) {\n return sql;\n }\n const aliasList = fields.map((field) => quoteIdentifier(field)).join(\", \");\n return `SELECT * FROM (${sql}) ${quoteIdentifier(LIVE_QUERY_TABLE_ALIAS)} (${aliasList})`;\n}\n",
|
|
16
|
-
"import { eq, like } from \"drizzle-orm\";\nimport { drizzle } from \"drizzle-orm/pglite\";\n\nimport { type MutationDiagnostics, type SyncTableRegistry } from \"@pgxsinkit/contracts\";\n\nimport { getLocalMetaTable } from \"./local-tables\";\nimport type { MutationDb } from \"./mutation\";\nimport { buildWipeLocalStoreSql, generateLocalSchemaSql, REGISTRY_FINGERPRINT_KEY } from \"./schema\";\n\n// Statements are AUTHORED as Drizzle builders over the meta-table object (rename-safe, typed,\n// schema-qualification handled by the table object) and rendered to text+params here, because they\n// EXECUTE through the caller's raw `MutationDb` seam — the one connection the mutation runtime and\n// its tests own (and mock).\nconst metaQueryBuilder = drizzle.mock();\n\n/**\n * The fingerprint-keyed local store (ADR-0006). The registry fingerprint the local PGlite\n * database was provisioned under is recorded in the local-meta table; comparing it to the\n * current fingerprint on boot is how a registry change is *detected* (rather than a\n * hand-bumped `idb://…-vN` suffix), which drives the drain-then-drop read-cache rebuild.\n */\n\n/** A boot-time registry-version reconciliation outcome (ADR-0006 drain-then-drop). */\nexport interface LocalStoreVersionEvent {\n status: \"rebuilt\" | \"deferred\";\n previousFingerprint: string;\n nextFingerprint: string;\n /** Mutations still owed to the server (pending + sending + failed + quarantined). */\n owedMutations: number;\n}\n\n/** The minimal mutation-runtime surface the version reconciliation needs. */\ninterface VersionReconcileRuntime {\n registryVersion: string;\n readMutationStats: () => Promise<MutationDiagnostics>;\n}\n\n/** The registry fingerprint the local store was last provisioned under, or null if unstamped. */\nexport async function readStoredRegistryFingerprint(\n db: MutationDb,\n registry: SyncTableRegistry,\n): Promise<string | null> {\n const meta = getLocalMetaTable(registry);\n const query = metaQueryBuilder\n .select({ value: meta.value })\n .from(meta)\n .where(eq(meta.key, REGISTRY_FINGERPRINT_KEY))\n .limit(1)\n .toSQL();\n const result = await db.query<{ value: string }>(query.sql, query.params as unknown[]);\n\n return result.rows[0]?.value ?? null;\n}\n\n/** Meta-key prefix for a persisted `lazy + persistent` group activation (ADR-0021 §2). */\nconst LAZY_ACTIVATION_PREFIX = \"lazy_active:\";\n\n/**\n * The consistency-group keys of `lazy + persistent` groups that were activated on a previous boot\n * (ADR-0021 §2). On boot these are promoted into the eager subscription set, so a once-activated durable\n * lazy group resumes permanently with no per-session re-evaluation. (`ephemeral` activation is never\n * persisted, so it never appears here.)\n */\nexport async function readActivatedLazyGroups(db: MutationDb, registry: SyncTableRegistry): Promise<Set<string>> {\n const meta = getLocalMetaTable(registry);\n const query = metaQueryBuilder\n .select({ key: meta.key })\n .from(meta)\n .where(like(meta.key, `${LAZY_ACTIVATION_PREFIX}%`))\n .toSQL();\n const result = await db.query<{ key: string }>(query.sql, query.params as unknown[]);\n return new Set(result.rows.map((row) => row.key.slice(LAZY_ACTIVATION_PREFIX.length)));\n}\n\n/** Upsert one meta key — the shared write shape for activations and the fingerprint stamp. */\nasync function upsertMetaValue(db: MutationDb, registry: SyncTableRegistry, key: string, value: string): Promise<void> {\n const meta = getLocalMetaTable(registry);\n const query = metaQueryBuilder\n .insert(meta)\n .values({ key, value })\n .onConflictDoUpdate({ target: meta.key, set: { value } })\n .toSQL();\n await db.query(query.sql, query.params as unknown[]);\n}\n\n/** Persist a `lazy + persistent` group's activation, so the next boot promotes it to eager (ADR-0021 §2). */\nexport async function writeLazyGroupActivation(\n db: MutationDb,\n registry: SyncTableRegistry,\n groupKey: string,\n): Promise<void> {\n await upsertMetaValue(db, registry, `${LAZY_ACTIVATION_PREFIX}${groupKey}`, \"1\");\n}\n\n/** Clear a persisted lazy activation — an explicit `desync` reverts the group to dormant next boot (ADR-0021 §2). */\nexport async function clearLazyGroupActivation(\n db: MutationDb,\n registry: SyncTableRegistry,\n groupKey: string,\n): Promise<void> {\n const meta = getLocalMetaTable(registry);\n const query = metaQueryBuilder\n .delete(meta)\n .where(eq(meta.key, `${LAZY_ACTIVATION_PREFIX}${groupKey}`))\n .toSQL();\n await db.query(query.sql, query.params as unknown[]);\n}\n\n/** Stamp the local store with the fingerprint it is now provisioned under. */\nexport async function writeStoredRegistryFingerprint(\n db: MutationDb,\n registry: SyncTableRegistry,\n fingerprint: string,\n): Promise<void> {\n await upsertMetaValue(db, registry, REGISTRY_FINGERPRINT_KEY, fingerprint);\n}\n\n/**\n * Reconcile the local store against the current registry fingerprint (ADR-0006). A fresh\n * (unstamped) store is stamped; an unchanged fingerprint is a no-op. On a change, the read\n * cache is dropped and rebuilt at the new shape **only when nothing is owed locally** —\n * otherwise the rebuild is deferred (and retried on a later boot) so un-flushed/quarantined\n * writes are never silently dropped. The drain happens across sessions: pending writes flush\n * and reconcile during normal use, and the rebuild completes once the journal is clear.\n *\n * An unstamped store is always treated as brand-new. There is no pre-fingerprint-store path:\n * the fingerprint mechanism shipped before launch, so every store in existence was\n * provisioned with it (and a stamped store's journal therefore always has `registry_version`).\n */\nexport async function reconcileLocalStoreVersion<TRegistry extends SyncTableRegistry>(args: {\n db: MutationDb;\n registry: TRegistry;\n runtime: VersionReconcileRuntime;\n onSchemaChange?: (event: LocalStoreVersionEvent) => void | Promise<void>;\n}): Promise<LocalStoreVersionEvent | null> {\n const { db, registry, runtime } = args;\n const stored = await readStoredRegistryFingerprint(db, registry);\n const current = runtime.registryVersion;\n\n if (stored === current) {\n return null;\n }\n\n if (stored === null) {\n await writeStoredRegistryFingerprint(db, registry, current);\n return null;\n }\n\n return rebuildReadCacheOrDefer(args, stored);\n}\n\n/**\n * The drain-then-drop core (ADR-0006): rebuild the read cache at the current shape when\n * nothing is owed locally, otherwise defer so un-flushed/quarantined writes are never\n * dropped (the drain completes on a later boot).\n */\nasync function rebuildReadCacheOrDefer<TRegistry extends SyncTableRegistry>(\n args: {\n db: MutationDb;\n registry: TRegistry;\n runtime: VersionReconcileRuntime;\n onSchemaChange?: (event: LocalStoreVersionEvent) => void | Promise<void>;\n },\n previousFingerprint: string,\n): Promise<LocalStoreVersionEvent> {\n const { db, registry, runtime, onSchemaChange } = args;\n const current = runtime.registryVersion;\n const stats = await runtime.readMutationStats();\n const owedMutations = stats.pendingCount + stats.sendingCount + stats.failedCount + stats.quarantinedCount;\n\n if (owedMutations > 0) {\n const event: LocalStoreVersionEvent = {\n status: \"deferred\",\n previousFingerprint,\n nextFingerprint: current,\n owedMutations,\n };\n await onSchemaChange?.(event);\n return event;\n }\n\n await db.exec(buildWipeLocalStoreSql(registry));\n await db.exec(generateLocalSchemaSql(registry));\n await writeStoredRegistryFingerprint(db, registry, current);\n const event: LocalStoreVersionEvent = {\n status: \"rebuilt\",\n previousFingerprint,\n nextFingerprint: current,\n owedMutations: 0,\n };\n await onSchemaChange?.(event);\n return event;\n}\n",
|
|
17
|
-
"import type { ColumnBuilderBase } from \"drizzle-orm\";\nimport { getColumns } from \"drizzle-orm\";\nimport {\n bigint,\n boolean,\n customType,\n getTableConfig,\n integer,\n pgSchema,\n pgTable,\n pgView,\n text,\n uuid,\n varchar,\n type AnyPgTable,\n type PgColumn,\n type PgTableWithColumns,\n type PgViewWithSelection,\n} from \"drizzle-orm/pg-core\";\n\nimport {\n deriveSyncColumnTypes,\n getLocalSyncedTablePrimaryKeyColumns,\n getSyncRegistrySchema,\n type SyncColumnType,\n type SyncTableEntry,\n type SyncTableRegistry,\n} from \"@pgxsinkit/contracts\";\n\nimport { LOCAL_META_TABLE } from \"./schema\";\n\n/**\n * Runtime Drizzle objects for the GENERATED local-store relations (ADR-0004): the per-writable-table\n * overlay (`<t>_overlay`), journal (`<t>_mutations`), sync-state view (`<t>_sync_state`), the projected\n * synced read cache, and the `pgxsinkit_local_meta` key/value table. The schema generator\n * (`schema.ts`) remains the one authority for the DDL — these objects exist so the mutation runtime,\n * consumers, and tests can AUTHOR queries against those relations as tier-① Drizzle objects\n * (rename-safe, type-checked) instead of hand-written SQL strings.\n *\n * They are query-authoring objects only — never feed them to drizzle-kit generation; the generated\n * DDL in `schema.ts` is the source of truth for the physical shape, and `local-tables.test`-level\n * coverage (the existing overlay/journal suites run against generator-provisioned stores) is what\n * keeps the two aligned.\n *\n * Every object is schema-QUALIFIED with the registry's own local schema (via `getSyncRegistrySchema`).\n * `entry.table` / `entry.localTable` are already qualified the same way (`defineSyncTable` builds them\n * with the caller's schema, and `attachSyncRegistrySchema` throws unless they match the registry schema),\n * so for the synced read cache the factory just tracks a `clientProjection.syncedTable` rename. The\n * factories earn their keep where no equally-qualified entry handle exists: `entry.view` is built\n * schema-UNqualified (a bare `pgView`), so a store in a non-public schema must author the read model\n * through `getReadModelView`; and the overlay / journal / sync-state relations have NO entry handle at all\n * — these factories are the only Drizzle objects for them. Each factory MEMOIZES its result per\n * `(registry, tableKey)` (the `pgxsinkit_local_meta` table per local schema), so repeated calls hand back\n * the same object identity.\n *\n * Typing tracks the registry the caller holds: with a concretely-typed registry (built by\n * `defineSyncRegistry`) the synced/overlay/read-model objects carry the entry's real per-column types, so\n * `.select({ x: overlay.col })`, `$inferInsert`, and `.values()` all typecheck by property key; with a\n * bare `SyncTableRegistry` they degrade to an open index-signature shape reached by bracket access.\n * `JournalTable` / `SyncStateView` are ALWAYS conservatively indexed for their entity/PK columns (the PK\n * name set is not recoverable at the type level — see those types).\n */\n\n/**\n * Microsecond/bigint columns the mutation runtime handles as **strings** (the JSON-safe form it has\n * always used): passthrough both ways, `bigint` in DDL position. Reads through the raw `MutationDb`\n * seam bypass drizzle result mapping anyway; this keeps `.values()`/`.set()` accepting the runtime's\n * string values without a lossy JS-number hop.\n */\nconst bigintText = customType<{ data: string; driverData: string }>({\n dataType() {\n return \"bigint\";\n },\n});\n\nfunction buildJournalFixedColumns() {\n return {\n mutationId: uuid(\"mutation_id\").primaryKey(),\n entityKeyJson: text(\"entity_key_json\").notNull(),\n mutationSeq: integer(\"mutation_seq\").notNull(),\n mutationKind: varchar(\"mutation_kind\", { length: 24 }).notNull(),\n status: varchar(\"status\", { length: 24 }).notNull(),\n registryVersion: text(\"registry_version\"),\n baseServerVersion: bigintText(\"base_server_version\"),\n writeUnit: text(\"write_unit\"),\n writeMode: varchar(\"write_mode\", { length: 24 }),\n payloadJson: text(\"payload_json\").notNull(),\n attemptCount: integer(\"attempt_count\").notNull().default(0),\n lastError: text(\"last_error\"),\n lastHttpStatus: integer(\"last_http_status\"),\n conflictReason: text(\"conflict_reason\"),\n serverUpdatedAtUs: bigintText(\"server_updated_at_us\"),\n enqueuedAtUs: bigintText(\"enqueued_at_us\").notNull(),\n nextRetryAtUs: bigintText(\"next_retry_at_us\"),\n sentAtUs: bigintText(\"sent_at_us\"),\n ackedAtUs: bigintText(\"acked_at_us\"),\n updatedAtUs: bigintText(\"updated_at_us\").notNull(),\n };\n}\n\nfunction buildOverlayFixedColumns() {\n return {\n overlayKind: varchar(\"overlay_kind\", { length: 24 }).notNull(),\n localUpdatedAtUs: bigintText(\"local_updated_at_us\").notNull(),\n };\n}\n\n/**\n * The two overlay columns the `<t>_read_model` view carries on top of the projected synced columns.\n * Read through real drizzle result mapping (a live query, not the raw `MutationDb` seam), so\n * `local_updated_at_us` is a `mode: \"bigint\"` int8 (PGlite returns it as a string at runtime) rather than\n * the journal/overlay `bigintText` passthrough. Snake-case property keys so consumers reach them the same\n * way the generator names them (`view[\"overlay_kind\"]`).\n */\nfunction buildReadModelFixedColumns() {\n return {\n overlay_kind: varchar(\"overlay_kind\", { length: 24 }).notNull(),\n local_updated_at_us: bigint(\"local_updated_at_us\", { mode: \"bigint\" }).notNull(),\n };\n}\n\nfunction buildSyncStateFixedColumns() {\n return {\n observedServerVersion: bigint(\"observed_server_version\", { mode: \"bigint\" }),\n ackedServerVersion: bigint(\"acked_server_version\", { mode: \"bigint\" }),\n pendingCount: bigint(\"pending_count\", { mode: \"number\" }).notNull(),\n hasAckedUnobservedWrite: boolean(\"has_acked_unobserved_write\").notNull(),\n localDeletePending: boolean(\"local_delete_pending\").notNull(),\n conflictState: text(\"conflict_state\"),\n quarantinedCount: bigint(\"quarantined_count\", { mode: \"number\" }).notNull(),\n quarantineState: text(\"quarantine_state\"),\n };\n}\n\n// Phantom shape tables: never created, never queried — they exist only so the derived relation types\n// carry strong typing on the FIXED column keys. The per-entry ENTITY columns are layered on top from\n// the concrete registry entry (see the `*<TEntry>` types below), so a caller whose registry is\n// concretely typed reaches real, projected `PgColumn`s by property key; only a caller holding a bare\n// `SyncTableRegistry` falls back to the open index-signature form these shapes' generic default gives.\nconst journalShape = pgTable(\"_pgxsinkit_journal_shape\", buildJournalFixedColumns());\nconst overlayShape = pgTable(\"_pgxsinkit_overlay_shape\", buildOverlayFixedColumns());\nconst syncStateShape = pgView(\"_pgxsinkit_sync_state_shape\", buildSyncStateFixedColumns()).existing();\nconst readModelShape = pgView(\"_pgxsinkit_read_model_shape\", buildReadModelFixedColumns()).existing();\nconst localMetaShape = pgTable(LOCAL_META_TABLE, {\n key: text(\"key\").primaryKey(),\n value: text(\"value\").notNull(),\n});\n\n/**\n * The entry's PROJECTED local table type — its server columns minus `clientProjection.omitColumns`,\n * exactly the shape `defineSyncTable` stamped onto `entry.localTable`. When `TEntry` is a concrete\n * entry (a registry built by `defineSyncRegistry`) this carries the real, typed columns; when it is a\n * bare `SyncTableEntry` (a generic `SyncTableRegistry`) it degrades to `AnyPgTable`, which pushes every\n * derived type below onto the open `Record<string, PgColumn>` index-signature fallback.\n */\ntype EntryLocalTable<TEntry> =\n TEntry extends SyncTableEntry<AnyPgTable, infer TLocal extends AnyPgTable> ? TLocal : AnyPgTable;\n\n/** The entry's projected columns keyed by drizzle property key (or the open `PgColumns` fallback). */\ntype EntryColumns<TEntry> = EntryLocalTable<TEntry>[\"_\"][\"columns\"];\ntype OverlayFixedColumns = (typeof overlayShape)[\"_\"][\"columns\"];\ntype ReadModelFixedColumns = (typeof readModelShape)[\"_\"][\"selectedFields\"];\n\n/**\n * The `<t>_overlay` optimistic-intent table: the entry's PROJECTED columns (same builders the generator\n * and `entry.localTable` carry) merged with the two fixed overlay columns. The entity columns read\n * back through real drizzle result mapping, so their types mirror the projected table exactly (a\n * `mode: \"bigint\"` column is `bigint`, etc.). The two overlay columns are `bigintText` passthrough\n * (`local_updated_at_us` reads as a string). `TEntry` defaults to a bare entry, giving the open\n * index-signature form the mutation runtime (generic over any registry) needs.\n */\nexport type OverlayTable<TEntry = SyncTableEntry> = PgTableWithColumns<{\n name: string;\n schema: string | undefined;\n columns: EntryColumns<TEntry> & OverlayFixedColumns;\n dialect: \"pg\";\n}>;\n\n/**\n * The `<t>_read_model` overlay-merged read view (ADR-0004): the entry's PROJECTED columns under their\n * property keys plus the two fixed overlay columns (`overlay_kind`, `local_updated_at_us`). Read\n * through a live query, so `local_updated_at_us` is an int8 `mode: \"bigint\"` column.\n */\nexport type ReadModelView<TEntry = SyncTableEntry> = PgViewWithSelection<\n string,\n true,\n EntryColumns<TEntry> & ReadModelFixedColumns\n>;\n\n/**\n * The projected SYNCED read-cache table — the entry's projected local table (or `AnyPgTable` fallback).\n * Type-level note: the phantom relation name here is the original `tableName` (inherited from\n * `ProjectedLocalTable`), but the runtime object `getSyncedLocalTable` returns honours a\n * `clientProjection.syncedTable` rename — so the rendered SQL uses the runtime name, not this type's name.\n */\nexport type SyncedLocalTable<TEntry = SyncTableEntry> = EntryLocalTable<TEntry>;\n\n/**\n * The `<t>_mutations` journal: fixed runtime columns + the entry's PK columns (index-signature access).\n * Kept conservatively indexed: the journal carries ONLY the PK columns, keyed by DB COLUMN NAME and\n * type-erased to `text`, but neither the PK column-name set nor the \"PK only\" subset is recoverable at\n * the type level from `SyncTableEntry` (its `primaryKey.columns` is an un-narrowed `string[]`), so an\n * honest per-entry type is not representable without a footgun (claiming non-PK columns that do not\n * exist on the journal at runtime). PK/entity columns therefore ride the index signature.\n */\nexport type JournalTable = typeof journalShape & { [columnName: string]: PgColumn };\n/**\n * The `<t>_sync_state` convergence view (ADR-0011): fixed state columns + the entry's PK columns.\n * Conservatively indexed for the same reason as {@link JournalTable} — it projects only the PK columns\n * (a subset not recoverable at the type level), so the PK columns ride the index signature.\n */\nexport type SyncStateView = typeof syncStateShape & { [columnName: string]: PgColumn };\n/** The `pgxsinkit_local_meta` key/value table (ADR-0006). */\nexport type LocalMetaTable = typeof localMetaShape;\n\n/**\n * Build a runtime `pgTable` for a local-store relation. An `ephemeral`-lifecycle entry (ADR-0021 §3)\n * renders **bare** regardless of the registry's local schema: its whole cluster is emitted as `TEMP`\n * with unqualified object names that resolve via `pg_temp`/search_path, exactly as\n * `generateLocalSchemaSql` renders it (a `pgSchema(localSchema).table(...)` reference would target a\n * durable schema the temp table does not live in — the latent qualification bug ADR-0029 records).\n */\nfunction makeTable(\n localSchema: string,\n name: string,\n columns: Record<string, ColumnBuilderBase>,\n ephemeral = false,\n): AnyPgTable {\n return localSchema === \"public\" || ephemeral ? pgTable(name, columns) : pgSchema(localSchema).table(name, columns);\n}\n\nfunction isEphemeral(entry: SyncTableEntry<AnyPgTable>): boolean {\n return entry.retention === \"ephemeral\";\n}\n\nfunction resolveSyncedTableName(entry: SyncTableEntry<AnyPgTable>): string {\n return entry.clientProjection?.syncedTable ?? getTableConfig(entry.table).name;\n}\n\n/**\n * The entry's projected column BUILDERS keyed by property key, re-created from the retained\n * `makeColumns` factory (registry.ts keeps it for exactly this kind of reuse) with\n * `clientProjection.omitColumns` applied — the same projection the generator's synced/overlay DDL\n * carries.\n */\nfunction projectedColumnBuilders(entry: SyncTableEntry<AnyPgTable>, tableKey: string) {\n const makeColumns = entry.makeColumns;\n if (!makeColumns) {\n throw new Error(\n `local table objects for ${tableKey} need the entry's makeColumns factory (built by defineSyncTable); ` +\n `hand-assembled entries cannot derive overlay/journal objects`,\n );\n }\n const omitted = new Set(entry.clientProjection?.omitColumns ?? []);\n return Object.fromEntries(Object.entries(makeColumns()).filter(([key]) => !omitted.has(key))) as Record<\n string,\n ColumnBuilderBase\n >;\n}\n\n/** Property-key ↔ column-name pairs for the entry's PK, resolved via the built local table. */\nfunction pkColumnPairs(entry: SyncTableEntry<AnyPgTable>, tableKey: string) {\n const localColumns = getColumns(entry.localTable) as Record<string, PgColumn>;\n return entry.primaryKey.columns.map((columnName) => {\n const pair = Object.entries(localColumns).find(([, column]) => column.name === columnName);\n if (!pair) {\n throw new Error(`Primary key column ${columnName} was not found on table ${tableKey}`);\n }\n return { propertyKey: pair[0], columnName };\n });\n}\n\ninterface EntryLocalTables {\n synced?: AnyPgTable;\n overlay?: OverlayTable;\n journal?: JournalTable;\n syncState?: SyncStateView;\n readModel?: ReadModelView;\n}\n\nconst localTablesCache = new WeakMap<SyncTableRegistry, Map<string, EntryLocalTables>>();\nconst localMetaCache = new Map<string, LocalMetaTable>();\n\nfunction cacheFor(registry: SyncTableRegistry, tableKey: string): EntryLocalTables {\n let byKey = localTablesCache.get(registry);\n if (!byKey) {\n byKey = new Map();\n localTablesCache.set(registry, byKey);\n }\n let slot = byKey.get(tableKey);\n if (!slot) {\n slot = {};\n byKey.set(tableKey, slot);\n }\n return slot;\n}\n\nfunction requireEntry(registry: SyncTableRegistry, tableKey: string): SyncTableEntry<AnyPgTable> {\n const entry = registry[tableKey];\n if (!entry) {\n throw new Error(`Unknown sync table: ${tableKey}`);\n }\n return entry;\n}\n\nfunction requireWritable(entry: SyncTableEntry<AnyPgTable>, tableKey: string, relation: string) {\n if (!entry.clientProjection?.overlayTable || !entry.clientProjection.journalTable) {\n throw new Error(`${relation} exists only for a writable table; ${tableKey} has no overlay/journal projection`);\n }\n return entry.clientProjection as { overlayTable: string; journalTable: string; syncedTable?: string };\n}\n\n/**\n * The projected SYNCED read-cache table as a runtime Drizzle object, under the resolved local name\n * (`clientProjection.syncedTable` override honoured) and the registry's local schema — the exact\n * relation the generator's `CREATE TABLE` provisions. Prefer `entry.localTable` where its name\n * already matches; this object exists for the runtime/tests that must track the projection rename.\n * Carries the entry's real projected columns under a concretely-typed registry, `AnyPgTable` under a\n * bare `SyncTableRegistry` (see {@link SyncedLocalTable}).\n */\nexport function getSyncedLocalTable<TRegistry extends SyncTableRegistry, TKey extends string & keyof TRegistry>(\n registry: TRegistry,\n tableKey: TKey,\n): SyncedLocalTable<TRegistry[TKey]> {\n const slot = cacheFor(registry, tableKey);\n if (slot.synced) {\n return slot.synced as SyncedLocalTable<TRegistry[TKey]>;\n }\n const entry = requireEntry(registry, tableKey);\n const localSchema = getSyncRegistrySchema(registry);\n const table = makeTable(\n localSchema,\n resolveSyncedTableName(entry),\n projectedColumnBuilders(entry, tableKey) as Record<string, ColumnBuilderBase>,\n isEphemeral(entry),\n );\n slot.synced = table;\n return table as SyncedLocalTable<TRegistry[TKey]>;\n}\n\n/**\n * The `<t>_overlay` optimistic-intent table as a runtime Drizzle object (writable tables only — throws\n * for a readonly entry, which has no overlay/journal projection). Its entity columns are typed exactly\n * as {@link OverlayTable} describes — real per-column types under a concretely-typed registry, the open\n * index-signature fallback under a bare `SyncTableRegistry` — plus the two fixed overlay columns.\n */\nexport function getOverlayTable<TRegistry extends SyncTableRegistry, TKey extends string & keyof TRegistry>(\n registry: TRegistry,\n tableKey: TKey,\n): OverlayTable<TRegistry[TKey]> {\n const slot = cacheFor(registry, tableKey);\n if (slot.overlay) {\n return slot.overlay as OverlayTable<TRegistry[TKey]>;\n }\n const entry = requireEntry(registry, tableKey);\n const projection = requireWritable(entry, tableKey, \"the overlay table\");\n const localSchema = getSyncRegistrySchema(registry);\n const table = makeTable(\n localSchema,\n projection.overlayTable,\n {\n ...(projectedColumnBuilders(entry, tableKey) as Record<string, ColumnBuilderBase>),\n ...buildOverlayFixedColumns(),\n },\n isEphemeral(entry),\n ) as OverlayTable;\n slot.overlay = table;\n return table as OverlayTable<TRegistry[TKey]>;\n}\n\n/**\n * The `<t>_mutations` journal table as a runtime Drizzle object (writable tables only). The fixed runtime\n * columns are typed; the PK/entity columns ride the index signature and are reached by DB column NAME\n * (`journal[\"id\"]`), because per-entry typing is not representable — see {@link JournalTable}.\n */\nexport function getJournalTable<TRegistry extends SyncTableRegistry>(\n registry: TRegistry,\n tableKey: string & keyof TRegistry,\n): JournalTable {\n const slot = cacheFor(registry, tableKey);\n if (slot.journal) {\n return slot.journal;\n }\n const entry = requireEntry(registry, tableKey);\n const projection = requireWritable(entry, tableKey, \"the journal table\");\n const localSchema = getSyncRegistrySchema(registry);\n const pkBuilders = Object.fromEntries(\n pkColumnPairs(entry, tableKey).map(({ columnName }) => [columnName, text(columnName).notNull()]),\n );\n const table = makeTable(\n localSchema,\n projection.journalTable,\n {\n ...pkBuilders,\n ...buildJournalFixedColumns(),\n },\n isEphemeral(entry),\n ) as JournalTable;\n slot.journal = table;\n return table;\n}\n\n/**\n * The `<t>_sync_state` convergence view (ADR-0011) as a runtime Drizzle object (writable tables only) —\n * PK columns under the entry's own property keys plus the fixed state columns, mirroring\n * `buildSyncStateView`'s projection. The fixed state columns are typed; the PK columns ride the index\n * signature (not recoverable at the type level — see {@link SyncStateView}) and are reached by their\n * drizzle PROPERTY key (`view[\"authorId\"]`), unlike the journal, which keys its PK columns by DB column\n * name.\n */\nexport function getSyncStateView<TRegistry extends SyncTableRegistry>(\n registry: TRegistry,\n tableKey: string & keyof TRegistry,\n): SyncStateView {\n const slot = cacheFor(registry, tableKey);\n if (slot.syncState) {\n return slot.syncState;\n }\n const entry = requireEntry(registry, tableKey);\n requireWritable(entry, tableKey, \"the sync-state view\");\n const localSchema = getSyncRegistrySchema(registry);\n const viewName = `${resolveSyncedTableName(entry)}_sync_state`;\n const builders = projectedColumnBuilders(entry, tableKey);\n const pkBuilders = Object.fromEntries(\n pkColumnPairs(entry, tableKey).map(({ propertyKey }) => {\n const builder = builders[propertyKey];\n if (!builder) {\n throw new Error(`Primary key property ${propertyKey} was not found on table ${tableKey}`);\n }\n return [propertyKey, builder];\n }),\n ) as Record<string, ColumnBuilderBase>;\n const columns = {\n ...(pkBuilders as Record<string, ColumnBuilderBase>),\n ...buildSyncStateFixedColumns(),\n };\n const view = (\n localSchema === \"public\" || isEphemeral(entry)\n ? pgView(viewName, columns).existing()\n : pgSchema(localSchema).view(viewName, columns).existing()\n ) as SyncStateView;\n slot.syncState = view;\n return view;\n}\n\n/**\n * The `<t>_read_model` overlay-merged read view (ADR-0004) as a runtime Drizzle object: every projected\n * synced column under the entry's own property key plus the two overlay columns (`overlay_kind`,\n * `local_updated_at_us`), mirroring the generator's `CREATE VIEW`. The entry's own `entry.view` is\n * schema-UNQUALIFIED (`defineSyncTable` builds it with a bare `pgView`), so a consumer whose local store\n * lives in a non-public schema must author against this qualified object instead of `entry.view`.\n */\nexport function getReadModelView<TRegistry extends SyncTableRegistry, TKey extends string & keyof TRegistry>(\n registry: TRegistry,\n tableKey: TKey,\n): ReadModelView<TRegistry[TKey]> {\n const slot = cacheFor(registry, tableKey);\n if (slot.readModel) {\n return slot.readModel as ReadModelView<TRegistry[TKey]>;\n }\n const entry = requireEntry(registry, tableKey);\n requireWritable(entry, tableKey, \"the read-model view\");\n const localSchema = getSyncRegistrySchema(registry);\n const viewName = `${resolveSyncedTableName(entry)}_read_model`;\n const columns = {\n ...(projectedColumnBuilders(entry, tableKey) as Record<string, ColumnBuilderBase>),\n ...buildReadModelFixedColumns(),\n };\n const view = (\n localSchema === \"public\" || isEphemeral(entry)\n ? pgView(viewName, columns).existing()\n : pgSchema(localSchema).view(viewName, columns).existing()\n ) as ReadModelView;\n slot.readModel = view;\n return view as ReadModelView<TRegistry[TKey]>;\n}\n\n/**\n * The read-path applier's resolved per-shape target (ADR-0029 D1/D2). Every table-scoped fact the\n * appliers need is derived once from the registry entry — the real projected synced table object, its\n * columns indexed by DB column name, the primary-key column names, and the model-derived column types —\n * so the appliers author over Drizzle objects (no name/schema strings, no `information_schema` probe).\n * Resolved once per shape at subscribe time; reused for every message. Electric change rows are keyed\n * by DB **column name**, while Drizzle DML keys by **property key**, so both indexes are carried.\n */\nexport interface ApplyTarget {\n /** The real projected synced local table (`getSyncedLocalTable`) — bare for ephemeral lifecycles. */\n table: AnyPgTable;\n /** DB column name → its Drizzle `PgColumn` (for `eq`/conflict-target/COPY clauses). */\n columnByName: Record<string, PgColumn>;\n /** DB column name → its Drizzle property key (to key `.values()`/`.set()` from a name-keyed row). */\n propertyKeyByName: Record<string, string>;\n /** Primary-key column NAMES, in order (from the entry, local-projection override honoured). */\n primaryKey: string[];\n /** Model-derived column types (`deriveSyncColumnTypes`), keyed by DB column name via `.name`. */\n columnTypes: SyncColumnType[];\n /**\n * Per-shape render-once cache for the batched-INSERT family (ADR-0029 D5): a rendered `{sqlText,\n * params}` per distinct (column-set, row-count), reused across batches with per-value codecs applied\n * at execution. Empty at resolution; populated lazily by the applier.\n */\n insertRenderCache: Map<string, { sqlText: string; params: unknown[] }>;\n}\n\n/**\n * Resolve a shape's {@link ApplyTarget} from its registry entry (ADR-0029 D1/D2). Called once per shape\n * at subscribe time — never per message. The single source is the registry item: identity via\n * `getSyncedLocalTable`, PKs via `getLocalSyncedTablePrimaryKeyColumns`, types via `deriveSyncColumnTypes`.\n */\nexport function resolveApplyTarget<TRegistry extends SyncTableRegistry, TKey extends string & keyof TRegistry>(\n registry: TRegistry,\n tableKey: TKey,\n): ApplyTarget {\n const entry = requireEntry(registry, tableKey);\n const table = getSyncedLocalTable(registry, tableKey);\n const columns = getColumns(table as AnyPgTable) as Record<string, PgColumn>;\n const columnByName: Record<string, PgColumn> = {};\n const propertyKeyByName: Record<string, string> = {};\n for (const [propertyKey, column] of Object.entries(columns)) {\n columnByName[column.name] = column;\n propertyKeyByName[column.name] = propertyKey;\n }\n return {\n table: table as AnyPgTable,\n columnByName,\n propertyKeyByName,\n primaryKey: getLocalSyncedTablePrimaryKeyColumns(entry),\n columnTypes: deriveSyncColumnTypes(entry),\n insertRenderCache: new Map(),\n };\n}\n\n/** The `pgxsinkit_local_meta` key/value table (ADR-0006) under the registry's local schema. */\nexport function getLocalMetaTable(registry: SyncTableRegistry): LocalMetaTable {\n const localSchema = getSyncRegistrySchema(registry);\n const cached = localMetaCache.get(localSchema);\n if (cached) {\n return cached;\n }\n const table = makeTable(localSchema, LOCAL_META_TABLE, {\n key: text(\"key\").primaryKey(),\n value: text(\"value\").notNull(),\n }) as LocalMetaTable;\n localMetaCache.set(localSchema, table);\n return table;\n}\n",
|
|
18
|
-
"import { getTableConfig, getViewConfig, type AnyPgTable } from \"drizzle-orm/pg-core\";\n\nimport {\n buildOverlayResolutionBarrier,\n buildSyncStateView,\n getLocalSyncPrimaryKeyColumns,\n getSyncRegistrySchema,\n getProjectedColumns,\n maybeQuoteIdentifier,\n quoteIdentifier,\n quoteSqlLiteral as quoteSqlStringLiteral,\n type SyncTableEntry,\n type SyncTableRegistry,\n} from \"@pgxsinkit/contracts\";\n\nimport { buildClearShapeTagsSql, shapeTableId } from \"./sync/tags\";\n\n/** Internal fully-qualified projection used within schema generation. */\ninterface ResolvedProjection {\n syncedTable: string;\n overlayTable?: string;\n journalTable?: string;\n readModel: string;\n /** The per-table `<table>_sync_state` convergence view (writable tables only — ADR-0011). */\n syncState: string;\n /**\n * The reconcile trigger's function — schema-qualified, because a function is a schema object.\n * Suffix-then-qualify (never `${qualifiedTable}_reconcile_on_sync`, which double-quotes a\n * non-public schema's qualified name into invalid SQL).\n */\n reconcileFunction: string;\n /**\n * The reconcile trigger itself — an UNqualified identifier. A trigger is not a schema object; it\n * is bound to its table via `ON <qualified table>`, so its name must not be schema-qualified.\n */\n reconcileTrigger: string;\n}\n\n/**\n * Local key/value metadata table. Holds the registry fingerprint the local store was\n * provisioned under (ADR-0006), so a registry change is detected on boot and the read\n * cache is rebuilt — rather than relying on a hand-bumped `idb://…-vN` suffix.\n */\nexport const LOCAL_META_TABLE = \"pgxsinkit_local_meta\";\nexport const REGISTRY_FINGERPRINT_KEY = \"registry_fingerprint\";\n\ntype TableColumn = ReturnType<typeof getProjectedColumns<AnyPgTable>>[number][\"column\"];\n\nexport function generateLocalSchemaSql<TRegistry extends SyncTableRegistry>(registry: TRegistry) {\n const statements: string[] = [];\n const localSchema = getSyncRegistrySchema(registry);\n\n if (localSchema !== \"public\") {\n statements.push(`CREATE SCHEMA IF NOT EXISTS ${quoteIdentifier(localSchema)};`);\n }\n\n statements.push(\n `CREATE TABLE IF NOT EXISTS ${qualifyIdentifier(localSchema, LOCAL_META_TABLE)} (\\n ${[\n \"key TEXT PRIMARY KEY\",\n \"value TEXT NOT NULL\",\n ].join(\",\\n \")}\\n);`,\n );\n\n const enumDefinitions = collectEnumDefinitions(registry, localSchema);\n\n for (const enumDefinition of enumDefinitions) {\n statements.push(buildCreateEnumTypeSql(enumDefinition));\n }\n\n for (const [tableKey, entry] of Object.entries(registry)) {\n // ADR-0021 §3: an `ephemeral` table's whole cluster is emitted as `TEMP` — bare (unqualified) object\n // names that resolve via `pg_temp` / search_path, so read- and write-ephemerality fall out together\n // (no durable trace). Object NAMES go bare+TEMP; column *types* (enums) stay in the persistent schema.\n // For a persistent table `temp` is \"\" and `objectSchema` is the registry schema → byte-identical output.\n const ephemeral = entry.retention === \"ephemeral\";\n const objectSchema = ephemeral ? \"public\" : localSchema;\n const temp = ephemeral ? \"TEMP \" : \"\";\n\n const projection = getClientProjection(entry, tableKey, objectSchema);\n const columns = getProjectedColumns(entry).map(({ column }) => column);\n const syncedTablePrimaryKeyColumns = getLocalSyncPrimaryKeyColumns(entry);\n const baseColumnsSql = buildTableColumnSql(columns, syncedTablePrimaryKeyColumns, localSchema);\n\n statements.push(`CREATE ${temp}TABLE IF NOT EXISTS ${projection.syncedTable} (\\n ${baseColumnsSql}\\n);`);\n\n if (entry.mode === \"readonly\") {\n continue;\n }\n\n if (!projection.overlayTable || !projection.journalTable) {\n throw new Error(`overlay and journal tables are required for writable table ${tableKey}`);\n }\n\n const journalTableName = entry.clientProjection?.journalTable;\n\n if (!journalTableName) {\n throw new Error(`journal table is required for writable table ${tableKey}`);\n }\n\n const primaryKeyColumns = entry.primaryKey.columns.map((columnName) => {\n const column = columns.find((candidate) => candidate.name === columnName);\n\n if (!column) {\n throw new Error(`Primary key column ${columnName} was not found on table ${tableKey}`);\n }\n\n return column;\n });\n const primaryKeyColumnNames = primaryKeyColumns.map((column) => column.name);\n const journalSequenceName = buildJournalSequenceName(journalTableName);\n const qualifiedJournalSequenceName = qualifyIdentifier(objectSchema, journalSequenceName);\n\n statements.push(\n `CREATE ${temp}TABLE IF NOT EXISTS ${projection.overlayTable} (\\n ${[\n ...columns.map((column) => buildColumnDefinition(column, primaryKeyColumnNames, localSchema)),\n \"overlay_kind VARCHAR(24) NOT NULL\",\n \"local_updated_at_us BIGINT NOT NULL\",\n ...buildCompositePrimaryKeyClauses(primaryKeyColumnNames),\n ].join(\",\\n \")}\\n);`,\n );\n\n statements.push(\n `CREATE ${temp}SEQUENCE IF NOT EXISTS ${qualifiedJournalSequenceName} AS integer START WITH 1 INCREMENT BY 1;`,\n );\n\n statements.push(\n `CREATE ${temp}TABLE IF NOT EXISTS ${projection.journalTable} (\\n ${[\n \"mutation_id UUID PRIMARY KEY\",\n ...primaryKeyColumns.map((column) => `${column.name} ${mapColumnType(column, localSchema)} NOT NULL`),\n \"entity_key_json TEXT NOT NULL\",\n `mutation_seq INTEGER NOT NULL UNIQUE DEFAULT nextval(${quoteSqlStringLiteral(qualifiedJournalSequenceName)})::integer`,\n \"mutation_kind VARCHAR(24) NOT NULL\",\n \"status VARCHAR(24) NOT NULL\",\n // The registry fingerprint (ADR-0004) this mutation was authored under, so a\n // version-boundary crossing is known before sending (ADR-0006 decision 4).\n \"registry_version TEXT\",\n // ADR-0011 reserved hook: the Server version the entity was observed at when this mutation\n // was authored. The slot lives on the journal (per-mutation, like registry_version above);\n // the stale-write conflict policy (ADR-0015) decides its exact semantics and stamps it.\n \"base_server_version BIGINT\",\n // ADR-0022: the dynamic write-unit tag stamped by a `transaction({ mode })` block — the shared\n // unit id grouping co-committed mutations, and the unit's write-mode. NULL for the default path\n // (an untagged mutation), where the flusher derives mode + unit from the table's static group.\n \"write_unit TEXT\",\n \"write_mode VARCHAR(24)\",\n \"payload_json TEXT NOT NULL\",\n \"attempt_count INTEGER NOT NULL DEFAULT 0\",\n \"last_error TEXT\",\n \"last_http_status INTEGER\",\n \"conflict_reason TEXT\",\n \"server_updated_at_us BIGINT\",\n \"enqueued_at_us BIGINT NOT NULL\",\n \"next_retry_at_us BIGINT\",\n \"sent_at_us BIGINT\",\n \"acked_at_us BIGINT\",\n \"updated_at_us BIGINT NOT NULL\",\n ].join(\",\\n \")}\\n);`,\n );\n\n // Journal indexes render through the SAME core the pgTable-driven renderer uses\n // ({@link renderCreateIndexStatement}), so the two index-emitting paths cannot drift in statement\n // shape. These names/columns are registry-derived bare identifiers, passed verbatim (the pgTable\n // path is the one that quotes) — output stays byte-identical to the former hand-built statements.\n statements.push(\n renderCreateIndexStatement(projection.journalTable, `${journalTableName}_status_idx`, [\n \"status\",\n \"enqueued_at_us\",\n ]),\n );\n statements.push(\n renderCreateIndexStatement(projection.journalTable, `${journalTableName}_status_retry_idx`, [\n \"status\",\n \"next_retry_at_us\",\n \"enqueued_at_us\",\n ]),\n );\n statements.push(\n renderCreateIndexStatement(projection.journalTable, `${journalTableName}_pk_seq_idx`, [\n ...entry.primaryKey.columns,\n \"mutation_seq\",\n ]),\n );\n statements.push(\n renderCreateIndexStatement(projection.journalTable, `${journalTableName}_entity_seq_idx`, [\n \"entity_key_json\",\n \"mutation_seq\",\n ]),\n );\n statements.push(\n renderCreateIndexStatement(projection.journalTable, `${journalTableName}_entity_status_seq_idx`, [\n \"entity_key_json\",\n \"status\",\n \"mutation_seq\",\n ]),\n );\n\n // Trigger: automatically clear overlay + journal entries when the sync\n // echo arrives. Fires on INSERT/UPDATE (new data from Electric) and DELETE\n // (row removed on server, synced back via Electric).\n const pkMatchSql = (alias: string) =>\n primaryKeyColumns\n .map((col) => `\"${alias}\".\"${col.name}\" = COALESCE(NEW.\"${col.name}\", OLD.\"${col.name}\")`)\n .join(\" AND \");\n const pkOverlayMatchSql = primaryKeyColumns\n .map((col) => `\"overlay\".\"${col.name}\" = COALESCE(NEW.\"${col.name}\", OLD.\"${col.name}\")`)\n .join(\" AND \");\n\n // ADR-0010: an acked create/update clears only once the synced echo's Server version reaches\n // the write's acked version — never on a bare key-match, which a stale or reordered echo could\n // satisfy and flip the read model to neither the optimistic nor the converged value. A delete\n // stays resolved by synced-row absence (NEW is NULL on the synced DELETE; the barrier reads\n // NULL there, so it never clears a create/update on a delete echo). One predicate, shared with\n // reconcileTable (mutation.ts), so the two sites cannot drift.\n const resolutionBarrier = buildOverlayResolutionBarrier(entry, { syncedAlias: \"NEW\" });\n\n // ADR-0021 §3: an ephemeral cluster's reconcile function lives in `pg_temp` alongside its temp table\n // (a permanent function cannot be a temp trigger's handler cleanly); a persistent one is unchanged.\n const reconcileFunctionRef = ephemeral ? `pg_temp.${projection.reconcileFunction}` : projection.reconcileFunction;\n\n statements.push(\n `CREATE OR REPLACE FUNCTION ${reconcileFunctionRef}() RETURNS TRIGGER AS $$\\n` +\n `BEGIN\\n` +\n ` -- ADR-0015: retire a terminal 'conflicted' row once a LATER write on the same entity has\\n` +\n ` -- been acked — that later write IS the resolution. The acked resolver is cleared by the\\n` +\n ` -- acked-delete below the moment its echo lands; if that echo wins the race against the\\n` +\n ` -- post-flush reconcileTable pass, the resolver is gone before reconcileTable's supersede-\\n` +\n ` -- retire can see it and the conflicted row orphans (its surfaced conflict_state never\\n` +\n ` -- clears). Doing the retire here too — in the trigger that has the echo context, BEFORE the\\n` +\n ` -- acked-clear — closes that race. Mirrors reconcileTable's retire (mutation.ts).\\n` +\n ` DELETE FROM ${projection.journalTable} AS \"conflicted\"\\n` +\n ` USING ${projection.journalTable} AS \"resolver\"\\n` +\n ` WHERE \"conflicted\".status = 'conflicted' AND (${pkMatchSql(\"conflicted\")})\\n` +\n ` AND \"resolver\".entity_key_json = \"conflicted\".entity_key_json\\n` +\n ` AND \"resolver\".mutation_seq > \"conflicted\".mutation_seq\\n` +\n ` AND \"resolver\".status = 'acked';\\n` +\n ` DELETE FROM ${projection.journalTable} AS \"journal\"\\n` +\n ` WHERE status = 'acked' AND (${pkMatchSql(\"journal\")})\\n` +\n ` AND (\\n` +\n ` (TG_OP <> 'DELETE' AND mutation_kind <> 'delete' AND ${resolutionBarrier})\\n` +\n ` OR (TG_OP = 'DELETE' AND mutation_kind = 'delete')\\n` +\n ` );\\n` +\n ` DELETE FROM ${projection.overlayTable} AS \"overlay\"\\n` +\n ` WHERE (${pkOverlayMatchSql})\\n` +\n ` AND NOT EXISTS (\\n` +\n ` SELECT 1 FROM ${projection.journalTable} AS j\\n` +\n ` WHERE (${pkMatchSql(\"j\")})\\n` +\n ` );\\n` +\n ` RETURN COALESCE(NEW, OLD);\\n` +\n `END;\\n` +\n `$$ LANGUAGE plpgsql;`,\n );\n\n statements.push(\n `CREATE OR REPLACE TRIGGER ${projection.reconcileTrigger}\\n` +\n `AFTER INSERT OR UPDATE OR DELETE ON ${projection.syncedTable}\\n` +\n `FOR EACH ROW EXECUTE FUNCTION ${reconcileFunctionRef}();`,\n );\n\n statements.push(\n `CREATE OR REPLACE ${temp}VIEW ${projection.readModel} AS\\n${buildReadModelViewSql(\n entry,\n projection,\n columns.map((column) => column.name),\n )};`,\n );\n\n // ADR-0011: the per-table convergence view — a derived projection over synced + overlay +\n // journal, distinct from the (lean) read model, whose acked-unobserved status derives from the\n // same barrier predicate the reconcile trigger above uses (decision 4, anti-drift).\n statements.push(\n `CREATE OR REPLACE ${temp}VIEW ${projection.syncState} AS\\n${buildSyncStateView(entry, {\n syncedTable: projection.syncedTable,\n overlayTable: projection.overlayTable,\n journalTable: projection.journalTable,\n })};`,\n );\n }\n\n return `${statements.join(\"\\n\\n\")}\\n`;\n}\n\nfunction buildReadModelViewSql(\n entry: SyncTableEntry<AnyPgTable>,\n projection: ResolvedProjection,\n columnNames: string[],\n) {\n if (!projection.overlayTable) {\n throw new Error(`overlay table is required for writable table ${projection.syncedTable}`);\n }\n\n const pkMatch = buildPrimaryKeyMatch(entry.primaryKey.columns);\n const syncedLocalUpdatedExpression = columnNames.includes(\"updated_at_us\") ? \"t.updated_at_us\" : \"CAST(0 AS BIGINT)\";\n\n return [\n \"SELECT\",\n ` ${columnNames.join(\",\\n \")},`,\n \" overlay_kind,\",\n \" local_updated_at_us\",\n `FROM ${projection.overlayTable}`,\n `WHERE overlay_kind <> 'pending_delete'`,\n \"UNION ALL\",\n \"SELECT\",\n ` ${columnNames.map((name) => `t.${name}`).join(\",\\n \")},`,\n ` 'synced' AS overlay_kind,`,\n ` ${syncedLocalUpdatedExpression} AS local_updated_at_us`,\n `FROM ${projection.syncedTable} AS t`,\n \"WHERE NOT EXISTS (\",\n \" SELECT 1\",\n ` FROM ${projection.overlayTable} AS o`,\n ` WHERE ${pkMatch}`,\n \")\",\n ].join(\"\\n\");\n}\n\nfunction buildTableColumnSql(columns: TableColumn[], primaryKeyColumns: string[], localSchema: string) {\n return [\n ...columns.map((column) => buildColumnDefinition(column, primaryKeyColumns, localSchema)),\n ...buildCompositePrimaryKeyClauses(primaryKeyColumns),\n ].join(\",\\n \");\n}\n\n/**\n * Render `CREATE TABLE IF NOT EXISTS` (plus a `CREATE INDEX IF NOT EXISTS` per declared index) for a\n * Drizzle `pgTable` / `pgSchema.table`, through the SAME column/PK/type machinery\n * ({@link buildTableColumnSql} → {@link buildColumnDefinition} → {@link mapColumnType}) that\n * {@link generateLocalSchemaSql} uses for every other local relation. The table is schema-qualified\n * when it declares a schema and bare otherwise (per the table object). Column types come from each\n * column's `getSQLType()`, NOT NULL and single-column PRIMARY KEY inline, composite PKs as a trailing\n * clause. Enum column types are qualified into the table's own schema — the metadata pgTables carry\n * none, but the path is shared with the local-store generator so it must stay honest.\n *\n * ADR-0029 D3: the metadata-store DDL renders from its `metadata-tables.ts` pgTables through this,\n * making the pgTable the single source. The OUTPUT is tier-③-by-nature runtime DDL (schema/table\n * identifiers assembled at construction), but it is GENERATED from the model, never hand-maintained.\n */\nexport function renderCreateTableSql(table: AnyPgTable): string[] {\n const config = getTableConfig(table);\n const schemaName = config.schema ?? \"public\";\n const qualifiedTableName = qualifyIdentifier(schemaName, config.name);\n const primaryKeyColumns = collectPgTablePrimaryKeyColumns(config);\n const columnSql = buildTableColumnSql(config.columns as unknown as TableColumn[], primaryKeyColumns, schemaName);\n\n const statements = [`CREATE TABLE IF NOT EXISTS ${qualifiedTableName} (\\n ${columnSql}\\n);`];\n\n for (const index of config.indexes) {\n statements.push(renderCreateIndexSql(qualifiedTableName, index));\n }\n\n return statements;\n}\n\n/** The PK column names of a `pgTable` — column-level `.primaryKey()` first, then composite `primaryKey({…})`. */\nfunction collectPgTablePrimaryKeyColumns(config: ReturnType<typeof getTableConfig>): string[] {\n const columnLevel = config.columns.filter((column) => column.primary).map((column) => column.name);\n const composite = config.primaryKeys.flatMap((pk) => pk.columns.map((column) => column.name));\n return [...columnLevel, ...composite];\n}\n\nfunction renderCreateIndexSql(qualifiedTableName: string, index: ReturnType<typeof getTableConfig>[\"indexes\"][number]) {\n const { name, unique, columns, where, method, with: withParams } = index.config;\n if (!name) {\n throw new Error(\"renderCreateIndexSql: anonymous indexes are not supported (declare a name)\");\n }\n // This renderer emits only a plain ascending btree over bare columns. Any modifier it does not\n // render must fail loudly — silently dropping one would produce a local index that differs from the\n // pgTable declaration (the very DDL-vs-model divergence ADR-0029 D3 removes for the metadata store).\n if (where) {\n throw new Error(`renderCreateIndexSql: partial indexes (.where) are not supported (index ${name})`);\n }\n if (method && method.toLowerCase() !== \"btree\") {\n throw new Error(\n `renderCreateIndexSql: non-btree index methods (.using \"${method}\") are not supported (index ${name})`,\n );\n }\n if (withParams && Object.keys(withParams).length > 0) {\n throw new Error(`renderCreateIndexSql: index storage parameters (.with) are not supported (index ${name})`);\n }\n const columnExpressions = columns.map((column) => {\n const columnName = (column as { name?: unknown }).name;\n if (typeof columnName !== \"string\") {\n throw new Error(`renderCreateIndexSql: expression index columns are not supported (index ${name})`);\n }\n const indexConfig = (column as { indexConfig?: { order?: string; nulls?: string; opClass?: string } }).indexConfig;\n if (indexConfig?.order === \"desc\") {\n throw new Error(`renderCreateIndexSql: descending index columns (.desc()) are not supported (index ${name})`);\n }\n // Drizzle fills `nulls` with the ascending-btree default (\"last\") on every column; only an\n // explicit NULLS FIRST diverges from what we render (a plain ascending btree is NULLS LAST).\n if (indexConfig?.nulls === \"first\") {\n throw new Error(`renderCreateIndexSql: NULLS FIRST ordering (.nullsFirst()) is not supported (index ${name})`);\n }\n if (indexConfig?.opClass) {\n throw new Error(`renderCreateIndexSql: index operator classes (.op()) are not supported (index ${name})`);\n }\n return maybeQuoteIdentifier(columnName);\n });\n\n return renderCreateIndexStatement(qualifiedTableName, maybeQuoteIdentifier(name), columnExpressions, { unique });\n}\n\n/**\n * The shared `CREATE INDEX` core: assemble one\n * `CREATE [UNIQUE] INDEX IF NOT EXISTS <name> ON <table> (<cols>)` over a qualified table, an\n * already-rendered index name, and already-rendered plain ascending column expressions. BOTH the\n * pgTable-driven renderer ({@link renderCreateIndexSql}) and the journal-index emitter in\n * {@link generateLocalSchemaSql} go through here, so the two index-emitting paths cannot drift in\n * statement shape. Identifier quoting is the caller's responsibility — the pgTable path quotes via\n * `maybeQuoteIdentifier`; the journal path passes its registry-derived bare names/columns verbatim —\n * this core only fixes the surrounding statement text.\n */\nfunction renderCreateIndexStatement(\n qualifiedTableName: string,\n indexName: string,\n columnExpressions: readonly string[],\n options: { unique?: boolean } = {},\n): string {\n const uniqueSql = options.unique ? \"UNIQUE \" : \"\";\n return `CREATE ${uniqueSql}INDEX IF NOT EXISTS ${indexName} ON ${qualifiedTableName} (${columnExpressions.join(\", \")});`;\n}\n\nfunction buildColumnDefinition(column: TableColumn, primaryKeyColumns: string[], localSchema: string) {\n const typeSql = mapColumnType(column, localSchema);\n const notNullSql = column.notNull ? \" NOT NULL\" : \"\";\n const primaryKeySql = primaryKeyColumns.length === 1 && primaryKeyColumns.includes(column.name) ? \" PRIMARY KEY\" : \"\";\n return `${column.name} ${typeSql}${notNullSql}${primaryKeySql}`;\n}\n\nfunction buildCompositePrimaryKeyClauses(primaryKeyColumns: string[]) {\n if (primaryKeyColumns.length <= 1) {\n return [];\n }\n\n return [`PRIMARY KEY (${primaryKeyColumns.join(\", \")})`];\n}\n\nfunction mapColumnType(column: TableColumn, localSchema: string) {\n const baseTypeSql = readBaseColumnTypeSql(column, localSchema);\n const dimensions = readArrayDimensions(column);\n\n if (dimensions > 0) {\n return `${baseTypeSql}${\"[]\".repeat(dimensions)}`;\n }\n\n return baseTypeSql;\n}\n\nfunction readBaseColumnTypeSql(column: TableColumn, localSchema: string) {\n const enumDefinition = readEnumColumnDefinition(column, localSchema);\n\n if (enumDefinition) {\n return qualifyIdentifier(enumDefinition.schemaName, enumDefinition.enumName);\n }\n\n const sqlType = (column as { getSQLType(): string }).getSQLType();\n\n if (!sqlType) {\n throw new Error(`Unsupported column type for local schema generation: ${column.columnType}`);\n }\n\n return sqlType;\n}\n\ntype EnumDefinition = {\n schemaName: string;\n enumName: string;\n enumValues: string[];\n};\n\nfunction collectEnumDefinitions(registry: SyncTableRegistry, localSchema: string) {\n return collectEnumDefinitionsFromEntries(Object.values(registry), localSchema);\n}\n\n/**\n * Collect the distinct enum types referenced by a GIVEN set of registry entries (deduped by name, values\n * cross-checked for conflicts, sorted for stable output). Factored out of {@link collectEnumDefinitions} so\n * the Data export (ADR-0035) can emit ONLY the enums its `-t` allowlist tables reference — the whole-registry\n * caller passes every entry, the data export passes just its owning persistent entries — through one honest\n * implementation, never a second enum-scanning path that could drift on the conflict/sort rules.\n */\nfunction collectEnumDefinitionsFromEntries(entries: SyncTableEntry[], localSchema: string) {\n const enumDefinitionsByName = new Map<string, EnumDefinition>();\n\n for (const entry of entries) {\n const columns = getProjectedColumns(entry).map(({ column }) => column);\n\n for (const column of columns) {\n const enumDefinition = readEnumColumnDefinition(column, localSchema);\n\n if (!enumDefinition) {\n continue;\n }\n\n const existingDefinition = enumDefinitionsByName.get(enumDefinition.enumName);\n\n if (!existingDefinition) {\n enumDefinitionsByName.set(enumDefinition.enumName, enumDefinition);\n continue;\n }\n\n if (!areEnumValuesEqual(existingDefinition.enumValues, enumDefinition.enumValues)) {\n throw new Error(\n `Enum ${enumDefinition.enumName} has conflicting values in sync registry: ${existingDefinition.enumValues.join(\", \")} vs ${enumDefinition.enumValues.join(\", \")}`,\n );\n }\n }\n }\n\n return [...enumDefinitionsByName.values()].sort((left, right) => left.enumName.localeCompare(right.enumName));\n}\n\n/**\n * Does this entry OWN a physical, persistent synced table — i.e. is it a `-t` allowlist candidate for the\n * Data export (ADR-0035 decision 1)? Two entries are excluded:\n *\n * - a **read PROJECTION** (`readProjection`) owns no table (its `table` is another entry's), so it must\n * never be listed — it would double-target the owner's physical table;\n * - an **ephemeral** entry's cluster is emitted as `pg_temp` TEMP objects (ADR-0021 §3), absent from the\n * throwaway clone by construction — and a `pg_dump -t` pattern that matches NOTHING makes `pg_dump` fail,\n * so an ephemeral table must not appear in the allowlist at all.\n *\n * Overlay/journal/meta tables, read-model/sync-state views, and reconcile functions are excluded by `-t`\n * semantics automatically (they are neither the synced table nor matched by its name), so they need no\n * filter here.\n */\nfunction ownsPersistentSyncedTable(entry: SyncTableEntry): boolean {\n return !entry.readProjection && entry.retention !== \"ephemeral\";\n}\n\n/**\n * The `-t` allowlist for a Data export (ADR-0035 decision 1): the schema-qualified PHYSICAL synced table\n * name for every registry entry that owns one, resolved through the SAME `getClientProjection` the local\n * DDL generator uses — NOT re-derived by string convention. This is deliberately the physical `syncedTable`,\n * never the read-model view (whose name can carry the entry name while the table differs): `-t` must target\n * the tables that hold the rows. Read-projection and ephemeral entries are excluded (see\n * {@link ownsPersistentSyncedTable}).\n */\nexport function collectDataExportSyncedTableNames<TRegistry extends SyncTableRegistry>(registry: TRegistry): string[] {\n const localSchema = getSyncRegistrySchema(registry);\n const names: string[] = [];\n\n for (const [tableKey, entry] of Object.entries(registry)) {\n if (!ownsPersistentSyncedTable(entry)) {\n continue;\n }\n\n names.push(getClientProjection(entry, tableKey, localSchema).syncedTable);\n }\n\n return names;\n}\n\n/**\n * The clone-cleanup SQL a Data export runs on its THROWAWAY clone before `pg_dump -t` (ADR-0035). The\n * reconcile trigger sits ON the synced table (`AFTER INSERT/UPDATE/DELETE ON <syncedTable>`), so\n * `pg_dump -t <syncedTable>` pulls the trigger into the dump — but its function is pgxsinkit machinery the\n * data export deliberately EXCLUDES, so the artefact would carry a trigger referencing a missing function\n * and fail to load into a vanilla Postgres. Because the clone is a memory-backed throwaway we fully own, we\n * drop each reconcile trigger (and its now-unreferenced function) on it first, so `-t` yields clean,\n * portable tables. Overlay/journal/views/metadata are NOT captured by `-t <syncedTable>` at all (a probe\n * confirmed only the table, its PK, its data, and this trigger appear), so nothing else needs dropping.\n * Returns `\"\"` when the registry declares no writable owning table.\n */\nexport function buildDataExportCloneCleanupSql<TRegistry extends SyncTableRegistry>(registry: TRegistry): string {\n const localSchema = getSyncRegistrySchema(registry);\n const statements: string[] = [];\n\n for (const [tableKey, entry] of Object.entries(registry)) {\n if (!ownsPersistentSyncedTable(entry) || entry.mode === \"readonly\") {\n continue;\n }\n\n const projection = getClientProjection(entry, tableKey, localSchema);\n // Drop the trigger first, then its now-unreferenced function (drop order avoids a dependency error).\n statements.push(`DROP TRIGGER IF EXISTS ${projection.reconcileTrigger} ON ${projection.syncedTable};`);\n statements.push(`DROP FUNCTION IF EXISTS ${projection.reconcileFunction}();`);\n }\n\n return statements.join(\"\\n\");\n}\n\n/**\n * The enum DDL header for a Data export artefact (ADR-0035 decision 1). `pg_dump -t <table>` emits the\n * tables but NOT the enum types their columns reference, so the portable artefact is this generated header\n * concatenated ahead of the `pg_dump` output. It reuses the SAME `CREATE TYPE` generation the local-schema\n * generator emits ({@link buildCreateEnumTypeSql}) — every enum wrapped in an idempotent `IF NOT EXISTS`\n * guard — restricted to the enums actually referenced by the exported (owning, persistent) tables, so a\n * dropped/ephemeral-only enum never bloats the artefact. When the registry uses a non-`public` schema, a\n * `CREATE SCHEMA IF NOT EXISTS` precedes the types (they live in that schema, and the header runs before\n * `pg_dump`'s own schema creation), so the header is self-contained against a bare Postgres. Returns `\"\"`\n * when no exported table references an enum.\n */\nexport function buildDataExportEnumHeaderSql<TRegistry extends SyncTableRegistry>(registry: TRegistry): string {\n const localSchema = getSyncRegistrySchema(registry);\n const exportedEntries = Object.values(registry).filter(ownsPersistentSyncedTable);\n const enumDefinitions = collectEnumDefinitionsFromEntries(exportedEntries, localSchema);\n\n if (enumDefinitions.length === 0) {\n return \"\";\n }\n\n const statements: string[] = [\n \"-- Enum types referenced by the exported tables. `pg_dump -t` does not emit the enum types\",\n \"-- its tables depend on, so pgxsinkit generates them here from the sync registry (ADR-0035).\",\n ];\n\n // A non-public schema must exist before its `CREATE TYPE` runs — this header precedes pg_dump's own\n // schema creation, so create it ourselves (idempotent), mirroring `generateLocalSchemaSql`.\n if (localSchema !== \"public\") {\n statements.push(`CREATE SCHEMA IF NOT EXISTS ${quoteIdentifier(localSchema)};`);\n }\n\n for (const enumDefinition of enumDefinitions) {\n statements.push(buildCreateEnumTypeSql(enumDefinition));\n }\n\n return `${statements.join(\"\\n\")}\\n`;\n}\n\nfunction buildCreateEnumTypeSql(enumDefinition: EnumDefinition) {\n const typeIdentifier = qualifyIdentifier(enumDefinition.schemaName, enumDefinition.enumName);\n const enumValuesSql = enumDefinition.enumValues.map((value) => quoteSqlStringLiteral(value)).join(\", \");\n\n return [\n \"DO $$\",\n \"BEGIN\",\n \" IF NOT EXISTS (\",\n \" SELECT 1\",\n \" FROM pg_type AS t\",\n \" INNER JOIN pg_namespace AS n ON n.oid = t.typnamespace\",\n ` WHERE t.typname = ${quoteSqlStringLiteral(enumDefinition.enumName)}`,\n ` AND n.nspname = ${quoteSqlStringLiteral(enumDefinition.schemaName)}`,\n \" ) THEN\",\n ` CREATE TYPE ${typeIdentifier} AS ENUM (${enumValuesSql});`,\n \" END IF;\",\n \"END\",\n \"$$;\",\n ].join(\"\\n\");\n}\n\nfunction areEnumValuesEqual(left: string[], right: string[]) {\n if (left.length !== right.length) {\n return false;\n }\n\n for (let index = 0; index < left.length; index += 1) {\n if (left[index] !== right[index]) {\n return false;\n }\n }\n\n return true;\n}\n\nfunction readEnumColumnDefinition(column: TableColumn, localSchema: string): EnumDefinition | undefined {\n const candidate = column as TableColumn & {\n enum?: {\n enumName?: unknown;\n enumValues?: unknown;\n };\n };\n\n if (!candidate.enum || typeof candidate.enum.enumName !== \"string\" || !Array.isArray(candidate.enum.enumValues)) {\n return undefined;\n }\n\n const enumValues = candidate.enum.enumValues.filter((value): value is string => typeof value === \"string\");\n\n if (enumValues.length !== candidate.enum.enumValues.length) {\n throw new Error(\n `Enum ${candidate.enum.enumName} includes non-string values and cannot be emitted in local schema SQL`,\n );\n }\n\n return {\n schemaName: localSchema,\n enumName: candidate.enum.enumName,\n enumValues,\n };\n}\n\nfunction readArrayDimensions(column: TableColumn) {\n const arrayColumn = column as TableColumn & { dimensions?: number };\n return arrayColumn.dimensions ?? 0;\n}\n\nfunction buildPrimaryKeyMatch(primaryKeyColumns: string[]) {\n return primaryKeyColumns.map((column) => `o.${column} = t.${column}`).join(\" AND \");\n}\n\nfunction getClientProjection(entry: SyncTableEntry, tableKey: string, localSchema: string): ResolvedProjection {\n const projection = baseProjection(entry, tableKey);\n const syncedTableName = projection.syncedTable ?? tableKey;\n const readModelName = entry.view != null ? getViewConfig(entry.view).name : syncedTableName;\n\n return {\n syncedTable: qualifyIdentifier(localSchema, syncedTableName),\n ...(projection.overlayTable ? { overlayTable: qualifyIdentifier(localSchema, projection.overlayTable) } : {}),\n ...(projection.journalTable ? { journalTable: qualifyIdentifier(localSchema, projection.journalTable) } : {}),\n readModel: qualifyIdentifier(localSchema, readModelName),\n syncState: qualifyIdentifier(localSchema, `${syncedTableName}_sync_state`),\n reconcileFunction: qualifyIdentifier(localSchema, `${syncedTableName}_reconcile_on_sync`),\n reconcileTrigger: maybeQuoteIdentifier(`${syncedTableName}_reconcile_on_sync`),\n };\n}\n\nfunction baseProjection(entry: SyncTableEntry, tableKey: string) {\n if (!entry.clientProjection) {\n throw new Error(`clientProjection is required for local client table ${tableKey}`);\n }\n\n return entry.clientProjection;\n}\n\nfunction qualifyIdentifier(schemaName: string, objectName: string) {\n if (schemaName === \"public\") {\n // Quote only when required so existing generated SQL stays stable, but a table/view named\n // after a reserved word (e.g. `group`) is a valid Postgres identifier and MUST be quoted or\n // the generated DDL and read queries fail to parse. The row-applier (src/sync) always quotes.\n return maybeQuoteIdentifier(objectName);\n }\n\n return `${quoteIdentifier(schemaName)}.${quoteIdentifier(objectName)}`;\n}\n\nfunction buildJournalSequenceName(journalTable: string) {\n return `${journalTable}_mutation_seq`;\n}\n\n/**\n * Drop the reconstructible **read cache** — the synced tables and their read-model views\n * and reconcile triggers/functions — while preserving the authority tables (overlay,\n * journal, the local-meta table). Re-running {@link generateLocalSchemaSql} then rebuilds\n * the synced tables at the current shape, and a re-sync refills them (ADR-0006). This is\n * the named drop primitive a returning-online upgrade uses after a clean drain.\n */\nexport function buildDropReadCacheSql<TRegistry extends SyncTableRegistry>(registry: TRegistry): string {\n const localSchema = getSyncRegistrySchema(registry);\n const statements: string[] = [];\n\n for (const [tableKey, entry] of Object.entries(registry)) {\n const projection = getClientProjection(entry, tableKey, localSchema);\n\n if (entry.mode !== \"readonly\") {\n statements.push(`DROP VIEW IF EXISTS ${projection.syncState};`);\n statements.push(`DROP VIEW IF EXISTS ${projection.readModel};`);\n statements.push(`DROP TRIGGER IF EXISTS ${projection.reconcileTrigger} ON ${projection.syncedTable};`);\n statements.push(`DROP FUNCTION IF EXISTS ${projection.reconcileFunction}();`);\n }\n\n statements.push(`DROP TABLE IF EXISTS ${projection.syncedTable} CASCADE;`);\n }\n\n return `${statements.join(\"\\n\")}\\n`;\n}\n\n/**\n * Wipe the **entire** local store provisioned from the registry — the read cache plus the\n * authority tables (overlay, journal, sequences), the enum types, and the local-meta row.\n * This is the full teardown reused by `destroy()` (ADR-0005 decision 5) and by the\n * drain-then-drop upgrade once a clean drain has confirmed nothing is owed (ADR-0006).\n */\nexport function buildWipeLocalStoreSql<TRegistry extends SyncTableRegistry>(registry: TRegistry): string {\n const localSchema = getSyncRegistrySchema(registry);\n const statements: string[] = [buildDropReadCacheSql(registry).trimEnd()];\n\n for (const [tableKey, entry] of Object.entries(registry)) {\n if (entry.mode === \"readonly\") {\n continue;\n }\n\n const projection = getClientProjection(entry, tableKey, localSchema);\n\n if (projection.overlayTable) {\n statements.push(`DROP TABLE IF EXISTS ${projection.overlayTable} CASCADE;`);\n }\n\n if (projection.journalTable && entry.clientProjection?.journalTable) {\n statements.push(`DROP TABLE IF EXISTS ${projection.journalTable} CASCADE;`);\n statements.push(\n `DROP SEQUENCE IF EXISTS ${qualifyIdentifier(localSchema, buildJournalSequenceName(entry.clientProjection.journalTable))};`,\n );\n }\n }\n\n for (const enumDefinition of collectEnumDefinitions(registry, localSchema)) {\n statements.push(`DROP TYPE IF EXISTS ${qualifyIdentifier(enumDefinition.schemaName, enumDefinition.enumName)};`);\n }\n\n statements.push(`DROP TABLE IF EXISTS ${qualifyIdentifier(localSchema, LOCAL_META_TABLE)} CASCADE;`);\n\n return `${statements.join(\"\\n\")}\\n`;\n}\n\n/**\n * Clean-truncate a single table's local read cache so a desynced `lazy` relation (ADR-0021 §2) returns\n * to an empty, dormant state: the synced table and — for a writable table — its optimistic overlay and\n * the journal, plus a sequence restart. It does NOT drop the cluster (the table/views/trigger persist),\n * so a later re-reference re-streams into it without a schema rebuild. Ephemeral-aware: bare/`pg_temp`\n * names for an ephemeral cluster, schema-qualified for a persistent one — mirroring\n * {@link generateLocalSchemaSql}. The caller (`desync`) first stops the group's stream (so nothing\n * re-populates mid-truncate) and refuses when the journal owes unsettled writes (so this never drops\n * un-acked local intent).\n */\nexport function buildDesyncTableSql<TRegistry extends SyncTableRegistry>(\n registry: TRegistry,\n tableKey: string,\n): string {\n const entry = registry[tableKey];\n\n if (!entry) {\n throw new Error(`buildDesyncTableSql: unknown table ${tableKey}`);\n }\n\n const localSchema = getSyncRegistrySchema(registry);\n const ephemeral = entry.retention === \"ephemeral\";\n const objectSchema = ephemeral ? \"public\" : localSchema;\n const projection = getClientProjection(entry, tableKey, objectSchema);\n const statements: string[] = [`TRUNCATE TABLE ${projection.syncedTable};`];\n\n if (entry.mode !== \"readonly\") {\n if (projection.overlayTable) {\n statements.push(`TRUNCATE TABLE ${projection.overlayTable};`);\n }\n\n if (projection.journalTable && entry.clientProjection?.journalTable) {\n statements.push(`TRUNCATE TABLE ${projection.journalTable};`);\n statements.push(\n `ALTER SEQUENCE ${qualifyIdentifier(objectSchema, buildJournalSequenceName(entry.clientProjection.journalTable))} RESTART WITH 1;`,\n );\n }\n }\n\n // ADR-0023 Slice 2: a desync reverts the relation to dormant and deletes its subscription, so the next\n // activation re-streams from scratch — drop this shape's tag-set too, or it would orphan tags for rows\n // that never come back. The key matches what the engine writes (`shapeTableId(shape.schema, table)`):\n // for ephemeral the engine passes no schema (→ `public`), exactly this `objectSchema`.\n const syncedTableNameRaw = baseProjection(entry, tableKey).syncedTable ?? tableKey;\n statements.push(buildClearShapeTagsSql(shapeTableId(objectSchema, syncedTableNameRaw)));\n\n return `${statements.join(\"\\n\")}\\n`;\n}\n",
|
|
19
|
-
"import type { ChangeMessage, MovePattern, Row } from \"@electric-sql/client\";\nimport type { PGliteInterface, Transaction } from \"@electric-sql/pglite\";\nimport { and, eq, inArray, like, sql } from \"drizzle-orm\";\nimport { getTableConfig } from \"drizzle-orm/pg-core\";\n\nimport { quoteIdentifier, quoteSqlLiteral } from \"@pgxsinkit/contracts\";\n\nimport type { ApplyTarget } from \"../local-tables\";\nimport { applyBulkDeletesToTable } from \"./apply\";\nimport { drizzleOverPg } from \"./drizzle-executor\";\nimport { getMetadataTables } from \"./metadata-tables\";\n\n/**\n * Electric **tagged-subquery** reconciliation (ADR-0023). A shape whose `where` contains a subquery\n * (membership-style row filters: `container_id IN (SELECT … FROM memberships WHERE member = $sub)`)\n * streams two extra things the plain change path ignores:\n *\n * - every change message carries `headers.tags` — the **reasons** the row is in the shape (one tag per\n * grant/membership), plus `removed_tags` on an update;\n * - a **`move-out` `EventMessage`** carries `patterns: { pos, value }[]` — \"the tag whose component at\n * index `pos` equals `value` is withdrawn\", i.e. that grant was revoked.\n *\n * A row leaves the shape only when it has **no remaining tag**. The engine drops the `EventMessage`\n * today, so a removed member keeps the revoked rows. This module persists each row's tag-set in one\n * metadata table and evicts rows whose last tag is withdrawn — closing the move-out gap without an\n * Electric change.\n *\n * Tag storage is a single metadata table keyed by the synced table + a canonical primary-key JSON:\n * `shape_row_tags(shape_table, pk_json, tag)`. It is created in `migrateSubscriptionMetadataTables`.\n */\n\n/**\n * The pgxsinkit-owned metadata schema (ADR-0009 decision 6) the tag store + subscription state live in.\n * The sync engine defaults its `metadataSchema` to this, and `createSyncClient` never overrides it — so\n * the desync path (which is outside the engine) can key the tag store by this same constant.\n */\nexport const DEFAULT_METADATA_SCHEMA = \"pgxsinkit\";\n\n/**\n * A bare, lowercase, unqualified SQL identifier: begins with a lowercase letter or underscore, then\n * lowercase letters, digits, and underscores.\n */\nconst METADATA_SCHEMA_PATTERN = /^[a-z_][a-z0-9_]*$/;\n\n/**\n * Validate the metadata schema name at engine construction. The name is interpolated RAW into two\n * positions a double-quoted identifier cannot cover:\n * - GUC space — `SET LOCAL <schema>.syncing` (sync/index.ts) and `SET <schema>.syncing = false`\n * (the metadata migration). GUC grammar takes a `namespace.name` of bare identifiers; it does not\n * accept a quoted identifier the way a table/column position does, so the name cannot be safely\n * quoted there.\n * - the `CREATE SCHEMA <schema>` DDL identifier position.\n * Rather than trust arbitrary caller input in those raw positions, restrict the name to a bare\n * lowercase identifier and reject uppercase/exotic names outright. The default \"pgxsinkit\" passes.\n */\nexport function assertValidMetadataSchema(metadataSchema: string): void {\n if (!METADATA_SCHEMA_PATTERN.test(metadataSchema)) {\n throw new Error(\n `Invalid metadataSchema ${JSON.stringify(metadataSchema)}: it must be a bare lowercase SQL ` +\n `identifier matching ${String(METADATA_SCHEMA_PATTERN)}. The name is interpolated unquoted into ` +\n `GUC (\\`SET <schema>.syncing\\`) and \\`CREATE SCHEMA\\` identifier positions where a quoted ` +\n `identifier is not accepted, so uppercase and exotic names are rejected at construction.`,\n );\n }\n}\n\n/**\n * The tag store's schema-qualified identifier, derived from the `shape_row_tags` pgTable config\n * (ADR-0029 D3 — single source; no parallel name string). The store itself is provisioned by\n * `migrateSubscriptionMetadataTables`, which renders that same pgTable.\n */\nexport function shapeRowTagsTableName(metadataSchema: string): string {\n const config = getTableConfig(getMetadataTables(metadataSchema).shapeRowTags);\n return `${quoteIdentifier(config.schema ?? \"public\")}.${quoteIdentifier(config.name)}`;\n}\n\n/** The `shape_table` key for the tag store: the synced table, schema-qualified (defaults `public`). */\nexport function shapeTableId(schema: string | undefined, table: string): string {\n return `${schema ?? \"public\"}.${table}`;\n}\n\n/**\n * Static SQL to drop a shape's tag-set, **guarded** by `to_regclass` so it is a no-op when the tag store\n * does not exist. Used by `buildDesyncTableSql` (ADR-0023 Slice 2), which may be exec'd standalone (a\n * caller/test that builds the local schema without booting the sync engine that creates the store). The\n * engine's own `clearShapeTags` runs inside a commit where the store is guaranteed present, so it is not\n * guarded.\n */\nexport function buildClearShapeTagsSql(shapeTable: string, metadataSchema: string = DEFAULT_METADATA_SCHEMA): string {\n const table = shapeRowTagsTableName(metadataSchema);\n return `DO $$ BEGIN\n IF to_regclass(${quoteSqlLiteral(table)}) IS NOT NULL THEN\n DELETE FROM ${table} WHERE shape_table = ${quoteSqlLiteral(shapeTable)};\n END IF;\nEND $$;`;\n}\n\n/**\n * Canonical primary-key JSON for a synced row — the tag store's per-row key. Built from the **mapped**\n * value (synced-table column names), with pk columns sorted so the string is stable, and `bigint`\n * rendered as a string (JSON has no bigint). Reversible via `JSON.parse` for the eviction DELETE.\n */\nexport function serializeRowPk(value: Row<unknown>, primaryKey: readonly string[]): string {\n const obj: Record<string, unknown> = {};\n for (const column of [...primaryKey].sort()) {\n obj[column] = value[column];\n }\n return JSON.stringify(obj, (_key, v: unknown) => (typeof v === \"bigint\" ? v.toString() : v));\n}\n\n/**\n * Split a composite `MoveTag` into its positional columns. A tag for a shape with N subquery conditions\n * is the per-condition grant values joined by `/` (an absent condition is an empty column) — e.g. a\n * two-condition shape yields `\"<grantHash>/1//\"` and `\"//<grantHash>/<grantHash>\"`. `\\/` is a literal\n * `/`, `\\\\` a literal `\\`. A single-condition shape's tag has no separator → `[tag]`.\n *\n * (The `MovePattern.pos` indexes into THIS split — confirmed against Electric 1.7.4 wire messages,\n * ADR-0023. The upstream type doc mentions `|`; the actual column separator on the wire is `/`.)\n */\nexport function splitTagComponents(tag: string): string[] {\n const parts: string[] = [];\n let current = \"\";\n for (let i = 0; i < tag.length; i++) {\n const char = tag[i]!;\n if (char === \"\\\\\" && i + 1 < tag.length) {\n current += tag[i + 1];\n i += 1;\n continue;\n }\n if (char === \"/\") {\n parts.push(current);\n current = \"\";\n continue;\n }\n current += char;\n }\n parts.push(current);\n return parts;\n}\n\n/**\n * Whether a tag is withdrawn by a `move-out` event. A revoked grant can appear at more than one column\n * of the shape's tag structure (one position per subquery condition that references it), so the event\n * enumerates those positions and a tag is withdrawn if it carries the value at **any** of them. A row\n * is then evicted only once **every** tag keeping it in the shape has been withdrawn (the caller's\n * empty-tag-set check) — so a row held by an independent second grant survives. Empty pattern set\n * matches nothing.\n */\nexport function tagMatchesPatterns(tag: string, patterns: readonly MovePattern[]): boolean {\n if (patterns.length === 0) return false;\n const parts = splitTagComponents(tag);\n return patterns.some((pattern) => parts[pattern.pos] === pattern.value);\n}\n\ninterface TagSyncOptions {\n pg: PGliteInterface | Transaction;\n metadataSchema: string;\n shapeTable: string;\n messages: ChangeMessage<Row<unknown>>[];\n primaryKey: string[];\n}\n\n/**\n * Maintain the tag-set for a shape from its drained change batch (ADR-0023). For a subquery shape every\n * change carries `headers.tags` (the row's current full reason-set), so insert/update **replace** the\n * row's tags; a delete drops them. `removed_tags` (without `tags`) deletes just those. A non-subquery\n * shape carries no `tags`, so this is a no-op for it. Runs before the data apply and the move-out\n * eviction in the same commit, so an add-then-remove within one batch resolves correctly.\n */\nexport async function applyShapeTagSync({\n pg,\n metadataSchema,\n shapeTable,\n messages,\n primaryKey,\n}: TagSyncOptions): Promise<void> {\n const { shapeRowTags } = getMetadataTables(metadataSchema);\n const db = drizzleOverPg(pg);\n\n for (const message of messages) {\n const data = message.value;\n const pkJson = serializeRowPk(data, primaryKey);\n\n if (message.headers.operation === \"delete\") {\n await db\n .delete(shapeRowTags)\n .where(and(eq(shapeRowTags.shape_table, shapeTable), eq(shapeRowTags.pk_json, pkJson)));\n continue;\n }\n\n const tags = message.headers.tags;\n if (tags !== undefined) {\n // `tags` is the authoritative current reason-set → replace.\n await db\n .delete(shapeRowTags)\n .where(and(eq(shapeRowTags.shape_table, shapeTable), eq(shapeRowTags.pk_json, pkJson)));\n if (tags.length > 0) {\n await db\n .insert(shapeRowTags)\n .values(tags.map((tag) => ({ shape_table: shapeTable, pk_json: pkJson, tag })))\n .onConflictDoNothing();\n }\n continue;\n }\n\n const removedTags = message.headers.removed_tags;\n if (removedTags && removedTags.length > 0) {\n await db\n .delete(shapeRowTags)\n .where(\n and(\n eq(shapeRowTags.shape_table, shapeTable),\n eq(shapeRowTags.pk_json, pkJson),\n inArray(shapeRowTags.tag, removedTags),\n ),\n );\n }\n }\n}\n\n/**\n * Record (union) a **move-in** row's tags without clearing the tags the row already carries (ADR-0024).\n * A move-in ADDS a reason a row is in the shape, so — unlike a regular change, whose `tags` is the\n * authoritative full reason-set and therefore REPLACES (see {@link applyShapeTagSync}) — a move-in must\n * not drop tags from an independent grant. Inserting with `ON CONFLICT DO NOTHING` is correct whether\n * Electric sends the row's full reason-set or only the newly-added grant on a move-in, so move-out\n * eviction afterwards stays correct under multi-grant without depending on the move-in's tag cardinality.\n * A row with no `tags` (a non-subquery shape) is a no-op.\n */\nexport async function addShapeRowTags({\n pg,\n metadataSchema,\n shapeTable,\n messages,\n primaryKey,\n}: TagSyncOptions): Promise<void> {\n const { shapeRowTags } = getMetadataTables(metadataSchema);\n const db = drizzleOverPg(pg);\n\n for (const message of messages) {\n const tags = message.headers.tags;\n if (!tags || tags.length === 0) continue;\n\n const data = message.value;\n const pkJson = serializeRowPk(data, primaryKey);\n await db\n .insert(shapeRowTags)\n .values(tags.map((tag) => ({ shape_table: shapeTable, pk_json: pkJson, tag })))\n .onConflictDoNothing();\n }\n}\n\ninterface MoveOutOptions {\n pg: PGliteInterface | Transaction;\n metadataSchema: string;\n shapeTable: string;\n /** The resolved apply target for the synced table the evicted rows are deleted from (ADR-0029 D1). */\n target: ApplyTarget;\n /** One entry per buffered `move-out` event, each its own pattern set. */\n patternSets: MovePattern[][];\n debug: boolean;\n}\n\n/**\n * Apply buffered `move-out` events for a shape (ADR-0023): withdraw the matched tag from every row that\n * carries it, then evict the synced rows left with **no** remaining tag — so a row held by two grants\n * survives losing one. Eviction goes through the tested bulk-delete path, so it fires the reconcile\n * trigger and the read-model/overlay stays consistent. Returns the number of rows evicted.\n */\nexport async function applyShapeMoveOut({\n pg,\n metadataSchema,\n shapeTable,\n target,\n patternSets,\n debug,\n}: MoveOutOptions): Promise<number> {\n const { shapeRowTags } = getMetadataTables(metadataSchema);\n const db = drizzleOverPg(pg);\n const evictedPkJsons = new Set<string>();\n\n for (const patterns of patternSets) {\n if (patterns.length === 0) continue;\n\n // Candidate tags: those containing every pattern value as a substring — a cheap superset of a real\n // positional match, confirmed in JS so composite/positional tags are handled correctly. Each\n // `like(tag, \"%value%\")` reproduces the former `tag LIKE '%' || $n || '%'` exactly: a param bound to\n // the concatenated pattern string, so any LIKE metacharacters in the value keep the same semantics.\n const candidateRows = await db\n .select({ pk_json: shapeRowTags.pk_json, tag: shapeRowTags.tag })\n .from(shapeRowTags)\n .where(\n and(\n eq(shapeRowTags.shape_table, shapeTable),\n ...patterns.map((pattern) => like(shapeRowTags.tag, `%${pattern.value}%`)),\n ),\n );\n const matched = candidateRows.filter((row) => tagMatchesPatterns(row.tag, patterns));\n if (matched.length === 0) continue;\n\n // Withdraw the moved-out tag from each matching row (one set-based delete of the (pk, tag) pairs).\n // Tier ② (ADR-0028): a set-based delete joined against a JSON recordset has no tier-① builder form —\n // the shape-tag table object is interpolated and the pair list is a bound `::json` param; the\n // alias-qualified `t.*` / `x.*` identifiers are raw only because the `USING`/recordset-join grammar\n // requires them.\n const pairs = matched.map((row) => ({ pk_json: row.pk_json, tag: row.tag }));\n await db.execute(\n sql`DELETE FROM ${shapeRowTags} AS t USING json_to_recordset(${JSON.stringify(pairs)}::json) AS x(pk_json text, tag text)\n WHERE t.shape_table = ${shapeTable} AND t.pk_json = x.pk_json AND t.tag = x.tag`,\n );\n\n // A row is evicted only if it has no tag left.\n const affected = [...new Set(matched.map((row) => row.pk_json))];\n // Tier ② (ADR-0028): bind the affected pk_json list as ONE array param via `= ANY(${param}::text[])`\n // — drizzle has no ANY(array-param) builder, and `sql.param` binds the whole array as a single\n // placeholder (removing the per-element bound-param ceiling `inArray` emits: one placeholder per PK,\n // a ~65k-param wire cap on a huge move-out). The explicit `::text[]` cast pins the param type for the\n // driver's extended-protocol type resolution. The `eq(shape_table)` conjunct and `selectDistinct`\n // shape are preserved.\n const remaining = await db\n .selectDistinct({ pk_json: shapeRowTags.pk_json })\n .from(shapeRowTags)\n .where(\n and(\n eq(shapeRowTags.shape_table, shapeTable),\n sql`${shapeRowTags.pk_json} = ANY(${sql.param(affected)}::text[])`,\n ),\n );\n const stillTagged = new Set(remaining.map((row) => row.pk_json));\n for (const pkJson of affected) {\n if (!stillTagged.has(pkJson)) evictedPkJsons.add(pkJson);\n }\n }\n\n if (evictedPkJsons.size === 0) return 0;\n\n // Evict via the bulk-delete path so the reconcile trigger fires and the read model converges.\n const messages = [...evictedPkJsons].map((pkJson) => ({\n key: pkJson,\n value: JSON.parse(pkJson) as Row<unknown>,\n headers: { operation: \"delete\" as const },\n }));\n await applyBulkDeletesToTable({\n pg,\n target,\n messages,\n debug,\n });\n\n return evictedPkJsons.size;\n}\n\n/** Drop a shape's entire tag-set — for a `must-refetch`/read-cache rebuild, before the re-snapshot (ADR-0023 Slice 2). */\nexport async function clearShapeTags({\n pg,\n metadataSchema,\n shapeTable,\n}: {\n pg: PGliteInterface | Transaction;\n metadataSchema: string;\n shapeTable: string;\n}): Promise<void> {\n const { shapeRowTags } = getMetadataTables(metadataSchema);\n await drizzleOverPg(pg).delete(shapeRowTags).where(eq(shapeRowTags.shape_table, shapeTable));\n}\n",
|
|
16
|
+
"import { and, eq, like, notExists, sql } from \"drizzle-orm\";\nimport { drizzle } from \"drizzle-orm/pglite\";\n\nimport { type MutationDiagnostics, type SyncTableRegistry } from \"@pgxsinkit/contracts\";\n\nimport { syncDebug } from \"./debug\";\nimport { getJournalTable, getLocalMetaTable } from \"./local-tables\";\nimport type { MutationDb } from \"./mutation\";\nimport {\n buildWipeLocalStoreSql,\n computeLocalSchemaFingerprint,\n generateLocalSchemaSql,\n LOCAL_SCHEMA_FINGERPRINT_KEY,\n REGISTRY_FINGERPRINT_KEY,\n} from \"./schema\";\n\n// Statements are AUTHORED as Drizzle builders over the meta-table object (rename-safe, typed,\n// schema-qualification handled by the table object) and rendered to text+params here, because they\n// EXECUTE through the caller's raw `MutationDb` seam — the one connection the mutation runtime and\n// its tests own (and mock).\nconst metaQueryBuilder = drizzle.mock();\n\n/**\n * The fingerprint-keyed local store (ADR-0006). The registry fingerprint the local PGlite\n * database was provisioned under is recorded in the local-meta table; comparing it to the\n * current fingerprint on boot is how a registry change is *detected* (rather than a\n * hand-bumped `idb://…-vN` suffix), which drives the drain-then-drop read-cache rebuild.\n */\n\n/** A boot-time registry-version reconciliation outcome (ADR-0006 drain-then-drop). */\nexport interface LocalStoreVersionEvent {\n status: \"rebuilt\" | \"deferred\";\n previousFingerprint: string;\n nextFingerprint: string;\n /** Mutations still owed to the server (pending + sending + failed + quarantined). */\n owedMutations: number;\n}\n\n/** The minimal mutation-runtime surface the version reconciliation needs. */\ninterface VersionReconcileRuntime {\n registryVersion: string;\n readMutationStats: () => Promise<MutationDiagnostics>;\n}\n\n/** The registry fingerprint the local store was last provisioned under, or null if unstamped. */\nexport async function readStoredRegistryFingerprint(\n db: MutationDb,\n registry: SyncTableRegistry,\n): Promise<string | null> {\n const meta = getLocalMetaTable(registry);\n const query = metaQueryBuilder\n .select({ value: meta.value })\n .from(meta)\n .where(eq(meta.key, REGISTRY_FINGERPRINT_KEY))\n .limit(1)\n .toSQL();\n const result = await db.query<{ value: string }>(query.sql, query.params as unknown[]);\n\n return result.rows[0]?.value ?? null;\n}\n\n/** Meta-key prefix for a persisted `lazy + persistent` group activation (ADR-0021 §2). */\nconst LAZY_ACTIVATION_PREFIX = \"lazy_active:\";\n\n/**\n * The consistency-group keys of `lazy + persistent` groups that were activated on a previous boot\n * (ADR-0021 §2). On boot these are promoted into the eager subscription set, so a once-activated durable\n * lazy group resumes permanently with no per-session re-evaluation. (`ephemeral` activation is never\n * persisted, so it never appears here.)\n */\nexport async function readActivatedLazyGroups(db: MutationDb, registry: SyncTableRegistry): Promise<Set<string>> {\n const meta = getLocalMetaTable(registry);\n const query = metaQueryBuilder\n .select({ key: meta.key })\n .from(meta)\n .where(like(meta.key, `${LAZY_ACTIVATION_PREFIX}%`))\n .toSQL();\n const result = await db.query<{ key: string }>(query.sql, query.params as unknown[]);\n return new Set(result.rows.map((row) => row.key.slice(LAZY_ACTIVATION_PREFIX.length)));\n}\n\n/** Upsert one meta key — the shared write shape for activations and the fingerprint stamp. */\nasync function upsertMetaValue(db: MutationDb, registry: SyncTableRegistry, key: string, value: string): Promise<void> {\n const meta = getLocalMetaTable(registry);\n const query = metaQueryBuilder\n .insert(meta)\n .values({ key, value })\n .onConflictDoUpdate({ target: meta.key, set: { value } })\n .toSQL();\n await db.query(query.sql, query.params as unknown[]);\n}\n\n/** Persist a `lazy + persistent` group's activation, so the next boot promotes it to eager (ADR-0021 §2). */\nexport async function writeLazyGroupActivation(\n db: MutationDb,\n registry: SyncTableRegistry,\n groupKey: string,\n): Promise<void> {\n await upsertMetaValue(db, registry, `${LAZY_ACTIVATION_PREFIX}${groupKey}`, \"1\");\n}\n\n/** Clear a persisted lazy activation — an explicit `desync` reverts the group to dormant next boot (ADR-0021 §2). */\nexport async function clearLazyGroupActivation(\n db: MutationDb,\n registry: SyncTableRegistry,\n groupKey: string,\n): Promise<void> {\n const meta = getLocalMetaTable(registry);\n const query = metaQueryBuilder\n .delete(meta)\n .where(eq(meta.key, `${LAZY_ACTIVATION_PREFIX}${groupKey}`))\n .toSQL();\n await db.query(query.sql, query.params as unknown[]);\n}\n\n/** Stamp the local store with the fingerprint it is now provisioned under. */\nexport async function writeStoredRegistryFingerprint(\n db: MutationDb,\n registry: SyncTableRegistry,\n fingerprint: string,\n): Promise<void> {\n await upsertMetaValue(db, registry, REGISTRY_FINGERPRINT_KEY, fingerprint);\n}\n\n/**\n * The durable-schema fingerprint the local store was last provisioned under (slice 3 / proposal §3), or null\n * when unstamped (a legacy store, or a store whose durable schema was never executed under this feature).\n * Follows the raw-seam read shape of {@link readStoredRegistryFingerprint}.\n */\nexport async function readStoredLocalSchemaFingerprint(\n db: MutationDb,\n registry: SyncTableRegistry,\n): Promise<string | null> {\n const meta = getLocalMetaTable(registry);\n const query = metaQueryBuilder\n .select({ value: meta.value })\n .from(meta)\n .where(eq(meta.key, LOCAL_SCHEMA_FINGERPRINT_KEY))\n .limit(1)\n .toSQL();\n const result = await db.query<{ value: string }>(query.sql, query.params as unknown[]);\n\n return result.rows[0]?.value ?? null;\n}\n\n/**\n * Stamp the durable-schema fingerprint the store is now provisioned under (slice 3). Called ONLY after a\n * successful durable-schema exec — every full durable exec (boot fast-path miss, reconcile rebuild,\n * `dropReadCache`) and its stamp travel together, so the fingerprint never claims a schema that was not run.\n */\nexport async function writeStoredLocalSchemaFingerprint(\n db: MutationDb,\n registry: SyncTableRegistry,\n fingerprint: string,\n): Promise<void> {\n await upsertMetaValue(db, registry, LOCAL_SCHEMA_FINGERPRINT_KEY, fingerprint);\n}\n\n/**\n * The durable recovery-required marker (warm-persisted-store-startup slice 2 / proposal §1). Its\n * `pgxsinkit_local_meta` value is `\"true\"` while a `sending` journal row MAY have been committed since the\n * last clean settle, and `\"false\"` once pgxsinkit has PROVEN no `sending` row remains. Absent = a\n * pre-feature (legacy) store: run one conservative legacy recovery pass, then initialize the marker.\n *\n * The invariant the whole slice protects: **the marker is never `\"false\"` while a committed `sending`\n * journal row exists.** It is upheld by marker-first ordering — {@link writeMutationRecoveryRequired}(true)\n * is awaited (and auto-commits) strictly BEFORE the first pending→sending transition of a dirty epoch — and\n * by the self-verifying clear ({@link clearMutationRecoveryMarkerIfSettled}), which only writes `\"false\"`\n * when NOT EXISTS any `sending` row across every writable journal.\n */\nexport const MUTATION_RECOVERY_REQUIRED_KEY = \"mutation_recovery_required\";\n\n/**\n * Read the durable recovery-required marker: `true`/`false` for the stored value, or `null` when the key is\n * absent (a legacy/pre-feature store). Follows the raw-seam read shape of\n * {@link readStoredRegistryFingerprint}.\n *\n * FIX 4 (fail closed): the marker is a SAFETY marker — `false` is the ONLY value that skips recovery, so any\n * present value that is not exactly `\"true\"` or `\"false\"` (corruption, a future encoding, stray whitespace, a\n * partial/manual edit) must NOT be decoded as clean. It is logged on the debug rail and treated as `true`\n * (recovery required); the recovery pass then rewrites a well-formed value.\n */\nexport async function readMutationRecoveryRequired(\n db: MutationDb,\n registry: SyncTableRegistry,\n): Promise<boolean | null> {\n const meta = getLocalMetaTable(registry);\n const query = metaQueryBuilder\n .select({ value: meta.value })\n .from(meta)\n .where(eq(meta.key, MUTATION_RECOVERY_REQUIRED_KEY))\n .limit(1)\n .toSQL();\n const result = await db.query<{ value: string }>(query.sql, query.params as unknown[]);\n const value = result.rows[0]?.value;\n if (value == null) {\n return null;\n }\n if (value === \"true\") return true;\n if (value === \"false\") return false;\n // Unexpected durable value → fail CLOSED: run recovery (which rewrites a well-formed marker afterward).\n syncDebug(\"mutation recovery marker has an unexpected value — treating as recovery-required (fail closed)\", {\n value,\n });\n return true;\n}\n\n/**\n * Upsert the durable recovery-required marker to `\"true\"`/`\"false\"` unconditionally. The `true` write is the\n * marker-first SET (awaited before the first `sending` transition of a dirty epoch); the `false` write\n * initializes an absent (legacy) marker AFTER a legacy recovery pass has guaranteed no `sending` row remains.\n */\nexport async function writeMutationRecoveryRequired(\n db: MutationDb,\n registry: SyncTableRegistry,\n required: boolean,\n): Promise<void> {\n await upsertMetaValue(db, registry, MUTATION_RECOVERY_REQUIRED_KEY, required ? \"true\" : \"false\");\n}\n\n/** The writable (non-`readonly`) table keys of a registry — the journals a recovery/clear pass spans. */\nfunction writableTableKeys(registry: SyncTableRegistry): string[] {\n return Object.keys(registry).filter((key) => registry[key]?.mode !== \"readonly\");\n}\n\n/**\n * Self-verifying clear (proposal §1 rule 2): set the marker to `\"false\"` in ONE guarded, Drizzle-composed\n * statement — but only where NOT EXISTS any `sending` row in ANY writable journal (the EXISTS-union is built\n * from the registry's journal Drizzle objects via {@link getJournalTable}). Correct regardless of JS\n * bookkeeping: a concurrent enqueue that committed a `sending` row makes the guard fail, so the marker stays\n * `\"true\"`. Returns `{ cleared }` from the statement's affected-row count (PGlite reports `affectedRows`) —\n * `true` when the guard passed (an existing marker row flipped/held at `\"false\"`), `false` when a `sending`\n * row blocked it OR no marker row exists yet. Off the boot path AND at the end of a boot recovery pass.\n *\n * The marker row must already exist for this UPDATE to take effect; the absent-store INIT is a distinct\n * unconditional {@link writeMutationRecoveryRequired}(false) after the legacy pass (a pure guarded UPDATE\n * cannot create the row, and drizzle-rc.4 cannot render a from-less guarded insert-select).\n */\nexport async function clearMutationRecoveryMarkerIfSettled(\n db: MutationDb,\n registry: SyncTableRegistry,\n): Promise<{ cleared: boolean }> {\n const meta = getLocalMetaTable(registry);\n const noSendingConditions = writableTableKeys(registry).map((key) => {\n const journal = getJournalTable(registry, key);\n return notExists(\n metaQueryBuilder\n .select({ one: sql`1` })\n .from(journal)\n .where(eq(journal.status, \"sending\")),\n );\n });\n const query = metaQueryBuilder\n .update(meta)\n .set({ value: \"false\" })\n .where(and(eq(meta.key, MUTATION_RECOVERY_REQUIRED_KEY), ...noSendingConditions))\n .toSQL();\n const result = (await db.query(query.sql, query.params as unknown[])) as { affectedRows?: number };\n return { cleared: (result.affectedRows ?? 0) > 0 };\n}\n\n/**\n * Reconcile the local store against the current registry fingerprint (ADR-0006). A fresh\n * (unstamped) store is stamped; an unchanged fingerprint is a no-op. On a change, the read\n * cache is dropped and rebuilt at the new shape **only when nothing is owed locally** —\n * otherwise the rebuild is deferred (and retried on a later boot) so un-flushed/quarantined\n * writes are never silently dropped. The drain happens across sessions: pending writes flush\n * and reconcile during normal use, and the rebuild completes once the journal is clear.\n *\n * An unstamped store is always treated as brand-new. There is no pre-fingerprint-store path:\n * the fingerprint mechanism shipped before launch, so every store in existence was\n * provisioned with it (and a stamped store's journal therefore always has `registry_version`).\n */\nexport async function reconcileLocalStoreVersion<TRegistry extends SyncTableRegistry>(args: {\n db: MutationDb;\n registry: TRegistry;\n runtime: VersionReconcileRuntime;\n onSchemaChange?: (event: LocalStoreVersionEvent) => void | Promise<void>;\n}): Promise<LocalStoreVersionEvent | null> {\n const { db, registry, runtime } = args;\n const stored = await readStoredRegistryFingerprint(db, registry);\n const current = runtime.registryVersion;\n\n if (stored === current) {\n return null;\n }\n\n if (stored === null) {\n await writeStoredRegistryFingerprint(db, registry, current);\n return null;\n }\n\n return rebuildReadCacheOrDefer(args, stored);\n}\n\n/**\n * The drain-then-drop core (ADR-0006): rebuild the read cache at the current shape when\n * nothing is owed locally, otherwise defer so un-flushed/quarantined writes are never\n * dropped (the drain completes on a later boot).\n */\nasync function rebuildReadCacheOrDefer<TRegistry extends SyncTableRegistry>(\n args: {\n db: MutationDb;\n registry: TRegistry;\n runtime: VersionReconcileRuntime;\n onSchemaChange?: (event: LocalStoreVersionEvent) => void | Promise<void>;\n },\n previousFingerprint: string,\n): Promise<LocalStoreVersionEvent> {\n const { db, registry, runtime, onSchemaChange } = args;\n const current = runtime.registryVersion;\n const stats = await runtime.readMutationStats();\n const owedMutations = stats.pendingCount + stats.sendingCount + stats.failedCount + stats.quarantinedCount;\n\n if (owedMutations > 0) {\n const event: LocalStoreVersionEvent = {\n status: \"deferred\",\n previousFingerprint,\n nextFingerprint: current,\n owedMutations,\n };\n await onSchemaChange?.(event);\n return event;\n }\n\n await db.exec(buildWipeLocalStoreSql(registry));\n await db.exec(generateLocalSchemaSql(registry));\n await writeStoredRegistryFingerprint(db, registry, current);\n // This is a full durable-schema exec, so re-stamp the durable-schema fingerprint alongside the registry\n // fingerprint (slice 3): exec and stamp travel together, so the next boot's fast path can trust the skip.\n await writeStoredLocalSchemaFingerprint(db, registry, computeLocalSchemaFingerprint(registry));\n const event: LocalStoreVersionEvent = {\n status: \"rebuilt\",\n previousFingerprint,\n nextFingerprint: current,\n owedMutations: 0,\n };\n await onSchemaChange?.(event);\n return event;\n}\n",
|
|
17
|
+
"import type { ColumnBuilderBase } from \"drizzle-orm\";\nimport { getColumns } from \"drizzle-orm\";\nimport {\n bigint,\n boolean,\n customType,\n getTableConfig,\n integer,\n pgSchema,\n pgTable,\n pgView,\n text,\n uuid,\n varchar,\n type AnyPgTable,\n type PgColumn,\n type PgTableWithColumns,\n type PgViewWithSelection,\n} from \"drizzle-orm/pg-core\";\n\nimport {\n deriveSyncColumnTypes,\n getLocalSyncedTablePrimaryKeyColumns,\n getSyncRegistrySchema,\n type SyncColumnType,\n type SyncTableEntry,\n type SyncTableRegistry,\n} from \"@pgxsinkit/contracts\";\n\nimport { ALL_MUTATIONS_VIEW, LOCAL_META_TABLE } from \"./schema\";\n\n/**\n * Runtime Drizzle objects for the GENERATED local-store relations (ADR-0004): the per-writable-table\n * overlay (`<t>_overlay`), journal (`<t>_mutations`), sync-state view (`<t>_sync_state`), the projected\n * synced read cache, and the `pgxsinkit_local_meta` key/value table. The schema generator\n * (`schema.ts`) remains the one authority for the DDL — these objects exist so the mutation runtime,\n * consumers, and tests can AUTHOR queries against those relations as tier-① Drizzle objects\n * (rename-safe, type-checked) instead of hand-written SQL strings.\n *\n * They are query-authoring objects only — never feed them to drizzle-kit generation; the generated\n * DDL in `schema.ts` is the source of truth for the physical shape, and `local-tables.test`-level\n * coverage (the existing overlay/journal suites run against generator-provisioned stores) is what\n * keeps the two aligned.\n *\n * Every object is schema-QUALIFIED with the registry's own local schema (via `getSyncRegistrySchema`).\n * `entry.table` / `entry.localTable` are already qualified the same way (`defineSyncTable` builds them\n * with the caller's schema, and `attachSyncRegistrySchema` throws unless they match the registry schema),\n * so for the synced read cache the factory just tracks a `clientProjection.syncedTable` rename. The\n * factories earn their keep where no equally-qualified entry handle exists: `entry.view` is built\n * schema-UNqualified (a bare `pgView`), so a store in a non-public schema must author the read model\n * through `getReadModelView`; and the overlay / journal / sync-state relations have NO entry handle at all\n * — these factories are the only Drizzle objects for them. Each factory MEMOIZES its result per\n * `(registry, tableKey)` (the `pgxsinkit_local_meta` table per local schema), so repeated calls hand back\n * the same object identity.\n *\n * Typing tracks the registry the caller holds: with a concretely-typed registry (built by\n * `defineSyncRegistry`) the synced/overlay/read-model objects carry the entry's real per-column types, so\n * `.select({ x: overlay.col })`, `$inferInsert`, and `.values()` all typecheck by property key; with a\n * bare `SyncTableRegistry` they degrade to an open index-signature shape reached by bracket access.\n * `JournalTable` / `SyncStateView` are ALWAYS conservatively indexed for their entity/PK columns (the PK\n * name set is not recoverable at the type level — see those types).\n */\n\n/**\n * Microsecond/bigint columns the mutation runtime handles as **strings** (the JSON-safe form it has\n * always used): passthrough both ways, `bigint` in DDL position. Reads through the raw `MutationDb`\n * seam bypass drizzle result mapping anyway; this keeps `.values()`/`.set()` accepting the runtime's\n * string values without a lossy JS-number hop.\n */\nconst bigintText = customType<{ data: string; driverData: string }>({\n dataType() {\n return \"bigint\";\n },\n});\n\nfunction buildJournalFixedColumns() {\n return {\n mutationId: uuid(\"mutation_id\").primaryKey(),\n entityKeyJson: text(\"entity_key_json\").notNull(),\n mutationSeq: integer(\"mutation_seq\").notNull(),\n mutationKind: varchar(\"mutation_kind\", { length: 24 }).notNull(),\n status: varchar(\"status\", { length: 24 }).notNull(),\n registryVersion: text(\"registry_version\"),\n baseServerVersion: bigintText(\"base_server_version\"),\n writeUnit: text(\"write_unit\"),\n writeMode: varchar(\"write_mode\", { length: 24 }),\n payloadJson: text(\"payload_json\").notNull(),\n attemptCount: integer(\"attempt_count\").notNull().default(0),\n lastError: text(\"last_error\"),\n lastHttpStatus: integer(\"last_http_status\"),\n conflictReason: text(\"conflict_reason\"),\n serverUpdatedAtUs: bigintText(\"server_updated_at_us\"),\n enqueuedAtUs: bigintText(\"enqueued_at_us\").notNull(),\n nextRetryAtUs: bigintText(\"next_retry_at_us\"),\n sentAtUs: bigintText(\"sent_at_us\"),\n ackedAtUs: bigintText(\"acked_at_us\"),\n updatedAtUs: bigintText(\"updated_at_us\").notNull(),\n };\n}\n\nfunction buildOverlayFixedColumns() {\n return {\n overlayKind: varchar(\"overlay_kind\", { length: 24 }).notNull(),\n localUpdatedAtUs: bigintText(\"local_updated_at_us\").notNull(),\n };\n}\n\n/**\n * The two overlay columns the `<t>_read_model` view carries on top of the projected synced columns.\n * Read through real drizzle result mapping (a live query, not the raw `MutationDb` seam), so\n * `local_updated_at_us` is a `mode: \"bigint\"` int8 (PGlite returns it as a string at runtime) rather than\n * the journal/overlay `bigintText` passthrough. Snake-case property keys so consumers reach them the same\n * way the generator names them (`view[\"overlay_kind\"]`).\n */\nfunction buildReadModelFixedColumns() {\n return {\n overlay_kind: varchar(\"overlay_kind\", { length: 24 }).notNull(),\n local_updated_at_us: bigint(\"local_updated_at_us\", { mode: \"bigint\" }).notNull(),\n };\n}\n\nfunction buildSyncStateFixedColumns() {\n return {\n observedServerVersion: bigint(\"observed_server_version\", { mode: \"bigint\" }),\n ackedServerVersion: bigint(\"acked_server_version\", { mode: \"bigint\" }),\n pendingCount: bigint(\"pending_count\", { mode: \"number\" }).notNull(),\n hasAckedUnobservedWrite: boolean(\"has_acked_unobserved_write\").notNull(),\n localDeletePending: boolean(\"local_delete_pending\").notNull(),\n conflictState: text(\"conflict_state\"),\n quarantinedCount: bigint(\"quarantined_count\", { mode: \"number\" }).notNull(),\n quarantineState: text(\"quarantine_state\"),\n };\n}\n\n// Phantom shape tables: never created, never queried — they exist only so the derived relation types\n// carry strong typing on the FIXED column keys. The per-entry ENTITY columns are layered on top from\n// the concrete registry entry (see the `*<TEntry>` types below), so a caller whose registry is\n// concretely typed reaches real, projected `PgColumn`s by property key; only a caller holding a bare\n// `SyncTableRegistry` falls back to the open index-signature form these shapes' generic default gives.\nconst journalShape = pgTable(\"_pgxsinkit_journal_shape\", buildJournalFixedColumns());\nconst overlayShape = pgTable(\"_pgxsinkit_overlay_shape\", buildOverlayFixedColumns());\nconst syncStateShape = pgView(\"_pgxsinkit_sync_state_shape\", buildSyncStateFixedColumns()).existing();\nconst readModelShape = pgView(\"_pgxsinkit_read_model_shape\", buildReadModelFixedColumns()).existing();\nconst localMetaShape = pgTable(LOCAL_META_TABLE, {\n key: text(\"key\").primaryKey(),\n value: text(\"value\").notNull(),\n});\n\n/**\n * The entry's PROJECTED local table type — its server columns minus `clientProjection.omitColumns`,\n * exactly the shape `defineSyncTable` stamped onto `entry.localTable`. When `TEntry` is a concrete\n * entry (a registry built by `defineSyncRegistry`) this carries the real, typed columns; when it is a\n * bare `SyncTableEntry` (a generic `SyncTableRegistry`) it degrades to `AnyPgTable`, which pushes every\n * derived type below onto the open `Record<string, PgColumn>` index-signature fallback.\n */\ntype EntryLocalTable<TEntry> =\n TEntry extends SyncTableEntry<AnyPgTable, infer TLocal extends AnyPgTable> ? TLocal : AnyPgTable;\n\n/** The entry's projected columns keyed by drizzle property key (or the open `PgColumns` fallback). */\ntype EntryColumns<TEntry> = EntryLocalTable<TEntry>[\"_\"][\"columns\"];\ntype OverlayFixedColumns = (typeof overlayShape)[\"_\"][\"columns\"];\ntype ReadModelFixedColumns = (typeof readModelShape)[\"_\"][\"selectedFields\"];\n\n/**\n * The `<t>_overlay` optimistic-intent table: the entry's PROJECTED columns (same builders the generator\n * and `entry.localTable` carry) merged with the two fixed overlay columns. The entity columns read\n * back through real drizzle result mapping, so their types mirror the projected table exactly (a\n * `mode: \"bigint\"` column is `bigint`, etc.). The two overlay columns are `bigintText` passthrough\n * (`local_updated_at_us` reads as a string). `TEntry` defaults to a bare entry, giving the open\n * index-signature form the mutation runtime (generic over any registry) needs.\n */\nexport type OverlayTable<TEntry = SyncTableEntry> = PgTableWithColumns<{\n name: string;\n schema: string | undefined;\n columns: EntryColumns<TEntry> & OverlayFixedColumns;\n dialect: \"pg\";\n}>;\n\n/**\n * The `<t>_read_model` overlay-merged read view (ADR-0004): the entry's PROJECTED columns under their\n * property keys plus the two fixed overlay columns (`overlay_kind`, `local_updated_at_us`). Read\n * through a live query, so `local_updated_at_us` is an int8 `mode: \"bigint\"` column.\n */\nexport type ReadModelView<TEntry = SyncTableEntry> = PgViewWithSelection<\n string,\n true,\n EntryColumns<TEntry> & ReadModelFixedColumns\n>;\n\n/**\n * The projected SYNCED read-cache table — the entry's projected local table (or `AnyPgTable` fallback).\n * Type-level note: the phantom relation name here is the original `tableName` (inherited from\n * `ProjectedLocalTable`), but the runtime object `getSyncedLocalTable` returns honours a\n * `clientProjection.syncedTable` rename — so the rendered SQL uses the runtime name, not this type's name.\n */\nexport type SyncedLocalTable<TEntry = SyncTableEntry> = EntryLocalTable<TEntry>;\n\n/**\n * The `<t>_mutations` journal: fixed runtime columns + the entry's PK columns (index-signature access).\n * Kept conservatively indexed: the journal carries ONLY the PK columns, keyed by DB COLUMN NAME and\n * type-erased to `text`, but neither the PK column-name set nor the \"PK only\" subset is recoverable at\n * the type level from `SyncTableEntry` (its `primaryKey.columns` is an un-narrowed `string[]`), so an\n * honest per-entry type is not representable without a footgun (claiming non-PK columns that do not\n * exist on the journal at runtime). PK/entity columns therefore ride the index signature.\n */\nexport type JournalTable = typeof journalShape & { [columnName: string]: PgColumn };\n/**\n * The `<t>_sync_state` convergence view (ADR-0011): fixed state columns + the entry's PK columns.\n * Conservatively indexed for the same reason as {@link JournalTable} — it projects only the PK columns\n * (a subset not recoverable at the type level), so the PK columns ride the index signature.\n */\nexport type SyncStateView = typeof syncStateShape & { [columnName: string]: PgColumn };\n/** The `pgxsinkit_local_meta` key/value table (ADR-0006). */\nexport type LocalMetaTable = typeof localMetaShape;\n\n/**\n * Build a runtime `pgTable` for a local-store relation. An `ephemeral`-lifecycle entry (ADR-0021 §3)\n * renders **bare** regardless of the registry's local schema: its whole cluster is emitted as `TEMP`\n * with unqualified object names that resolve via `pg_temp`/search_path, exactly as\n * `generateLocalSchemaSql` renders it (a `pgSchema(localSchema).table(...)` reference would target a\n * durable schema the temp table does not live in — the latent qualification bug ADR-0029 records).\n */\nfunction makeTable(\n localSchema: string,\n name: string,\n columns: Record<string, ColumnBuilderBase>,\n ephemeral = false,\n): AnyPgTable {\n return localSchema === \"public\" || ephemeral ? pgTable(name, columns) : pgSchema(localSchema).table(name, columns);\n}\n\nfunction isEphemeral(entry: SyncTableEntry<AnyPgTable>): boolean {\n return entry.retention === \"ephemeral\";\n}\n\nfunction resolveSyncedTableName(entry: SyncTableEntry<AnyPgTable>): string {\n return entry.clientProjection?.syncedTable ?? getTableConfig(entry.table).name;\n}\n\n/**\n * The entry's projected column BUILDERS keyed by property key, re-created from the retained\n * `makeColumns` factory (registry.ts keeps it for exactly this kind of reuse) with\n * `clientProjection.omitColumns` applied — the same projection the generator's synced/overlay DDL\n * carries.\n */\nfunction projectedColumnBuilders(entry: SyncTableEntry<AnyPgTable>, tableKey: string) {\n const makeColumns = entry.makeColumns;\n if (!makeColumns) {\n throw new Error(\n `local table objects for ${tableKey} need the entry's makeColumns factory (built by defineSyncTable); ` +\n `hand-assembled entries cannot derive overlay/journal objects`,\n );\n }\n const omitted = new Set(entry.clientProjection?.omitColumns ?? []);\n return Object.fromEntries(Object.entries(makeColumns()).filter(([key]) => !omitted.has(key))) as Record<\n string,\n ColumnBuilderBase\n >;\n}\n\n/** Property-key ↔ column-name pairs for the entry's PK, resolved via the built local table. */\nfunction pkColumnPairs(entry: SyncTableEntry<AnyPgTable>, tableKey: string) {\n const localColumns = getColumns(entry.localTable) as Record<string, PgColumn>;\n return entry.primaryKey.columns.map((columnName) => {\n const pair = Object.entries(localColumns).find(([, column]) => column.name === columnName);\n if (!pair) {\n throw new Error(`Primary key column ${columnName} was not found on table ${tableKey}`);\n }\n return { propertyKey: pair[0], columnName };\n });\n}\n\ninterface EntryLocalTables {\n synced?: AnyPgTable;\n overlay?: OverlayTable;\n journal?: JournalTable;\n syncState?: SyncStateView;\n readModel?: ReadModelView;\n}\n\nconst localTablesCache = new WeakMap<SyncTableRegistry, Map<string, EntryLocalTables>>();\nconst localMetaCache = new Map<string, LocalMetaTable>();\n\nfunction cacheFor(registry: SyncTableRegistry, tableKey: string): EntryLocalTables {\n let byKey = localTablesCache.get(registry);\n if (!byKey) {\n byKey = new Map();\n localTablesCache.set(registry, byKey);\n }\n let slot = byKey.get(tableKey);\n if (!slot) {\n slot = {};\n byKey.set(tableKey, slot);\n }\n return slot;\n}\n\nfunction requireEntry(registry: SyncTableRegistry, tableKey: string): SyncTableEntry<AnyPgTable> {\n const entry = registry[tableKey];\n if (!entry) {\n throw new Error(`Unknown sync table: ${tableKey}`);\n }\n return entry;\n}\n\nfunction requireWritable(entry: SyncTableEntry<AnyPgTable>, tableKey: string, relation: string) {\n if (!entry.clientProjection?.overlayTable || !entry.clientProjection.journalTable) {\n throw new Error(`${relation} exists only for a writable table; ${tableKey} has no overlay/journal projection`);\n }\n return entry.clientProjection as { overlayTable: string; journalTable: string; syncedTable?: string };\n}\n\n/**\n * The projected SYNCED read-cache table as a runtime Drizzle object, under the resolved local name\n * (`clientProjection.syncedTable` override honoured) and the registry's local schema — the exact\n * relation the generator's `CREATE TABLE` provisions. Prefer `entry.localTable` where its name\n * already matches; this object exists for the runtime/tests that must track the projection rename.\n * Carries the entry's real projected columns under a concretely-typed registry, `AnyPgTable` under a\n * bare `SyncTableRegistry` (see {@link SyncedLocalTable}).\n */\nexport function getSyncedLocalTable<TRegistry extends SyncTableRegistry, TKey extends string & keyof TRegistry>(\n registry: TRegistry,\n tableKey: TKey,\n): SyncedLocalTable<TRegistry[TKey]> {\n const slot = cacheFor(registry, tableKey);\n if (slot.synced) {\n return slot.synced as SyncedLocalTable<TRegistry[TKey]>;\n }\n const entry = requireEntry(registry, tableKey);\n const localSchema = getSyncRegistrySchema(registry);\n const table = makeTable(\n localSchema,\n resolveSyncedTableName(entry),\n projectedColumnBuilders(entry, tableKey) as Record<string, ColumnBuilderBase>,\n isEphemeral(entry),\n );\n slot.synced = table;\n return table as SyncedLocalTable<TRegistry[TKey]>;\n}\n\n/**\n * The `<t>_overlay` optimistic-intent table as a runtime Drizzle object (writable tables only — throws\n * for a readonly entry, which has no overlay/journal projection). Its entity columns are typed exactly\n * as {@link OverlayTable} describes — real per-column types under a concretely-typed registry, the open\n * index-signature fallback under a bare `SyncTableRegistry` — plus the two fixed overlay columns.\n */\nexport function getOverlayTable<TRegistry extends SyncTableRegistry, TKey extends string & keyof TRegistry>(\n registry: TRegistry,\n tableKey: TKey,\n): OverlayTable<TRegistry[TKey]> {\n const slot = cacheFor(registry, tableKey);\n if (slot.overlay) {\n return slot.overlay as OverlayTable<TRegistry[TKey]>;\n }\n const entry = requireEntry(registry, tableKey);\n const projection = requireWritable(entry, tableKey, \"the overlay table\");\n const localSchema = getSyncRegistrySchema(registry);\n const table = makeTable(\n localSchema,\n projection.overlayTable,\n {\n ...(projectedColumnBuilders(entry, tableKey) as Record<string, ColumnBuilderBase>),\n ...buildOverlayFixedColumns(),\n },\n isEphemeral(entry),\n ) as OverlayTable;\n slot.overlay = table;\n return table as OverlayTable<TRegistry[TKey]>;\n}\n\n/**\n * The `<t>_mutations` journal table as a runtime Drizzle object (writable tables only). The fixed runtime\n * columns are typed; the PK/entity columns ride the index signature and are reached by DB column NAME\n * (`journal[\"id\"]`), because per-entry typing is not representable — see {@link JournalTable}.\n */\nexport function getJournalTable<TRegistry extends SyncTableRegistry>(\n registry: TRegistry,\n tableKey: string & keyof TRegistry,\n): JournalTable {\n const slot = cacheFor(registry, tableKey);\n if (slot.journal) {\n return slot.journal;\n }\n const entry = requireEntry(registry, tableKey);\n const projection = requireWritable(entry, tableKey, \"the journal table\");\n const localSchema = getSyncRegistrySchema(registry);\n const pkBuilders = Object.fromEntries(\n pkColumnPairs(entry, tableKey).map(({ columnName }) => [columnName, text(columnName).notNull()]),\n );\n const table = makeTable(\n localSchema,\n projection.journalTable,\n {\n ...pkBuilders,\n ...buildJournalFixedColumns(),\n },\n isEphemeral(entry),\n ) as JournalTable;\n slot.journal = table;\n return table;\n}\n\n/**\n * The `<t>_sync_state` convergence view (ADR-0011) as a runtime Drizzle object (writable tables only) —\n * PK columns under the entry's own property keys plus the fixed state columns, mirroring\n * `buildSyncStateView`'s projection. The fixed state columns are typed; the PK columns ride the index\n * signature (not recoverable at the type level — see {@link SyncStateView}) and are reached by their\n * drizzle PROPERTY key (`view[\"authorId\"]`), unlike the journal, which keys its PK columns by DB column\n * name.\n */\nexport function getSyncStateView<TRegistry extends SyncTableRegistry>(\n registry: TRegistry,\n tableKey: string & keyof TRegistry,\n): SyncStateView {\n const slot = cacheFor(registry, tableKey);\n if (slot.syncState) {\n return slot.syncState;\n }\n const entry = requireEntry(registry, tableKey);\n requireWritable(entry, tableKey, \"the sync-state view\");\n const localSchema = getSyncRegistrySchema(registry);\n const viewName = `${resolveSyncedTableName(entry)}_sync_state`;\n const builders = projectedColumnBuilders(entry, tableKey);\n const pkBuilders = Object.fromEntries(\n pkColumnPairs(entry, tableKey).map(({ propertyKey }) => {\n const builder = builders[propertyKey];\n if (!builder) {\n throw new Error(`Primary key property ${propertyKey} was not found on table ${tableKey}`);\n }\n return [propertyKey, builder];\n }),\n ) as Record<string, ColumnBuilderBase>;\n const columns = {\n ...(pkBuilders as Record<string, ColumnBuilderBase>),\n ...buildSyncStateFixedColumns(),\n };\n const view = (\n localSchema === \"public\" || isEphemeral(entry)\n ? pgView(viewName, columns).existing()\n : pgSchema(localSchema).view(viewName, columns).existing()\n ) as SyncStateView;\n slot.syncState = view;\n return view;\n}\n\n/**\n * The `<t>_read_model` overlay-merged read view (ADR-0004) as a runtime Drizzle object: every projected\n * synced column under the entry's own property key plus the two overlay columns (`overlay_kind`,\n * `local_updated_at_us`), mirroring the generator's `CREATE VIEW`. The entry's own `entry.view` is\n * schema-UNQUALIFIED (`defineSyncTable` builds it with a bare `pgView`), so a consumer whose local store\n * lives in a non-public schema must author against this qualified object instead of `entry.view`.\n */\nexport function getReadModelView<TRegistry extends SyncTableRegistry, TKey extends string & keyof TRegistry>(\n registry: TRegistry,\n tableKey: TKey,\n): ReadModelView<TRegistry[TKey]> {\n const slot = cacheFor(registry, tableKey);\n if (slot.readModel) {\n return slot.readModel as ReadModelView<TRegistry[TKey]>;\n }\n const entry = requireEntry(registry, tableKey);\n requireWritable(entry, tableKey, \"the read-model view\");\n const localSchema = getSyncRegistrySchema(registry);\n const viewName = `${resolveSyncedTableName(entry)}_read_model`;\n const columns = {\n ...(projectedColumnBuilders(entry, tableKey) as Record<string, ColumnBuilderBase>),\n ...buildReadModelFixedColumns(),\n };\n const view = (\n localSchema === \"public\" || isEphemeral(entry)\n ? pgView(viewName, columns).existing()\n : pgSchema(localSchema).view(viewName, columns).existing()\n ) as ReadModelView;\n slot.readModel = view;\n return view as ReadModelView<TRegistry[TKey]>;\n}\n\n/**\n * The read-path applier's resolved per-shape target (ADR-0029 D1/D2). Every table-scoped fact the\n * appliers need is derived once from the registry entry — the real projected synced table object, its\n * columns indexed by DB column name, the primary-key column names, and the model-derived column types —\n * so the appliers author over Drizzle objects (no name/schema strings, no `information_schema` probe).\n * Resolved once per shape at subscribe time; reused for every message. Electric change rows are keyed\n * by DB **column name**, while Drizzle DML keys by **property key**, so both indexes are carried.\n */\nexport interface ApplyTarget {\n /** The real projected synced local table (`getSyncedLocalTable`) — bare for ephemeral lifecycles. */\n table: AnyPgTable;\n /** DB column name → its Drizzle `PgColumn` (for `eq`/conflict-target/COPY clauses). */\n columnByName: Record<string, PgColumn>;\n /** DB column name → its Drizzle property key (to key `.values()`/`.set()` from a name-keyed row). */\n propertyKeyByName: Record<string, string>;\n /** Primary-key column NAMES, in order (from the entry, local-projection override honoured). */\n primaryKey: string[];\n /** Model-derived column types (`deriveSyncColumnTypes`), keyed by DB column name via `.name`. */\n columnTypes: SyncColumnType[];\n /**\n * Per-shape render-once cache for the batched-INSERT family (ADR-0029 D5): a rendered `{sqlText,\n * params}` per distinct (column-set, row-count), reused across batches with per-value codecs applied\n * at execution. Empty at resolution; populated lazily by the applier.\n */\n insertRenderCache: Map<string, { sqlText: string; params: unknown[] }>;\n}\n\n/**\n * Resolve a shape's {@link ApplyTarget} from its registry entry (ADR-0029 D1/D2). Called once per shape\n * at subscribe time — never per message. The single source is the registry item: identity via\n * `getSyncedLocalTable`, PKs via `getLocalSyncedTablePrimaryKeyColumns`, types via `deriveSyncColumnTypes`.\n */\nexport function resolveApplyTarget<TRegistry extends SyncTableRegistry, TKey extends string & keyof TRegistry>(\n registry: TRegistry,\n tableKey: TKey,\n): ApplyTarget {\n const entry = requireEntry(registry, tableKey);\n const table = getSyncedLocalTable(registry, tableKey);\n const columns = getColumns(table as AnyPgTable) as Record<string, PgColumn>;\n const columnByName: Record<string, PgColumn> = {};\n const propertyKeyByName: Record<string, string> = {};\n for (const [propertyKey, column] of Object.entries(columns)) {\n columnByName[column.name] = column;\n propertyKeyByName[column.name] = propertyKey;\n }\n return {\n table: table as AnyPgTable,\n columnByName,\n propertyKeyByName,\n primaryKey: getLocalSyncedTablePrimaryKeyColumns(entry),\n columnTypes: deriveSyncColumnTypes(entry),\n insertRenderCache: new Map(),\n };\n}\n\n/**\n * The fixed columns of the registry-wide `pgxsinkit_all_mutations` view (ADR-0021/slice 4): a `table_key`\n * literal per branch plus the shared fixed journal columns ({@link ALL_MUTATIONS_JOURNAL_COLUMNS} in\n * schema.ts) — MINUS `payload_json` and the per-table PK columns. The `_us` bigints are the same\n * `bigintText` passthrough the journal object uses (read back through the raw seam / the live-rows seam,\n * which return rows UNMAPPED — no drizzle result mapping), so the runtime reads them as strings.\n */\nfunction buildAllMutationsViewColumns() {\n return {\n tableKey: text(\"table_key\").notNull(),\n mutationId: uuid(\"mutation_id\").notNull(),\n entityKeyJson: text(\"entity_key_json\").notNull(),\n mutationSeq: integer(\"mutation_seq\").notNull(),\n mutationKind: varchar(\"mutation_kind\", { length: 24 }).notNull(),\n status: varchar(\"status\", { length: 24 }).notNull(),\n registryVersion: text(\"registry_version\"),\n baseServerVersion: bigintText(\"base_server_version\"),\n writeUnit: text(\"write_unit\"),\n writeMode: varchar(\"write_mode\", { length: 24 }),\n attemptCount: integer(\"attempt_count\").notNull(),\n lastError: text(\"last_error\"),\n lastHttpStatus: integer(\"last_http_status\"),\n conflictReason: text(\"conflict_reason\"),\n serverUpdatedAtUs: bigintText(\"server_updated_at_us\"),\n enqueuedAtUs: bigintText(\"enqueued_at_us\").notNull(),\n nextRetryAtUs: bigintText(\"next_retry_at_us\"),\n sentAtUs: bigintText(\"sent_at_us\"),\n ackedAtUs: bigintText(\"acked_at_us\"),\n updatedAtUs: bigintText(\"updated_at_us\").notNull(),\n };\n}\n\nconst allMutationsShape = pgView(ALL_MUTATIONS_VIEW, buildAllMutationsViewColumns()).existing();\n\n/**\n * The registry-wide `pgxsinkit_all_mutations` cross-journal view (slice 4) as a runtime Drizzle object. Its\n * columns are the fixed journal columns (typed) plus the `table_key` registry-key literal — no per-table PK\n * columns, no payload. Unlike the other view factories this is schema-INDEPENDENT: the view is always emitted\n * `TEMP` (it may reference `pg_temp` ephemeral journals), so it resolves bare via `pg_temp`/search_path\n * regardless of the registry's local schema — hence one memoized instance for every registry. The\n * `client.mutations.*` API authors its summary/detail queries over THIS object (tier ①).\n */\nexport type AllMutationsView = typeof allMutationsShape;\n\nexport function getAllMutationsView(_registry: SyncTableRegistry): AllMutationsView {\n return allMutationsShape;\n}\n\n/** The `pgxsinkit_local_meta` key/value table (ADR-0006) under the registry's local schema. */\nexport function getLocalMetaTable(registry: SyncTableRegistry): LocalMetaTable {\n const localSchema = getSyncRegistrySchema(registry);\n const cached = localMetaCache.get(localSchema);\n if (cached) {\n return cached;\n }\n const table = makeTable(localSchema, LOCAL_META_TABLE, {\n key: text(\"key\").primaryKey(),\n value: text(\"value\").notNull(),\n }) as LocalMetaTable;\n localMetaCache.set(localSchema, table);\n return table;\n}\n",
|
|
18
|
+
"import { getTableConfig, getViewConfig, type AnyPgTable } from \"drizzle-orm/pg-core\";\n\nimport {\n buildOverlayResolutionBarrier,\n buildSyncStateView,\n getLocalSyncPrimaryKeyColumns,\n getSyncRegistrySchema,\n getProjectedColumns,\n hashString,\n maybeQuoteIdentifier,\n quoteIdentifier,\n quoteSqlLiteral as quoteSqlStringLiteral,\n type SyncTableEntry,\n type SyncTableRegistry,\n} from \"@pgxsinkit/contracts\";\n\nimport { buildClearShapeTagsSql, shapeTableId } from \"./sync/tags\";\n\n/** Internal fully-qualified projection used within schema generation. */\ninterface ResolvedProjection {\n syncedTable: string;\n overlayTable?: string;\n journalTable?: string;\n readModel: string;\n /** The per-table `<table>_sync_state` convergence view (writable tables only — ADR-0011). */\n syncState: string;\n /**\n * The reconcile trigger's function — schema-qualified, because a function is a schema object.\n * Suffix-then-qualify (never `${qualifiedTable}_reconcile_on_sync`, which double-quotes a\n * non-public schema's qualified name into invalid SQL).\n */\n reconcileFunction: string;\n /**\n * The reconcile trigger itself — an UNqualified identifier. A trigger is not a schema object; it\n * is bound to its table via `ON <qualified table>`, so its name must not be schema-qualified.\n */\n reconcileTrigger: string;\n}\n\n/**\n * Local key/value metadata table. Holds the registry fingerprint the local store was\n * provisioned under (ADR-0006), so a registry change is detected on boot and the read\n * cache is rebuilt — rather than relying on a hand-bumped `idb://…-vN` suffix.\n */\nexport const LOCAL_META_TABLE = \"pgxsinkit_local_meta\";\nexport const REGISTRY_FINGERPRINT_KEY = \"registry_fingerprint\";\n/**\n * The `pgxsinkit_local_meta` key holding the DURABLE-schema fingerprint the local store was last\n * provisioned under (warm-persisted-store-startup slice 3 / proposal §3). Its value is\n * `lsf1:<hash(durable SQL)>` (see {@link computeLocalSchemaFingerprint}); a boot compares it against the\n * freshly-generated durable SQL's hash to SKIP the durable replay when they match.\n */\nexport const LOCAL_SCHEMA_FINGERPRINT_KEY = \"local_schema_fingerprint\";\n/** The versioned value prefix for {@link LOCAL_SCHEMA_FINGERPRINT_KEY} (bump only if the encoding changes). */\nexport const LOCAL_SCHEMA_FINGERPRINT_PREFIX = \"lsf1:\";\n\n/**\n * The registry-wide cross-journal mutation view (warm-persisted-store-startup slice 4 / proposal §5,\n * option 1). A `TEMP` view UNION-ALL-ing every writable table's journal down to the shared fixed columns\n * (plus a `table_key` literal per branch), so a consumer can render one global mutation summary/detail\n * subscription instead of one live query per writable journal. It MUST be `TEMP`: an ephemeral entry's\n * journal is a `pg_temp` relation (ADR-0021 §3), which a durable view cannot reference — and it is\n * recreated on every engine boot (a TEMP view dies with the old engine), so it lives in the always-applied\n * ephemeral schema portion, NOT the durable (fingerprint-gated) portion. See {@link getAllMutationsView}\n * for the query-authoring Drizzle object over it.\n */\nexport const ALL_MUTATIONS_VIEW = \"pgxsinkit_all_mutations\";\n\n/**\n * The shared fixed journal columns the {@link ALL_MUTATIONS_VIEW} branches project (in journal-DDL order),\n * mirroring `buildJournalFixedColumns` (local-tables.ts) MINUS `payload_json` (detail rows stay\n * payload-free by default — entity identity comes from `entity_key_json`) and the per-table PRIMARY KEY\n * columns (they differ per branch, so they cannot appear in a UNION ALL). `mutation_seq` is retained: it is\n * a shared fixed column and {@link import(\"./mutation\").MutationDetail} carries it — but it is per-journal,\n * NOT globally ordered, so the detail API orders by `enqueued_at_us`, never this.\n */\nexport const ALL_MUTATIONS_JOURNAL_COLUMNS = [\n \"mutation_id\",\n \"entity_key_json\",\n \"mutation_seq\",\n \"mutation_kind\",\n \"status\",\n \"registry_version\",\n \"base_server_version\",\n \"write_unit\",\n \"write_mode\",\n \"attempt_count\",\n \"last_error\",\n \"last_http_status\",\n \"conflict_reason\",\n \"server_updated_at_us\",\n \"enqueued_at_us\",\n \"next_retry_at_us\",\n \"sent_at_us\",\n \"acked_at_us\",\n \"updated_at_us\",\n] as const;\n\ntype TableColumn = ReturnType<typeof getProjectedColumns<AnyPgTable>>[number][\"column\"];\n\n/** Join a statement list into a single executable script, matching the historical generator's separator. */\nfunction joinSchemaStatements(statements: string[]): string {\n return `${statements.join(\"\\n\\n\")}\\n`;\n}\n\n/**\n * The schema-create (non-public only) + `pgxsinkit_local_meta` CREATE-IF-NOT-EXISTS — the minimal durable\n * bootstrap every boot needs BEFORE it can read/write the local-schema fingerprint. Emitted standalone by\n * {@link buildLocalMetaBootstrapSql}, and first in the durable statement stream.\n */\nfunction localMetaBootstrapStatements(localSchema: string): string[] {\n const statements: string[] = [];\n\n if (localSchema !== \"public\") {\n statements.push(`CREATE SCHEMA IF NOT EXISTS ${quoteIdentifier(localSchema)};`);\n }\n\n statements.push(\n `CREATE TABLE IF NOT EXISTS ${qualifyIdentifier(localSchema, LOCAL_META_TABLE)} (\\n ${[\n \"key TEXT PRIMARY KEY\",\n \"value TEXT NOT NULL\",\n ].join(\",\\n \")}\\n);`,\n );\n\n return statements;\n}\n\n/**\n * The minimal durable bootstrap (schema + meta table) as an executable script (slice 3). Run as the first,\n * tiny crossing on every client-owned boot so the `local_schema_fingerprint` read/write has its table before\n * the fingerprint fast path decides whether to replay the rest of the durable schema. Depends on the\n * registry only for its local schema name, so it is a function rather than a bare constant.\n */\nexport function buildLocalMetaBootstrapSql<TRegistry extends SyncTableRegistry>(registry: TRegistry): string {\n return joinSchemaStatements(localMetaBootstrapStatements(getSyncRegistrySchema(registry)));\n}\n\n/**\n * Build the full DDL cluster for ONE registry entry — synced table, and (for a writable entry) overlay,\n * sequence, journal + its indexes, reconcile function + trigger, and the read-model/sync-state views. This\n * is the per-entry body {@link generateDurableLocalSchemaSql} and {@link generateEphemeralLocalSchemaSql}\n * share (partitioned by `retention === \"ephemeral\"`), so the two paths cannot drift.\n *\n * ADR-0021 §3: an `ephemeral` entry's whole cluster is emitted as `TEMP` — bare (unqualified) object names\n * that resolve via `pg_temp` / search_path, so read- and write-ephemerality fall out together (no durable\n * trace). Object NAMES go bare+TEMP; column *types* (enums) stay in the persistent schema. For a persistent\n * entry `temp` is \"\" and `objectSchema` is the registry schema.\n */\nfunction buildEntryClusterStatements(entry: SyncTableEntry, tableKey: string, localSchema: string): string[] {\n const statements: string[] = [];\n const ephemeral = entry.retention === \"ephemeral\";\n const objectSchema = ephemeral ? \"public\" : localSchema;\n const temp = ephemeral ? \"TEMP \" : \"\";\n\n const projection = getClientProjection(entry, tableKey, objectSchema);\n const columns = getProjectedColumns(entry).map(({ column }) => column);\n const syncedTablePrimaryKeyColumns = getLocalSyncPrimaryKeyColumns(entry);\n const baseColumnsSql = buildTableColumnSql(columns, syncedTablePrimaryKeyColumns, localSchema);\n\n statements.push(`CREATE ${temp}TABLE IF NOT EXISTS ${projection.syncedTable} (\\n ${baseColumnsSql}\\n);`);\n\n if (entry.mode === \"readonly\") {\n return statements;\n }\n\n if (!projection.overlayTable || !projection.journalTable) {\n throw new Error(`overlay and journal tables are required for writable table ${tableKey}`);\n }\n\n const journalTableName = entry.clientProjection?.journalTable;\n\n if (!journalTableName) {\n throw new Error(`journal table is required for writable table ${tableKey}`);\n }\n\n const primaryKeyColumns = entry.primaryKey.columns.map((columnName) => {\n const column = columns.find((candidate) => candidate.name === columnName);\n\n if (!column) {\n throw new Error(`Primary key column ${columnName} was not found on table ${tableKey}`);\n }\n\n return column;\n });\n const primaryKeyColumnNames = primaryKeyColumns.map((column) => column.name);\n const journalSequenceName = buildJournalSequenceName(journalTableName);\n const qualifiedJournalSequenceName = qualifyIdentifier(objectSchema, journalSequenceName);\n\n statements.push(\n `CREATE ${temp}TABLE IF NOT EXISTS ${projection.overlayTable} (\\n ${[\n ...columns.map((column) => buildColumnDefinition(column, primaryKeyColumnNames, localSchema)),\n \"overlay_kind VARCHAR(24) NOT NULL\",\n \"local_updated_at_us BIGINT NOT NULL\",\n ...buildCompositePrimaryKeyClauses(primaryKeyColumnNames),\n ].join(\",\\n \")}\\n);`,\n );\n\n statements.push(\n `CREATE ${temp}SEQUENCE IF NOT EXISTS ${qualifiedJournalSequenceName} AS integer START WITH 1 INCREMENT BY 1;`,\n );\n\n statements.push(\n `CREATE ${temp}TABLE IF NOT EXISTS ${projection.journalTable} (\\n ${[\n \"mutation_id UUID PRIMARY KEY\",\n ...primaryKeyColumns.map((column) => `${column.name} ${mapColumnType(column, localSchema)} NOT NULL`),\n \"entity_key_json TEXT NOT NULL\",\n `mutation_seq INTEGER NOT NULL UNIQUE DEFAULT nextval(${quoteSqlStringLiteral(qualifiedJournalSequenceName)})::integer`,\n \"mutation_kind VARCHAR(24) NOT NULL\",\n \"status VARCHAR(24) NOT NULL\",\n // The registry fingerprint (ADR-0004) this mutation was authored under, so a\n // version-boundary crossing is known before sending (ADR-0006 decision 4).\n \"registry_version TEXT\",\n // ADR-0011 reserved hook: the Server version the entity was observed at when this mutation\n // was authored. The slot lives on the journal (per-mutation, like registry_version above);\n // the stale-write conflict policy (ADR-0015) decides its exact semantics and stamps it.\n \"base_server_version BIGINT\",\n // ADR-0022: the dynamic write-unit tag stamped by a `transaction({ mode })` block — the shared\n // unit id grouping co-committed mutations, and the unit's write-mode. NULL for the default path\n // (an untagged mutation), where the flusher derives mode + unit from the table's static group.\n \"write_unit TEXT\",\n \"write_mode VARCHAR(24)\",\n \"payload_json TEXT NOT NULL\",\n \"attempt_count INTEGER NOT NULL DEFAULT 0\",\n \"last_error TEXT\",\n \"last_http_status INTEGER\",\n \"conflict_reason TEXT\",\n \"server_updated_at_us BIGINT\",\n \"enqueued_at_us BIGINT NOT NULL\",\n \"next_retry_at_us BIGINT\",\n \"sent_at_us BIGINT\",\n \"acked_at_us BIGINT\",\n \"updated_at_us BIGINT NOT NULL\",\n ].join(\",\\n \")}\\n);`,\n );\n\n // Journal indexes render through the SAME core the pgTable-driven renderer uses\n // ({@link renderCreateIndexStatement}), so the two index-emitting paths cannot drift in statement\n // shape. These names/columns are registry-derived bare identifiers, passed verbatim (the pgTable\n // path is the one that quotes) — output stays byte-identical to the former hand-built statements.\n statements.push(\n renderCreateIndexStatement(projection.journalTable, `${journalTableName}_status_idx`, [\"status\", \"enqueued_at_us\"]),\n );\n statements.push(\n renderCreateIndexStatement(projection.journalTable, `${journalTableName}_status_retry_idx`, [\n \"status\",\n \"next_retry_at_us\",\n \"enqueued_at_us\",\n ]),\n );\n statements.push(\n renderCreateIndexStatement(projection.journalTable, `${journalTableName}_pk_seq_idx`, [\n ...entry.primaryKey.columns,\n \"mutation_seq\",\n ]),\n );\n statements.push(\n renderCreateIndexStatement(projection.journalTable, `${journalTableName}_entity_seq_idx`, [\n \"entity_key_json\",\n \"mutation_seq\",\n ]),\n );\n statements.push(\n renderCreateIndexStatement(projection.journalTable, `${journalTableName}_entity_status_seq_idx`, [\n \"entity_key_json\",\n \"status\",\n \"mutation_seq\",\n ]),\n );\n\n // Trigger: automatically clear overlay + journal entries when the sync\n // echo arrives. Fires on INSERT/UPDATE (new data from Electric) and DELETE\n // (row removed on server, synced back via Electric).\n const pkMatchSql = (alias: string) =>\n primaryKeyColumns\n .map((col) => `\"${alias}\".\"${col.name}\" = COALESCE(NEW.\"${col.name}\", OLD.\"${col.name}\")`)\n .join(\" AND \");\n const pkOverlayMatchSql = primaryKeyColumns\n .map((col) => `\"overlay\".\"${col.name}\" = COALESCE(NEW.\"${col.name}\", OLD.\"${col.name}\")`)\n .join(\" AND \");\n\n // ADR-0010: an acked create/update clears only once the synced echo's Server version reaches\n // the write's acked version — never on a bare key-match, which a stale or reordered echo could\n // satisfy and flip the read model to neither the optimistic nor the converged value. A delete\n // stays resolved by synced-row absence (NEW is NULL on the synced DELETE; the barrier reads\n // NULL there, so it never clears a create/update on a delete echo). One predicate, shared with\n // reconcileTable (mutation.ts), so the two sites cannot drift.\n const resolutionBarrier = buildOverlayResolutionBarrier(entry, { syncedAlias: \"NEW\" });\n\n // ADR-0021 §3: an ephemeral cluster's reconcile function lives in `pg_temp` alongside its temp table\n // (a permanent function cannot be a temp trigger's handler cleanly); a persistent one is unchanged.\n const reconcileFunctionRef = ephemeral ? `pg_temp.${projection.reconcileFunction}` : projection.reconcileFunction;\n\n statements.push(\n `CREATE OR REPLACE FUNCTION ${reconcileFunctionRef}() RETURNS TRIGGER AS $$\\n` +\n `BEGIN\\n` +\n ` -- ADR-0015: retire a terminal 'conflicted' row once a LATER write on the same entity has\\n` +\n ` -- been acked — that later write IS the resolution. The acked resolver is cleared by the\\n` +\n ` -- acked-delete below the moment its echo lands; if that echo wins the race against the\\n` +\n ` -- post-flush reconcileTable pass, the resolver is gone before reconcileTable's supersede-\\n` +\n ` -- retire can see it and the conflicted row orphans (its surfaced conflict_state never\\n` +\n ` -- clears). Doing the retire here too — in the trigger that has the echo context, BEFORE the\\n` +\n ` -- acked-clear — closes that race. Mirrors reconcileTable's retire (mutation.ts).\\n` +\n ` DELETE FROM ${projection.journalTable} AS \"conflicted\"\\n` +\n ` USING ${projection.journalTable} AS \"resolver\"\\n` +\n ` WHERE \"conflicted\".status = 'conflicted' AND (${pkMatchSql(\"conflicted\")})\\n` +\n ` AND \"resolver\".entity_key_json = \"conflicted\".entity_key_json\\n` +\n ` AND \"resolver\".mutation_seq > \"conflicted\".mutation_seq\\n` +\n ` AND \"resolver\".status = 'acked';\\n` +\n ` DELETE FROM ${projection.journalTable} AS \"journal\"\\n` +\n ` WHERE status = 'acked' AND (${pkMatchSql(\"journal\")})\\n` +\n ` AND (\\n` +\n ` (TG_OP <> 'DELETE' AND mutation_kind <> 'delete' AND ${resolutionBarrier})\\n` +\n ` OR (TG_OP = 'DELETE' AND mutation_kind = 'delete')\\n` +\n ` );\\n` +\n ` DELETE FROM ${projection.overlayTable} AS \"overlay\"\\n` +\n ` WHERE (${pkOverlayMatchSql})\\n` +\n ` AND NOT EXISTS (\\n` +\n ` SELECT 1 FROM ${projection.journalTable} AS j\\n` +\n ` WHERE (${pkMatchSql(\"j\")})\\n` +\n ` );\\n` +\n ` RETURN COALESCE(NEW, OLD);\\n` +\n `END;\\n` +\n `$$ LANGUAGE plpgsql;`,\n );\n\n statements.push(\n `CREATE OR REPLACE TRIGGER ${projection.reconcileTrigger}\\n` +\n `AFTER INSERT OR UPDATE OR DELETE ON ${projection.syncedTable}\\n` +\n `FOR EACH ROW EXECUTE FUNCTION ${reconcileFunctionRef}();`,\n );\n\n statements.push(\n `CREATE OR REPLACE ${temp}VIEW ${projection.readModel} AS\\n${buildReadModelViewSql(\n entry,\n projection,\n columns.map((column) => column.name),\n )};`,\n );\n\n // ADR-0011: the per-table convergence view — a derived projection over synced + overlay +\n // journal, distinct from the (lean) read model, whose acked-unobserved status derives from the\n // same barrier predicate the reconcile trigger above uses (decision 4, anti-drift).\n statements.push(\n `CREATE OR REPLACE ${temp}VIEW ${projection.syncState} AS\\n${buildSyncStateView(entry, {\n syncedTable: projection.syncedTable,\n overlayTable: projection.overlayTable,\n journalTable: projection.journalTable,\n })};`,\n );\n\n return statements;\n}\n\n/**\n * The DURABLE half of the local schema (slice 3): the schema + `pgxsinkit_local_meta` bootstrap, ALL enum\n * types the registry references (enums are persistent DB objects — they live in the durable schema even for\n * ephemeral tables, ADR-0021 §3 — so they belong here and their change invalidates the fingerprint), and the\n * full cluster of every PERSISTENT entry, in registry order. This is the exact statement stream the\n * `local_schema_fingerprint` hashes and the boot fast path may SKIP on a warm store.\n */\nfunction durableSchemaStatements<TRegistry extends SyncTableRegistry>(registry: TRegistry): string[] {\n const localSchema = getSyncRegistrySchema(registry);\n const statements: string[] = [...localMetaBootstrapStatements(localSchema)];\n\n for (const enumDefinition of collectEnumDefinitions(registry, localSchema)) {\n statements.push(buildCreateEnumTypeSql(enumDefinition));\n }\n\n for (const [tableKey, entry] of Object.entries(registry)) {\n if (entry.retention === \"ephemeral\") {\n continue;\n }\n\n statements.push(...buildEntryClusterStatements(entry, tableKey, localSchema));\n }\n\n return statements;\n}\n\n/**\n * The EPHEMERAL half of the local schema (slice 3): re-emitted idempotent enum guards for the enums the\n * ephemeral entries reference (a subset of the durable enum header — the `DO $$ IF NOT EXISTS` blocks are\n * cheap no-ops when the durable enums already exist, and re-emitting removes any ordering dependency on the\n * durable portion when this runs standalone on a fingerprint-skipped warm boot), followed by the full TEMP\n * cluster of every EPHEMERAL entry, and finally the registry-wide `pgxsinkit_all_mutations` TEMP VIEW\n * (slice 4) whenever the registry has ≥1 writable table. Always applied on boot (TEMP relations die with the\n * old engine), and empty (`[]`) only when the registry declares no ephemeral entry AND no writable table, so\n * the boot skips the crossing entirely.\n */\nfunction ephemeralSchemaStatements<TRegistry extends SyncTableRegistry>(registry: TRegistry): string[] {\n const localSchema = getSyncRegistrySchema(registry);\n const ephemeralEntries = Object.entries(registry).filter(([, entry]) => entry.retention === \"ephemeral\");\n\n const statements: string[] = [];\n\n if (ephemeralEntries.length > 0) {\n for (const enumDefinition of collectEnumDefinitionsFromEntries(\n ephemeralEntries.map(([, entry]) => entry),\n localSchema,\n )) {\n statements.push(buildCreateEnumTypeSql(enumDefinition));\n }\n\n for (const [tableKey, entry] of ephemeralEntries) {\n statements.push(...buildEntryClusterStatements(entry, tableKey, localSchema));\n }\n }\n\n // The registry-wide cross-journal mutation view (slice 4). Always-applied and TEMP (correction 4): it may\n // reference `pg_temp` ephemeral journals AND persistent journals, so it lives here regardless of whether the\n // registry declares any ephemeral entry. Emitted only when the registry has ≥1 writable table (a journal to\n // union); a registry of only readonly tables emits nothing and this whole portion stays empty.\n statements.push(...allMutationsViewStatements(registry));\n\n return statements;\n}\n\n/**\n * The `CREATE OR REPLACE TEMP VIEW pgxsinkit_all_mutations` statement (slice 4 / proposal §5, option 1), or\n * `[]` when the registry has no writable table. Each branch selects a `table_key` literal plus the shared\n * fixed journal columns ({@link ALL_MUTATIONS_JOURNAL_COLUMNS}) from one writable journal, UNION-ALL-ed.\n * Generated DDL (existing generator style): the branch column list is a fixed identifier set and each\n * `table_key` is a bound string literal — every RUNTIME query authors over {@link getAllMutationsView}\n * (tier ①), never this text. The journal name resolves through the SAME `getClientProjection` the DDL\n * generator uses (ephemeral → bare `pg_temp` name; persistent → schema-qualified), so the two cannot drift.\n */\nfunction allMutationsViewStatements<TRegistry extends SyncTableRegistry>(registry: TRegistry): string[] {\n const localSchema = getSyncRegistrySchema(registry);\n const branches: string[] = [];\n\n for (const [tableKey, entry] of Object.entries(registry)) {\n if (entry.mode === \"readonly\" || !entry.clientProjection?.journalTable) {\n continue;\n }\n\n const objectSchema = entry.retention === \"ephemeral\" ? \"public\" : localSchema;\n const projection = getClientProjection(entry, tableKey, objectSchema);\n\n if (!projection.journalTable) {\n continue;\n }\n\n branches.push(\n `SELECT ${quoteSqlStringLiteral(tableKey)} AS table_key,\\n ${ALL_MUTATIONS_JOURNAL_COLUMNS.join(\",\\n \")}\\nFROM ${projection.journalTable}`,\n );\n }\n\n if (branches.length === 0) {\n return [];\n }\n\n return [`CREATE OR REPLACE TEMP VIEW ${ALL_MUTATIONS_VIEW} AS\\n${branches.join(\"\\nUNION ALL\\n\")};`];\n}\n\n/** The DURABLE local schema as an executable script (slice 3) — the fingerprint's basis. See {@link durableSchemaStatements}. */\nexport function generateDurableLocalSchemaSql<TRegistry extends SyncTableRegistry>(registry: TRegistry): string {\n return joinSchemaStatements(durableSchemaStatements(registry));\n}\n\n/**\n * The EPHEMERAL (always-applied) local schema as an executable script (slice 3), or `\"\"` when the registry\n * has no ephemeral entry (so the boot skips the crossing). See {@link ephemeralSchemaStatements}.\n */\nexport function generateEphemeralLocalSchemaSql<TRegistry extends SyncTableRegistry>(registry: TRegistry): string {\n const statements = ephemeralSchemaStatements(registry);\n return statements.length === 0 ? \"\" : joinSchemaStatements(statements);\n}\n\n/**\n * The complete local schema — durable statements then ephemeral statements — the single script the\n * wipe/rebuild paths and every external caller keep using. For an all-persistent registry the durable stream\n * IS the historical stream in registry order, now followed by the always-applied ephemeral portion — which\n * for any registry with a writable table carries the `pgxsinkit_all_mutations` TEMP VIEW (slice 4), so the\n * full script is no longer byte-identical to the pre-slice-4 output (it gains the trailing view). For a MIXED\n * registry it is also idempotent-equivalent, NOT byte-identical to a single-pass interleave: the persistent\n * clusters precede the ephemeral ones and the ephemeral portion re-emits idempotent enum guards — a\n * reordering of independent `IF NOT EXISTS` DDL that executes to the same schema. Equals `durable + ephemeral`\n * by construction (test-covered).\n */\nexport function generateLocalSchemaSql<TRegistry extends SyncTableRegistry>(registry: TRegistry): string {\n return joinSchemaStatements([...durableSchemaStatements(registry), ...ephemeralSchemaStatements(registry)]);\n}\n\n/**\n * The durable-schema fingerprint value (slice 3 / proposal §3): `lsf1:<FNV-1a hash of the durable SQL>`. The\n * hash is over the generated durable DDL body itself (no composed inputs, no hand-maintained format-version\n * constant), so it auto-invalidates on ANY generator change, registry change, or projection rename — the\n * ADR-0018 apply-function-fingerprint precedent applied to the local schema. Stamped into\n * {@link LOCAL_SCHEMA_FINGERPRINT_KEY} only after a successful durable exec.\n */\nexport function computeLocalSchemaFingerprint<TRegistry extends SyncTableRegistry>(registry: TRegistry): string {\n return `${LOCAL_SCHEMA_FINGERPRINT_PREFIX}${hashString(generateDurableLocalSchemaSql(registry))}`;\n}\n\nfunction buildReadModelViewSql(\n entry: SyncTableEntry<AnyPgTable>,\n projection: ResolvedProjection,\n columnNames: string[],\n) {\n if (!projection.overlayTable) {\n throw new Error(`overlay table is required for writable table ${projection.syncedTable}`);\n }\n\n const pkMatch = buildPrimaryKeyMatch(entry.primaryKey.columns);\n const syncedLocalUpdatedExpression = columnNames.includes(\"updated_at_us\") ? \"t.updated_at_us\" : \"CAST(0 AS BIGINT)\";\n\n return [\n \"SELECT\",\n ` ${columnNames.join(\",\\n \")},`,\n \" overlay_kind,\",\n \" local_updated_at_us\",\n `FROM ${projection.overlayTable}`,\n `WHERE overlay_kind <> 'pending_delete'`,\n \"UNION ALL\",\n \"SELECT\",\n ` ${columnNames.map((name) => `t.${name}`).join(\",\\n \")},`,\n ` 'synced' AS overlay_kind,`,\n ` ${syncedLocalUpdatedExpression} AS local_updated_at_us`,\n `FROM ${projection.syncedTable} AS t`,\n \"WHERE NOT EXISTS (\",\n \" SELECT 1\",\n ` FROM ${projection.overlayTable} AS o`,\n ` WHERE ${pkMatch}`,\n \")\",\n ].join(\"\\n\");\n}\n\nfunction buildTableColumnSql(columns: TableColumn[], primaryKeyColumns: string[], localSchema: string) {\n return [\n ...columns.map((column) => buildColumnDefinition(column, primaryKeyColumns, localSchema)),\n ...buildCompositePrimaryKeyClauses(primaryKeyColumns),\n ].join(\",\\n \");\n}\n\n/**\n * Render `CREATE TABLE IF NOT EXISTS` (plus a `CREATE INDEX IF NOT EXISTS` per declared index) for a\n * Drizzle `pgTable` / `pgSchema.table`, through the SAME column/PK/type machinery\n * ({@link buildTableColumnSql} → {@link buildColumnDefinition} → {@link mapColumnType}) that\n * {@link generateLocalSchemaSql} uses for every other local relation. The table is schema-qualified\n * when it declares a schema and bare otherwise (per the table object). Column types come from each\n * column's `getSQLType()`, NOT NULL and single-column PRIMARY KEY inline, composite PKs as a trailing\n * clause. Enum column types are qualified into the table's own schema — the metadata pgTables carry\n * none, but the path is shared with the local-store generator so it must stay honest.\n *\n * ADR-0029 D3: the metadata-store DDL renders from its `metadata-tables.ts` pgTables through this,\n * making the pgTable the single source. The OUTPUT is tier-③-by-nature runtime DDL (schema/table\n * identifiers assembled at construction), but it is GENERATED from the model, never hand-maintained.\n *\n * ADR-0042: `{ temp: true }` renders the SESSION variant — `CREATE TEMP TABLE IF NOT EXISTS <bare name>`\n * (+ each index `ON <bare name>`), IGNORING the pgTable's declared schema for the RELATION name. TEMP DDL\n * takes the UNqualified relation name (the TEMP keyword places it in `pg_temp`; a `CREATE TEMP TABLE\n * pg_temp.x` target is not portable). Same relation/index NAMES as the durable form: an index name lives\n * per schema, so the durable (metadata-schema) and session (`pg_temp`) indexes coexist without collision\n * (probed on real PGlite).\n *\n * CAVEAT — the `temp` flag only bares the RELATION name; `buildTableColumnSql` below still receives\n * `schemaName` and would qualify any ENUM column type into THAT schema. That is correct only because the\n * metadata pgTables (the sole callers of `{ temp: true }`) carry no enum columns. A future enum-bearing TEMP\n * render would emit `<metadataSchema>.<enum>` for the column type — which is exactly what we want (enums are\n * persistent DB objects living in the durable schema even for TEMP tables, ADR-0021 §3), NOT a `pg_temp`\n * qualification. If this path ever renders a TEMP relation with an enum, keep the enum durable-qualified;\n * do not fold the `temp` flag into the column-type schema.\n */\nexport function renderCreateTableSql(table: AnyPgTable, options: { temp?: boolean } = {}): string[] {\n const config = getTableConfig(table);\n const temp = options.temp === true;\n const schemaName = config.schema ?? \"public\";\n // The DML paths qualify the session tables into `pg_temp`; the DDL must NOT — see the doc comment.\n const tableRef = temp ? maybeQuoteIdentifier(config.name) : qualifyIdentifier(schemaName, config.name);\n const primaryKeyColumns = collectPgTablePrimaryKeyColumns(config);\n const columnSql = buildTableColumnSql(config.columns as unknown as TableColumn[], primaryKeyColumns, schemaName);\n\n const createKeyword = temp ? \"CREATE TEMP TABLE\" : \"CREATE TABLE\";\n const statements = [`${createKeyword} IF NOT EXISTS ${tableRef} (\\n ${columnSql}\\n);`];\n\n for (const index of config.indexes) {\n statements.push(renderCreateIndexSql(tableRef, index));\n }\n\n return statements;\n}\n\n/** The PK column names of a `pgTable` — column-level `.primaryKey()` first, then composite `primaryKey({…})`. */\nfunction collectPgTablePrimaryKeyColumns(config: ReturnType<typeof getTableConfig>): string[] {\n const columnLevel = config.columns.filter((column) => column.primary).map((column) => column.name);\n const composite = config.primaryKeys.flatMap((pk) => pk.columns.map((column) => column.name));\n return [...columnLevel, ...composite];\n}\n\nfunction renderCreateIndexSql(qualifiedTableName: string, index: ReturnType<typeof getTableConfig>[\"indexes\"][number]) {\n const { name, unique, columns, where, method, with: withParams } = index.config;\n if (!name) {\n throw new Error(\"renderCreateIndexSql: anonymous indexes are not supported (declare a name)\");\n }\n // This renderer emits only a plain ascending btree over bare columns. Any modifier it does not\n // render must fail loudly — silently dropping one would produce a local index that differs from the\n // pgTable declaration (the very DDL-vs-model divergence ADR-0029 D3 removes for the metadata store).\n if (where) {\n throw new Error(`renderCreateIndexSql: partial indexes (.where) are not supported (index ${name})`);\n }\n if (method && method.toLowerCase() !== \"btree\") {\n throw new Error(\n `renderCreateIndexSql: non-btree index methods (.using \"${method}\") are not supported (index ${name})`,\n );\n }\n if (withParams && Object.keys(withParams).length > 0) {\n throw new Error(`renderCreateIndexSql: index storage parameters (.with) are not supported (index ${name})`);\n }\n const columnExpressions = columns.map((column) => {\n const columnName = (column as { name?: unknown }).name;\n if (typeof columnName !== \"string\") {\n throw new Error(`renderCreateIndexSql: expression index columns are not supported (index ${name})`);\n }\n const indexConfig = (column as { indexConfig?: { order?: string; nulls?: string; opClass?: string } }).indexConfig;\n if (indexConfig?.order === \"desc\") {\n throw new Error(`renderCreateIndexSql: descending index columns (.desc()) are not supported (index ${name})`);\n }\n // Drizzle fills `nulls` with the ascending-btree default (\"last\") on every column; only an\n // explicit NULLS FIRST diverges from what we render (a plain ascending btree is NULLS LAST).\n if (indexConfig?.nulls === \"first\") {\n throw new Error(`renderCreateIndexSql: NULLS FIRST ordering (.nullsFirst()) is not supported (index ${name})`);\n }\n if (indexConfig?.opClass) {\n throw new Error(`renderCreateIndexSql: index operator classes (.op()) are not supported (index ${name})`);\n }\n return maybeQuoteIdentifier(columnName);\n });\n\n return renderCreateIndexStatement(qualifiedTableName, maybeQuoteIdentifier(name), columnExpressions, { unique });\n}\n\n/**\n * The shared `CREATE INDEX` core: assemble one\n * `CREATE [UNIQUE] INDEX IF NOT EXISTS <name> ON <table> (<cols>)` over a qualified table, an\n * already-rendered index name, and already-rendered plain ascending column expressions. BOTH the\n * pgTable-driven renderer ({@link renderCreateIndexSql}) and the journal-index emitter in\n * {@link generateLocalSchemaSql} go through here, so the two index-emitting paths cannot drift in\n * statement shape. Identifier quoting is the caller's responsibility — the pgTable path quotes via\n * `maybeQuoteIdentifier`; the journal path passes its registry-derived bare names/columns verbatim —\n * this core only fixes the surrounding statement text.\n */\nfunction renderCreateIndexStatement(\n qualifiedTableName: string,\n indexName: string,\n columnExpressions: readonly string[],\n options: { unique?: boolean } = {},\n): string {\n const uniqueSql = options.unique ? \"UNIQUE \" : \"\";\n return `CREATE ${uniqueSql}INDEX IF NOT EXISTS ${indexName} ON ${qualifiedTableName} (${columnExpressions.join(\", \")});`;\n}\n\nfunction buildColumnDefinition(column: TableColumn, primaryKeyColumns: string[], localSchema: string) {\n const typeSql = mapColumnType(column, localSchema);\n const notNullSql = column.notNull ? \" NOT NULL\" : \"\";\n const primaryKeySql = primaryKeyColumns.length === 1 && primaryKeyColumns.includes(column.name) ? \" PRIMARY KEY\" : \"\";\n return `${column.name} ${typeSql}${notNullSql}${primaryKeySql}`;\n}\n\nfunction buildCompositePrimaryKeyClauses(primaryKeyColumns: string[]) {\n if (primaryKeyColumns.length <= 1) {\n return [];\n }\n\n return [`PRIMARY KEY (${primaryKeyColumns.join(\", \")})`];\n}\n\nfunction mapColumnType(column: TableColumn, localSchema: string) {\n const baseTypeSql = readBaseColumnTypeSql(column, localSchema);\n const dimensions = readArrayDimensions(column);\n\n if (dimensions > 0) {\n return `${baseTypeSql}${\"[]\".repeat(dimensions)}`;\n }\n\n return baseTypeSql;\n}\n\nfunction readBaseColumnTypeSql(column: TableColumn, localSchema: string) {\n const enumDefinition = readEnumColumnDefinition(column, localSchema);\n\n if (enumDefinition) {\n return qualifyIdentifier(enumDefinition.schemaName, enumDefinition.enumName);\n }\n\n const sqlType = (column as { getSQLType(): string }).getSQLType();\n\n if (!sqlType) {\n throw new Error(`Unsupported column type for local schema generation: ${column.columnType}`);\n }\n\n return sqlType;\n}\n\ntype EnumDefinition = {\n schemaName: string;\n enumName: string;\n enumValues: string[];\n};\n\nfunction collectEnumDefinitions(registry: SyncTableRegistry, localSchema: string) {\n return collectEnumDefinitionsFromEntries(Object.values(registry), localSchema);\n}\n\n/**\n * Collect the distinct enum types referenced by a GIVEN set of registry entries (deduped by name, values\n * cross-checked for conflicts, sorted for stable output). Factored out of {@link collectEnumDefinitions} so\n * the Data export (ADR-0035) can emit ONLY the enums its `-t` allowlist tables reference — the whole-registry\n * caller passes every entry, the data export passes just its owning persistent entries — through one honest\n * implementation, never a second enum-scanning path that could drift on the conflict/sort rules.\n */\nfunction collectEnumDefinitionsFromEntries(entries: SyncTableEntry[], localSchema: string) {\n const enumDefinitionsByName = new Map<string, EnumDefinition>();\n\n for (const entry of entries) {\n const columns = getProjectedColumns(entry).map(({ column }) => column);\n\n for (const column of columns) {\n const enumDefinition = readEnumColumnDefinition(column, localSchema);\n\n if (!enumDefinition) {\n continue;\n }\n\n const existingDefinition = enumDefinitionsByName.get(enumDefinition.enumName);\n\n if (!existingDefinition) {\n enumDefinitionsByName.set(enumDefinition.enumName, enumDefinition);\n continue;\n }\n\n if (!areEnumValuesEqual(existingDefinition.enumValues, enumDefinition.enumValues)) {\n throw new Error(\n `Enum ${enumDefinition.enumName} has conflicting values in sync registry: ${existingDefinition.enumValues.join(\", \")} vs ${enumDefinition.enumValues.join(\", \")}`,\n );\n }\n }\n }\n\n return [...enumDefinitionsByName.values()].sort((left, right) => left.enumName.localeCompare(right.enumName));\n}\n\n/**\n * Does this entry OWN a physical, persistent synced table — i.e. is it a `-t` allowlist candidate for the\n * Data export (ADR-0035 decision 1)? Two entries are excluded:\n *\n * - a **read PROJECTION** (`readProjection`) owns no table (its `table` is another entry's), so it must\n * never be listed — it would double-target the owner's physical table;\n * - an **ephemeral** entry's cluster is emitted as `pg_temp` TEMP objects (ADR-0021 §3), absent from the\n * throwaway clone by construction — and a `pg_dump -t` pattern that matches NOTHING makes `pg_dump` fail,\n * so an ephemeral table must not appear in the allowlist at all.\n *\n * Overlay/journal/meta tables, read-model/sync-state views, and reconcile functions are excluded by `-t`\n * semantics automatically (they are neither the synced table nor matched by its name), so they need no\n * filter here.\n */\nfunction ownsPersistentSyncedTable(entry: SyncTableEntry): boolean {\n return !entry.readProjection && entry.retention !== \"ephemeral\";\n}\n\n/**\n * The `-t` allowlist for a Data export (ADR-0035 decision 1): the schema-qualified PHYSICAL synced table\n * name for every registry entry that owns one, resolved through the SAME `getClientProjection` the local\n * DDL generator uses — NOT re-derived by string convention. This is deliberately the physical `syncedTable`,\n * never the read-model view (whose name can carry the entry name while the table differs): `-t` must target\n * the tables that hold the rows. Read-projection and ephemeral entries are excluded (see\n * {@link ownsPersistentSyncedTable}).\n */\nexport function collectDataExportSyncedTableNames<TRegistry extends SyncTableRegistry>(registry: TRegistry): string[] {\n const localSchema = getSyncRegistrySchema(registry);\n const names: string[] = [];\n\n for (const [tableKey, entry] of Object.entries(registry)) {\n if (!ownsPersistentSyncedTable(entry)) {\n continue;\n }\n\n names.push(getClientProjection(entry, tableKey, localSchema).syncedTable);\n }\n\n return names;\n}\n\n/**\n * The clone-cleanup SQL a Data export runs on its THROWAWAY clone before `pg_dump -t` (ADR-0035). The\n * reconcile trigger sits ON the synced table (`AFTER INSERT/UPDATE/DELETE ON <syncedTable>`), so\n * `pg_dump -t <syncedTable>` pulls the trigger into the dump — but its function is pgxsinkit machinery the\n * data export deliberately EXCLUDES, so the artefact would carry a trigger referencing a missing function\n * and fail to load into a vanilla Postgres. Because the clone is a memory-backed throwaway we fully own, we\n * drop each reconcile trigger (and its now-unreferenced function) on it first, so `-t` yields clean,\n * portable tables. Overlay/journal/views/metadata are NOT captured by `-t <syncedTable>` at all (a probe\n * confirmed only the table, its PK, its data, and this trigger appear), so nothing else needs dropping.\n * Returns `\"\"` when the registry declares no writable owning table.\n */\nexport function buildDataExportCloneCleanupSql<TRegistry extends SyncTableRegistry>(registry: TRegistry): string {\n const localSchema = getSyncRegistrySchema(registry);\n const statements: string[] = [];\n\n for (const [tableKey, entry] of Object.entries(registry)) {\n if (!ownsPersistentSyncedTable(entry) || entry.mode === \"readonly\") {\n continue;\n }\n\n const projection = getClientProjection(entry, tableKey, localSchema);\n // Drop the trigger first, then its now-unreferenced function (drop order avoids a dependency error).\n statements.push(`DROP TRIGGER IF EXISTS ${projection.reconcileTrigger} ON ${projection.syncedTable};`);\n statements.push(`DROP FUNCTION IF EXISTS ${projection.reconcileFunction}();`);\n }\n\n return statements.join(\"\\n\");\n}\n\n/**\n * The enum DDL header for a Data export artefact (ADR-0035 decision 1). `pg_dump -t <table>` emits the\n * tables but NOT the enum types their columns reference, so the portable artefact is this generated header\n * concatenated ahead of the `pg_dump` output. It reuses the SAME `CREATE TYPE` generation the local-schema\n * generator emits ({@link buildCreateEnumTypeSql}) — every enum wrapped in an idempotent `IF NOT EXISTS`\n * guard — restricted to the enums actually referenced by the exported (owning, persistent) tables, so a\n * dropped/ephemeral-only enum never bloats the artefact. When the registry uses a non-`public` schema, a\n * `CREATE SCHEMA IF NOT EXISTS` precedes the types (they live in that schema, and the header runs before\n * `pg_dump`'s own schema creation), so the header is self-contained against a bare Postgres. Returns `\"\"`\n * when no exported table references an enum.\n */\nexport function buildDataExportEnumHeaderSql<TRegistry extends SyncTableRegistry>(registry: TRegistry): string {\n const localSchema = getSyncRegistrySchema(registry);\n const exportedEntries = Object.values(registry).filter(ownsPersistentSyncedTable);\n const enumDefinitions = collectEnumDefinitionsFromEntries(exportedEntries, localSchema);\n\n if (enumDefinitions.length === 0) {\n return \"\";\n }\n\n const statements: string[] = [\n \"-- Enum types referenced by the exported tables. `pg_dump -t` does not emit the enum types\",\n \"-- its tables depend on, so pgxsinkit generates them here from the sync registry (ADR-0035).\",\n ];\n\n // A non-public schema must exist before its `CREATE TYPE` runs — this header precedes pg_dump's own\n // schema creation, so create it ourselves (idempotent), mirroring `generateLocalSchemaSql`.\n if (localSchema !== \"public\") {\n statements.push(`CREATE SCHEMA IF NOT EXISTS ${quoteIdentifier(localSchema)};`);\n }\n\n for (const enumDefinition of enumDefinitions) {\n statements.push(buildCreateEnumTypeSql(enumDefinition));\n }\n\n return `${statements.join(\"\\n\")}\\n`;\n}\n\nfunction buildCreateEnumTypeSql(enumDefinition: EnumDefinition) {\n const typeIdentifier = qualifyIdentifier(enumDefinition.schemaName, enumDefinition.enumName);\n const enumValuesSql = enumDefinition.enumValues.map((value) => quoteSqlStringLiteral(value)).join(\", \");\n\n return [\n \"DO $$\",\n \"BEGIN\",\n \" IF NOT EXISTS (\",\n \" SELECT 1\",\n \" FROM pg_type AS t\",\n \" INNER JOIN pg_namespace AS n ON n.oid = t.typnamespace\",\n ` WHERE t.typname = ${quoteSqlStringLiteral(enumDefinition.enumName)}`,\n ` AND n.nspname = ${quoteSqlStringLiteral(enumDefinition.schemaName)}`,\n \" ) THEN\",\n ` CREATE TYPE ${typeIdentifier} AS ENUM (${enumValuesSql});`,\n \" END IF;\",\n \"END\",\n \"$$;\",\n ].join(\"\\n\");\n}\n\nfunction areEnumValuesEqual(left: string[], right: string[]) {\n if (left.length !== right.length) {\n return false;\n }\n\n for (let index = 0; index < left.length; index += 1) {\n if (left[index] !== right[index]) {\n return false;\n }\n }\n\n return true;\n}\n\nfunction readEnumColumnDefinition(column: TableColumn, localSchema: string): EnumDefinition | undefined {\n const candidate = column as TableColumn & {\n enum?: {\n enumName?: unknown;\n enumValues?: unknown;\n };\n };\n\n if (!candidate.enum || typeof candidate.enum.enumName !== \"string\" || !Array.isArray(candidate.enum.enumValues)) {\n return undefined;\n }\n\n const enumValues = candidate.enum.enumValues.filter((value): value is string => typeof value === \"string\");\n\n if (enumValues.length !== candidate.enum.enumValues.length) {\n throw new Error(\n `Enum ${candidate.enum.enumName} includes non-string values and cannot be emitted in local schema SQL`,\n );\n }\n\n return {\n schemaName: localSchema,\n enumName: candidate.enum.enumName,\n enumValues,\n };\n}\n\nfunction readArrayDimensions(column: TableColumn) {\n const arrayColumn = column as TableColumn & { dimensions?: number };\n return arrayColumn.dimensions ?? 0;\n}\n\nfunction buildPrimaryKeyMatch(primaryKeyColumns: string[]) {\n return primaryKeyColumns.map((column) => `o.${column} = t.${column}`).join(\" AND \");\n}\n\nfunction getClientProjection(entry: SyncTableEntry, tableKey: string, localSchema: string): ResolvedProjection {\n const projection = baseProjection(entry, tableKey);\n const syncedTableName = projection.syncedTable ?? tableKey;\n const readModelName = entry.view != null ? getViewConfig(entry.view).name : syncedTableName;\n\n return {\n syncedTable: qualifyIdentifier(localSchema, syncedTableName),\n ...(projection.overlayTable ? { overlayTable: qualifyIdentifier(localSchema, projection.overlayTable) } : {}),\n ...(projection.journalTable ? { journalTable: qualifyIdentifier(localSchema, projection.journalTable) } : {}),\n readModel: qualifyIdentifier(localSchema, readModelName),\n syncState: qualifyIdentifier(localSchema, `${syncedTableName}_sync_state`),\n reconcileFunction: qualifyIdentifier(localSchema, `${syncedTableName}_reconcile_on_sync`),\n reconcileTrigger: maybeQuoteIdentifier(`${syncedTableName}_reconcile_on_sync`),\n };\n}\n\nfunction baseProjection(entry: SyncTableEntry, tableKey: string) {\n if (!entry.clientProjection) {\n throw new Error(`clientProjection is required for local client table ${tableKey}`);\n }\n\n return entry.clientProjection;\n}\n\nfunction qualifyIdentifier(schemaName: string, objectName: string) {\n if (schemaName === \"public\") {\n // Quote only when required so existing generated SQL stays stable, but a table/view named\n // after a reserved word (e.g. `group`) is a valid Postgres identifier and MUST be quoted or\n // the generated DDL and read queries fail to parse. The row-applier (src/sync) always quotes.\n return maybeQuoteIdentifier(objectName);\n }\n\n return `${quoteIdentifier(schemaName)}.${quoteIdentifier(objectName)}`;\n}\n\nfunction buildJournalSequenceName(journalTable: string) {\n return `${journalTable}_mutation_seq`;\n}\n\n/**\n * Drop the reconstructible **read cache** — the synced tables and their read-model views\n * and reconcile triggers/functions — while preserving the authority tables (overlay,\n * journal, the local-meta table). Re-running {@link generateLocalSchemaSql} then rebuilds\n * the synced tables at the current shape, and a re-sync refills them (ADR-0006). This is\n * the named drop primitive a returning-online upgrade uses after a clean drain.\n */\nexport function buildDropReadCacheSql<TRegistry extends SyncTableRegistry>(registry: TRegistry): string {\n const localSchema = getSyncRegistrySchema(registry);\n const statements: string[] = [];\n\n for (const [tableKey, entry] of Object.entries(registry)) {\n const projection = getClientProjection(entry, tableKey, localSchema);\n\n if (entry.mode !== \"readonly\") {\n statements.push(`DROP VIEW IF EXISTS ${projection.syncState};`);\n statements.push(`DROP VIEW IF EXISTS ${projection.readModel};`);\n statements.push(`DROP TRIGGER IF EXISTS ${projection.reconcileTrigger} ON ${projection.syncedTable};`);\n statements.push(`DROP FUNCTION IF EXISTS ${projection.reconcileFunction}();`);\n }\n\n statements.push(`DROP TABLE IF EXISTS ${projection.syncedTable} CASCADE;`);\n }\n\n return `${statements.join(\"\\n\")}\\n`;\n}\n\n/**\n * Wipe the **entire** local store provisioned from the registry — the read cache plus the\n * authority tables (overlay, journal, sequences), the enum types, and the local-meta row.\n * This is the full teardown reused by `destroy()` (ADR-0005 decision 5) and by the\n * drain-then-drop upgrade once a clean drain has confirmed nothing is owed (ADR-0006).\n */\nexport function buildWipeLocalStoreSql<TRegistry extends SyncTableRegistry>(registry: TRegistry): string {\n const localSchema = getSyncRegistrySchema(registry);\n const statements: string[] = [buildDropReadCacheSql(registry).trimEnd()];\n\n for (const [tableKey, entry] of Object.entries(registry)) {\n if (entry.mode === \"readonly\") {\n continue;\n }\n\n const projection = getClientProjection(entry, tableKey, localSchema);\n\n if (projection.overlayTable) {\n statements.push(`DROP TABLE IF EXISTS ${projection.overlayTable} CASCADE;`);\n }\n\n if (projection.journalTable && entry.clientProjection?.journalTable) {\n statements.push(`DROP TABLE IF EXISTS ${projection.journalTable} CASCADE;`);\n statements.push(\n `DROP SEQUENCE IF EXISTS ${qualifyIdentifier(localSchema, buildJournalSequenceName(entry.clientProjection.journalTable))};`,\n );\n }\n }\n\n for (const enumDefinition of collectEnumDefinitions(registry, localSchema)) {\n statements.push(`DROP TYPE IF EXISTS ${qualifyIdentifier(enumDefinition.schemaName, enumDefinition.enumName)};`);\n }\n\n statements.push(`DROP TABLE IF EXISTS ${qualifyIdentifier(localSchema, LOCAL_META_TABLE)} CASCADE;`);\n\n return `${statements.join(\"\\n\")}\\n`;\n}\n\n/**\n * Clean-truncate a single table's local read cache so a desynced `lazy` relation (ADR-0021 §2) returns\n * to an empty, dormant state: the synced table and — for a writable table — its optimistic overlay and\n * the journal, plus a sequence restart. It does NOT drop the cluster (the table/views/trigger persist),\n * so a later re-reference re-streams into it without a schema rebuild. Ephemeral-aware: bare/`pg_temp`\n * names for an ephemeral cluster, schema-qualified for a persistent one — mirroring\n * {@link generateLocalSchemaSql}. The caller (`desync`) first stops the group's stream (so nothing\n * re-populates mid-truncate) and refuses when the journal owes unsettled writes (so this never drops\n * un-acked local intent).\n */\nexport function buildDesyncTableSql<TRegistry extends SyncTableRegistry>(\n registry: TRegistry,\n tableKey: string,\n): string {\n const entry = registry[tableKey];\n\n if (!entry) {\n throw new Error(`buildDesyncTableSql: unknown table ${tableKey}`);\n }\n\n const localSchema = getSyncRegistrySchema(registry);\n const ephemeral = entry.retention === \"ephemeral\";\n const objectSchema = ephemeral ? \"public\" : localSchema;\n const projection = getClientProjection(entry, tableKey, objectSchema);\n const statements: string[] = [`TRUNCATE TABLE ${projection.syncedTable};`];\n\n if (entry.mode !== \"readonly\") {\n if (projection.overlayTable) {\n statements.push(`TRUNCATE TABLE ${projection.overlayTable};`);\n }\n\n if (projection.journalTable && entry.clientProjection?.journalTable) {\n statements.push(`TRUNCATE TABLE ${projection.journalTable};`);\n statements.push(\n `ALTER SEQUENCE ${qualifyIdentifier(objectSchema, buildJournalSequenceName(entry.clientProjection.journalTable))} RESTART WITH 1;`,\n );\n }\n }\n\n // ADR-0023 Slice 2: a desync reverts the relation to dormant and deletes its subscription, so the next\n // activation re-streams from scratch — drop this shape's tag-set too, or it would orphan tags for rows\n // that never come back. The key matches what the engine writes (`shapeTableId(shape.schema, table)`):\n // for ephemeral the engine passes no schema (→ `public`), exactly this `objectSchema`.\n const syncedTableNameRaw = baseProjection(entry, tableKey).syncedTable ?? tableKey;\n statements.push(buildClearShapeTagsSql(shapeTableId(objectSchema, syncedTableNameRaw)));\n\n return `${statements.join(\"\\n\")}\\n`;\n}\n",
|
|
19
|
+
"import type { ChangeMessage, MovePattern, Row } from \"@electric-sql/client\";\nimport type { PGliteInterface, Transaction } from \"@electric-sql/pglite\";\nimport { and, eq, inArray, like, sql } from \"drizzle-orm\";\nimport { getTableConfig } from \"drizzle-orm/pg-core\";\n\nimport { quoteIdentifier, quoteSqlLiteral } from \"@pgxsinkit/contracts\";\n\nimport type { ApplyTarget } from \"../local-tables\";\nimport { applyBulkDeletesToTable } from \"./apply\";\nimport { drizzleOverPg } from \"./drizzle-executor\";\nimport { getMetadataTables, getSessionMetadataTables, pickMetadataTables } from \"./metadata-tables\";\n\n/**\n * Electric **tagged-subquery** reconciliation (ADR-0023). A shape whose `where` contains a subquery\n * (membership-style row filters: `container_id IN (SELECT … FROM memberships WHERE member = $sub)`)\n * streams two extra things the plain change path ignores:\n *\n * - every change message carries `headers.tags` — the **reasons** the row is in the shape (one tag per\n * grant/membership), plus `removed_tags` on an update;\n * - a **`move-out` `EventMessage`** carries `patterns: { pos, value }[]` — \"the tag whose component at\n * index `pos` equals `value` is withdrawn\", i.e. that grant was revoked.\n *\n * A row leaves the shape only when it has **no remaining tag**. The engine drops the `EventMessage`\n * today, so a removed member keeps the revoked rows. This module persists each row's tag-set in one\n * metadata table and evicts rows whose last tag is withdrawn — closing the move-out gap without an\n * Electric change.\n *\n * Tag storage is a single metadata table keyed by the synced table + a canonical primary-key JSON:\n * `shape_row_tags(shape_table, pk_json, tag)`. It is created in `migrateSubscriptionMetadataTables`.\n */\n\n/**\n * The pgxsinkit-owned metadata schema (ADR-0009 decision 6) the tag store + subscription state live in.\n * The sync engine defaults its `metadataSchema` to this, and `createSyncClient` never overrides it — so\n * the desync path (which is outside the engine) can key the tag store by this same constant.\n */\nexport const DEFAULT_METADATA_SCHEMA = \"pgxsinkit\";\n\n/**\n * A bare, lowercase, unqualified SQL identifier: begins with a lowercase letter or underscore, then\n * lowercase letters, digits, and underscores.\n */\nconst METADATA_SCHEMA_PATTERN = /^[a-z_][a-z0-9_]*$/;\n\n/**\n * Validate the metadata schema name at engine construction. The name is interpolated RAW into two\n * positions a double-quoted identifier cannot cover:\n * - GUC space — `SET LOCAL <schema>.syncing` (sync/index.ts) and `SET <schema>.syncing = false`\n * (the metadata migration). GUC grammar takes a `namespace.name` of bare identifiers; it does not\n * accept a quoted identifier the way a table/column position does, so the name cannot be safely\n * quoted there.\n * - the `CREATE SCHEMA <schema>` DDL identifier position.\n * Rather than trust arbitrary caller input in those raw positions, restrict the name to a bare\n * lowercase identifier and reject uppercase/exotic names outright. The default \"pgxsinkit\" passes.\n */\nexport function assertValidMetadataSchema(metadataSchema: string): void {\n if (!METADATA_SCHEMA_PATTERN.test(metadataSchema)) {\n throw new Error(\n `Invalid metadataSchema ${JSON.stringify(metadataSchema)}: it must be a bare lowercase SQL ` +\n `identifier matching ${String(METADATA_SCHEMA_PATTERN)}. The name is interpolated unquoted into ` +\n `GUC (\\`SET <schema>.syncing\\`) and \\`CREATE SCHEMA\\` identifier positions where a quoted ` +\n `identifier is not accepted, so uppercase and exotic names are rejected at construction.`,\n );\n }\n}\n\n/**\n * The tag store's schema-qualified identifier, derived from the `shape_row_tags` pgTable config\n * (ADR-0029 D3 — single source; no parallel name string). The store itself is provisioned by\n * `migrateSubscriptionMetadataTables`, which renders that same pgTable.\n */\nexport function shapeRowTagsTableName(metadataSchema: string): string {\n const config = getTableConfig(getMetadataTables(metadataSchema).shapeRowTags);\n return `${quoteIdentifier(config.schema ?? \"public\")}.${quoteIdentifier(config.name)}`;\n}\n\n/**\n * The SESSION (`pg_temp`) tag store's qualified identifier (ADR-0042), derived from the session\n * `shape_row_tags` pgTable config — the same relation name, in `pg_temp`. Used by the scope-blind\n * {@link buildClearShapeTagsSql} so a desync/discard clears an ephemeral shape's tags wherever they live.\n */\nexport function shapeRowTagsSessionTableName(): string {\n const config = getTableConfig(getSessionMetadataTables().shapeRowTags);\n return `${quoteIdentifier(config.schema ?? \"public\")}.${quoteIdentifier(config.name)}`;\n}\n\n/** The `shape_table` key for the tag store: the synced table, schema-qualified (defaults `public`). */\nexport function shapeTableId(schema: string | undefined, table: string): string {\n return `${schema ?? \"public\"}.${table}`;\n}\n\n/**\n * Static SQL to drop a shape's tag-set, **guarded** by `to_regclass` so it is a no-op when the tag store\n * does not exist. Used by `buildDesyncTableSql` (ADR-0023 Slice 2), which may be exec'd standalone (a\n * caller/test that builds the local schema without booting the sync engine that creates the store). The\n * engine's own `clearShapeTags` runs inside a commit where the store is guaranteed present, so it is not\n * guarded.\n */\nexport function buildClearShapeTagsSql(shapeTable: string, metadataSchema: string = DEFAULT_METADATA_SCHEMA): string {\n // ADR-0042: SCOPE-BLIND — clear the shape's tags from BOTH the durable and the session (`pg_temp`) tag\n // store, each guarded independently by `to_regclass` (a desync/discard may run on a persistent table whose\n // session store never existed, or standalone before any engine boot). `to_regclass('pg_temp.shape_row_tags')`\n // resolves the session table via the per-session `pg_temp` alias (probed on real PGlite).\n const clearOne = (table: string) => ` IF to_regclass(${quoteSqlLiteral(table)}) IS NOT NULL THEN\n DELETE FROM ${table} WHERE shape_table = ${quoteSqlLiteral(shapeTable)};\n END IF;`;\n return `DO $$ BEGIN\n${clearOne(shapeRowTagsTableName(metadataSchema))}\n${clearOne(shapeRowTagsSessionTableName())}\nEND $$;`;\n}\n\n/**\n * Canonical primary-key JSON for a synced row — the tag store's per-row key. Built from the **mapped**\n * value (synced-table column names), with pk columns sorted so the string is stable, and `bigint`\n * rendered as a string (JSON has no bigint). Reversible via `JSON.parse` for the eviction DELETE.\n */\nexport function serializeRowPk(value: Row<unknown>, primaryKey: readonly string[]): string {\n const obj: Record<string, unknown> = {};\n for (const column of [...primaryKey].sort()) {\n obj[column] = value[column];\n }\n return JSON.stringify(obj, (_key, v: unknown) => (typeof v === \"bigint\" ? v.toString() : v));\n}\n\n/**\n * Split a composite `MoveTag` into its positional columns. A tag for a shape with N subquery conditions\n * is the per-condition grant values joined by `/` (an absent condition is an empty column) — e.g. a\n * two-condition shape yields `\"<grantHash>/1//\"` and `\"//<grantHash>/<grantHash>\"`. `\\/` is a literal\n * `/`, `\\\\` a literal `\\`. A single-condition shape's tag has no separator → `[tag]`.\n *\n * (The `MovePattern.pos` indexes into THIS split — confirmed against Electric 1.7.4 wire messages,\n * ADR-0023. The upstream type doc mentions `|`; the actual column separator on the wire is `/`.)\n */\nexport function splitTagComponents(tag: string): string[] {\n const parts: string[] = [];\n let current = \"\";\n for (let i = 0; i < tag.length; i++) {\n const char = tag[i]!;\n if (char === \"\\\\\" && i + 1 < tag.length) {\n current += tag[i + 1];\n i += 1;\n continue;\n }\n if (char === \"/\") {\n parts.push(current);\n current = \"\";\n continue;\n }\n current += char;\n }\n parts.push(current);\n return parts;\n}\n\n/**\n * Whether a tag is withdrawn by a `move-out` event. A revoked grant can appear at more than one column\n * of the shape's tag structure (one position per subquery condition that references it), so the event\n * enumerates those positions and a tag is withdrawn if it carries the value at **any** of them. A row\n * is then evicted only once **every** tag keeping it in the shape has been withdrawn (the caller's\n * empty-tag-set check) — so a row held by an independent second grant survives. Empty pattern set\n * matches nothing.\n */\nexport function tagMatchesPatterns(tag: string, patterns: readonly MovePattern[]): boolean {\n if (patterns.length === 0) return false;\n const parts = splitTagComponents(tag);\n return patterns.some((pattern) => parts[pattern.pos] === pattern.value);\n}\n\ninterface TagSyncOptions {\n pg: PGliteInterface | Transaction;\n metadataSchema: string;\n shapeTable: string;\n messages: ChangeMessage<Row<unknown>>[];\n primaryKey: string[];\n /** ADR-0042: route the tag DML to the SESSION (`pg_temp`) store for an ephemeral group. */\n sessionScoped?: boolean;\n}\n\n/**\n * Maintain the tag-set for a shape from its drained change batch (ADR-0023). For a subquery shape every\n * change carries `headers.tags` (the row's current full reason-set), so insert/update **replace** the\n * row's tags; a delete drops them. `removed_tags` (without `tags`) deletes just those. A non-subquery\n * shape carries no `tags`, so this is a no-op for it. Runs before the data apply and the move-out\n * eviction in the same commit, so an add-then-remove within one batch resolves correctly.\n */\nexport async function applyShapeTagSync({\n pg,\n metadataSchema,\n shapeTable,\n messages,\n primaryKey,\n sessionScoped = false,\n}: TagSyncOptions): Promise<void> {\n const { shapeRowTags } = pickMetadataTables(metadataSchema, sessionScoped);\n const db = drizzleOverPg(pg);\n\n for (const message of messages) {\n const data = message.value;\n const pkJson = serializeRowPk(data, primaryKey);\n\n if (message.headers.operation === \"delete\") {\n await db\n .delete(shapeRowTags)\n .where(and(eq(shapeRowTags.shape_table, shapeTable), eq(shapeRowTags.pk_json, pkJson)));\n continue;\n }\n\n const tags = message.headers.tags;\n if (tags !== undefined) {\n // `tags` is the authoritative current reason-set → replace.\n await db\n .delete(shapeRowTags)\n .where(and(eq(shapeRowTags.shape_table, shapeTable), eq(shapeRowTags.pk_json, pkJson)));\n if (tags.length > 0) {\n await db\n .insert(shapeRowTags)\n .values(tags.map((tag) => ({ shape_table: shapeTable, pk_json: pkJson, tag })))\n .onConflictDoNothing();\n }\n continue;\n }\n\n const removedTags = message.headers.removed_tags;\n if (removedTags && removedTags.length > 0) {\n await db\n .delete(shapeRowTags)\n .where(\n and(\n eq(shapeRowTags.shape_table, shapeTable),\n eq(shapeRowTags.pk_json, pkJson),\n inArray(shapeRowTags.tag, removedTags),\n ),\n );\n }\n }\n}\n\n/**\n * Record (union) a **move-in** row's tags without clearing the tags the row already carries (ADR-0024).\n * A move-in ADDS a reason a row is in the shape, so — unlike a regular change, whose `tags` is the\n * authoritative full reason-set and therefore REPLACES (see {@link applyShapeTagSync}) — a move-in must\n * not drop tags from an independent grant. Inserting with `ON CONFLICT DO NOTHING` is correct whether\n * Electric sends the row's full reason-set or only the newly-added grant on a move-in, so move-out\n * eviction afterwards stays correct under multi-grant without depending on the move-in's tag cardinality.\n * A row with no `tags` (a non-subquery shape) is a no-op.\n */\nexport async function addShapeRowTags({\n pg,\n metadataSchema,\n shapeTable,\n messages,\n primaryKey,\n sessionScoped = false,\n}: TagSyncOptions): Promise<void> {\n const { shapeRowTags } = pickMetadataTables(metadataSchema, sessionScoped);\n const db = drizzleOverPg(pg);\n\n for (const message of messages) {\n const tags = message.headers.tags;\n if (!tags || tags.length === 0) continue;\n\n const data = message.value;\n const pkJson = serializeRowPk(data, primaryKey);\n await db\n .insert(shapeRowTags)\n .values(tags.map((tag) => ({ shape_table: shapeTable, pk_json: pkJson, tag })))\n .onConflictDoNothing();\n }\n}\n\ninterface MoveOutOptions {\n pg: PGliteInterface | Transaction;\n metadataSchema: string;\n shapeTable: string;\n /** The resolved apply target for the synced table the evicted rows are deleted from (ADR-0029 D1). */\n target: ApplyTarget;\n /** One entry per buffered `move-out` event, each its own pattern set. */\n patternSets: MovePattern[][];\n debug: boolean;\n /** ADR-0042: route the tag reads/evictions to the SESSION (`pg_temp`) store for an ephemeral group. */\n sessionScoped?: boolean;\n}\n\n/**\n * Apply buffered `move-out` events for a shape (ADR-0023): withdraw the matched tag from every row that\n * carries it, then evict the synced rows left with **no** remaining tag — so a row held by two grants\n * survives losing one. Eviction goes through the tested bulk-delete path, so it fires the reconcile\n * trigger and the read-model/overlay stays consistent. Returns the number of rows evicted.\n */\nexport async function applyShapeMoveOut({\n pg,\n metadataSchema,\n shapeTable,\n target,\n patternSets,\n debug,\n sessionScoped = false,\n}: MoveOutOptions): Promise<number> {\n const { shapeRowTags } = pickMetadataTables(metadataSchema, sessionScoped);\n const db = drizzleOverPg(pg);\n const evictedPkJsons = new Set<string>();\n\n for (const patterns of patternSets) {\n if (patterns.length === 0) continue;\n\n // Candidate tags: those containing every pattern value as a substring — a cheap superset of a real\n // positional match, confirmed in JS so composite/positional tags are handled correctly. Each\n // `like(tag, \"%value%\")` reproduces the former `tag LIKE '%' || $n || '%'` exactly: a param bound to\n // the concatenated pattern string, so any LIKE metacharacters in the value keep the same semantics.\n const candidateRows = await db\n .select({ pk_json: shapeRowTags.pk_json, tag: shapeRowTags.tag })\n .from(shapeRowTags)\n .where(\n and(\n eq(shapeRowTags.shape_table, shapeTable),\n ...patterns.map((pattern) => like(shapeRowTags.tag, `%${pattern.value}%`)),\n ),\n );\n const matched = candidateRows.filter((row) => tagMatchesPatterns(row.tag, patterns));\n if (matched.length === 0) continue;\n\n // Withdraw the moved-out tag from each matching row (one set-based delete of the (pk, tag) pairs).\n // Tier ② (ADR-0028): a set-based delete joined against a JSON recordset has no tier-① builder form —\n // the shape-tag table object is interpolated and the pair list is a bound `::json` param; the\n // alias-qualified `t.*` / `x.*` identifiers are raw only because the `USING`/recordset-join grammar\n // requires them.\n const pairs = matched.map((row) => ({ pk_json: row.pk_json, tag: row.tag }));\n await db.execute(\n sql`DELETE FROM ${shapeRowTags} AS t USING json_to_recordset(${JSON.stringify(pairs)}::json) AS x(pk_json text, tag text)\n WHERE t.shape_table = ${shapeTable} AND t.pk_json = x.pk_json AND t.tag = x.tag`,\n );\n\n // A row is evicted only if it has no tag left.\n const affected = [...new Set(matched.map((row) => row.pk_json))];\n // Tier ② (ADR-0028): bind the affected pk_json list as ONE array param via `= ANY(${param}::text[])`\n // — drizzle has no ANY(array-param) builder, and `sql.param` binds the whole array as a single\n // placeholder (removing the per-element bound-param ceiling `inArray` emits: one placeholder per PK,\n // a ~65k-param wire cap on a huge move-out). The explicit `::text[]` cast pins the param type for the\n // driver's extended-protocol type resolution. The `eq(shape_table)` conjunct and `selectDistinct`\n // shape are preserved.\n const remaining = await db\n .selectDistinct({ pk_json: shapeRowTags.pk_json })\n .from(shapeRowTags)\n .where(\n and(\n eq(shapeRowTags.shape_table, shapeTable),\n sql`${shapeRowTags.pk_json} = ANY(${sql.param(affected)}::text[])`,\n ),\n );\n const stillTagged = new Set(remaining.map((row) => row.pk_json));\n for (const pkJson of affected) {\n if (!stillTagged.has(pkJson)) evictedPkJsons.add(pkJson);\n }\n }\n\n if (evictedPkJsons.size === 0) return 0;\n\n // Evict via the bulk-delete path so the reconcile trigger fires and the read model converges.\n const messages = [...evictedPkJsons].map((pkJson) => ({\n key: pkJson,\n value: JSON.parse(pkJson) as Row<unknown>,\n headers: { operation: \"delete\" as const },\n }));\n await applyBulkDeletesToTable({\n pg,\n target,\n messages,\n debug,\n });\n\n return evictedPkJsons.size;\n}\n\n/** Drop a shape's entire tag-set — for a `must-refetch`/read-cache rebuild, before the re-snapshot (ADR-0023 Slice 2). */\nexport async function clearShapeTags({\n pg,\n metadataSchema,\n shapeTable,\n sessionScoped = false,\n}: {\n pg: PGliteInterface | Transaction;\n metadataSchema: string;\n shapeTable: string;\n /** ADR-0042: clear the SESSION (`pg_temp`) tag store for an ephemeral group's must-refetch rebuild. */\n sessionScoped?: boolean;\n}): Promise<void> {\n const { shapeRowTags } = pickMetadataTables(metadataSchema, sessionScoped);\n await drizzleOverPg(pg).delete(shapeRowTags).where(eq(shapeRowTags.shape_table, shapeTable));\n}\n",
|
|
20
20
|
"// Started life as a copy of @electric-sql/pglite-sync (Apache-2.0, © ElectricSQL — see NOTICE).\n// Fully internalized (ADR-0009); upstream compatibility is an explicit anti-goal (ADR-0028) — evolve freely.\nimport type { ChangeMessage, Row } from \"@electric-sql/client\";\nimport type { PGliteInterface, Transaction } from \"@electric-sql/pglite\";\nimport { and, eq, fillPlaceholders, sql } from \"drizzle-orm\";\nimport { getTableConfig, type PgColumn } from \"drizzle-orm/pg-core\";\n\nimport { quoteIdentifier } from \"@pgxsinkit/contracts\";\n\nimport type { ApplyTarget } from \"../local-tables\";\nimport { generateCopyData } from \"./copy\";\nimport { drizzleOverPg } from \"./drizzle-executor\";\nimport type { InsertChangeMessage } from \"./types\";\n\n/**\n * Re-key an Electric change row (keyed by DB **column name**) to the Drizzle **property keys** the\n * query builder addresses columns by (ADR-0029 D1). A column absent from the local projected table is a\n * config error and surfaces, rather than silently binding to nothing.\n */\nfunction toDriverRow(target: ApplyTarget, data: Row<unknown>): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n for (const name of Object.keys(data)) {\n const propertyKey = target.propertyKeyByName[name];\n if (propertyKey === undefined) {\n throw new Error(`sync apply: column ${JSON.stringify(name)} is not present on the local synced table`);\n }\n out[propertyKey] = data[name];\n }\n return out;\n}\n\n/** The `PgColumn` for a DB column name on the target table (for `eq`/conflict-target/COPY clauses). */\nfunction targetColumn(target: ApplyTarget, name: string): PgColumn {\n const column = target.columnByName[name];\n if (!column) {\n throw new Error(`sync apply: column ${JSON.stringify(name)} not found on the local synced table`);\n }\n return column;\n}\n\nexport interface ApplyMessageToTableOptions {\n pg: PGliteInterface | Transaction;\n target: ApplyTarget;\n message: ChangeMessage<Row<unknown>>;\n debug: boolean;\n}\n\nexport async function applyMessageToTable({ pg, target, message, debug }: ApplyMessageToTableOptions) {\n const data = message.value;\n const db = drizzleOverPg(pg);\n\n switch (message.headers.operation) {\n case \"insert\": {\n if (debug) console.log(\"inserting\", data);\n // Apply exactly what Electric sent: an `insert` is a new row (post-truncate or first send), so\n // it is a plain INSERT. A genuine primary-key collision must surface, never be silently upserted.\n return await db.insert(target.table).values(toDriverRow(target, data) as never);\n }\n\n case \"update\": {\n if (debug) console.log(\"updating\", data);\n const setColumns = Object.keys(data).filter((column) => !target.primaryKey.includes(column));\n if (setColumns.length === 0) return;\n const setValues: Record<string, unknown> = {};\n for (const column of setColumns) setValues[target.propertyKeyByName[column]!] = data[column];\n return await db\n .update(target.table)\n .set(setValues as never)\n .where(and(...target.primaryKey.map((column) => eq(targetColumn(target, column), data[column]))));\n }\n\n case \"delete\": {\n if (debug) console.log(\"deleting\", data);\n return await db\n .delete(target.table)\n .where(and(...target.primaryKey.map((column) => eq(targetColumn(target, column), data[column]))));\n }\n }\n}\n\nexport interface BulkApplyMessagesToTableOptions {\n pg: PGliteInterface | Transaction;\n target: ApplyTarget;\n messages: InsertChangeMessage[];\n debug: boolean;\n}\n\nconst MAX_INSERT_PARAMS = 32_000;\nconst MAX_INSERT_BYTES = 50 * 1024 * 1024;\n\n/**\n * The rendered `{sqlText, params}` for a batched INSERT of `rowCount` rows over `colNames` (ADR-0029\n * D5's render-once remedy). Rendered ONCE per distinct (column-set, row-count) via a placeholder INSERT\n * over the real table, then reused for every batch of that shape — driving the per-row × per-column\n * builder-AST cost to zero. `sql.placeholder` cells make Drizzle emit `$n` markers without applying a\n * codec at render time; the codec is applied per value at execution (see {@link executeInsertBatch}).\n */\nfunction renderInsert(\n db: ReturnType<typeof drizzleOverPg>,\n target: ApplyTarget,\n colNames: string[],\n rowCount: number,\n): { sqlText: string; params: unknown[] } {\n const key = JSON.stringify([rowCount, colNames]);\n const cached = target.insertRenderCache.get(key);\n if (cached) return cached;\n const placeholderRows = Array.from({ length: rowCount }, (_, r) =>\n Object.fromEntries(colNames.map((name, ci) => [target.propertyKeyByName[name]!, sql.placeholder(`${r}_${ci}`)])),\n );\n const rendered = db\n .insert(target.table)\n .values(placeholderRows as never)\n .toSQL();\n const value = { sqlText: rendered.sql, params: rendered.params as unknown[] };\n target.insertRenderCache.set(key, value);\n return value;\n}\n\n/**\n * Execute one rendered batch: fill the render-once placeholders with this batch's values, applying the\n * real per-column codec (`fillPlaceholders` runs each column's `mapToDriverValue`, with a null guard —\n * byte-identical to a plain `.values()` bind), then run the pre-rendered statement on the executor.\n */\nasync function executeInsertBatch(\n pg: PGliteInterface | Transaction,\n db: ReturnType<typeof drizzleOverPg>,\n target: ApplyTarget,\n colNames: string[],\n batch: Row<unknown>[],\n): Promise<void> {\n const rendered = renderInsert(db, target, colNames, batch.length);\n const values: Record<string, unknown> = {};\n for (let r = 0; r < batch.length; r++) {\n const row = batch[r]!;\n for (let ci = 0; ci < colNames.length; ci++) {\n values[`${r}_${ci}`] = row[colNames[ci]!];\n }\n }\n const flat = fillPlaceholders(rendered.params, values);\n await pg.query(rendered.sqlText, flat as unknown[]);\n}\n\nexport async function applyInsertsToTable({ pg, target, messages, debug }: BulkApplyMessagesToTableOptions) {\n const data: Row<unknown>[] = messages.map((message) => message.value);\n const firstRow = data[0];\n if (!firstRow) {\n return;\n }\n\n if (debug) console.log(\"inserting\", data);\n const columns = Object.keys(firstRow);\n const db = drizzleOverPg(pg);\n\n const getValueSize = (value: unknown): number => {\n if (value === null) return 0;\n if (value instanceof ArrayBuffer) return value.byteLength;\n if (value instanceof Blob) return value.size;\n if (value instanceof Uint8Array) return value.byteLength;\n if (value instanceof DataView) return value.byteLength;\n if (ArrayBuffer.isView(value)) return value.byteLength;\n\n switch (typeof value) {\n case \"string\":\n return value.length;\n case \"number\":\n return 8;\n case \"boolean\":\n return 1;\n case \"bigint\":\n case \"symbol\":\n return value.toString().length;\n case \"function\":\n case \"undefined\":\n return 0;\n default: {\n // Remaining typeof: object (null was handled above).\n if (value instanceof Date) return 8;\n try {\n return JSON.stringify(value)?.length ?? 0;\n } catch {\n // Non-serialisable nested value (e.g. bigint inside jsonb).\n return 16;\n }\n }\n }\n };\n\n const getRowSize = (row: Row<unknown>): number => {\n return columns.reduce((size, column) => {\n const value = row[column];\n if (value === null) return size;\n\n if (Array.isArray(value)) {\n if (value.length === 0) return size;\n const firstElement = value[0];\n\n switch (typeof firstElement) {\n case \"number\":\n return size + value.length * 8;\n case \"string\":\n return size + value.reduce((arrSize, str) => arrSize + str.length, 0);\n case \"boolean\":\n return size + value.length;\n default:\n if (firstElement instanceof Date) {\n return size + value.length * 8;\n }\n return size + value.reduce((arrSize, item) => arrSize + getValueSize(item), 0);\n }\n }\n\n return size + getValueSize(value);\n }, 0);\n };\n\n let currentBatch: Row<unknown>[] = [];\n let currentBatchSize = 0;\n let currentBatchParams = 0;\n\n for (const row of data) {\n const rowSize = getRowSize(row);\n const rowParams = columns.length;\n\n if (\n currentBatch.length > 0 &&\n (currentBatchSize + rowSize > MAX_INSERT_BYTES || currentBatchParams + rowParams > MAX_INSERT_PARAMS)\n ) {\n if (debug && currentBatchSize + rowSize > MAX_INSERT_BYTES) {\n console.log(\"batch size limit exceeded, executing batch\");\n }\n if (debug && currentBatchParams + rowParams > MAX_INSERT_PARAMS) {\n console.log(\"batch params limit exceeded, executing batch\");\n }\n await executeInsertBatch(pg, db, target, columns, currentBatch);\n currentBatch = [];\n currentBatchSize = 0;\n currentBatchParams = 0;\n }\n\n currentBatch.push(row);\n currentBatchSize += rowSize;\n currentBatchParams += rowParams;\n }\n\n if (currentBatch.length > 0) {\n await executeInsertBatch(pg, db, target, columns, currentBatch);\n }\n\n if (debug) console.log(`Inserted ${messages.length} rows using INSERT`);\n}\n\n/**\n * Bulk **upsert** for tagged-subquery move-in rows (ADR-0024). A move-in is an existing row ENTERING the\n * shape — unlike a CDC `insert` (a brand-new row) it may already be present locally via an independent\n * grant, or be re-delivered on a resume from before the move-in's offset. So it is applied idempotently:\n * `INSERT … ON CONFLICT (pk) DO UPDATE` refreshes to the move-in's authoritative value (or `DO NOTHING`\n * for a pk-only table). The plain-`INSERT` invariant of the CDC path — a genuine PK collision must\n * surface ({@link applyInsertsToTable}) — is intentionally NOT used here, because for a move-in a present\n * row is expected, not a bug. Batched by parameter count (move-in volume is incremental, not a backfill).\n */\nexport async function applyUpsertsToTable({ pg, target, messages, debug }: BulkKeyedApplyOptions) {\n const primaryKey = target.primaryKey;\n if (primaryKey.length === 0) throw new Error(\"applyUpsertsToTable requires a primary key\");\n\n const data: Row<unknown>[] = messages.map((message) => message.value);\n const firstRow = data[0];\n if (!firstRow) return;\n\n const columns = Object.keys(firstRow);\n const pkSet = new Set(primaryKey);\n const nonPkColumns = columns.filter((column) => !pkSet.has(column));\n\n const conflictTarget = primaryKey.map((column) => targetColumn(target, column));\n // `DO UPDATE SET col = excluded.col` for every non-pk column; `excluded.<col>` is the standard\n // conflict pseudo-relation reference, authored via `sql.identifier` so the column stays a quoted bare\n // identifier (not table-qualified). A pk-only table has nothing to refresh → `DO NOTHING`.\n const conflictSet: Record<string, unknown> = {};\n for (const column of nonPkColumns) {\n conflictSet[target.propertyKeyByName[column]!] = sql`excluded.${sql.identifier(column)}`;\n }\n\n const perRow = columns.length;\n const rowsPerBatch = Math.max(1, Math.floor(MAX_INSERT_PARAMS / perRow));\n const db = drizzleOverPg(pg);\n\n for (let i = 0; i < data.length; i += rowsPerBatch) {\n const batch = data.slice(i, i + rowsPerBatch).map((row) => toDriverRow(target, row));\n const insert = db.insert(target.table).values(batch as never);\n if (nonPkColumns.length > 0) {\n await insert.onConflictDoUpdate({ target: conflictTarget, set: conflictSet as never });\n } else {\n // Target the PK explicitly so a pk-only conflict is a no-op ONLY on the primary key — a bare\n // `ON CONFLICT DO NOTHING` would swallow conflicts on any unique constraint.\n await insert.onConflictDoNothing({ target: conflictTarget });\n }\n }\n\n if (debug) console.log(`Upserted ${messages.length} move-in rows`);\n}\n\n/** A column's name plus the SQL type to cast it to inside a `json_to_recordset` record definition. */\ninterface JsonRecordsetColumn {\n name: string;\n castType: string;\n}\n\n/**\n * The `json_to_recordset` casts for the rows being applied, narrowed to the columns actually present in\n * the synced row, from the model-derived {@link ApplyTarget.columnTypes} (ADR-0029 D2 — never from a\n * catalog probe: the types are always present, derived from the same Drizzle definitions the local\n * store was rendered from).\n */\nfunction jsonRecordsetColumns(target: ApplyTarget, firstRow: Row<unknown>): JsonRecordsetColumn[] {\n const present = (name: string) => Object.prototype.hasOwnProperty.call(firstRow, name);\n return target.columnTypes\n .filter((column) => present(column.name))\n .map((column) => ({ name: column.name, castType: `${column.sqlType}${column.isArray ? \"[]\" : \"\"}` }));\n}\n\nexport async function applyMessagesToTableWithJson({ pg, target, messages, debug }: BulkApplyMessagesToTableOptions) {\n if (debug) console.log(\"applying messages with json_to_recordset\");\n\n const data: Row<unknown>[] = messages.map((message) => message.value);\n const firstRow = data[0];\n if (!firstRow) {\n return;\n }\n const columns = jsonRecordsetColumns(target, firstRow);\n const targetTable = target.table;\n // Tier ② (ADR-0028): the target table is an interpolated table object and the batch is a single bound\n // param (`sql.param` binds the raw JS array unchanged, exactly as the old `[batch]` did — critically,\n // NOT `JSON.stringify`, which would throw on the bigints this path carries). The `x(col type, …)`\n // record definition is raw text: `json_to_recordset`'s grammar requires bare column identifiers and\n // type names there, which no tier-①/② builder expresses.\n const recordDef = columns.map((column) => `${quoteIdentifier(column.name)} ${column.castType}`).join(\", \");\n const db = drizzleOverPg(pg);\n\n const max = 10_000;\n for (let i = 0; i < data.length; i += max) {\n const batch = data.slice(i, i + max);\n await db.execute(\n sql`INSERT INTO ${targetTable} SELECT x.* from json_to_recordset(${sql.param(batch)}) as x(${sql.raw(recordDef)})`,\n );\n }\n\n if (debug) {\n console.log(`Inserted ${messages.length} rows using json_to_recordset`);\n }\n}\n\n/**\n * Each column mapped to its Postgres `udt_name` for the COPY serializer, which needs it only to\n * disambiguate `json`/`jsonb` (whose parsed values are indistinguishable from SQL arrays/objects by\n * runtime type alone). Derived from the model ({@link ApplyTarget.columnTypes}), never introspected\n * (ADR-0029 D2).\n */\nfunction copyColumnUdts(target: ApplyTarget): Record<string, string> {\n const map: Record<string, string> = {};\n for (const column of target.columnTypes) {\n const base = column.sqlType\n .replace(/\\(.*\\)/g, \"\")\n .trim()\n .toLowerCase();\n if (base === \"json\" || base === \"jsonb\") {\n map[column.name] = column.isArray ? `_${base}` : base;\n }\n }\n return map;\n}\n\nexport async function applyMessagesToTableWithCopy({ pg, target, messages, debug }: BulkApplyMessagesToTableOptions) {\n if (debug) console.log(\"applying messages with COPY\");\n\n const data: Row<unknown>[] = messages.map((message) => message.value);\n const firstRow = data[0];\n if (!firstRow) {\n return;\n }\n const columns = Object.keys(firstRow);\n\n // Serialize rows using Postgres' own COPY TEXT format — a faithful port of the backend's\n // CopyAttributeOutText / array_out routines (see ./copy) — so arrays (incl. multi-dimensional),\n // json/jsonb, bytea, timestamps and strings with embedded delimiters/newlines all round-trip,\n // unlike the previous hand-rolled CSV encoder.\n const columnUdts = copyColumnUdts(target);\n const copyData = generateCopyData(data, columns, columnUdts);\n const copyBlob = new Blob([copyData], { type: \"text/plain\" });\n\n // TEXT is the default COPY format; its default delimiter is a tab and NULL marker is `\\N`, both of\n // which generateCopyData emits.\n //\n // Tier ③ (ADR-0028 allow-list): `COPY … FROM '/dev/blob'` is PGlite's blob-ingest grammar — it has no\n // Drizzle builder form, so the statement stays a raw string. The table reference is taken from the real\n // synced table object: a bare name (ephemeral → `pg_temp` via search_path) or a schema-qualified one.\n const { name: tableName, schema } = getTableConfig(target.table);\n const copyTarget = schema ? `${quoteIdentifier(schema)}.${quoteIdentifier(tableName)}` : quoteIdentifier(tableName);\n await pg.query(\n `\n COPY ${copyTarget} (${columns.map((column) => quoteIdentifier(column)).join(\", \")})\n FROM '/dev/blob'\n WITH (FORMAT text)\n `,\n [],\n {\n blob: copyBlob,\n },\n );\n\n if (debug) console.log(`Inserted ${messages.length} rows using COPY`);\n}\n\nconst JSON_RECORDSET_BATCH = 10_000;\n\n/**\n * The `json_to_recordset` casts for an **explicit, ordered** column list — the bulk UPDATE/DELETE source\n * relations need the PK columns (plus, for updates, the group's SET columns) in a known order. Derived\n * from the model ({@link ApplyTarget.columnTypes}), never introspected (ADR-0029 D2).\n */\nfunction recordsetColumnCasts(target: ApplyTarget, columnNames: string[]): JsonRecordsetColumn[] {\n const byName = new Map(target.columnTypes.map((column) => [column.name, column]));\n return columnNames.map((name) => {\n const column = byName.get(name);\n if (!column) {\n throw new Error(`recordsetColumnCasts: no registered type for column ${JSON.stringify(name)}`);\n }\n return { name, castType: `${column.sqlType}${column.isArray ? \"[]\" : \"\"}` };\n });\n}\n\nexport interface BulkKeyedApplyOptions {\n pg: PGliteInterface | Transaction;\n target: ApplyTarget;\n /** Folded messages: for deletes the value carries the PK; for updates the PK plus merged columns. */\n messages: ChangeMessage<Row<unknown>>[];\n debug: boolean;\n}\n\n/**\n * Bulk DELETE by primary key via `DELETE … USING json_to_recordset(…)` (ADR-0014 Phase 3). Safe\n * because the read-path fold already left **one row per PK** — no same-PK duplicate in the source.\n */\nexport async function applyBulkDeletesToTable({ pg, target, messages, debug }: BulkKeyedApplyOptions) {\n const primaryKey = target.primaryKey;\n if (primaryKey.length === 0) throw new Error(\"applyBulkDeletesToTable requires a primary key\");\n if (messages.length === 0) return;\n\n const rows = messages.map((message) => {\n const data = message.value;\n return Object.fromEntries(primaryKey.map((column) => [column, data[column]]));\n });\n\n const casts = recordsetColumnCasts(target, primaryKey);\n const recordDef = casts.map((column) => `${quoteIdentifier(column.name)} ${column.castType}`).join(\", \");\n const whereJoin = primaryKey\n .map((column) => `t.${quoteIdentifier(column)} = x.${quoteIdentifier(column)}`)\n .join(\" AND \");\n const targetTable = target.table;\n const db = drizzleOverPg(pg);\n\n for (let i = 0; i < rows.length; i += JSON_RECORDSET_BATCH) {\n const batch = rows.slice(i, i + JSON_RECORDSET_BATCH);\n // Tier ② (ADR-0028): the target table is an interpolated table object; the pk-projection batch is a\n // single bound param (`sql.param` binds the raw JS array unchanged — as the old `[batch]` did, and\n // NOT `JSON.stringify`, which would throw on bigint pks). No cast is needed — `json_to_recordset`\n // has a single json-typed signature. The `x(col type, …)` record definition and the alias-qualified\n // `t.*`/`x.*` join are raw text: the `USING`/recordset-join grammar requires those bare identifiers.\n await db.execute(\n sql`DELETE FROM ${targetTable} AS t USING json_to_recordset(${sql.param(batch)}) AS x(${sql.raw(recordDef)}) WHERE ${sql.raw(whereJoin)}`,\n );\n }\n\n if (debug) console.log(`Deleted ${messages.length} rows using json_to_recordset`);\n}\n\n/**\n * Bulk UPDATE via `UPDATE … FROM json_to_recordset(…)` (ADR-0014 Phase 3), **grouped by the set of\n * non-PK columns** each row carries. Electric's default replica sends only the changed columns, so\n * two rows in one batch can set different columns; one `UPDATE … FROM` per distinct column-set keeps\n * each statement uniform. Safe from the same-PK join hazard because the fold already left one row per\n * PK, so no PK appears twice within a group.\n */\nexport async function applyBulkUpdatesToTable({ pg, target, messages, debug }: BulkKeyedApplyOptions) {\n const primaryKey = target.primaryKey;\n if (primaryKey.length === 0) throw new Error(\"applyBulkUpdatesToTable requires a primary key\");\n if (messages.length === 0) return;\n\n const pkSet = new Set(primaryKey);\n const groups = new Map<string, { setColumns: string[]; rows: Row<unknown>[] }>();\n for (const message of messages) {\n const data = message.value;\n const setColumns = Object.keys(data)\n .filter((column) => !pkSet.has(column))\n .sort();\n // A PK-only update sets nothing — the per-row applyMessageToTable returns early on this too.\n if (setColumns.length === 0) continue;\n const groupKey = setColumns.join(\" \");\n let group = groups.get(groupKey);\n if (!group) {\n group = { setColumns, rows: [] };\n groups.set(groupKey, group);\n }\n group.rows.push(Object.fromEntries([...primaryKey, ...setColumns].map((column) => [column, data[column]])));\n }\n\n const targetTable = target.table;\n const db = drizzleOverPg(pg);\n\n for (const { setColumns, rows } of groups.values()) {\n const casts = recordsetColumnCasts(target, [...primaryKey, ...setColumns]);\n const recordDef = casts.map((column) => `${quoteIdentifier(column.name)} ${column.castType}`).join(\", \");\n const setClause = setColumns\n .map((column) => `${quoteIdentifier(column)} = x.${quoteIdentifier(column)}`)\n .join(\", \");\n const whereJoin = primaryKey\n .map((column) => `t.${quoteIdentifier(column)} = x.${quoteIdentifier(column)}`)\n .join(\" AND \");\n\n for (let i = 0; i < rows.length; i += JSON_RECORDSET_BATCH) {\n const batch = rows.slice(i, i + JSON_RECORDSET_BATCH);\n // Tier ② (ADR-0028), as applyBulkDeletesToTable above: interpolated target table + single bound\n // `sql.param` batch (raw array, not `JSON.stringify` — bigint-safe), no cast needed; the `SET` /\n // `x(col type, …)` record def and the alias-qualified `t.*`/`x.*` join stay raw text (grammar).\n await db.execute(\n sql`UPDATE ${targetTable} AS t SET ${sql.raw(setClause)} FROM json_to_recordset(${sql.param(batch)}) AS x(${sql.raw(recordDef)}) WHERE ${sql.raw(whereJoin)}`,\n );\n }\n }\n\n if (debug) console.log(`Updated ${messages.length} rows using json_to_recordset`);\n}\n",
|
|
21
21
|
"// Started life as a copy of @electric-sql/pglite-sync (Apache-2.0, © ElectricSQL — see NOTICE) —\n// specifically a port of the serializer from electric-sql/pglite PR #1035.\n// Fully internalized (ADR-0009); upstream compatibility is an explicit anti-goal (ADR-0028) — evolve freely.\n/**\n * Serialization of JavaScript values into a PostgreSQL `COPY ... WITH (FORMAT\n * text)` stream.\n *\n * The Electric client parses the wire values it receives into native JS values\n * before they reach this module: `int2`/`int4`/`float4`/`float8` become\n * `number`, `int8` becomes `bigint`, `bool` becomes `boolean`, `json`/`jsonb`\n * become parsed objects/arrays, array columns become (possibly nested) JS\n * arrays, and every other type is left as its raw Postgres text representation\n * (a `string`). To feed those values back into `COPY` we have to reverse that:\n * turn each value into the exact text Postgres' input functions expect, then\n * apply the COPY framing.\n *\n * Rather than invent an escaping scheme (the previous CSV-based approach broke\n * on arrays, JSON, embedded delimiters, etc.) this is a faithful port of the\n * two relevant PostgreSQL backend routines:\n *\n * - `CopyAttributeOutText` (src/backend/commands/copyto.c) — field escaping\n * - `array_out` (src/backend/utils/adt/arrayfuncs.c) — array literals\n *\n * The TEXT format is used (not CSV) because it is what Postgres itself emits\n * internally, has a single well-defined escaping algorithm, and round-trips\n * every built-in type.\n */\n\n// Defaults for COPY ... WITH (FORMAT text), matching the Postgres backend.\nconst DELIMITER = \"\\t\";\nconst NULL_MARKER = \"\\\\N\";\nconst ROW_SEPARATOR = \"\\n\";\n\n// CopyAttributeOutText escapes the backslash, the field delimiter, and the\n// control characters that have C-style escapes. Every other byte is emitted\n// literally. Our delimiter is a tab, which already has a C-style escape, so the\n// single map below covers all cases.\nconst COPY_TEXT_ESCAPES: Record<string, string> = {\n \"\\\\\": \"\\\\\\\\\",\n \"\\b\": \"\\\\b\",\n \"\\f\": \"\\\\f\",\n \"\\n\": \"\\\\n\",\n \"\\r\": \"\\\\r\",\n \"\\t\": \"\\\\t\",\n \"\\v\": \"\\\\v\",\n};\nconst COPY_TEXT_ESCAPE_RE = /[\\\\\\b\\f\\n\\r\\t\\v]/g;\n\n/** Escape an already-stringified field value per `CopyAttributeOutText`. */\nfunction escapeCopyText(value: string): string {\n return value.replace(COPY_TEXT_ESCAPE_RE, (c) => COPY_TEXT_ESCAPES[c] ?? c);\n}\n\n/**\n * Convert a Uint8Array to Postgres `bytea` hex-format text (`\\xDEADBEEF`).\n * Electric normally delivers `bytea` already as such a string, so this only\n * matters for callers using a custom parser that yields binary.\n */\nfunction byteaToText(bytes: Uint8Array): string {\n let hex = \"\";\n for (const byte of bytes) {\n hex += byte.toString(16).padStart(2, \"0\");\n }\n return \"\\\\x\" + hex;\n}\n\n/**\n * Render a JS `number` the way Postgres' float/int input accepts it. The only\n * special cases are the non-finite values, which Postgres spells out in words.\n */\nfunction numberToText(value: number): string {\n if (Number.isNaN(value)) return \"NaN\";\n if (value === Infinity) return \"Infinity\";\n if (value === -Infinity) return \"-Infinity\";\n return String(value);\n}\n\n// array_out quotes an element when it is empty, looks like the literal NULL, or\n// contains a brace, the element delimiter (comma), a double-quote, a backslash,\n// or ASCII whitespace. We mirror `array_isspace`, which is stricter than JS\n// `\\s` (it excludes Unicode whitespace), so the output matches Postgres' own\n// `array_out` TEXT format exactly and re-parses correctly on `COPY FROM`.\nconst ARRAY_NEEDS_QUOTE_RE = /[{}\",\\\\ \\t\\n\\r\\v\\f]/;\n\n/** Quote/escape a single array element's text per `array_out`. */\nfunction quoteArrayElement(text: string): string {\n const needsQuote = text.length === 0 || text.toLowerCase() === \"null\" || ARRAY_NEEDS_QUOTE_RE.test(text);\n if (!needsQuote) return text;\n // Inside quotes only `\"` and `\\` are escaped, each with a single backslash.\n return '\"' + text.replace(/([\"\\\\])/g, \"\\\\$1\") + '\"';\n}\n\n/**\n * Build a Postgres array literal (`{...}`) from a JS array, recursing into\n * nested arrays for multi-dimensional arrays. NULL elements become an unquoted\n * `NULL`; nested arrays are emitted as bare `{...}` (never quoted), exactly as\n * `array_out` does.\n */\nfunction arrayToText(arr: ReadonlyArray<unknown>): string {\n const elements = arr.map((el) => {\n if (el === null || el === undefined) return \"NULL\";\n if (Array.isArray(el)) return arrayToText(el);\n return quoteArrayElement(valueToText(el));\n });\n return \"{\" + elements.join(\",\") + \"}\";\n}\n\n/**\n * Convert a non-null JS value to its bare Postgres text representation (before\n * COPY field escaping is applied). Dispatch is on the runtime type produced by\n * the Electric parser. `json`/`jsonb` columns are handled ahead of this by\n * `serializeCopyValue` when a column type is known; reaching the object branch\n * here is the type-less fallback.\n */\nfunction valueToText(value: unknown): string {\n switch (typeof value) {\n case \"string\":\n return value;\n case \"number\":\n return numberToText(value);\n case \"bigint\":\n return value.toString();\n case \"boolean\":\n return value ? \"t\" : \"f\";\n case \"object\": {\n if (Array.isArray(value)) return arrayToText(value);\n if (value instanceof Date) return value.toISOString();\n if (value instanceof Uint8Array) return byteaToText(value);\n if (value instanceof ArrayBuffer) return byteaToText(new Uint8Array(value));\n if (ArrayBuffer.isView(value)) {\n const view = value as ArrayBufferView;\n return byteaToText(new Uint8Array(view.buffer, view.byteOffset, view.byteLength));\n }\n // json / jsonb arrive already parsed; re-serialize them.\n return JSON.stringify(value);\n }\n default:\n // Should be unreachable for Electric-parsed values; be defensive.\n return String(value);\n }\n}\n\n/**\n * Build a Postgres array literal from a `json[]`/`jsonb[]` value. Each element\n * is JSON text (re-serialized from the parsed value), so we cannot reuse the\n * generic array path: a JSON array element must stay JSON (`[1,2]`), not be\n * turned into a nested SQL array (`{1,2}`).\n */\nfunction jsonArrayToText(arr: ReadonlyArray<unknown>): string {\n const elements = arr.map((el) => (el === null || el === undefined ? \"NULL\" : quoteArrayElement(jsonToText(el))));\n return \"{\" + elements.join(\",\") + \"}\";\n}\n\n/**\n * Re-serialize a parsed `json`/`jsonb` value to its JSON text form. Electric\n * delivers these columns already run through `JSON.parse`, so the value is the\n * decoded JS value (object, array, string, number, boolean or null) and always\n * needs `JSON.stringify` to become valid JSON input again — including scalars\n * (the string `hi` must be written as `\"hi\"`).\n */\nfunction jsonToText(value: unknown): string {\n return JSON.stringify(value);\n}\n\n/**\n * Postgres `udt_name`s that need JSON-aware serialization rather than the\n * generic runtime-type dispatch. Used to resolve the otherwise undecidable\n * \"is this JS array a SQL array or a JSON array?\" ambiguity.\n */\nconst JSON_UDT_NAMES = new Set([\"json\", \"jsonb\"]);\nconst JSON_ARRAY_UDT_NAMES = new Set([\"_json\", \"_jsonb\"]);\n\n/**\n * Serialize a single value into one COPY TEXT field. `null`/`undefined` become\n * the NULL marker (`\\N`); everything else is converted to text and escaped.\n *\n * `udtName` is the column's Postgres `udt_name`. When supplied it disambiguates\n * `json`/`jsonb` columns; when omitted the value's runtime type is used (which\n * cannot tell a `jsonb` array from a SQL array).\n */\nexport function serializeCopyValue(value: unknown, udtName?: string): string {\n if (value === null || value === undefined) return NULL_MARKER;\n if (udtName !== undefined) {\n if (JSON_UDT_NAMES.has(udtName)) return escapeCopyText(jsonToText(value));\n if (JSON_ARRAY_UDT_NAMES.has(udtName) && Array.isArray(value)) return escapeCopyText(jsonArrayToText(value));\n }\n return escapeCopyText(valueToText(value));\n}\n\n/**\n * Serialize a list of row objects into the body of a `COPY ... FROM` request in\n * TEXT format. Columns are emitted in the given order, fields are tab\n * separated, and rows are newline separated.\n *\n * `columnTypes` optionally maps a column name to its Postgres `udt_name`; pass\n * it so `json`/`jsonb` columns serialize correctly.\n */\nexport function generateCopyData(\n rows: ReadonlyArray<Record<string, unknown>>,\n columns: ReadonlyArray<string>,\n columnTypes?: Readonly<Record<string, string | undefined>>,\n): string {\n return rows\n .map((row) => columns.map((column) => serializeCopyValue(row[column], columnTypes?.[column])).join(DELIMITER))\n .join(ROW_SEPARATOR);\n}\n",
|
|
22
22
|
"import type { PGlite, PGliteInterface, Transaction } from \"@electric-sql/pglite\";\nimport { drizzle, type PgliteDatabase } from \"drizzle-orm/pglite\";\n\n/**\n * A Drizzle handle whose executor is an already-open PGlite connection *or* an open PGlite\n * `Transaction` — the tier-① authoring/execution surface for the sync engine's metadata-store DML\n * (ADR-0028 decision 4).\n *\n * The blocker the old convertibility report cited was \"`drizzle-orm/pglite` wraps only a PGlite\n * instance, not a Transaction\". That is a *type* boundary, not a runtime one: drizzle's pglite session\n * layer only ever calls `client.query(sql, params, { rowMode, parsers })` on the wrapped client (verified\n * against drizzle-orm 1.0.0-rc.4 `pglite/session.js` — the executor touches nothing but `.query`; the\n * only other member it would reach is `.transaction`, and only if someone calls `db.transaction()`).\n * PGlite's `Transaction` exposes a `query` with the identical `(sql, params, options)` shape, so a handle\n * built over a `Transaction` executes every statement **on that transaction** — participating in the\n * engine's commit boundary rather than opening its own.\n *\n * The cast to `PGlite` is the narrowest honest one: at runtime the session only calls `.query`, which\n * both `PGliteInterface` and `Transaction` satisfy; the type just does not express that union. It is the\n * expected single-expression cast for this seam.\n *\n * CONTRACT: `.transaction()` on the returned handle is **forbidden**. The engine owns transaction\n * boundaries itself (`pg.transaction(async (tx) => …)` + explicit `tx.rollback()` on unsubscribe, sync\n * index.ts); calling `db.transaction()` here would (a) require the wrapped client to be a full PGlite,\n * which a `Transaction` is not, and (b) open a nested boundary the engine does not expect. Do not expose\n * or use it.\n *\n * MUST be the `{ client }` config form: drizzle's pglite driver destructures `{ connection, client }`\n * from a bare first argument, so `drizzle(pg)` misdetects the handle as a config object and silently\n * constructs a NEW in-memory PGlite — every statement would then hit an empty, throwaway database.\n */\n\n// One drizzle handle per underlying connection/transaction object. The handle for a given `Transaction`\n// is short-lived (one commit) but reused across the several metadata statements that run within that\n// commit — the tag-store hot path — so memoizing per handle avoids re-wrapping on every statement while\n// never leaking across transactions (a `Transaction` object is a fresh identity each commit, and the\n// WeakMap drops it once the commit's closure is collected).\nconst handles = new WeakMap<PGliteInterface | Transaction, PgliteDatabase<never>>();\n\n/** A (memoized) Drizzle handle over an open PGlite connection or transaction — engine-internal. */\nexport function drizzleOverPg(pg: PGliteInterface | Transaction): PgliteDatabase<never> {\n let db = handles.get(pg);\n if (!db) {\n db = drizzle({ client: pg as unknown as PGlite }) as PgliteDatabase<never>;\n handles.set(pg, db);\n }\n return db;\n}\n",
|
|
23
|
-
"import { index, jsonb, pgSchema, primaryKey, text } from \"drizzle-orm/pg-core\";\n\nimport type { ShapeSubscriptionState } from \"./subscription-state\";\n\n/**\n * The two metadata-store relations the sync engine provisions at boot (ADR-0028 decision 4). The\n * metadata schema name is dynamic (per-client config) but fixed at engine construction, so the tables\n * are built per schema string and memoized.\n *\n * ADR-0029 D3: these pgTables are the SINGLE SOURCE for the relations. `migrateSubscriptionMetadataTables`\n * (subscription-state.ts) renders their `CREATE TABLE`/`CREATE INDEX` DDL FROM these definitions via the\n * in-house `renderCreateTableSql` (schema.ts), and the DML paths query them directly — so the DDL and the\n * pgTable can no longer diverge, and the former drift guard in `tests/unit/sync-drizzle-executor.test.ts`\n * is now a plain provisioning round-trip.\n *\n * Property keys are deliberately snake_case to mirror the row shapes the callers already consume\n * (`shape_metadata`, `last_lsn`, `pk_json`, …), so a `select()` returns rows in the existing shape with\n * no alias mapping.\n */\n\nexport interface MetadataTables {\n /** `<schema>.subscriptions_metadata` — one row per subscription key. */\n readonly subscriptionsMetadata: ReturnType<typeof buildSubscriptionsMetadata>;\n /** `<schema>.shape_row_tags` — the tagged-subquery reason-set store (ADR-0023). */\n readonly shapeRowTags: ReturnType<typeof buildShapeRowTags>;\n}\n\nfunction buildSubscriptionsMetadata(schema: ReturnType<typeof pgSchema>) {\n return schema.table(\"subscriptions_metadata\", {\n key: text(\"key\").primaryKey(),\n // JSONB NOT NULL — round-trips as a parsed object (drizzle's jsonb codec), matching the raw path.\n shape_metadata: jsonb(\"shape_metadata\").$type<Record<string, ShapeSubscriptionState>>().notNull(),\n // The LSN is persisted as TEXT (a bigint has no JSON/portable-column form); callers `BigInt(...)` it.\n last_lsn: text(\"last_lsn\").notNull(),\n });\n}\n\nfunction buildShapeRowTags(schema: ReturnType<typeof pgSchema>) {\n return schema.table(\n \"shape_row_tags\",\n {\n shape_table: text(\"shape_table\").notNull(),\n pk_json: text(\"pk_json\").notNull(),\n tag: text(\"tag\").notNull(),\n },\n (t) => [\n primaryKey({ columns: [t.shape_table, t.pk_json, t.tag] }),\n index(\"shape_row_tags_shape_tag_idx\").on(t.shape_table, t.tag),\n ],\n );\n}\n\nconst cache = new Map<string, MetadataTables>();\n\n/** The (memoized) metadata-store `pgTable`s for a given metadata schema name. */\nexport function getMetadataTables(metadataSchema: string): MetadataTables {\n let tables = cache.get(metadataSchema);\n if (!tables) {\n const schema = pgSchema(metadataSchema);\n tables = {\n subscriptionsMetadata: buildSubscriptionsMetadata(schema),\n shapeRowTags: buildShapeRowTags(schema),\n };\n cache.set(metadataSchema, tables);\n }\n return tables;\n}\n",
|
|
24
|
-
"import {\n and,\n desc,\n eq,\n exists,\n getColumns,\n gt,\n inArray,\n is,\n isNotNull,\n isNull,\n lt,\n ne,\n notExists,\n SQL,\n sql,\n} from \"drizzle-orm\";\nimport {\n alias,\n getTableConfig,\n getViewConfig,\n PgDialect,\n type AnyPgTable,\n type PgColumn,\n type PgInsertValue,\n} from \"drizzle-orm/pg-core\";\nimport { drizzle } from \"drizzle-orm/pglite\";\n\nimport {\n getJournalTable,\n getOverlayTable,\n getSyncedLocalTable,\n type JournalTable,\n type OverlayTable,\n} from \"./local-tables\";\n\n// Statements are AUTHORED as Drizzle builders over the journal/overlay/synced table objects\n// (rename-safe, typed, schema-qualification handled by the table objects) and rendered to\n// text+params here, because they EXECUTE through the caller's raw `MutationDb` seam — the one\n// connection the mutation runtime and its tests own (and mock). `drizzle.mock()` builds queries\n// without a connection; `queryDialect` renders standalone `sql` fragments the builders cannot\n// express (compound CTE shapes, derived-table wrappers).\nconst queryBuilder = drizzle.mock();\nconst queryDialect = new PgDialect();\n\n/**\n * Strip the two internal overlay columns that appear on _read_model views\n * (`overlay_kind`, `local_updated_at_us`) from any user-supplied input or\n * patch object before it is serialised into a mutation payload. Callers\n * that spread a view row directly into a create/update call would otherwise\n * hit `TypeError: Do not know how to serialize a BigInt` because\n * `local_updated_at_us` is stored as a native JS `bigint`.\n */\nfunction stripReadModelOverlayFields<T>(value: T): T {\n if (value === null || typeof value !== \"object\") return value;\n const obj = value as Record<string, unknown>;\n if (!(\"overlay_kind\" in obj) && !(\"local_updated_at_us\" in obj)) return value;\n const { overlay_kind: _ok, local_updated_at_us: _lu, ...rest } = obj;\n return rest as T;\n}\n\n/**\n * JSON replacer that serialises `bigint` values as strings. PostgreSQL\n * accepts string literals for BIGINT columns, and JSON has no native bigint\n * type, so this is the safest cross-boundary representation.\n */\nfunction bigintReplacer(_key: string, value: unknown): unknown {\n return typeof value === \"bigint\" ? String(value) : value;\n}\n\nfunction jsonStringifyPayload(value: unknown): string {\n return JSON.stringify(value, bigintReplacer);\n}\n\nimport type {\n BatchMutationAck,\n MutationAck,\n MutationDiagnostics,\n MutationRejection,\n SyncTableCreateInput,\n SyncTableEntry,\n SyncTableName,\n SyncTableRecord,\n SyncTableRegistry,\n SyncTableUpdateInput,\n WriteMode,\n} from \"@pgxsinkit/contracts\";\nimport {\n batchMutationErrorSchema,\n buildOverlayResolutionBarrier,\n fingerprintRegistry,\n getProjectedColumns as getProjectedTableColumns,\n getSyncRegistrySchema,\n maybeQuoteIdentifier,\n quoteIdentifier,\n resolveServerVersionColumnName,\n} from \"@pgxsinkit/contracts\";\n\nimport { syncDebug } from \"./debug\";\nimport {\n assertValidMutationTransition,\n classifyFailureStatus,\n DEFAULT_MAX_MUTATION_ATTEMPTS,\n type MutationStatus,\n} from \"./mutation-state\";\n\nexport type { MutationStatus } from \"./mutation-state\";\nexport type MutationKind = \"create\" | \"update\" | \"delete\";\n\n/**\n * The dynamic write-unit tag (ADR-0022 §2) a `transaction({ mode })` block stamps onto the mutations\n * authored within it: a shared `id` grouping the co-committed mutations, and the unit's `mode`. Persisted\n * on each journal row (`write_unit` / `write_mode`); absent for the default path, where the flusher derives\n * mode + unit from the table's static consistency group.\n */\nexport interface WriteUnit {\n id: string;\n mode: WriteMode;\n}\n\nexport type MutationBatchItem<TRegistry extends SyncTableRegistry> = {\n [TKey in SyncTableName<TRegistry>]:\n | {\n table: TKey;\n kind: \"create\";\n input: SyncTableCreateInput<TRegistry, TKey>;\n }\n | {\n table: TKey;\n kind: \"update\";\n entityKey: Record<string, string>;\n patch: SyncTableUpdateInput<TRegistry, TKey>;\n /**\n * A **blind** update (ADR-0022 addendum): plan a journal row ONLY — no local base row is required\n * and no optimistic overlay is written. Set exclusively by the transaction handle's `updateBlind`;\n * valid only when the write routes pessimistically (a `pessimistic` unit, or a statically-pessimistic\n * table), and rejected at enqueue otherwise. Absent/false for an ordinary update.\n */\n blind?: boolean;\n }\n | {\n table: TKey;\n kind: \"delete\";\n entityKey: Record<string, string>;\n };\n}[SyncTableName<TRegistry>];\n\nexport const DEFAULT_FLUSH_BATCH_SIZE = 100;\n\nexport interface MutationDetail {\n tableName: string;\n entityKey: Record<string, string>;\n mutationId: string;\n mutationSeq: number;\n mutationKind: MutationKind;\n status: MutationStatus;\n attemptCount: number;\n lastHttpStatus: number | null;\n lastError: string | null;\n conflictReason: string | null;\n nextRetryAtUs: string | null;\n serverUpdatedAtUs: string | null;\n updatedAtUs: string;\n /** Registry fingerprint (ADR-0004) the mutation was authored under, or null if unstamped. */\n registryVersion: string | null;\n}\n\nexport interface MutationDb {\n exec: (sql: string) => Promise<unknown>;\n query: <TRow extends Record<string, unknown> = Record<string, unknown>>(\n sql: string,\n params?: unknown[],\n ) => Promise<{ rows: TRow[] }>;\n}\n\nexport interface CreateMutationRuntimeOptions<TRegistry extends SyncTableRegistry> {\n db: MutationDb;\n registry: TRegistry;\n writeUrl: string;\n getAuthToken?: () => Promise<string | undefined>;\n /** Static headers added to every write request (e.g. a Supabase Cloud `apikey`); see {@link CreateSyncClientOptions.requestHeaders}. */\n requestHeaders?: Record<string, string>;\n /**\n * Registry fingerprint (ADR-0004) stamped onto each enqueued mutation as its\n * `registry_version`, so a version-boundary crossing is known before sending (ADR-0006).\n */\n registryVersion?: string;\n /**\n * Hard cap on send attempts before a still-failing mutation is quarantined\n * (ADR-0005 congestion policy). Defaults to {@link DEFAULT_MAX_MUTATION_ATTEMPTS}.\n */\n maxMutationAttempts?: number;\n /**\n * Max mutations drained per flush HTTP request; a flush loops slices until the journal is empty.\n * Defaults to {@link DEFAULT_FLUSH_BATCH_SIZE}. Primarily a test seam (a small value exercises the\n * multi-slice drain path without enqueueing hundreds of mutations).\n */\n flushBatchSize?: number;\n /**\n * Invoked after a flush whenever mutations transition to `quarantined` (terminal,\n * permanently rejected). Receives the newly-quarantined details so the app can surface\n * them, then either re-author + resubmit or roll back via {@link MutationRuntime.discardQuarantined}\n * (clears the kept overlay + quarantined journal rows, so the entity accepts new mutations again).\n * The library never silently drops these (ADR-0006 decision 4).\n */\n onQuarantine?: (quarantined: MutationDetail[]) => void | Promise<void>;\n /**\n * Invoked after a flush whenever mutations transition to `conflicted` — a stale write the\n * server declined under the `reject-if-stale` Conflict policy (ADR-0015). Distinct from\n * `onQuarantine` (structural rejection): the optimistic Overlay is KEPT, so the app surfaces a\n * resolution/diff UI and resolves each as a new write (or `discardConflict`s it). Never silent.\n */\n onConflict?: (conflicted: MutationDetail[]) => void | Promise<void>;\n /**\n * Invoked after an authoritative (pessimistic) flush whenever a write-unit was `rejected` (ADR-0022) —\n * a business decline the client could not evaluate locally (capacity/quota/uniqueness). The inverse of\n * `onConflict`: the optimistic Overlay was **auto-discarded** for every member of the unit, so the app\n * surfaces the typed reason (e.g. \"full\") rather than a resolve/diff UI. Never silent.\n */\n onReject?: (rejected: MutationDetail[]) => void | Promise<void>;\n /**\n * Invoked once per enqueue with the DISTINCT non-blind table keys of the planned batch (ADR-0039).\n * An ordinary optimistic `create`/`update`/`delete` is a reference to its target, and a reference\n * activates the target's lazy consistency group — the read path does this implicitly, the write path\n * did not. The client wires this to a fire-and-forget `ensureSynced`, so the group is open by the time\n * the echo returns. Purely-blind batches (only `updateBlind`) report nothing: a blind write is the\n * deliberate no-echo, no-activation write-only exception. Fire-and-forget from the runtime's view —\n * never awaited, and a throw here must never fail the enqueue (the runtime guards the call).\n */\n onOrdinaryEnqueue?: (tables: readonly string[]) => void;\n}\n\ninterface TableContext {\n key: string;\n entry: SyncTableEntry<AnyPgTable>;\n readModel: string;\n syncedTable: string;\n overlayTable: string;\n journalTable: string;\n journalSequence: string;\n pkColumnNames: string[];\n pkPropertyKeys: string[];\n /**\n * The Server version (ADR-0010) column name (e.g. `updated_at_us`) and its drizzle property key,\n * resolved from the table's managed fields. Used to capture the Base server version (ADR-0015) at\n * enqueue — the value the user's edit was authored against. `null` would mean no Server version,\n * which registry validation already forbids for a writable table.\n */\n serverVersionColumnName: string | null;\n serverVersionPropertyKey: string | null;\n /**\n * Property keys of the table's `nowMicroseconds` managed fields (governance), resolved generically\n * rather than by the `createdAtUs`/`updatedAtUs` naming convention. The optimistic overlay stamps\n * these client-side so a custom-named managed timestamp (e.g. a Server version not called\n * `updated_at_us`) is materialised correctly — closing the split interpreter between the generic\n * server applier (which reads governance) and the local path (ADR-0004).\n *\n * - `managedNowMicrosecondsPropertyKeys` — every `nowMicroseconds` field, stamped on create.\n * - `updateManagedNowMicrosecondsPropertyKeys` — those that apply on update, re-stamped each update.\n *\n * These augment, and never remove, the convention fill in `createOptimisticRecordFromContext`,\n * which remains the safety net for a `created_at_us`/`updated_at_us` column that carries a SQL\n * `DEFAULT` (unmaterialisable client-side) yet is not declared a managed field.\n */\n managedNowMicrosecondsPropertyKeys: string[];\n updateManagedNowMicrosecondsPropertyKeys: string[];\n /**\n * The table's `authClaim` managed fields that apply on create (governance), each with the JSON\n * claimPath it stamps from. The server stamps these from the verified request claims, so they are\n * stripped from the create input type and never sent in the flushed payload. But the optimistic\n * overlay still needs a value — such a column is typically `NOT NULL` (an owner/author/created_by) —\n * so the runtime fills it client-side from the decoded JWT claim at the same path (the same value the\n * server will stamp), so the local row renders attributed immediately and never flips on convergence.\n * (`auth.uid()` is just `claimPath: [\"sub\"]`, so this one path covers it.)\n */\n managedAuthClaimCreateFields: Array<{ propertyKey: string; claimPath: string[] }>;\n recordIncludesOverlayState: boolean;\n columns: Array<{\n propertyKey: string;\n column: ReturnType<typeof getProjectedTableColumns<AnyPgTable>>[number][\"column\"];\n }>;\n /**\n * The generated local relations as runtime Drizzle table objects (local-tables.ts), so the\n * runtime's statements are AUTHORED as tier-① builders while still EXECUTING through the raw\n * `MutationDb` seam. Journal fixed columns are camelCase-keyed; per-entry PK columns are keyed\n * by DB column name; overlay/synced columns are keyed by drizzle property key.\n */\n tables: {\n synced: AnyPgTable;\n overlay: OverlayTable;\n journal: JournalTable;\n };\n /** Overlay columns keyed by property key (`getColumns` memo — overlay keys are property keys, not DB names). */\n overlayColumnsByPropertyKey: Record<string, PgColumn>;\n /** Synced read-cache columns keyed by property key. */\n syncedColumnsByPropertyKey: Record<string, PgColumn>;\n /** The entry's PK columns ON THE OVERLAY, resolved by DB column name (ordered like `pkColumnNames`). */\n overlayPkColumns: PgColumn[];\n /** The entry's PK columns ON THE SYNCED table, resolved by DB column name (ordered like `pkColumnNames`). */\n syncedPkColumns: PgColumn[];\n /** The Server version column ON THE SYNCED table (ADR-0010), or null when the table declares none. */\n syncedServerVersionColumn: PgColumn | null;\n /**\n * Memoized render of the reconcile idle probe (the per-tick hot statement): built once per\n * context so every convergence tick pays only a plain `db.query` of a cached string.\n */\n reconcileIdleProbe?: { sql: string; params: unknown[] };\n}\n\nexport interface MutationRuntime<TRegistry extends SyncTableRegistry> {\n /** The registry fingerprint (ADR-0004) this runtime stamps onto enqueued mutations. */\n registryVersion: string;\n create: <TKey extends SyncTableName<TRegistry>>(\n table: TKey,\n input: SyncTableCreateInput<TRegistry, TKey>,\n ) => Promise<void>;\n update: <TKey extends SyncTableName<TRegistry>>(\n table: TKey,\n entityKey: Record<string, string>,\n patch: SyncTableUpdateInput<TRegistry, TKey>,\n ) => Promise<void>;\n delete: <TKey extends SyncTableName<TRegistry>>(table: TKey, entityKey: Record<string, string>) => Promise<void>;\n /**\n * Enqueue an atomic batch of mutations. An optional {@link WriteUnit} tags every row of the batch as one\n * dynamic write-unit (ADR-0022 §2) — the `transaction({ mode })` block passes it; the per-table\n * `create`/`update`/`delete` helpers do not (their write-mode comes from the static group at flush).\n */\n batch: (items: ReadonlyArray<MutationBatchItem<TRegistry>>, unit?: WriteUnit) => Promise<void>;\n /**\n * Discard a `conflicted` entity (ADR-0015): clear its conflicted journal entries and the kept\n * optimistic Overlay, so the Read model falls back to the synced (server) value. Use when the user\n * abandons their stale edit instead of resolving it as a new write. No-op for an entity with no\n * conflicted entry.\n */\n discardConflict: <TKey extends SyncTableName<TRegistry>>(\n table: TKey,\n entityKey: Record<string, string>,\n ) => Promise<void>;\n /**\n * Discard a `quarantined` entity (ADR-0006): clear its quarantined journal entries and the kept\n * optimistic Overlay, so the Read model falls back to the synced (server) value and the entity\n * accepts new mutations again. The rollback path for a permanently-rejected write (e.g. an RLS\n * policy denial routed to quarantine). Symmetric to {@link discardConflict}. No-op for an entity\n * with no quarantined entry; the overlay is kept when another still-owed write depends on it.\n */\n discardQuarantined: <TKey extends SyncTableName<TRegistry>>(\n table: TKey,\n entityKey: Record<string, string>,\n ) => Promise<void>;\n flush: (table?: SyncTableName<TRegistry>) => Promise<void>;\n /**\n * Flush one pessimistic write-unit (ADR-0022) to the authoritative endpoint and apply its per-mutation\n * result inline: `acked` clears via the synced echo, `conflicted` keeps the overlay (surfaced), and\n * `rejected` auto-discards the overlay for the whole unit (surfaced via `onReject`). A foreground\n * operation — it resolves once the server has decided. Throws on transport failure (the overlay is kept\n * for a retry). Returns the server acks. Used by the client `transaction({ mode: \"pessimistic\" })` block.\n */\n flushUnit: (unitId: string) => Promise<{ acks: MutationAck[] }>;\n reconcile: (table?: SyncTableName<TRegistry>) => Promise<void>;\n retryFailed: (table?: SyncTableName<TRegistry>) => Promise<void>;\n recoverSending: (table?: SyncTableName<TRegistry>) => Promise<void>;\n /**\n * Quarantine EVERY non-terminal journal row recovered from a backup (`pending`/`sending`/`failed` →\n * `quarantined`) — the restore-boot rule (ADR-0035 decision 6). Nothing recovered from a store backup\n * may ever auto-flush: the write path keeps `mutationId` in `operations_log` but never consults it, so\n * there is no dedupe ledger, and a replayed mutation would silently re-apply stale values over newer\n * writes on a last-write-wins table (and a replayed create collides on its PK). Terminal states\n * (`acked`/`conflicted`/`rejected`) are left untouched. Run ONCE, on the restore boot only, AFTER\n * `recoverSending` (which first lifts any `sending` back to `pending`); the app then inspects\n * `diagnostics()` and resolves each row via `discardQuarantined` (quarantine is terminal — \"release\"\n * means discard and re-author as a new mutation) before going online. A no-op on a clean journal.\n */\n quarantineRecovered: (table?: SyncTableName<TRegistry>) => Promise<void>;\n readMutationStats: (table?: SyncTableName<TRegistry>) => Promise<MutationDiagnostics>;\n readMutationDetails: (table?: SyncTableName<TRegistry>) => Promise<MutationDetail[]>;\n createOptimisticRecord: <TKey extends SyncTableName<TRegistry>>(\n table: TKey,\n input: SyncTableCreateInput<TRegistry, TKey>,\n ) => SyncTableRecord<TRegistry, TKey>;\n}\n\nexport function nowMicroseconds(): string {\n return (BigInt(Date.now()) * 1000n).toString();\n}\n\n/**\n * Best-effort decode of a JWT's claims payload, for stamping `authClaim` managed fields into the\n * optimistic overlay (the value the server will independently stamp from the same claim path). This is\n * **not** a verification — the token is trusted only for a local, optimistic projection that the server\n * re-stamps authoritatively on apply; a forged claim could never make the server attribute the row\n * differently. Returns `undefined` for a malformed token.\n */\nexport function decodeJwtClaims(token: string): Record<string, unknown> | undefined {\n const segments = token.split(\".\");\n if (segments.length < 2 || !segments[1]) {\n return undefined;\n }\n try {\n const normalized = segments[1].replace(/-/g, \"+\").replace(/_/g, \"/\");\n const padded = normalized.padEnd(normalized.length + ((4 - (normalized.length % 4)) % 4), \"=\");\n const binary = atob(padded);\n const bytes = Uint8Array.from(binary, (char) => char.charCodeAt(0));\n const payload = JSON.parse(new TextDecoder().decode(bytes)) as unknown;\n return typeof payload === \"object\" && payload !== null ? (payload as Record<string, unknown>) : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Read a claim at a JSON path out of a decoded claims object, returning it as a string (the form the\n * optimistic overlay column expects, mirroring the server's `jsonb #>>` text extraction). Returns\n * `undefined` if the path is absent or the leaf is not a string/number.\n */\nexport function readJwtClaimPath(claims: Record<string, unknown>, claimPath: string[]): string | undefined {\n let cursor: unknown = claims;\n for (const segment of claimPath) {\n if (typeof cursor !== \"object\" || cursor === null) {\n return undefined;\n }\n cursor = (cursor as Record<string, unknown>)[segment];\n }\n if (typeof cursor === \"string\") {\n return cursor;\n }\n return typeof cursor === \"number\" ? String(cursor) : undefined;\n}\n\nexport function computeBackoffDelayMs(attemptCount: number) {\n const exponent = Math.max(attemptCount - 1, 0);\n return Math.min(1000 * 2 ** exponent, 30_000);\n}\n\n/**\n * Retry delay with equal jitter around the {@link computeBackoffDelayMs} ceiling: half\n * the ceiling plus a random share of the other half. Spreads retries so a fleet of\n * clients does not stampede the server in lockstep after an outage (ADR-0005 congestion\n * policy). `random` is injectable for deterministic tests.\n */\nexport function computeRetryDelayMs(attemptCount: number, random: () => number = Math.random) {\n const ceiling = computeBackoffDelayMs(attemptCount);\n return Math.round(ceiling / 2 + random() * (ceiling / 2));\n}\n\nexport function computeNextRetryAtUs(nowUs: string, attemptCount: number, random: () => number = Math.random) {\n return (BigInt(nowUs) + BigInt(computeRetryDelayMs(attemptCount, random)) * 1000n).toString();\n}\n\nexport function createMutationRuntime<TRegistry extends SyncTableRegistry>(\n options: CreateMutationRuntimeOptions<TRegistry>,\n): MutationRuntime<TRegistry> {\n const resolveAuthToken = async () => {\n if (options.getAuthToken) {\n return await options.getAuthToken();\n }\n\n return undefined;\n };\n\n // The decoded JWT claims for stamping `authClaim` create-managed fields into the optimistic overlay\n // (the same value the server stamps from the same claim path). Resolved only when a create needs it\n // (a table with such a field), so tokenless registries never pay a token lookup.\n const resolveAuthClaims = async (): Promise<Record<string, unknown> | undefined> => {\n const token = await resolveAuthToken();\n return token ? decodeJwtClaims(token) : undefined;\n };\n\n const tableContexts = buildTableContexts(options.registry);\n const maxMutationAttempts = options.maxMutationAttempts ?? DEFAULT_MAX_MUTATION_ATTEMPTS;\n const flushBatchSize = options.flushBatchSize ?? DEFAULT_FLUSH_BATCH_SIZE;\n // The fingerprint (ADR-0004) stamped onto each enqueued mutation (ADR-0006). The runtime\n // owns the registry, so it derives this itself; an explicit override is honoured for tests.\n const registryVersion = options.registryVersion ?? fingerprintRegistry(options.registry);\n let flushQueue = Promise.resolve();\n\n const getTableContext = (table: SyncTableName<TRegistry>) => {\n const context = tableContexts[table];\n\n if (!context) {\n throw new Error(`Unknown mutation table: ${String(table)}`);\n }\n\n return context;\n };\n\n const runInTransaction = async (operation: () => Promise<void>) => {\n await options.db.exec(\"BEGIN\");\n\n try {\n await operation();\n await options.db.exec(\"COMMIT\");\n } catch (error) {\n await options.db.exec(\"ROLLBACK\");\n throw error;\n }\n };\n\n const normalizeBatchItem = (\n item: MutationBatchItem<TRegistry>,\n order: number,\n claims: Record<string, unknown> | undefined,\n ): NormalizedBatchItem => {\n const context = getTableContext(item.table as SyncTableName<TRegistry>);\n const mutationId = globalThis.crypto.randomUUID();\n const nowUs = nowMicroseconds();\n\n switch (item.kind) {\n case \"create\": {\n const strippedInput = stripReadModelOverlayFields(item.input);\n const optimisticRecord = ensureRecord(createOptimisticRecordFromContext(context, strippedInput, claims));\n const entityKey = buildEntityKeyFromRecord(context, optimisticRecord);\n\n return {\n context,\n kind: \"create\",\n entityKey,\n entityKeyJson: serializeEntityKey(entityKey),\n optimisticRecord,\n input: strippedInput,\n mutationId,\n nowUs,\n order,\n };\n }\n case \"update\": {\n const entityKey = normalizeEntityKey(context, item.entityKey);\n const patch = ensureRecord(stripReadModelOverlayFields(item.patch));\n\n return {\n context,\n kind: \"update\",\n entityKey,\n entityKeyJson: serializeEntityKey(entityKey),\n patch,\n blind: item.blind ?? false,\n mutationId,\n nowUs,\n order,\n };\n }\n case \"delete\": {\n const entityKey = normalizeEntityKey(context, item.entityKey);\n\n return {\n context,\n kind: \"delete\",\n entityKey,\n entityKeyJson: serializeEntityKey(entityKey),\n mutationId,\n nowUs,\n order,\n };\n }\n }\n };\n\n const enqueueBatch = async (\n items: ReadonlyArray<MutationBatchItem<TRegistry>>,\n unit?: WriteUnit,\n ): Promise<string[]> => {\n if (items.length === 0) {\n return [];\n }\n\n // The distinct pessimistic write-unit ids this enqueue tagged — returned so the caller can\n // foreground-route them to the authoritative endpoint (ADR-0022). Empty for a purely optimistic batch.\n const pessimisticUnitIds = new Set<string>();\n\n // Resolve the decoded claims once per batch, but only if a create actually needs them (a target\n // table with an `authClaim` create-managed field). Avoids a token lookup for every other write.\n const needsAuthClaims = items.some(\n (item) =>\n item.kind === \"create\" &&\n getTableContext(item.table as SyncTableName<TRegistry>).managedAuthClaimCreateFields.length > 0,\n );\n const claims = needsAuthClaims ? await resolveAuthClaims() : undefined;\n\n const normalizedItems = items.map((item, index) => normalizeBatchItem(item, index, claims));\n\n // ADR-0039: report the DISTINCT non-blind table keys so the client can fire-and-forget activate\n // each target's lazy consistency group. A blind update plans a journal row only (no echo, no\n // activation — the write-only pattern), so it is never reported; create/delete are never blind.\n const ordinaryTables = new Set<string>();\n for (const item of normalizedItems) {\n if (item.kind === \"update\" && item.blind) {\n continue;\n }\n ordinaryTables.add(item.context.key);\n }\n if (ordinaryTables.size > 0 && options.onOrdinaryEnqueue) {\n try {\n options.onOrdinaryEnqueue([...ordinaryTables]);\n } catch {\n // A hook throw must never fail the enqueue (ADR-0039): the activation is a fire-and-forget\n // best-effort; the group self-heals on its next activation regardless.\n }\n }\n\n const batchGroups = new Map<string, { context: TableContext; items: NormalizedBatchItem[] }>();\n\n for (const item of normalizedItems) {\n const existing = batchGroups.get(item.context.key);\n\n if (existing) {\n existing.items.push(item);\n continue;\n }\n\n batchGroups.set(item.context.key, {\n context: item.context,\n items: [item],\n });\n }\n\n for (const { context, items: groupedItems } of batchGroups.values()) {\n groupedItems.sort((left, right) => left.order - right.order);\n const uniqueEntities = dedupeBatchEntities(groupedItems);\n const latestMutationStates = await readLatestMutationStates(options.db, context, uniqueEntities);\n const currentRecordStates = await readCurrentRecordStates(options.db, context, uniqueEntities);\n const entityStates = new Map<string, BatchEntityState>();\n\n for (const entity of uniqueEntities) {\n const latestState = latestMutationStates.get(entity.entityKeyJson);\n const currentState = currentRecordStates.get(entity.entityKeyJson);\n\n entityStates.set(entity.entityKeyJson, {\n entityKey: entity.entityKey,\n entityKeyJson: entity.entityKeyJson,\n record: currentState ? extractRecordFromState(context, currentState) : null,\n overlayKind: currentState?.overlayKind ?? null,\n localUpdatedAtUs: currentState?.localUpdatedAtUs ?? null,\n latestMutationSeq: latestState?.latestMutationSeq ?? null,\n latestMutationKind: latestState?.latestMutationKind ?? null,\n latestMutationStatus: latestState?.latestMutationStatus ?? null,\n });\n }\n\n const plannedMutations: PlannedMutationInsert[] = [];\n const plannedOverlays = new Map<string, PlannedOverlayUpsert>();\n\n for (const item of groupedItems) {\n const entityState = entityStates.get(item.entityKeyJson);\n\n if (!entityState) {\n throw new Error(`Missing batch state for table ${context.key}`);\n }\n\n switch (item.kind) {\n case \"create\": {\n if ((entityState.latestMutationSeq ?? 0) !== 0) {\n throw new Error(`${context.key} already has queued mutations`);\n }\n\n plannedMutations.push({\n mutationId: item.mutationId,\n entityKey: item.entityKey,\n entityKeyJson: item.entityKeyJson,\n mutationKind: \"create\",\n payloadJson: jsonStringifyPayload({\n kind: \"create\",\n value: item.input,\n }),\n nowUs: item.nowUs,\n // A create has no Base server version (ADR-0015): its conflict is a PK collision, a\n // separate concern from the stale-write check.\n baseServerVersion: null,\n });\n\n entityState.record = item.optimisticRecord;\n entityState.overlayKind = \"pending_create\";\n entityState.localUpdatedAtUs = item.nowUs;\n entityState.latestMutationSeq = (entityState.latestMutationSeq ?? 0) + 1;\n entityState.latestMutationKind = \"create\";\n entityState.latestMutationStatus = \"pending\";\n plannedOverlays.set(item.entityKeyJson, {\n entityKey: item.entityKey,\n record: item.optimisticRecord,\n overlayKind: \"pending_create\",\n localUpdatedAtUs: item.nowUs,\n });\n break;\n }\n case \"update\": {\n if (item.blind) {\n // ADR-0022 addendum — a BLIND update: the write target is excluded from the actor's read\n // shape (its rows never stream here), so there is no local base row to seed and no optimistic\n // state to show. It is meaningful ONLY when the write routes to the authoritative endpoint (the\n // /unit expander is authoritative): an optimistic-routed blind write has nothing to converge, so\n // it is rejected at enqueue. The `unit` fixes the route inside a `transaction` block; a plain\n // enqueue on a statically-pessimistic table earns its own pessimistic unit downstream.\n const routesPessimistic = unit ? unit.mode === \"pessimistic\" : context.entry.writeMode === \"pessimistic\";\n if (!routesPessimistic) {\n throw new Error(\n `${context.key}: updateBlind requires a pessimistic write unit — use transaction({ mode: \"pessimistic\" }) (an optimistic blind write has nothing to show and no base to converge)`,\n );\n }\n\n // KEEP the already-queued-for-deletion guard (journal-derived; needs no local record).\n if (entityState.latestMutationKind === \"delete\" && entityState.latestMutationStatus !== \"acked\") {\n throw new Error(`${context.key} is already queued for deletion`);\n }\n\n // Plan a journal row ONLY — no overlay, so nothing enters the read model and nothing can linger\n // there. `baseServerVersion: null`: the /unit expander is authoritative, there is no base to\n // capture. The `pessimistic-blind` marker keeps the row off the optimistic flusher and lets\n // reconcile retire it after ack WITHOUT a synced echo (there is no visible row to converge).\n plannedMutations.push({\n mutationId: item.mutationId,\n entityKey: item.entityKey,\n entityKeyJson: item.entityKeyJson,\n mutationKind: \"update\",\n payloadJson: jsonStringifyPayload({\n kind: \"update\",\n patch: item.patch,\n }),\n nowUs: item.nowUs,\n baseServerVersion: null,\n writeMode: \"pessimistic-blind\",\n });\n\n // Advance only the journal-derived tracking (no record/overlay): so a later same-batch item on\n // this entity chains in author order and sees the pending blind write.\n entityState.latestMutationSeq = (entityState.latestMutationSeq ?? 0) + 1;\n entityState.latestMutationKind = \"update\";\n entityState.latestMutationStatus = \"pending\";\n break;\n }\n\n if (!entityState.record) {\n throw new Error(`${context.key} not found in local read model`);\n }\n\n if (entityState.latestMutationKind === \"delete\" && entityState.latestMutationStatus !== \"acked\") {\n throw new Error(`${context.key} is already queued for deletion`);\n }\n\n // ADR-0015: capture the Base server version BEFORE the record is replaced by the\n // optimistic value below (which overwrites the Server version with the client clock).\n const updateBaseServerVersion = captureChainHeadBase(context, entityState);\n const overlayKind = entityState.overlayKind === \"pending_create\" ? \"pending_create\" : \"pending_update\";\n const optimisticRecord = ensureRecord(\n buildOptimisticRecord(\n context,\n {\n ...entityState.record,\n ...item.patch,\n // Re-stamp the on-update managed timestamp(s) generically (governance-driven) — for a\n // convention table this is exactly `updatedAtUs`, for a custom-named Server version\n // it is that column, so the optimistic row never carries a stale managed value.\n ...buildUpdateManagedNowStamp(context, item.nowUs),\n },\n {\n overlayKind,\n localUpdatedAtUs: item.nowUs,\n },\n ),\n );\n plannedMutations.push({\n mutationId: item.mutationId,\n entityKey: item.entityKey,\n entityKeyJson: item.entityKeyJson,\n mutationKind: \"update\",\n payloadJson: jsonStringifyPayload({\n kind: \"update\",\n patch: item.patch,\n }),\n nowUs: item.nowUs,\n baseServerVersion: updateBaseServerVersion,\n });\n\n entityState.record = optimisticRecord;\n entityState.overlayKind = overlayKind;\n entityState.localUpdatedAtUs = item.nowUs;\n entityState.latestMutationSeq = (entityState.latestMutationSeq ?? 0) + 1;\n entityState.latestMutationKind = \"update\";\n entityState.latestMutationStatus = \"pending\";\n plannedOverlays.set(item.entityKeyJson, {\n entityKey: item.entityKey,\n record: optimisticRecord,\n overlayKind,\n localUpdatedAtUs: item.nowUs,\n });\n break;\n }\n case \"delete\": {\n if (!entityState.record) {\n throw new Error(`${context.key} not found in local read model`);\n }\n\n if (entityState.latestMutationKind === \"delete\" && entityState.latestMutationStatus !== \"acked\") {\n throw new Error(`${context.key} is already queued for deletion`);\n }\n\n const deleteBaseServerVersion = captureChainHeadBase(context, entityState);\n plannedMutations.push({\n mutationId: item.mutationId,\n entityKey: item.entityKey,\n entityKeyJson: item.entityKeyJson,\n mutationKind: \"delete\",\n payloadJson: jsonStringifyPayload({\n kind: \"delete\",\n entityKey: item.entityKey,\n }),\n nowUs: item.nowUs,\n baseServerVersion: deleteBaseServerVersion,\n });\n\n entityState.overlayKind = \"pending_delete\";\n entityState.localUpdatedAtUs = item.nowUs;\n entityState.latestMutationSeq = (entityState.latestMutationSeq ?? 0) + 1;\n entityState.latestMutationKind = \"delete\";\n entityState.latestMutationStatus = \"pending\";\n plannedOverlays.set(item.entityKeyJson, {\n entityKey: item.entityKey,\n record: entityState.record,\n overlayKind: \"pending_delete\",\n localUpdatedAtUs: item.nowUs,\n });\n break;\n }\n }\n }\n\n // ADR-0022: an explicit unit (from a `transaction` block) tags the whole batch; otherwise a\n // statically-`pessimistic` table earns its own per-enqueue unit, so its writes route to the\n // authoritative endpoint too. An optimistic table with no explicit unit stays untagged.\n const effectiveUnit: WriteUnit | undefined =\n unit ??\n (context.entry.writeMode === \"pessimistic\"\n ? { id: globalThis.crypto.randomUUID(), mode: \"pessimistic\" }\n : undefined);\n if (effectiveUnit?.mode === \"pessimistic\") {\n pessimisticUnitIds.add(effectiveUnit.id);\n }\n await insertMutationsBulk(options.db, context, plannedMutations, registryVersion, effectiveUnit);\n await upsertOverlayRecordsBulk(options.db, context, [...plannedOverlays.values()]);\n }\n\n return [...pessimisticUnitIds];\n };\n\n const runFlush = async (table?: SyncTableName<TRegistry>) => {\n const affectedContexts = new Map<string, TableContext>();\n const quarantinedMutationIds = new Set<string>();\n const conflictedMutationIds = new Set<string>();\n let processedCount = 0;\n\n do {\n const batchResult = await flushBatch(\n options.db,\n tableContexts as Record<string, TableContext>,\n options.writeUrl,\n maxMutationAttempts,\n flushBatchSize,\n table,\n resolveAuthToken,\n options.requestHeaders,\n );\n\n processedCount = batchResult.processedCount;\n\n for (const context of batchResult.affectedContexts) {\n affectedContexts.set(context.key, context);\n }\n\n for (const mutationId of batchResult.quarantinedMutationIds) {\n quarantinedMutationIds.add(mutationId);\n }\n\n for (const mutationId of batchResult.conflictedMutationIds) {\n conflictedMutationIds.add(mutationId);\n }\n } while (processedCount > 0);\n\n for (const context of affectedContexts.values()) {\n await reconcileTable(options.db, context);\n }\n\n // Surface newly-quarantined mutations after reconciliation so the app never has to\n // poll for permanently-rejected writes (ADR-0006 decision 4). Never silent loss.\n if (quarantinedMutationIds.size > 0 && options.onQuarantine) {\n const details = await readMutationDetailsForContexts(\n options.db,\n [...affectedContexts.values()],\n quarantinedMutationIds,\n );\n\n if (details.length > 0) {\n await options.onQuarantine(details);\n }\n }\n\n // Surface newly-conflicted (stale) writes (ADR-0015). The optimistic Overlay is kept, so the app\n // can show a resolution/diff UI and resolve each as a new write (or discard it). Never silent.\n if (conflictedMutationIds.size > 0 && options.onConflict) {\n const details = await readMutationDetailsForContexts(\n options.db,\n [...affectedContexts.values()],\n conflictedMutationIds,\n );\n\n if (details.length > 0) {\n await options.onConflict(details);\n }\n }\n };\n\n const runtime: MutationRuntime<TRegistry> = {\n registryVersion,\n create: async (table, input) => {\n let unitIds: string[] = [];\n await runInTransaction(async () => {\n unitIds = await enqueueBatch([{ table, kind: \"create\", input }]);\n });\n // A statically-`pessimistic` table foreground-routes its write to the authoritative endpoint\n // (ADR-0022) — the write is server-authoritative, so it is sent immediately, not left for the\n // optimistic convergence loop (which skips pessimistic rows).\n for (const unitId of unitIds) {\n await runtime.flushUnit(unitId);\n }\n },\n update: async (table, entityKeyInput, patch) => {\n let unitIds: string[] = [];\n await runInTransaction(async () => {\n unitIds = await enqueueBatch([{ table, kind: \"update\", entityKey: entityKeyInput, patch }]);\n });\n for (const unitId of unitIds) {\n await runtime.flushUnit(unitId);\n }\n },\n delete: async (table, entityKeyInput) => {\n let unitIds: string[] = [];\n await runInTransaction(async () => {\n unitIds = await enqueueBatch([{ table, kind: \"delete\", entityKey: entityKeyInput }]);\n });\n for (const unitId of unitIds) {\n await runtime.flushUnit(unitId);\n }\n },\n batch: async (items, unit) => {\n let unitIds: string[] = [];\n await runInTransaction(async () => {\n unitIds = await enqueueBatch(items, unit);\n });\n // An explicit unit (from a `transaction` block) is flushed by the caller; only foreground-route the\n // units a plain `batch()` generated for statically-pessimistic tables.\n if (!unit) {\n for (const unitId of unitIds) {\n await runtime.flushUnit(unitId);\n }\n }\n },\n discardConflict: async (table, entityKeyInput) => {\n const context = getTableContext(table);\n const entityKey = normalizeEntityKey(context, entityKeyInput);\n const entityKeyJson = serializeEntityKey(entityKey);\n\n // discardTerminalEntity owns its own transaction (like reconcileTable), so it is not wrapped.\n await discardTerminalEntity(options.db, context, entityKey, entityKeyJson, \"conflicted\");\n },\n discardQuarantined: async (table, entityKeyInput) => {\n const context = getTableContext(table);\n const entityKey = normalizeEntityKey(context, entityKeyInput);\n const entityKeyJson = serializeEntityKey(entityKey);\n\n // Symmetric to discardConflict — retire the entity's `quarantined` journal rows and clear the\n // kept overlay behind the same owed-guard, so a permanently-rejected write is a real rollback.\n await discardTerminalEntity(options.db, context, entityKey, entityKeyJson, \"quarantined\");\n },\n flush: async (table) => {\n const nextFlush = flushQueue.then(() => runFlush(table));\n flushQueue = nextFlush.catch(() => undefined);\n await nextFlush;\n },\n flushUnit: async (unitId) => {\n const contexts = Object.values(tableContexts).filter((context): context is TableContext => context != null);\n const unitRows = await readUnitPendingRows(options.db, contexts, unitId);\n if (unitRows.length === 0) {\n return { acks: [] };\n }\n\n // Prepare the unit's rows (entity key + envelope payload) and group them by table.\n const prepared: PreparedBatchRow[] = [];\n const byContext = new Map<string, PreparedBatchRow[]>();\n for (const row of unitRows) {\n const context = tableContexts[row.tableKey];\n if (!context) {\n continue;\n }\n const entityKey = JSON.parse(row.entityKeyJson) as Record<string, string>;\n const rawPayload = JSON.parse(row.payloadJson) as Record<string, unknown>;\n const preparedRow: PreparedBatchRow = {\n ...row,\n context,\n entityKey,\n envelopePayload:\n row.mutationKind === \"delete\"\n ? entityKey\n : toSqlColumnPayload(\n context,\n stripManagedFields(\n context,\n (rawPayload[\"value\"] ?? rawPayload[\"patch\"] ?? rawPayload) as Record<string, unknown>,\n row.mutationKind as \"create\" | \"update\",\n ),\n ),\n sqlTableName: context.entry.shape?.tableName ?? context.key,\n };\n prepared.push(preparedRow);\n const list = byContext.get(context.key);\n if (list) {\n list.push(preparedRow);\n } else {\n byContext.set(context.key, [preparedRow]);\n }\n }\n\n // Mark every member sending (persist the resolved Base server version, like the batch path).\n const sentAtUs = nowMicroseconds();\n for (const rows of byContext.values()) {\n await applyMutationStatusUpdates(\n options.db,\n rows[0]!.context,\n rows.map((row) => ({\n mutationId: row.mutationId,\n status: \"sending\" as const,\n attemptCount: row.attemptCount + 1,\n updatedAtUs: sentAtUs,\n sentAtUs,\n replaceSentAtUs: true,\n baseServerVersion: row.baseServerVersion,\n replaceBaseServerVersion: true,\n lastError: null,\n nextRetryAtUs: null,\n lastHttpStatus: null,\n conflictReason: null,\n })),\n );\n }\n\n const mutations = prepared.map((row) => ({\n tableName: row.sqlTableName,\n entityKey: row.entityKey,\n mutationId: row.mutationId,\n mutationSeq: row.mutationSeq,\n kind: row.mutationKind as \"create\" | \"update\" | \"delete\",\n payload: row.envelopePayload,\n clientTimestampUs: sentAtUs,\n ...(row.baseServerVersion != null ? { baseServerVersion: row.baseServerVersion } : {}),\n }));\n\n const url = resolveAuthoritativeMutationUrl(options.writeUrl);\n let acksByMutationId: Map<string, BatchMutationAck[\"acks\"][number]>;\n\n try {\n const authToken = await options.getAuthToken?.();\n let response = await fetch(url, {\n method: \"POST\",\n headers: buildRequestHeaders(authToken, options.requestHeaders),\n body: jsonStringifyPayload({ writeUnit: unitId, mutations }),\n });\n\n if ([401, 403].includes(response.status) && options.getAuthToken) {\n response = await fetch(url, {\n method: \"POST\",\n headers: buildRequestHeaders(await options.getAuthToken(), options.requestHeaders),\n body: jsonStringifyPayload({ writeUnit: unitId, mutations }),\n });\n }\n\n if (!response.ok) {\n const text = await response.text();\n throw new MutationRequestError(\n text.length > 0 ? text : `Authoritative write responded with ${response.status}`,\n response.status,\n parseBatchRejections(text),\n );\n }\n\n const responseJson = (await response.json()) as BatchMutationAck;\n acksByMutationId = new Map(responseJson.acks.map((ack) => [ack.mutationId, ack]));\n } catch (error) {\n // A pessimistic write is foreground: it never reached the server (transport / non-2xx), so the\n // unit did not happen. Mark it failed — KEEPING the optimistic overlay so a retry can resend — and\n // rethrow so the caller surfaces it. There is no background retry for pessimistic units.\n const failedAtUs = nowMicroseconds();\n const httpStatus = error instanceof MutationRequestError ? error.status : null;\n const errorMessage = error instanceof Error ? error.message : \"Authoritative write failed\";\n for (const rows of byContext.values()) {\n await applyMutationStatusUpdates(\n options.db,\n rows[0]!.context,\n rows.map((row) => {\n const attemptCount = row.attemptCount + 1;\n const outcome = resolveBatchFailureOutcome(attemptCount, maxMutationAttempts, failedAtUs);\n return {\n mutationId: row.mutationId,\n status: outcome.status,\n attemptCount,\n updatedAtUs: failedAtUs,\n lastError: errorMessage,\n nextRetryAtUs: outcome.nextRetryAtUs,\n lastHttpStatus: httpStatus,\n conflictReason: null,\n };\n }),\n );\n }\n throw error;\n }\n\n // Apply each member's ack.\n const ackedAtUs = nowMicroseconds();\n const failedAtUs = nowMicroseconds();\n const rejectedIds = new Set<string>();\n const conflictedIds = new Set<string>();\n\n for (const rows of byContext.values()) {\n await applyMutationStatusUpdates(\n options.db,\n rows[0]!.context,\n rows.map((row) => {\n const ack = acksByMutationId.get(row.mutationId);\n\n if (ack?.status === \"rejected\") {\n // ADR-0022 §4: a business rejection. Terminal `rejected`; the overlay is auto-discarded below.\n rejectedIds.add(row.mutationId);\n return {\n mutationId: row.mutationId,\n status: \"rejected\" as const,\n attemptCount: row.attemptCount + 1,\n updatedAtUs: failedAtUs,\n lastError: ack.rejectionReason ?? \"Rejected by the authoritative endpoint\",\n nextRetryAtUs: null,\n lastHttpStatus: ack.httpStatus ?? 409,\n conflictReason: ack.rejectionReason ?? \"Rejected by the authoritative endpoint\",\n };\n }\n\n if (ack?.status === \"conflicted\") {\n // ADR-0015: a stale member — terminal `conflicted`, overlay KEPT (resolve as a new write).\n conflictedIds.add(row.mutationId);\n return {\n mutationId: row.mutationId,\n status: \"conflicted\" as const,\n attemptCount: row.attemptCount + 1,\n updatedAtUs: failedAtUs,\n serverUpdatedAtUs: ack.serverUpdatedAtUs ?? null,\n replaceServerUpdatedAtUs: true,\n lastError: ack.conflictReason ?? \"Stale write rejected (reject-if-stale)\",\n nextRetryAtUs: null,\n lastHttpStatus: ack.httpStatus ?? 409,\n conflictReason: ack.conflictReason ?? \"Stale write rejected (reject-if-stale)\",\n };\n }\n\n if (!ack || ack.status !== \"acked\") {\n const attemptCount = row.attemptCount + 1;\n const outcome = resolveFailureOutcome(\n ack?.httpStatus ?? null,\n attemptCount,\n maxMutationAttempts,\n failedAtUs,\n );\n return {\n mutationId: row.mutationId,\n status: outcome.status,\n attemptCount,\n updatedAtUs: failedAtUs,\n lastError: ack?.conflictReason ?? \"Authoritative write not acknowledged\",\n nextRetryAtUs: outcome.nextRetryAtUs,\n lastHttpStatus: ack?.httpStatus ?? null,\n conflictReason: null,\n };\n }\n\n return {\n mutationId: row.mutationId,\n status: \"acked\" as const,\n attemptCount: row.attemptCount + 1,\n updatedAtUs: ackedAtUs,\n ackedAtUs,\n replaceAckedAtUs: true,\n serverUpdatedAtUs: ack.serverUpdatedAtUs ?? null,\n replaceServerUpdatedAtUs: true,\n lastError: null,\n nextRetryAtUs: null,\n lastHttpStatus: row.mutationKind === \"delete\" ? 204 : 200,\n conflictReason: null,\n };\n }),\n );\n }\n\n // ADR-0022 §4: auto-discard the optimistic overlay for every rejected entity (the whole unit was\n // declined). The terminal `rejected` journal row is kept for diagnostics + `onReject`.\n for (const row of prepared) {\n if (rejectedIds.has(row.mutationId)) {\n await discardOverlayForSettledEntity(options.db, row.context, row.entityKey, row.entityKeyJson);\n }\n }\n\n const affectedContexts = [...byContext.keys()]\n .map((key) => tableContexts[key])\n .filter((context): context is TableContext => context != null);\n for (const context of affectedContexts) {\n await reconcileTable(options.db, context);\n }\n\n if (rejectedIds.size > 0 && options.onReject) {\n const details = await readMutationDetailsForContexts(options.db, affectedContexts, rejectedIds);\n if (details.length > 0) {\n await options.onReject(details);\n }\n }\n if (conflictedIds.size > 0 && options.onConflict) {\n const details = await readMutationDetailsForContexts(options.db, affectedContexts, conflictedIds);\n if (details.length > 0) {\n await options.onConflict(details);\n }\n }\n\n return { acks: [...acksByMutationId.values()] };\n },\n reconcile: async (table) => {\n const contexts = filterContexts(tableContexts, table);\n\n for (const context of contexts) {\n await reconcileTable(options.db, context);\n }\n },\n retryFailed: async (table) => {\n assertValidMutationTransition(\"failed\", \"pending\");\n const contexts = filterContexts(tableContexts, table);\n const nowUs = nowMicroseconds();\n\n for (const context of contexts) {\n const journal = context.tables.journal;\n const query = queryBuilder\n .update(journal)\n .set({ status: \"pending\", nextRetryAtUs: nowUs, updatedAtUs: nowUs, conflictReason: null })\n .where(eq(journal.status, \"failed\"))\n .toSQL();\n await options.db.query(query.sql, query.params as unknown[]);\n }\n },\n recoverSending: async (table) => {\n assertValidMutationTransition(\"sending\", \"pending\");\n const contexts = filterContexts(tableContexts, table);\n const nowUs = nowMicroseconds();\n\n for (const context of contexts) {\n const journal = context.tables.journal;\n const query = queryBuilder\n .update(journal)\n .set({\n status: \"pending\",\n updatedAtUs: nowUs,\n sentAtUs: null,\n nextRetryAtUs: nowUs,\n lastError: null,\n lastHttpStatus: null,\n conflictReason: null,\n })\n .where(eq(journal.status, \"sending\"))\n .toSQL();\n await options.db.query(query.sql, query.params as unknown[]);\n }\n },\n quarantineRecovered: async (table) => {\n // The restore-boot quarantine (ADR-0035 decision 6): every non-terminal recovered row is parked in the\n // terminal `quarantined` state so NOTHING recovered from a backup auto-flushes (no dedupe ledger →\n // unsafe replay). `pending -> quarantined` is a restore-only edge (see mutation-state.ts); `sending`\n // and `failed` already reach quarantine. Assert all three edges up front so a future transition-table\n // change that breaks restore fails loudly here rather than silently skipping the quarantine.\n assertValidMutationTransition(\"pending\", \"quarantined\");\n assertValidMutationTransition(\"sending\", \"quarantined\");\n assertValidMutationTransition(\"failed\", \"quarantined\");\n const contexts = filterContexts(tableContexts, table);\n const nowUs = nowMicroseconds();\n\n for (const context of contexts) {\n const journal = context.tables.journal;\n const query = queryBuilder\n .update(journal)\n .set({\n status: \"quarantined\",\n updatedAtUs: nowUs,\n // Terminal: never retried, so clear the retry cursor and name restore as the cause on the row so\n // an inspecting app can tell a restore-quarantined write from a server-rejected one.\n nextRetryAtUs: null,\n lastError: \"Quarantined on restore: recovered from a store backup, not replayed (ADR-0035).\",\n conflictReason: null,\n })\n .where(inArray(journal.status, [\"pending\", \"sending\", \"failed\"]))\n .toSQL();\n await options.db.query(query.sql, query.params as unknown[]);\n }\n },\n readMutationStats: async (table) => {\n const contexts = filterContexts(tableContexts, table);\n const totals: MutationDiagnostics = {\n pendingCount: 0,\n sendingCount: 0,\n failedCount: 0,\n quarantinedCount: 0,\n conflictedCount: 0,\n ackedCount: 0,\n };\n\n for (const context of contexts) {\n const journal = context.tables.journal;\n // Drizzle has no `FILTER` operator (tier ②): each aggregate is a typed `sql` fragment over the\n // journal `status` column object with a bound status literal, aliased to the exact camelCase row\n // key the totals below read (the raw seam returns rows UNMAPPED, so aliases are load-bearing).\n const filteredCount = (status: MutationStatus, columnAlias: string) =>\n sql<number>`count(*) filter (where ${journal.status} = ${status})::int`.as(columnAlias);\n const query = queryBuilder\n .select({\n pendingCount: filteredCount(\"pending\", \"pendingCount\"),\n sendingCount: filteredCount(\"sending\", \"sendingCount\"),\n failedCount: filteredCount(\"failed\", \"failedCount\"),\n quarantinedCount: filteredCount(\"quarantined\", \"quarantinedCount\"),\n conflictedCount: filteredCount(\"conflicted\", \"conflictedCount\"),\n ackedCount: filteredCount(\"acked\", \"ackedCount\"),\n })\n .from(journal)\n .toSQL();\n const result = await options.db.query<MutationDiagnostics & Record<string, unknown>>(\n query.sql,\n query.params as unknown[],\n );\n\n const row = result.rows[0];\n if (!row) {\n continue;\n }\n\n totals.pendingCount += row.pendingCount;\n totals.sendingCount += row.sendingCount;\n totals.failedCount += row.failedCount;\n totals.quarantinedCount += row.quarantinedCount;\n totals.conflictedCount += row.conflictedCount;\n totals.ackedCount += row.ackedCount;\n }\n\n return totals;\n },\n readMutationDetails: async (table) => {\n const contexts = filterContexts(tableContexts, table);\n return readMutationDetailsForContexts(options.db, contexts);\n },\n createOptimisticRecord: (table, input) => {\n const context = getTableContext(table);\n return createOptimisticRecordFromContext(context, input);\n },\n };\n\n return runtime;\n}\n\n/**\n * Read journal entries across the given contexts as {@link MutationDetail}s, newest first.\n * Shared by the public `readMutationDetails` and the flush path's quarantine surfacing,\n * optionally narrowed to a set of mutation ids.\n */\nasync function readMutationDetailsForContexts(\n db: MutationDb,\n contexts: TableContext[],\n mutationIds?: ReadonlySet<string>,\n): Promise<MutationDetail[]> {\n const rows: MutationDetail[] = [];\n\n for (const context of contexts) {\n const journal = context.tables.journal;\n // The raw seam returns rows UNMAPPED (no drizzle result mapping), so every field is aliased\n // explicitly to its camelCase row key, and the `_us` bigints keep their `::text` casts.\n const query = queryBuilder\n .select({\n mutationId: sql<string>`${journal.mutationId}`.as(\"mutationId\"),\n entityKeyJson: sql<string>`${journal.entityKeyJson}`.as(\"entityKeyJson\"),\n mutationSeq: sql<number>`${journal.mutationSeq}`.as(\"mutationSeq\"),\n mutationKind: sql<MutationKind>`${journal.mutationKind}`.as(\"mutationKind\"),\n status: journal.status,\n attemptCount: sql<number>`${journal.attemptCount}`.as(\"attemptCount\"),\n lastHttpStatus: sql<number | null>`${journal.lastHttpStatus}`.as(\"lastHttpStatus\"),\n lastError: sql<string | null>`${journal.lastError}`.as(\"lastError\"),\n conflictReason: sql<string | null>`${journal.conflictReason}`.as(\"conflictReason\"),\n nextRetryAtUs: sql<string | null>`${journal.nextRetryAtUs}::text`.as(\"nextRetryAtUs\"),\n serverUpdatedAtUs: sql<string | null>`${journal.serverUpdatedAtUs}::text`.as(\"serverUpdatedAtUs\"),\n updatedAtUs: sql<string>`${journal.updatedAtUs}::text`.as(\"updatedAtUs\"),\n registryVersion: sql<string | null>`${journal.registryVersion}`.as(\"registryVersion\"),\n })\n .from(journal)\n .orderBy(desc(journal.updatedAtUs), desc(journal.mutationSeq))\n .toSQL();\n const result = await db.query<MutationDetailRow>(query.sql, query.params as unknown[]);\n\n for (const row of result.rows) {\n if (mutationIds && !mutationIds.has(row.mutationId)) {\n continue;\n }\n\n rows.push({\n tableName: context.key,\n entityKey: JSON.parse(row.entityKeyJson) as Record<string, string>,\n mutationId: row.mutationId,\n mutationSeq: row.mutationSeq,\n mutationKind: row.mutationKind,\n status: row.status,\n attemptCount: row.attemptCount,\n lastHttpStatus: row.lastHttpStatus,\n lastError: row.lastError,\n conflictReason: row.conflictReason,\n nextRetryAtUs: row.nextRetryAtUs,\n serverUpdatedAtUs: row.serverUpdatedAtUs,\n updatedAtUs: row.updatedAtUs,\n registryVersion: row.registryVersion,\n });\n }\n }\n\n return rows.sort((left, right) => Number(right.updatedAtUs) - Number(left.updatedAtUs));\n}\n\ninterface MutationRow extends Record<string, unknown> {\n mutationId: string;\n entityKeyJson: string;\n mutationSeq: number;\n mutationKind: MutationKind;\n status: MutationStatus;\n payloadJson: string;\n attemptCount: number;\n lastHttpStatus: number | null;\n lastError: string | null;\n conflictReason: string | null;\n nextRetryAtUs: string | null;\n serverUpdatedAtUs: string | null;\n registryVersion: string | null;\n}\n\ninterface MutationDetailRow extends Record<string, unknown> {\n mutationId: string;\n entityKeyJson: string;\n mutationSeq: number;\n mutationKind: MutationKind;\n status: MutationStatus;\n attemptCount: number;\n lastHttpStatus: number | null;\n lastError: string | null;\n conflictReason: string | null;\n nextRetryAtUs: string | null;\n serverUpdatedAtUs: string | null;\n updatedAtUs: string;\n registryVersion: string | null;\n}\n\ninterface CurrentRecordStateRow extends Record<string, unknown> {\n overlayKind: string;\n localUpdatedAtUs: string;\n latestMutationSeq: number | null;\n latestMutationKind: MutationKind | null;\n latestMutationStatus: MutationStatus | null;\n}\n\ninterface BatchLatestMutationStateRow extends Record<string, unknown> {\n entityKeyJson: string;\n latestMutationSeq: number | null;\n latestMutationKind: MutationKind | null;\n latestMutationStatus: MutationStatus | null;\n}\n\ninterface BatchCurrentRecordStateRow extends Record<string, unknown> {\n entityKeyJson: string;\n overlayKind: string;\n localUpdatedAtUs: string;\n}\n\ninterface BatchEntityRef {\n entityKey: Record<string, string>;\n entityKeyJson: string;\n}\n\ninterface PlannedMutationInsert {\n mutationId: string;\n entityKey: Record<string, string>;\n entityKeyJson: string;\n mutationKind: MutationKind;\n payloadJson: string;\n nowUs: string;\n /**\n * The Base server version (ADR-0015) stamped at enqueue: the synced Server version the user saw,\n * for a **chain head** (the first staged write on the entity). `null` for a `create` (no base) and\n * for a **chained** write — the latter resolves its base at flush from its acked predecessor\n * (readPendingBatchRows), by Per-entity flush serialization (ADR-0014).\n */\n baseServerVersion: string | null;\n /**\n * A per-row `write_mode` override (ADR-0022 addendum). Left unset for an ordinary row, which inherits the\n * unit's mode at insert. A blind update sets `\"pessimistic-blind\"` so the row is flushed only by its unit's\n * foreground path (never the optimistic batch) and retires from the journal without a synced echo.\n */\n writeMode?: string | null;\n}\n\ninterface PlannedOverlayUpsert {\n entityKey: Record<string, string>;\n record: Record<string, unknown>;\n overlayKind: string;\n localUpdatedAtUs: string;\n}\n\ninterface BatchEntityState {\n entityKey: Record<string, string>;\n entityKeyJson: string;\n record: Record<string, unknown> | null;\n overlayKind: string | null;\n localUpdatedAtUs: string | null;\n latestMutationSeq: number | null;\n latestMutationKind: MutationKind | null;\n latestMutationStatus: MutationStatus | null;\n}\n\ntype NormalizedBatchItem =\n | {\n context: TableContext;\n kind: \"create\";\n entityKey: Record<string, string>;\n entityKeyJson: string;\n optimisticRecord: Record<string, unknown>;\n input: unknown;\n mutationId: string;\n nowUs: string;\n order: number;\n }\n | {\n context: TableContext;\n kind: \"update\";\n entityKey: Record<string, string>;\n entityKeyJson: string;\n patch: Record<string, unknown>;\n /** A blind update (ADR-0022 addendum): journal-only, no base-row presence check, no overlay. */\n blind: boolean;\n mutationId: string;\n nowUs: string;\n order: number;\n }\n | {\n context: TableContext;\n kind: \"delete\";\n entityKey: Record<string, string>;\n entityKeyJson: string;\n mutationId: string;\n nowUs: string;\n order: number;\n };\n\n/**\n * The Base server version (ADR-0015) to stamp at enqueue for an update/delete. Only a **chain head**\n * — the first staged write on the entity (no earlier unresolved mutation) — captures an enqueue-time\n * base: the synced Server version the user's edit was authored against, so a genuine external write\n * between view and apply is caught. A **chained** write (an earlier same-entity mutation is still\n * owed) returns `null` here; it resolves its base at flush from its acked predecessor, so an entity's\n * own successive edits never self-conflict (decision 2).\n */\nfunction captureChainHeadBase(context: TableContext, entityState: BatchEntityState): string | null {\n if ((entityState.latestMutationSeq ?? 0) !== 0) {\n return null;\n }\n\n if (!context.serverVersionPropertyKey || !entityState.record) {\n return null;\n }\n\n // The Server version is a bigint count of microseconds, surfaced as a string/number/bigint\n // depending on the read path. Anything else (null/object) means no observable base.\n const raw = entityState.record[context.serverVersionPropertyKey];\n if (typeof raw === \"string\" || typeof raw === \"number\" || typeof raw === \"bigint\") {\n return String(raw);\n }\n\n return null;\n}\n\nfunction buildTableContexts<TRegistry extends SyncTableRegistry>(registry: TRegistry) {\n const localSchema = getSyncRegistrySchema(registry);\n\n return Object.fromEntries(\n Object.entries(registry)\n .filter(([, entry]) => entry.mode !== \"readonly\")\n .map(([key, entry]) => [key, buildTableContext(registry, key, entry, localSchema)]),\n ) as Partial<Record<SyncTableName<TRegistry>, TableContext>>;\n}\n\nfunction buildTableContext<TRegistry extends SyncTableRegistry>(\n registry: TRegistry,\n key: string,\n entry: SyncTableEntry<AnyPgTable>,\n localSchema: string,\n): TableContext {\n if (!entry.clientProjection?.overlayTable || !entry.clientProjection.journalTable) {\n throw new Error(`overlay and journal tables are required for writable table ${key}`);\n }\n\n const columns = getProjectedTableColumns(entry).map(({ propertyKey, column }) => ({\n propertyKey,\n column,\n }));\n\n const pkPropertyKeys = entry.primaryKey.columns.map((columnName) => {\n const column = columns.find((candidate) => candidate.column.name === columnName);\n\n if (!column) {\n throw new Error(`Primary key column ${columnName} was not found on table ${key}`);\n }\n\n return column.propertyKey;\n });\n\n const serverVersionColumnName = resolveServerVersionColumnName(entry) ?? null;\n const serverVersionPropertyKey = serverVersionColumnName\n ? (columns.find((candidate) => candidate.column.name === serverVersionColumnName)?.propertyKey ?? null)\n : null;\n\n // Resolve the `nowMicroseconds` managed fields generically from governance, not by property name.\n // `field.column` is a drizzle property key, but tolerate a column-name declaration too.\n const resolveManagedPropertyKey = (fieldColumn: string): string | undefined =>\n columns.find((candidate) => candidate.propertyKey === fieldColumn || candidate.column.name === fieldColumn)\n ?.propertyKey;\n const nowMicrosecondsManagedFields = (entry.governance?.managedFields ?? []).filter(\n (field) => field.strategy === \"nowMicroseconds\",\n );\n const managedNowMicrosecondsPropertyKeys = nowMicrosecondsManagedFields\n .map((field) => resolveManagedPropertyKey(field.column as string))\n .filter((propertyKey): propertyKey is string => propertyKey !== undefined);\n const updateManagedNowMicrosecondsPropertyKeys = nowMicrosecondsManagedFields\n .filter((field) => field.applyOn.includes(\"update\"))\n .map((field) => resolveManagedPropertyKey(field.column as string))\n .filter((propertyKey): propertyKey is string => propertyKey !== undefined);\n\n const managedAuthClaimCreateFields = (entry.governance?.managedFields ?? [])\n .filter((field) => field.strategy === \"authClaim\" && field.applyOn.includes(\"create\"))\n .flatMap((field) => {\n const propertyKey = resolveManagedPropertyKey(field.column as string);\n return propertyKey && field.claimPath ? [{ propertyKey, claimPath: field.claimPath }] : [];\n });\n\n // The generated local relations as runtime Drizzle objects (memoized per registry+key in\n // local-tables.ts), plus name-resolved column handles the statement authors below need:\n // overlay/synced columns are keyed by PROPERTY key, so PK columns (a DB-column-name concept,\n // ADR-0012) are resolved once here by matching `.name`.\n const tables = {\n synced: getSyncedLocalTable(registry, key as string & keyof TRegistry),\n overlay: getOverlayTable(registry, key as string & keyof TRegistry),\n journal: getJournalTable(registry, key as string & keyof TRegistry),\n };\n const overlayColumnsByPropertyKey = getColumns(tables.overlay) as Record<string, PgColumn>;\n const syncedColumnsByPropertyKey = getColumns(tables.synced) as Record<string, PgColumn>;\n const resolvePkColumns = (columnsByKey: Record<string, PgColumn>, relation: string) =>\n entry.primaryKey.columns.map((columnName) => {\n const column = Object.values(columnsByKey).find((candidate) => candidate.name === columnName);\n if (!column) {\n throw new Error(`Primary key column ${columnName} was not found on the ${relation} table for ${key}`);\n }\n return column;\n });\n const syncedServerVersionColumn = serverVersionColumnName\n ? (Object.values(syncedColumnsByPropertyKey).find((candidate) => candidate.name === serverVersionColumnName) ??\n null)\n : null;\n\n return {\n key,\n entry,\n readModel: qualifyLocalIdentifier(\n localSchema,\n entry.view != null\n ? getViewConfig(entry.view).name\n : (entry.clientProjection?.syncedTable ?? getTableConfig(entry.table).name),\n ),\n syncedTable: qualifyLocalIdentifier(\n localSchema,\n entry.clientProjection?.syncedTable ?? getTableConfig(entry.table).name,\n ),\n overlayTable: qualifyLocalIdentifier(localSchema, entry.clientProjection.overlayTable),\n journalTable: qualifyLocalIdentifier(localSchema, entry.clientProjection.journalTable),\n journalSequence: qualifyLocalIdentifier(localSchema, buildJournalSequenceName(entry.clientProjection.journalTable)),\n pkColumnNames: [...entry.primaryKey.columns],\n pkPropertyKeys,\n serverVersionColumnName,\n serverVersionPropertyKey,\n managedNowMicrosecondsPropertyKeys,\n updateManagedNowMicrosecondsPropertyKeys,\n managedAuthClaimCreateFields,\n recordIncludesOverlayState: \"overlayTable\" in (entry.clientProjection ?? {}),\n columns,\n tables,\n overlayColumnsByPropertyKey,\n syncedColumnsByPropertyKey,\n overlayPkColumns: resolvePkColumns(overlayColumnsByPropertyKey, \"overlay\"),\n syncedPkColumns: resolvePkColumns(syncedColumnsByPropertyKey, \"synced\"),\n syncedServerVersionColumn,\n };\n}\n\nfunction filterContexts<TRegistry extends SyncTableRegistry>(\n contexts: Partial<Record<SyncTableName<TRegistry>, TableContext>>,\n table?: SyncTableName<TRegistry>,\n) {\n if (table) {\n const context = contexts[table];\n return context ? [context] : [];\n }\n\n return Object.values(contexts).filter((context): context is TableContext => context !== undefined);\n}\n\n/**\n * Materialise a column's default into a concrete JS value for the optimistic overlay\n * row. The overlay INSERT writes an explicit value for every projected column (an\n * omitted column becomes a literal `NULL`, which overrides any table-level DEFAULT), so\n * a column declared `NOT NULL DEFAULT <x>` that the caller omits would violate the\n * overlay's NOT NULL constraint unless we fill the default here — mirroring what the\n * authoritative server applies on the base table.\n *\n * Only values we can produce client-side are materialised: a value-returning `defaultFn`\n * (e.g. `$defaultFn`) or a literal `.default(value)`. SQL-expression defaults\n * (`.default(sql\\`…\\`)`, `defaultRandom()`, `defaultNow()`) cannot be evaluated without\n * the database, so they are left to the server (the column is then expected to be either\n * caller-supplied or nullable in the optimistic row).\n */\nfunction materializeColumnDefault(column: TableContext[\"columns\"][number][\"column\"]): {\n ok: boolean;\n value?: unknown;\n} {\n if (!column.hasDefault) {\n return { ok: false };\n }\n\n if (typeof column.defaultFn === \"function\") {\n const produced = column.defaultFn();\n return is(produced, SQL) ? { ok: false } : { ok: true, value: produced };\n }\n\n if (column.default !== undefined && !is(column.default, SQL)) {\n return { ok: true, value: column.default };\n }\n\n return { ok: false };\n}\n\nfunction createOptimisticRecordFromContext<TCreate, TRecord>(\n context: TableContext,\n input: TCreate,\n claims?: Record<string, unknown>,\n): TRecord {\n const record = {\n ...(isRecord(input) ? input : {}),\n };\n const nowUs = nowMicroseconds();\n\n // Stamp `authClaim` create-managed fields (owner/author/created_by) from the decoded claim at the\n // field's path, so the optimistic overlay row is attributed locally and satisfies the column's NOT\n // NULL — the server independently stamps the same claim on apply, so the value never flips on\n // convergence. (`auth.uid()` is just `claimPath: [\"sub\"]`.)\n if (claims != null) {\n for (const { propertyKey, claimPath } of context.managedAuthClaimCreateFields) {\n if (record[propertyKey] === undefined) {\n const value = readJwtClaimPath(claims, claimPath);\n if (value !== undefined) {\n record[propertyKey] = value;\n }\n }\n }\n }\n\n if (hasProperty(context, \"createdAtUs\") && record[\"createdAtUs\"] === undefined) {\n record[\"createdAtUs\"] = nowUs;\n }\n\n if (hasProperty(context, \"updatedAtUs\") && record[\"updatedAtUs\"] === undefined) {\n record[\"updatedAtUs\"] = nowUs;\n }\n\n // Generic managed-timestamp fill (governance-driven): stamp any `nowMicroseconds` managed field the\n // convention block above did not — e.g. a Server version column not named `updated_at_us`. Additive\n // and idempotent, so convention tables are unaffected (their fields are already filled).\n for (const propertyKey of context.managedNowMicrosecondsPropertyKeys) {\n if (record[propertyKey] === undefined) {\n record[propertyKey] = nowUs;\n }\n }\n\n for (const { propertyKey, column } of context.columns) {\n if (record[propertyKey] !== undefined) {\n continue;\n }\n\n const materialized = materializeColumnDefault(column);\n if (materialized.ok) {\n record[propertyKey] = materialized.value;\n }\n }\n\n return buildOptimisticRecord(context, record, {\n overlayKind: \"pending_create\",\n localUpdatedAtUs: nowUs,\n }) as TRecord;\n}\n\n/**\n * Stamp every on-update `nowMicroseconds` managed field with `nowUs` (governance-driven, ADR-0004),\n * keyed by drizzle property key. For a convention table this is exactly `{ updatedAtUs: nowUs }`; for\n * a custom-named Server version it targets that column — so the local optimistic path never assumes\n * the demo naming the generic server applier does not.\n */\nfunction buildUpdateManagedNowStamp(context: TableContext, nowUs: string): Record<string, string> {\n return Object.fromEntries(\n context.updateManagedNowMicrosecondsPropertyKeys.map((propertyKey) => [propertyKey, nowUs]),\n );\n}\n\nfunction buildOptimisticRecord(\n context: TableContext,\n record: Record<string, unknown>,\n options: {\n overlayKind: string;\n localUpdatedAtUs: string;\n },\n) {\n if (!context.recordIncludesOverlayState) {\n return record;\n }\n\n return {\n ...record,\n overlayKind: options.overlayKind,\n localUpdatedAtUs: options.localUpdatedAtUs,\n };\n}\n\nfunction buildEntityKeyFromRecord(context: TableContext, record: unknown) {\n const recordObject = ensureRecord(record);\n return normalizeEntityKey(\n context,\n Object.fromEntries(context.pkPropertyKeys.map((propertyKey) => [propertyKey, String(recordObject[propertyKey])])),\n );\n}\n\nfunction normalizeEntityKey(context: TableContext, input: Record<string, string>) {\n // The public API accepts the identity by drizzle property name (ergonomics); past this\n // boundary the canonical Entity identity is column-keyed (ADR-0012), matching the\n // journal/overlay PK columns, entity_key_json, and the applier's `v_entity_key->>'<column>'`.\n // pkPropertyKeys[i] ↔ pkColumnNames[i] by construction (buildTableContext), so we map once here.\n return Object.fromEntries(\n context.pkPropertyKeys.map((propertyKey, index) => {\n const value = input[propertyKey];\n\n if (value === undefined) {\n throw new Error(`Missing entity key property ${propertyKey} for table ${context.key}`);\n }\n\n return [context.pkColumnNames[index]!, String(value)];\n }),\n );\n}\n\nfunction serializeEntityKey(entityKey: Record<string, string>) {\n return JSON.stringify(entityKey);\n}\n\nfunction dedupeBatchEntities(items: ReadonlyArray<NormalizedBatchItem>): BatchEntityRef[] {\n const entities = new Map<string, BatchEntityRef>();\n\n for (const item of items) {\n if (!entities.has(item.entityKeyJson)) {\n entities.set(item.entityKeyJson, {\n entityKey: item.entityKey,\n entityKeyJson: item.entityKeyJson,\n });\n }\n }\n\n return [...entities.values()];\n}\n\nasync function readLatestMutationStates(\n db: MutationDb,\n context: TableContext,\n entities: ReadonlyArray<BatchEntityRef>,\n) {\n if (entities.length === 0) {\n return new Map<string, BatchLatestMutationStateRow>();\n }\n\n // The old VALUES-CTE + LEFT-JOIN-back-to-input existed only to emit null rows for entities with\n // no journal history; the caller reads via `map.get(...) ?? null`, so a missing key is equivalent.\n const journal = context.tables.journal;\n const query = queryBuilder\n .selectDistinctOn([journal.entityKeyJson], {\n entityKeyJson: sql<string>`${journal.entityKeyJson}`.as(\"entityKeyJson\"),\n latestMutationSeq: sql<number>`${journal.mutationSeq}`.as(\"latestMutationSeq\"),\n latestMutationKind: sql<MutationKind>`${journal.mutationKind}`.as(\"latestMutationKind\"),\n latestMutationStatus: sql<MutationStatus>`${journal.status}`.as(\"latestMutationStatus\"),\n })\n .from(journal)\n .where(\n inArray(\n journal.entityKeyJson,\n entities.map((entity) => entity.entityKeyJson),\n ),\n )\n .orderBy(journal.entityKeyJson, desc(journal.mutationSeq))\n .toSQL();\n const result = await db.query<BatchLatestMutationStateRow>(query.sql, query.params as unknown[]);\n\n return new Map(result.rows.map((row) => [row.entityKeyJson, row]));\n}\n\nasync function readCurrentRecordStates(db: MutationDb, context: TableContext, entities: ReadonlyArray<BatchEntityRef>) {\n if (entities.length === 0) {\n return new Map<string, BatchCurrentRecordStateRow>();\n }\n\n // Tier ②: the overlay-∪-synced shape over an input VALUES table. The input CTE carries each\n // entity's `entity_key_json` alongside its PK values (the caller maps rows back by that JSON), so\n // it cannot be a plain builder select; every identifier still comes from the table objects /\n // `sql.identifier`, and every value is a bound (cast-typed) param.\n const overlay = context.tables.overlay;\n const synced = context.tables.synced;\n const inputCte = buildEntityInputCte(context, entities);\n const overlaySelectColumns = buildProjectedSelectColumns(context, context.overlayColumnsByPropertyKey);\n const syncedSelectColumns = buildProjectedSelectColumns(context, context.syncedColumnsByPropertyKey);\n const inputOverlayJoin = buildEntityInputJoin(context.pkColumnNames, context.overlayPkColumns);\n const inputSyncedJoin = buildEntityInputJoin(context.pkColumnNames, context.syncedPkColumns);\n const syncedUpdatedAtColumn = context.syncedColumnsByPropertyKey[\"updatedAtUs\"];\n const syncedLocalUpdated =\n hasProperty(context, \"updatedAtUs\") && syncedUpdatedAtColumn\n ? sql`${syncedUpdatedAtColumn}::text AS \"localUpdatedAtUs\"`\n : sql`'0' AS \"localUpdatedAtUs\"`;\n\n const query = queryDialect.sqlToQuery(sql`\n WITH ${inputCte},\n overlay_rows AS (\n SELECT\n input.entity_key_json AS \"entityKeyJson\",\n ${overlaySelectColumns},\n ${overlay.overlayKind} AS \"overlayKind\",\n ${overlay.localUpdatedAtUs}::text AS \"localUpdatedAtUs\"\n FROM input_entities AS input\n JOIN ${overlay}\n ON ${inputOverlayJoin}\n ),\n synced_rows AS (\n SELECT\n input.entity_key_json AS \"entityKeyJson\",\n ${syncedSelectColumns},\n ${\"synced\"} AS \"overlayKind\",\n ${syncedLocalUpdated}\n FROM input_entities AS input\n JOIN ${synced}\n ON ${inputSyncedJoin}\n WHERE NOT EXISTS (\n SELECT 1\n FROM ${overlay}\n WHERE ${inputOverlayJoin}\n )\n )\n SELECT *\n FROM overlay_rows\n UNION ALL\n SELECT *\n FROM synced_rows\n `);\n const result = await db.query<BatchCurrentRecordStateRow>(query.sql, query.params as unknown[]);\n\n return new Map(result.rows.map((row) => [row.entityKeyJson, row]));\n}\n\nasync function insertMutationsBulk(\n db: MutationDb,\n context: TableContext,\n rows: ReadonlyArray<PlannedMutationInsert>,\n registryVersion: string | null,\n unit?: WriteUnit,\n) {\n if (rows.length === 0) {\n return;\n }\n\n // ADR-0022: a dynamic write-unit tags every row of the batch with one shared unit id + mode; the\n // default path leaves both NULL (the flusher derives mode/unit from the static group). A blind row\n // carries its own `write_mode` override (`pessimistic-blind`), so the mode is resolved per row.\n const writeUnit = unit?.id ?? null;\n const journal = context.tables.journal;\n // `mutationSeq` is intentionally omitted: the generated journal DDL carries\n // `mutation_seq ... DEFAULT nextval(<journal sequence>)`, so the DB default assigns it — drizzle\n // renders `default` for every column a row does not provide.\n const values = rows.map((row) => ({\n mutationId: row.mutationId,\n ...Object.fromEntries(context.pkColumnNames.map((columnName) => [columnName, row.entityKey[columnName]])),\n entityKeyJson: row.entityKeyJson,\n mutationKind: row.mutationKind,\n status: \"pending\",\n registryVersion,\n baseServerVersion: row.baseServerVersion,\n payloadJson: row.payloadJson,\n enqueuedAtUs: row.nowUs,\n nextRetryAtUs: row.nowUs,\n updatedAtUs: row.nowUs,\n writeUnit,\n writeMode: row.writeMode ?? unit?.mode ?? null,\n }));\n\n const query = queryBuilder\n .insert(journal)\n .values(values as PgInsertValue<JournalTable>[])\n .toSQL();\n await db.query(query.sql, query.params as unknown[]);\n\n // Lifecycle origin: the moment each mutation is first staged into the journal. Correlates by id with\n // the later \"board-write sending\"/\"board-write acks\" lines (staged → sent → acked, per id).\n for (const row of rows) {\n syncDebug(\"mutation staged\", { mutationId: row.mutationId, table: context.key });\n }\n}\n\nasync function upsertOverlayRecordsBulk(\n db: MutationDb,\n context: TableContext,\n rows: ReadonlyArray<PlannedOverlayUpsert>,\n) {\n if (rows.length === 0) {\n return;\n }\n\n const overlay = context.tables.overlay;\n const values = rows.map((row) => ({\n ...Object.fromEntries(context.columns.map(({ propertyKey }) => [propertyKey, row.record[propertyKey] ?? null])),\n overlayKind: row.overlayKind,\n localUpdatedAtUs: row.localUpdatedAtUs,\n }));\n // Every inserted column (the projection + the two overlay columns) takes its EXCLUDED value on\n // conflict — the fixed alias PostgreSQL defines for the proposed row; its column names are the\n // table's own, so they come from the column objects via `sql.identifier`.\n const excludedSet = Object.fromEntries([\n ...context.columns.map(({ propertyKey, column }) => [propertyKey, sql`excluded.${sql.identifier(column.name)}`]),\n [\"overlayKind\", sql`excluded.${sql.identifier(overlay.overlayKind.name)}`],\n [\"localUpdatedAtUs\", sql`excluded.${sql.identifier(overlay.localUpdatedAtUs.name)}`],\n ]) as Record<string, SQL>;\n\n const query = queryBuilder\n .insert(overlay)\n .values(values as PgInsertValue<OverlayTable>[])\n .onConflictDoUpdate({ target: context.overlayPkColumns, set: excludedSet })\n .toSQL();\n await db.query(query.sql, query.params as unknown[]);\n}\n\n/**\n * The batch-input CTE as a typed fragment: `input_entities (entity_key_json, <pks…>) AS (VALUES …)`\n * with every value a bound param, cast to its PK column's type (an untyped VALUES column would\n * otherwise default to text and break the join against a uuid/int PK).\n */\nfunction buildEntityInputCte(context: TableContext, entities: ReadonlyArray<BatchEntityRef>): SQL {\n const columnNames = [\"entity_key_json\", ...context.pkColumnNames];\n const tuples = entities.map((entity) => {\n const values = [\n sql`${entity.entityKeyJson}`,\n ...context.pkColumnNames.map((columnName) => {\n const columnEntry = context.columns.find(({ column }) => column.name === columnName);\n const castSuffix = columnEntry ? resolveInputCastSuffix(columnEntry.column.columnType) : \"\";\n // The cast keyword is a FIXED type suffix selected from the closed switch below — never\n // derived from user data — so `sql.raw` is safe here; the value itself is a bound param.\n return castSuffix\n ? sql`${entity.entityKey[columnName]}${sql.raw(castSuffix)}`\n : sql`${entity.entityKey[columnName]}`;\n }),\n ];\n return sql`(${sql.join(values, sql`, `)})`;\n });\n\n return sql`input_entities (${sql.join(\n columnNames.map((columnName) => sql.identifier(columnName)),\n sql`, `,\n )}) AS (VALUES ${sql.join(tuples, sql`, `)})`;\n}\n\nfunction resolveInputCastSuffix(columnType: string): string {\n switch (columnType) {\n case \"PgUUID\":\n return \"::uuid\";\n case \"PgBigInt64\":\n case \"PgBigInt53\":\n return \"::bigint\";\n case \"PgInteger\":\n case \"PgSerial\":\n case \"PgSmallInt\":\n return \"::int\";\n case \"PgBoolean\":\n return \"::boolean\";\n case \"PgTimestamp\":\n case \"PgTimestampString\":\n return \"::timestamp\";\n default:\n return \"\";\n }\n}\n\n/**\n * The projected columns of one branch (overlay or synced) as select-list fragments, aliased to\n * their camelCase property keys — the raw seam returns rows unmapped, so the aliases ARE the row\n * keys — with `::text` casts on the bigint columns (matching how the runtime reads them).\n */\nfunction buildProjectedSelectColumns(context: TableContext, columnsByPropertyKey: Record<string, PgColumn>): SQL {\n return sql.join(\n context.columns.map(({ propertyKey, column }) => {\n const target = columnsByPropertyKey[propertyKey];\n if (!target) {\n throw new Error(`Projected column ${propertyKey} was not found on the local tables for ${context.key}`);\n }\n if (column.columnType === \"PgBigInt64\" || column.columnType === \"PgBigInt53\") {\n return sql`${target}::text AS ${sql.identifier(propertyKey)}`;\n }\n return sql`${target} AS ${sql.identifier(propertyKey)}`;\n }),\n sql`, `,\n );\n}\n\n/** PK equality between a branch table's columns and the `input` CTE, as a typed fragment. */\nfunction buildEntityInputJoin(pkColumnNames: string[], pkColumns: PgColumn[]): SQL {\n return sql.join(\n pkColumnNames.map((columnName, index) => sql`${pkColumns[index]!} = input.${sql.identifier(columnName)}`),\n sql` AND `,\n );\n}\n\n// ---------------------------------------------------------------------------\n// Batch flush — sends one send-eligible slice of pending mutations across all\n// target tables in a single POST /api/mutations call. The public flush()\n// wrapper loops until no more eligible rows remain.\n// ---------------------------------------------------------------------------\n\ninterface PendingBatchRow extends MutationRow {\n tableKey: string;\n enqueuedAtUs: string;\n /** The resolved Base server version (ADR-0015), or null when the table predates the policy. */\n baseServerVersion: string | null;\n}\n\ninterface PreparedBatchRow extends PendingBatchRow {\n context: TableContext;\n entityKey: Record<string, string>;\n envelopePayload: Record<string, unknown>;\n sqlTableName: string;\n}\n\ninterface FlushBatchResult {\n processedCount: number;\n affectedContexts: TableContext[];\n /** Mutation ids that transitioned to `quarantined` in this slice (ADR-0006), for surfacing. */\n quarantinedMutationIds: string[];\n /** Mutation ids that transitioned to `conflicted` in this slice (ADR-0015), for surfacing. */\n conflictedMutationIds: string[];\n}\n\ninterface MutationStatusUpdate {\n mutationId: string;\n status: MutationStatus;\n attemptCount: number;\n updatedAtUs: string;\n sentAtUs?: string | null;\n replaceSentAtUs?: boolean;\n ackedAtUs?: string | null;\n replaceAckedAtUs?: boolean;\n serverUpdatedAtUs?: string | null;\n replaceServerUpdatedAtUs?: boolean;\n baseServerVersion?: string | null;\n replaceBaseServerVersion?: boolean;\n lastError?: string | null;\n nextRetryAtUs?: string | null;\n lastHttpStatus?: number | null;\n conflictReason?: string | null;\n}\n\n/**\n * The resolved Base server version (ADR-0015) for a row at flush. A **chain head** already carries\n * `base_server_version` (stamped at enqueue), so COALESCE returns it untouched — keeping the\n * enqueue-time base means a genuine external write between view and apply is still caught. A\n * **chained** write has NULL there; it resolves to its **acked predecessor's** Server version (by\n * Per-entity flush serialization the predecessor is already acked when this row flushes), falling\n * back to the entity's current synced version once that predecessor has been reconciled away. Either\n * fallback yields the entity's own latest server state, so its own chain never self-conflicts.\n */\nfunction buildResolvedBaseServerVersion(context: TableContext): SQL {\n const journal = context.tables.journal;\n const synced = context.tables.synced;\n const pred = alias(journal, \"pred\");\n const predecessor = queryBuilder\n .select({ value: sql`MAX(${pred.serverUpdatedAtUs})` })\n .from(pred)\n .where(\n and(\n eq(pred.entityKeyJson, journal.entityKeyJson),\n lt(pred.mutationSeq, journal.mutationSeq),\n eq(pred.status, \"acked\"),\n ),\n );\n\n if (!context.syncedServerVersionColumn) {\n return sql`COALESCE(${journal.baseServerVersion}, ${predecessor})::text`;\n }\n\n const syncedFallback = queryBuilder\n .select({ value: sql`${context.syncedServerVersionColumn}` })\n .from(synced)\n .where(\n and(\n ...context.pkColumnNames.map((columnName, index) => eq(context.syncedPkColumns[index]!, journal[columnName]!)),\n ),\n );\n\n return sql`COALESCE(${journal.baseServerVersion}, ${predecessor}, ${syncedFallback})::text`;\n}\n\n/**\n * One table's send-eligible journal rows as a builder select with the shared {@link PendingBatchRow}\n * projection — the aliases ARE the row keys (raw seam), `tableKey` rides as a bound param, and the\n * resolved Base server version (ADR-0015) is the typed COALESCE fragment above.\n */\nfunction buildPendingRowsProjection(context: TableContext) {\n const journal = context.tables.journal;\n return {\n tableKey: sql<string>`${context.key}`.as(\"tableKey\"),\n mutationId: sql<string>`${journal.mutationId}`.as(\"mutationId\"),\n entityKeyJson: sql<string>`${journal.entityKeyJson}`.as(\"entityKeyJson\"),\n mutationSeq: sql<number>`${journal.mutationSeq}`.as(\"mutationSeq\"),\n mutationKind: sql<MutationKind>`${journal.mutationKind}`.as(\"mutationKind\"),\n status: journal.status,\n payloadJson: sql<string>`${journal.payloadJson}`.as(\"payloadJson\"),\n attemptCount: sql<number>`${journal.attemptCount}`.as(\"attemptCount\"),\n lastHttpStatus: sql<number | null>`${journal.lastHttpStatus}`.as(\"lastHttpStatus\"),\n lastError: sql<string | null>`${journal.lastError}`.as(\"lastError\"),\n conflictReason: sql<string | null>`${journal.conflictReason}`.as(\"conflictReason\"),\n nextRetryAtUs: sql<string | null>`${journal.nextRetryAtUs}::text`.as(\"nextRetryAtUs\"),\n serverUpdatedAtUs: sql<string | null>`${journal.serverUpdatedAtUs}::text`.as(\"serverUpdatedAtUs\"),\n baseServerVersion: buildResolvedBaseServerVersion(context).as(\"baseServerVersion\"),\n enqueuedAtUs: sql<string>`${journal.enqueuedAtUs}::text`.as(\"enqueuedAtUs\"),\n };\n}\n\nasync function readPendingBatchRows(db: MutationDb, contexts: TableContext[], nowUs: string, batchSize: number) {\n if (contexts.length === 0) {\n return [] as PendingBatchRow[];\n }\n\n const branches = contexts.map((context) => {\n const journal = context.tables.journal;\n const earlier = alias(journal, \"earlier\");\n return queryBuilder\n .select(buildPendingRowsProjection(context))\n .from(journal)\n .where(\n and(\n inArray(journal.status, [\"pending\", \"failed\"]),\n // ADR-0022: pessimistic rows are flushed by the authoritative unit path (flushUnit), never the\n // optimistic batch — exclude them here so a tagged write is never optimistically sent. The\n // `NOT LIKE 'pessimistic%'` also excludes a `pessimistic-blind` row (ADR-0022 addendum), which\n // belongs to its unit's foreground flush too.\n sql`COALESCE(${journal.writeMode}, '') NOT LIKE 'pessimistic%'`,\n sql`COALESCE(${journal.nextRetryAtUs}, 0) <= ${nowUs}::bigint`,\n notExists(\n queryBuilder\n .select({ one: sql`1` })\n .from(earlier)\n .where(\n and(\n eq(earlier.entityKeyJson, journal.entityKeyJson),\n lt(earlier.mutationSeq, journal.mutationSeq),\n // A still-unresolved earlier mutation blocks later same-entity ones so the\n // server applies them in author order. The quarantined status is included: a\n // later mutation must not flush past a prerequisite the server permanently\n // rejected (it would itself fail); resolving the quarantine unblocks the queue.\n inArray(earlier.status, [\"pending\", \"failed\", \"sending\", \"quarantined\"]),\n ),\n ),\n ),\n ),\n );\n });\n\n // The union rides inside a derived table because the outer ORDER BY casts the (text) output\n // columns — a set operation's own ORDER BY may only name plain output columns. The `pending`\n // alias and its two quoted output-column names are fixed by the projection above, not data.\n const query = queryDialect.sqlToQuery(\n sql`SELECT * FROM (${sql.join(branches, sql` UNION ALL `)}) AS pending ORDER BY pending.\"enqueuedAtUs\"::bigint ASC, pending.\"mutationSeq\" ASC LIMIT ${batchSize}`,\n );\n const result = await db.query<PendingBatchRow>(query.sql, query.params as unknown[]);\n\n return result.rows;\n}\n\n/**\n * Read one pessimistic write-unit's send-eligible rows (ADR-0022) across every table, ordered by author\n * sequence. Unlike {@link readPendingBatchRows} it has no per-entity ordering gate: a unit is enqueued and\n * sent atomically, so its members go together.\n */\nasync function readUnitPendingRows(\n db: MutationDb,\n contexts: TableContext[],\n unitId: string,\n): Promise<PendingBatchRow[]> {\n if (contexts.length === 0) {\n return [];\n }\n\n const branches = contexts.map((context) => {\n const journal = context.tables.journal;\n return queryBuilder\n .select(buildPendingRowsProjection(context))\n .from(journal)\n .where(and(eq(journal.writeUnit, unitId), inArray(journal.status, [\"pending\", \"failed\"])));\n });\n\n const query = queryDialect.sqlToQuery(\n sql`SELECT * FROM (${sql.join(branches, sql` UNION ALL `)}) AS unit ORDER BY unit.\"mutationSeq\" ASC`,\n );\n const result = await db.query<PendingBatchRow>(query.sql, query.params as unknown[]);\n\n return result.rows;\n}\n\nasync function flushBatch(\n db: MutationDb,\n tableContexts: Record<string, TableContext>,\n batchWriteUrl: string,\n maxAttempts: number,\n batchSize: number,\n tableFilter?: string,\n getAuthToken?: () => Promise<string | undefined>,\n requestHeaders?: Record<string, string>,\n): Promise<FlushBatchResult> {\n const contexts = filterContexts(tableContexts, tableFilter);\n const nowUs = nowMicroseconds();\n const quarantinedMutationIds: string[] = [];\n const conflictedMutationIds: string[] = [];\n\n // Collect send-eligible mutations across all target tables.\n const pendingRows = await readPendingBatchRows(db, contexts, nowUs, batchSize);\n const pending: PreparedBatchRow[] = [];\n const pendingByTable = new Map<string, PreparedBatchRow[]>();\n\n for (const row of pendingRows) {\n const context = tableContexts[row.tableKey];\n\n if (!context) {\n continue;\n }\n\n const entityKey = JSON.parse(row.entityKeyJson) as Record<string, string>;\n const rawPayload = JSON.parse(row.payloadJson) as Record<string, unknown>;\n const preparedRow: PreparedBatchRow = {\n ...row,\n context,\n entityKey,\n envelopePayload:\n row.mutationKind === \"delete\"\n ? entityKey\n : toSqlColumnPayload(\n context,\n stripManagedFields(\n context,\n (rawPayload[\"value\"] ?? rawPayload[\"patch\"] ?? rawPayload) as Record<string, unknown>,\n row.mutationKind as \"create\" | \"update\",\n ),\n ),\n sqlTableName: context.entry.shape?.tableName ?? context.key,\n };\n\n pending.push(preparedRow);\n\n const existingTableRows = pendingByTable.get(context.key);\n\n if (existingTableRows) {\n existingTableRows.push(preparedRow);\n } else {\n pendingByTable.set(context.key, [preparedRow]);\n }\n }\n\n if (pending.length === 0) {\n // If a write just enqueued and requested a pass, but this flush sees nothing, the pass raced the\n // journal commit (or everything is already in-flight/backed-off) — the write then waits for a\n // later pass. Worth seeing explicitly when chasing flush latency.\n syncDebug(\"flushBatch: no send-eligible mutations this pass\");\n return {\n processedCount: 0,\n affectedContexts: [],\n quarantinedMutationIds,\n conflictedMutationIds,\n };\n }\n\n syncDebug(\"flushBatch sending to board-write\", { count: pending.length });\n\n // Mark all as sending.\n const sentAtUs = nowMicroseconds();\n\n for (const rows of pendingByTable.values()) {\n await applyMutationStatusUpdates(\n db,\n rows[0]!.context,\n rows.map((row) => ({\n mutationId: row.mutationId,\n status: \"sending\",\n attemptCount: row.attemptCount + 1,\n updatedAtUs: sentAtUs,\n sentAtUs,\n replaceSentAtUs: true,\n // Persist the resolved Base server version (ADR-0015) so a chained write's flush-resolved\n // base is durable and matches exactly what the envelope carries to the server.\n baseServerVersion: row.baseServerVersion,\n replaceBaseServerVersion: true,\n lastError: null,\n nextRetryAtUs: null,\n lastHttpStatus: null,\n conflictReason: null,\n })),\n );\n }\n\n const mutations = pending.map((row) => {\n return {\n tableName: row.sqlTableName,\n entityKey: row.entityKey,\n mutationId: row.mutationId,\n mutationSeq: row.mutationSeq,\n kind: row.mutationKind as \"create\" | \"update\" | \"delete\",\n payload: row.envelopePayload,\n clientTimestampUs: sentAtUs,\n // ADR-0015: carry the resolved Base server version so the applier can detect a stale write.\n // Omitted for a create / a table that predates the policy (null) — then no stale check runs.\n ...(row.baseServerVersion != null ? { baseServerVersion: row.baseServerVersion } : {}),\n };\n });\n\n let responseOk = false;\n let acksByMutationId: Map<string, BatchMutationAck[\"acks\"][number]> = new Map();\n const batchMutationUrl = resolveBatchMutationUrl(batchWriteUrl);\n\n try {\n // Resolve the auth token and the network round-trip separately: in the board, `getAuthToken` calls\n // `supabase.auth.getSession()` per send, which can itself stall (token refresh) and would otherwise\n // be invisibly folded into \"the write was slow\".\n const authStart = typeof performance !== \"undefined\" ? performance.now() : Date.now();\n const authToken = await getAuthToken?.();\n const fetchStart = typeof performance !== \"undefined\" ? performance.now() : Date.now();\n syncDebug(\"board-write auth token resolved\", { ms: Math.round(fetchStart - authStart) });\n\n let response = await fetch(batchMutationUrl, {\n method: \"POST\",\n headers: buildRequestHeaders(authToken, requestHeaders),\n body: jsonStringifyPayload({ mutations }),\n });\n\n if ([401, 403].includes(response.status) && getAuthToken) {\n response = await fetch(batchMutationUrl, {\n method: \"POST\",\n headers: buildRequestHeaders(await getAuthToken(), requestHeaders),\n body: jsonStringifyPayload({ mutations }),\n });\n }\n\n const fetchEnd = typeof performance !== \"undefined\" ? performance.now() : Date.now();\n syncDebug(\"board-write responded\", { status: response.status, ms: Math.round(fetchEnd - fetchStart) });\n\n if (response.ok) {\n const responseJson = (await response.json()) as BatchMutationAck;\n responseOk = true;\n acksByMutationId = new Map(responseJson.acks.map((ack) => [ack.mutationId, ack]));\n syncDebug(\"board-write acks\", {\n acks: responseJson.acks.map((ack) => `${ack.mutationId.slice(0, 8)}:${ack.status}`),\n });\n } else {\n const text = await response.text();\n throw new MutationRequestError(\n text.length > 0 ? text : `Bulk write responded with ${response.status}`,\n response.status,\n parseBatchRejections(text),\n );\n }\n } catch (error) {\n const failedAtUs = nowMicroseconds();\n const httpStatus = error instanceof MutationRequestError ? error.status : null;\n const errorMessage = error instanceof Error ? error.message : \"Unknown batch write failure\";\n // The server attributed the failure to specific mutations (a structural validation\n // rejection of an atomic batch). When present, we quarantine exactly those and leave the\n // innocent siblings immediately retryable; absent (transport / 5xx / auth / malformed\n // envelope), the whole batch stays retryable under the shared attempt cap.\n const rejectionById =\n error instanceof MutationRequestError && error.rejections\n ? new Map(error.rejections.map((rejection) => [rejection.mutationId, rejection]))\n : null;\n\n for (const rows of pendingByTable.values()) {\n await applyMutationStatusUpdates(\n db,\n rows[0]!.context,\n rows.map((row) => {\n const attemptCount = row.attemptCount + 1;\n\n if (rejectionById) {\n const rejection = rejectionById.get(row.mutationId);\n\n if (rejection) {\n // Named as the cause: terminal quarantine (it will never succeed unchanged).\n quarantinedMutationIds.push(row.mutationId);\n return {\n mutationId: row.mutationId,\n status: \"quarantined\" as const,\n attemptCount,\n updatedAtUs: failedAtUs,\n lastError: rejection.reason,\n nextRetryAtUs: null,\n lastHttpStatus: httpStatus,\n conflictReason: rejection.reason,\n };\n }\n\n // Innocent sibling: nothing was applied (atomic batch), so make it immediately\n // retryable — no backoff (the fault was the now-quarantined mutation, not\n // congestion) — and the next flush proceeds without the poison.\n return {\n mutationId: row.mutationId,\n status: \"failed\" as const,\n attemptCount,\n updatedAtUs: failedAtUs,\n lastError: \"Batch rejected due to a sibling mutation; retrying without it\",\n nextRetryAtUs: null,\n lastHttpStatus: httpStatus,\n conflictReason: null,\n };\n }\n\n // Unattributed batch-level failure: stays retryable with jittered backoff; only the\n // hard attempt cap escalates to terminal quarantined. A structural 4xx is NOT\n // quarantined here (a stray 404/413/malformed envelope would otherwise permanently\n // kill unrelated valid writes).\n const outcome = resolveBatchFailureOutcome(attemptCount, maxAttempts, failedAtUs);\n\n if (outcome.status === \"quarantined\") {\n quarantinedMutationIds.push(row.mutationId);\n }\n\n return {\n mutationId: row.mutationId,\n status: outcome.status,\n attemptCount,\n updatedAtUs: failedAtUs,\n lastError: errorMessage,\n nextRetryAtUs: outcome.nextRetryAtUs,\n lastHttpStatus: httpStatus,\n conflictReason: null,\n };\n }),\n );\n }\n\n return {\n processedCount: pending.length,\n affectedContexts: [...new Set(pending.map((row) => row.context))],\n quarantinedMutationIds,\n conflictedMutationIds,\n };\n }\n\n if (!responseOk) {\n return {\n processedCount: pending.length,\n affectedContexts: [...new Set(pending.map((row) => row.context))],\n quarantinedMutationIds,\n conflictedMutationIds,\n };\n }\n\n // Apply per-mutation ack results.\n const ackedAtUs = nowMicroseconds();\n const failedAtUs = nowMicroseconds();\n\n for (const rows of pendingByTable.values()) {\n await applyMutationStatusUpdates(\n db,\n rows[0]!.context,\n rows.map((row) => {\n const ack = acksByMutationId.get(row.mutationId);\n\n if (ack && ack.status === \"conflicted\") {\n // ADR-0015: a stale write the reject-if-stale policy declined. Move to the terminal\n // `conflicted` status — NOT a failure (never retried as-is, the base is still stale) — and\n // KEEP the optimistic Overlay (reconcile only clears acked rows, so the user's edit stays\n // visible). The server's current Server version rides on the journal row for the diff UI.\n conflictedMutationIds.push(row.mutationId);\n return {\n mutationId: row.mutationId,\n status: \"conflicted\" as const,\n attemptCount: row.attemptCount + 1,\n updatedAtUs: failedAtUs,\n serverUpdatedAtUs: ack.serverUpdatedAtUs ?? null,\n replaceServerUpdatedAtUs: true,\n lastError: ack.conflictReason ?? \"Stale write rejected (reject-if-stale)\",\n nextRetryAtUs: null,\n lastHttpStatus: ack.httpStatus ?? 409,\n conflictReason: ack.conflictReason ?? \"Stale write rejected (reject-if-stale)\",\n };\n }\n\n if (!ack || ack.status !== \"acked\") {\n const attemptCount = row.attemptCount + 1;\n const httpStatus = ack?.httpStatus ?? null;\n const outcome = resolveFailureOutcome(httpStatus, attemptCount, maxAttempts, failedAtUs);\n\n if (outcome.status === \"quarantined\") {\n quarantinedMutationIds.push(row.mutationId);\n }\n\n return {\n mutationId: row.mutationId,\n status: outcome.status,\n attemptCount,\n updatedAtUs: failedAtUs,\n lastError: ack?.conflictReason ?? \"Batch mutation not acknowledged\",\n nextRetryAtUs: outcome.nextRetryAtUs,\n lastHttpStatus: httpStatus,\n conflictReason: ack?.conflictReason ?? null,\n };\n }\n\n if (row.mutationKind === \"delete\") {\n return {\n mutationId: row.mutationId,\n status: \"acked\",\n attemptCount: row.attemptCount + 1,\n updatedAtUs: ackedAtUs,\n ackedAtUs,\n replaceAckedAtUs: true,\n lastError: null,\n nextRetryAtUs: null,\n lastHttpStatus: 204,\n conflictReason: null,\n };\n }\n\n return {\n mutationId: row.mutationId,\n status: \"acked\",\n attemptCount: row.attemptCount + 1,\n updatedAtUs: ackedAtUs,\n ackedAtUs,\n replaceAckedAtUs: true,\n serverUpdatedAtUs: ack.serverUpdatedAtUs ?? null,\n replaceServerUpdatedAtUs: true,\n lastError: null,\n nextRetryAtUs: null,\n lastHttpStatus: 200,\n conflictReason: null,\n };\n }),\n );\n }\n\n return {\n processedCount: pending.length,\n affectedContexts: [...new Set(pending.map((row) => row.context))],\n quarantinedMutationIds,\n conflictedMutationIds,\n };\n}\n\n/**\n * Resolve a flush failure into the durable journal outcome (ADR-0006). A structural\n * rejection ({@link classifyFailureStatus}) or hitting the hard attempt cap ends the\n * retry loop with a terminal `quarantined` (no `next_retry_at_us`); otherwise the\n * mutation stays `failed` with a jittered backoff (ADR-0005 congestion policy).\n */\nfunction resolveFailureOutcome(\n httpStatus: number | null,\n attemptCount: number,\n maxAttempts: number,\n failedAtUs: string,\n): { status: \"failed\" | \"quarantined\"; nextRetryAtUs: string | null } {\n if (classifyFailureStatus(httpStatus) === \"quarantined\" || attemptCount >= maxAttempts) {\n return { status: \"quarantined\", nextRetryAtUs: null };\n }\n\n return { status: \"failed\", nextRetryAtUs: computeNextRetryAtUs(failedAtUs, attemptCount) };\n}\n\n/**\n * Resolve a *batch-level* failure — the whole POST failed (transport error, 5xx, auth, or a\n * non-2xx the server did not attribute to a specific mutation). Unlike a per-mutation ack\n * rejection, the fault cannot be pinned on any one mutation, so a structural 4xx must NOT\n * quarantine the batch (a stray 404/413/malformed envelope would permanently kill unrelated\n * valid offline writes). These failures stay retryable `failed` with jittered backoff; only\n * the hard attempt cap escalates to terminal `quarantined`.\n */\nfunction resolveBatchFailureOutcome(\n attemptCount: number,\n maxAttempts: number,\n failedAtUs: string,\n): { status: \"failed\" | \"quarantined\"; nextRetryAtUs: string | null } {\n if (attemptCount >= maxAttempts) {\n return { status: \"quarantined\", nextRetryAtUs: null };\n }\n\n return { status: \"failed\", nextRetryAtUs: computeNextRetryAtUs(failedAtUs, attemptCount) };\n}\n\nfunction resolveBatchMutationUrl(batchWriteUrl: string): string {\n const trimmed = batchWriteUrl.replace(/\\/+$/, \"\");\n\n if (trimmed.endsWith(\"/mutations\")) {\n return trimmed;\n }\n\n return `${trimmed}/mutations`;\n}\n\n/** The authoritative (pessimistic) write endpoint (ADR-0022): the batch URL with `/unit` appended. */\nfunction resolveAuthoritativeMutationUrl(batchWriteUrl: string): string {\n return `${resolveBatchMutationUrl(batchWriteUrl)}/unit`;\n}\n\nfunction stripManagedFields(\n context: TableContext,\n payload: Record<string, unknown>,\n operation: \"create\" | \"update\",\n): Record<string, unknown> {\n const managedColumns = new Set<string>();\n\n for (const mf of context.entry.governance?.managedFields ?? []) {\n if (mf.applyOn.includes(operation)) {\n managedColumns.add(mf.column);\n }\n }\n\n if (managedColumns.size === 0) return payload;\n\n return Object.fromEntries(Object.entries(payload).filter(([key]) => !managedColumns.has(key)));\n}\n\nfunction toSqlColumnPayload(context: TableContext, payload: Record<string, unknown>): Record<string, unknown> {\n const normalized: Record<string, unknown> = {};\n\n for (const { propertyKey, column } of context.columns) {\n const columnName = column.name;\n\n if (Object.prototype.hasOwnProperty.call(payload, columnName)) {\n normalized[columnName] = payload[columnName];\n continue;\n }\n\n if (Object.prototype.hasOwnProperty.call(payload, propertyKey)) {\n normalized[columnName] = payload[propertyKey];\n }\n }\n\n return normalized;\n}\n\n/**\n * Discard a terminal-state entity: clear its journal rows in the given terminal status\n * (`conflicted` — ADR-0015; or `quarantined` — ADR-0006) and its kept optimistic Overlay row, so the\n * Read model falls back to the synced (server) value. The overlay is removed only when no OTHER journal\n * row still owes the entity (a pending/sending/failed/acked write), mirroring reconcileTable's\n * overlay-clear guard — so a discard never strips an overlay another un-resolved write still depends\n * on. Both public discards (`discardConflict`, `discardQuarantined`) are this one body parameterized by\n * the terminal status they retire; owning its own transaction (like reconcileTable), it is not wrapped.\n */\nasync function discardTerminalEntity(\n db: MutationDb,\n context: TableContext,\n entityKey: Record<string, string>,\n entityKeyJson: string,\n terminalStatus: \"conflicted\" | \"quarantined\",\n) {\n await db.exec(\"BEGIN\");\n\n try {\n const journal = context.tables.journal;\n const clearQuery = queryBuilder\n .delete(journal)\n .where(and(eq(journal.status, terminalStatus), eq(journal.entityKeyJson, entityKeyJson)))\n .toSQL();\n await db.query(clearQuery.sql, clearQuery.params as unknown[]);\n\n // Clear the kept overlay only when no journal row still owes this entity — so a discard never\n // strips an overlay another un-resolved write (e.g. a resolution already enqueued) depends on.\n const overlayQuery = buildOverlayDiscardQuery(context, entityKey, entityKeyJson);\n await db.query(overlayQuery.sql, overlayQuery.params as unknown[]);\n\n await db.exec(\"COMMIT\");\n } catch (error) {\n await db.exec(\"ROLLBACK\");\n throw error;\n }\n}\n\n/**\n * The shared overlay-discard statement: delete the entity's overlay row unless a journal row still\n * owes the entity — `owedStatuses` narrows which journal rows count as \"owed\" (all of them for a\n * conflict discard; only the un-sent pending/sending/failed set for a settled-unit discard).\n */\nfunction buildOverlayDiscardQuery(\n context: TableContext,\n entityKey: Record<string, string>,\n entityKeyJson: string,\n owedStatuses?: MutationStatus[],\n) {\n const overlay = context.tables.overlay;\n const journal = context.tables.journal;\n const owed = queryBuilder\n .select({ one: sql`1` })\n .from(journal)\n .where(\n owedStatuses\n ? and(eq(journal.entityKeyJson, entityKeyJson), inArray(journal.status, owedStatuses))\n : eq(journal.entityKeyJson, entityKeyJson),\n );\n\n return queryBuilder\n .delete(overlay)\n .where(\n and(\n ...context.pkColumnNames.map((columnName, index) =>\n eq(context.overlayPkColumns[index]!, entityKey[columnName]),\n ),\n notExists(owed),\n ),\n )\n .toSQL();\n}\n\n/**\n * Auto-discard the optimistic overlay for an entity whose pessimistic write-unit the authoritative endpoint\n * `rejected` (ADR-0022 §4). Unlike {@link discardTerminalEntity} this KEEPS the terminal `rejected` journal\n * row (for diagnostics + `onReject`); it only clears the overlay, and only when no still-owed\n * (`pending`/`sending`/`failed`) journal row depends on it — so a later un-sent write never loses its overlay.\n */\nasync function discardOverlayForSettledEntity(\n db: MutationDb,\n context: TableContext,\n entityKey: Record<string, string>,\n entityKeyJson: string,\n) {\n const query = buildOverlayDiscardQuery(context, entityKey, entityKeyJson, [\"pending\", \"sending\", \"failed\"]);\n await db.query(query.sql, query.params as unknown[]);\n}\n\nasync function reconcileTable(db: MutationDb, context: TableContext) {\n // Idle fast-path. Reconcile only retires/clears journal rows in a terminal-clearable state — 'acked'\n // (clear the overlay once the echo lands) or 'conflicted' (retire once a later write resolved it). When\n // none exist — the steady state of an idle entity set — all three statements below are no-ops, so skip\n // the whole transaction. This matters because the convergence driver runs reconcile for EVERY writable\n // table on its interval (default 1.5s), and each CTE pays full PGlite plan+execute cost even against an\n // empty journal: left unguarded it is the dominant idle-CPU cost. The real-time cleanup path is the\n // <table>_reconcile_on_sync trigger; this bulk pass is a fallback, so skipping it when there is nothing\n // to clear changes no outcome. The guard is a single existence probe over the (small, usually empty)\n // journal.\n const journal = context.tables.journal;\n const overlay = context.tables.overlay;\n const synced = context.tables.synced;\n // This is the idle-CPU hot statement (it runs for every writable table on every convergence\n // tick), so the rendered text+params are memoized per context — each tick pays only a plain\n // `db.query` of a cached string, and it stays OUTSIDE any transaction (no BEGIN on the idle path).\n let idleProbe = context.reconcileIdleProbe;\n if (!idleProbe) {\n const probeQuery = queryDialect.sqlToQuery(\n sql`SELECT ${exists(\n queryBuilder\n .select({ one: sql`1` })\n .from(journal)\n .where(inArray(journal.status, [\"acked\", \"conflicted\"])),\n )} AS \"hasWork\"`,\n );\n idleProbe = { sql: probeQuery.sql, params: probeQuery.params as unknown[] };\n context.reconcileIdleProbe = idleProbe;\n }\n const work = await db.query<{ hasWork: boolean }>(idleProbe.sql, idleProbe.params);\n if (work.rows[0]?.hasWork !== true) {\n return;\n }\n\n // The Convergence barrier (ADR-0010) gates the acked-row clearing below; the synced-table trigger\n // handles real-time cleanup, and this is the bulk recovery/fallback path that runs after every flush.\n await db.exec(\"BEGIN\");\n\n try {\n // ADR-0015: retire a terminal `conflicted` row once the user has RESOLVED it — i.e. a LATER write\n // on the same entity has been acked (resolution is an ordinary new mutation). Without this, the old\n // conflicted row lingers forever: `<table>_sync_state.conflict_state` keeps surfacing the resolved\n // conflict and `diagnostics().conflictedCount` never drops. Run before the acked-clear below so the\n // resolving row is still present to supersede it. (`discardConflict` is the explicit throw-away path.)\n // Drizzle DELETE has no USING; the resolver leg is the equivalent EXISTS semi-join.\n const resolver = alias(journal, \"resolver\");\n const retireQuery = queryBuilder\n .delete(journal)\n .where(\n and(\n eq(journal.status, \"conflicted\"),\n exists(\n queryBuilder\n .select({ one: sql`1` })\n .from(resolver)\n .where(\n and(\n eq(resolver.entityKeyJson, journal.entityKeyJson),\n gt(resolver.mutationSeq, journal.mutationSeq),\n eq(resolver.status, \"acked\"),\n ),\n ),\n ),\n ),\n )\n .toSQL();\n await db.query(retireQuery.sql, retireQuery.params as unknown[]);\n\n // ADR-0022 addendum — retire an acked `pessimistic-blind` row with NO echo barrier. A blind update's\n // write target is excluded from this actor's read shape, so no synced echo will ever land for it and no\n // overlay was ever planned: the standard acked-clear below (gated on a synced row reaching the acked\n // version) would keep it forever. Nothing local converges for these rows, so once the authoritative unit\n // acked them there is nothing left to do but drop the journal row. Crash-safe: any later reconcile tick\n // clears a blind row the foreground flushUnit didn't survive to reconcile.\n const blindRetireQuery = queryBuilder\n .delete(journal)\n .where(and(eq(journal.status, \"acked\"), eq(journal.writeMode, \"pessimistic-blind\")))\n .toSQL();\n await db.query(blindRetireQuery.sql, blindRetireQuery.params as unknown[]);\n\n // Clear acknowledged non-delete mutations + matching overlays. ADR-0010: gated by the\n // Convergence barrier (same predicate as the trigger) — the acked write clears only once the\n // synced echo's Server version has reached its acked version. Joining the synced table makes\n // the comparison possible (and means an un-synced acked write is held until its echo lands).\n // Drizzle authoring: DELETE..USING becomes the equivalent EXISTS semi-join, chained through a\n // data-modifying CTE (both sub-statements see the same statement-start snapshot, exactly like\n // the USING form). The barrier predicate stays the shared contracts helper (single authority\n // with the trigger); it renders against the tables' own names, which is how drizzle references\n // their columns here (no aliases on a DELETE target).\n const barrier = sql.raw(\n buildOverlayResolutionBarrier(context.entry, {\n journalAlias: quoteIdentifier(getTableConfig(journal).name),\n syncedAlias: quoteIdentifier(getTableConfig(synced).name),\n }),\n );\n const clearedJournal = queryBuilder.$with(\"cleared_journal\").as(\n queryBuilder\n .delete(journal)\n .where(\n and(\n eq(journal.status, \"acked\"),\n isNotNull(journal.serverUpdatedAtUs),\n ne(journal.mutationKind, \"delete\"),\n exists(\n queryBuilder\n .select({ one: sql`1` })\n .from(synced)\n .where(\n and(\n ...context.pkColumnNames.map((columnName, index) =>\n eq(context.syncedPkColumns[index]!, journal[columnName]!),\n ),\n barrier,\n ),\n ),\n ),\n ),\n )\n .returning(\n Object.fromEntries([\n [\"entity_key_json\", journal.entityKeyJson],\n ...context.pkColumnNames.map((columnName) => [columnName, journal[columnName]!]),\n ]),\n ),\n );\n const clearedJournalColumns = clearedJournal as unknown as Record<string, PgColumn>;\n const ackedClearQuery = queryBuilder\n .with(clearedJournal)\n .delete(overlay)\n .where(\n exists(\n queryBuilder\n .select({ one: sql`1` })\n .from(clearedJournal)\n .where(\n and(\n ...context.pkColumnNames.map((columnName, index) =>\n eq(context.overlayPkColumns[index]!, clearedJournalColumns[columnName]!),\n ),\n notExists(\n queryBuilder\n .select({ one: sql`1` })\n .from(journal)\n .where(\n and(\n eq(journal.entityKeyJson, clearedJournalColumns[\"entity_key_json\"]!),\n inArray(journal.status, [\"pending\", \"sending\", \"failed\"]),\n ),\n ),\n ),\n ),\n ),\n ),\n )\n .toSQL();\n await db.query(ackedClearQuery.sql, ackedClearQuery.params as unknown[]);\n\n // Clear acknowledged delete mutations where synced row is absent\n // Single compound CTE — PGlite does not support multi-statement query().\n const clearableEntities = queryBuilder.$with(\"clearable_entities\").as(\n queryBuilder\n .selectDistinct(\n Object.fromEntries([\n [\"entity_key_json\", journal.entityKeyJson],\n ...context.pkColumnNames.map((columnName) => [columnName, journal[columnName]!]),\n ]),\n )\n .from(journal)\n .leftJoin(\n synced,\n and(\n ...context.pkColumnNames.map((columnName, index) =>\n eq(context.syncedPkColumns[index]!, journal[columnName]!),\n ),\n ),\n )\n .where(\n and(eq(journal.status, \"acked\"), eq(journal.mutationKind, \"delete\"), isNull(context.syncedPkColumns[0]!)),\n ),\n );\n const clearableEntityColumns = clearableEntities as unknown as Record<string, PgColumn>;\n const deletedOverlay = queryBuilder.$with(\"deleted_overlay\").as(\n queryBuilder.delete(overlay).where(\n exists(\n queryBuilder\n .select({ one: sql`1` })\n .from(clearableEntities)\n .where(\n and(\n ...context.pkColumnNames.map((columnName, index) =>\n eq(context.overlayPkColumns[index]!, clearableEntityColumns[columnName]!),\n ),\n ),\n ),\n ),\n ),\n );\n const deleteClearQuery = queryBuilder\n .with(clearableEntities, deletedOverlay)\n .delete(journal)\n .where(\n and(\n eq(journal.status, \"acked\"),\n eq(journal.mutationKind, \"delete\"),\n exists(\n queryBuilder\n .select({ one: sql`1` })\n .from(clearableEntities)\n .where(\n and(\n ...context.pkColumnNames.map((columnName) =>\n eq(journal[columnName]!, clearableEntityColumns[columnName]!),\n ),\n ),\n ),\n ),\n ),\n )\n .toSQL();\n await db.query(deleteClearQuery.sql, deleteClearQuery.params as unknown[]);\n await db.exec(\"COMMIT\");\n } catch (error) {\n await db.exec(\"ROLLBACK\");\n throw error;\n }\n}\n\nfunction buildRequestHeaders(bearerToken?: string, requestHeaders?: Record<string, string>): Record<string, string> {\n // Static headers first so the toolkit-owned Content-Type/Authorization always win.\n return {\n ...(requestHeaders ?? {}),\n \"Content-Type\": \"application/json\",\n ...(bearerToken ? { Authorization: `Bearer ${bearerToken}` } : {}),\n };\n}\n\nasync function applyMutationStatusUpdates(db: MutationDb, context: TableContext, updates: MutationStatusUpdate[]) {\n if (updates.length === 0) {\n return;\n }\n\n // Tier ②: `update().from(<VALUES>)`. Every value is a bound param with the same cast as before;\n // the `updates` alias and its column list are fixed by this function (not derived from data), so\n // the alias-qualified references in SET/WHERE are fixed template text, while the journal side of\n // each CASE interpolates the column objects.\n const journal = context.tables.journal;\n const tuples = updates.map(\n (update) =>\n sql`(${update.mutationId}, ${update.status}, ${update.attemptCount}::int, ${update.updatedAtUs}::bigint, ${\n update.sentAtUs ?? null\n }::bigint, ${update.replaceSentAtUs ?? false}::boolean, ${update.ackedAtUs ?? null}::bigint, ${\n update.replaceAckedAtUs ?? false\n }::boolean, ${update.serverUpdatedAtUs ?? null}::bigint, ${update.replaceServerUpdatedAtUs ?? false}::boolean, ${\n update.baseServerVersion ?? null\n }::bigint, ${update.replaceBaseServerVersion ?? false}::boolean, ${update.lastError ?? null}, ${\n update.nextRetryAtUs ?? null\n }::bigint, ${update.lastHttpStatus ?? null}::int, ${update.conflictReason ?? null})`,\n );\n const updatesTable = sql`(VALUES ${sql.join(\n tuples,\n sql`, `,\n )}) AS updates (mutation_id, status, attempt_count, updated_at_us, sent_at_us, replace_sent_at_us, acked_at_us, replace_acked_at_us, server_updated_at_us, replace_server_updated_at_us, base_server_version, replace_base_server_version, last_error, next_retry_at_us, last_http_status, conflict_reason)`;\n\n const query = queryBuilder\n .update(journal)\n .set({\n status: sql`updates.status`,\n attemptCount: sql`updates.attempt_count`,\n updatedAtUs: sql`updates.updated_at_us::bigint`,\n sentAtUs: sql`CASE WHEN updates.replace_sent_at_us THEN updates.sent_at_us::bigint ELSE ${journal.sentAtUs} END`,\n ackedAtUs: sql`CASE WHEN updates.replace_acked_at_us THEN updates.acked_at_us::bigint ELSE ${journal.ackedAtUs} END`,\n serverUpdatedAtUs: sql`CASE WHEN updates.replace_server_updated_at_us THEN updates.server_updated_at_us::bigint ELSE ${journal.serverUpdatedAtUs} END`,\n baseServerVersion: sql`CASE WHEN updates.replace_base_server_version THEN updates.base_server_version::bigint ELSE ${journal.baseServerVersion} END`,\n lastError: sql`updates.last_error`,\n nextRetryAtUs: sql`updates.next_retry_at_us::bigint`,\n lastHttpStatus: sql`updates.last_http_status`,\n conflictReason: sql`updates.conflict_reason`,\n })\n .from(updatesTable)\n .where(eq(journal.mutationId, sql`updates.mutation_id::uuid`))\n .toSQL();\n await db.query(query.sql, query.params as unknown[]);\n}\n\nfunction qualifyLocalIdentifier(schemaName: string, tableName: string) {\n if (schemaName === \"public\") {\n // Quote-when-needed: a reserved-word or mixed-case table name (e.g. `group`)\n // MUST be quoted or the generated SQL fails to parse (ADR-0004). Normal names\n // stay bare, so existing generated SQL is unchanged.\n return maybeQuoteIdentifier(tableName);\n }\n\n return `${quoteIdentifier(schemaName)}.${quoteIdentifier(tableName)}`;\n}\n\nfunction buildJournalSequenceName(journalTable: string) {\n return `${journalTable}_mutation_seq`;\n}\n\nfunction hasProperty(context: TableContext, propertyKey: string) {\n return context.columns.some((column) => column.propertyKey === propertyKey);\n}\n\nfunction ensureRecord(value: unknown) {\n if (!isRecord(value)) {\n throw new Error(\"Mutation runtime expected a record payload\");\n }\n\n return value;\n}\n\nfunction extractRecordFromState(context: TableContext, state: CurrentRecordStateRow | BatchCurrentRecordStateRow) {\n return Object.fromEntries(context.columns.map(({ propertyKey }) => [propertyKey, state[propertyKey] ?? null]));\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null;\n}\n\nclass MutationRequestError extends Error {\n readonly status: number;\n /** Per-mutation attribution the server returned for a structural rejection, or null. */\n readonly rejections: MutationRejection[] | null;\n\n constructor(message: string, status: number, rejections: MutationRejection[] | null = null) {\n super(message);\n this.name = \"MutationRequestError\";\n this.status = status;\n this.rejections = rejections;\n }\n}\n\n/**\n * Extract per-mutation attribution from a non-2xx batch-write body. The server names the\n * offending mutations on a structural (validation) rejection; an absent, non-JSON, or\n * empty-`rejections` body yields null, so the failure is treated as non-attributable\n * (whole batch stays retryable).\n */\nfunction parseBatchRejections(body: string): MutationRejection[] | null {\n if (body.length === 0) {\n return null;\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(body);\n } catch {\n return null;\n }\n\n const result = batchMutationErrorSchema.safeParse(parsed);\n const rejections = result.success ? result.data.rejections : undefined;\n return rejections && rejections.length > 0 ? rejections : null;\n}\n",
|
|
23
|
+
"import { index, jsonb, pgSchema, primaryKey, text } from \"drizzle-orm/pg-core\";\n\nimport type { ShapeSubscriptionState } from \"./subscription-state\";\n\n/**\n * The two metadata-store relations the sync engine provisions at boot (ADR-0028 decision 4). The\n * metadata schema name is dynamic (per-client config) but fixed at engine construction, so the tables\n * are built per schema string and memoized.\n *\n * ADR-0029 D3: these pgTables are the SINGLE SOURCE for the relations. `migrateSubscriptionMetadataTables`\n * (subscription-state.ts) renders their `CREATE TABLE`/`CREATE INDEX` DDL FROM these definitions via the\n * in-house `renderCreateTableSql` (schema.ts), and the DML paths query them directly — so the DDL and the\n * pgTable can no longer diverge, and the former drift guard in `tests/unit/sync-drizzle-executor.test.ts`\n * is now a plain provisioning round-trip.\n *\n * Property keys are deliberately snake_case to mirror the row shapes the callers already consume\n * (`shape_metadata`, `last_lsn`, `pk_json`, …), so a `select()` returns rows in the existing shape with\n * no alias mapping.\n */\n\nexport interface MetadataTables {\n /** `<schema>.subscriptions_metadata` — one row per subscription key. */\n readonly subscriptionsMetadata: ReturnType<typeof buildSubscriptionsMetadata>;\n /** `<schema>.shape_row_tags` — the tagged-subquery reason-set store (ADR-0023). */\n readonly shapeRowTags: ReturnType<typeof buildShapeRowTags>;\n}\n\n/**\n * The `pg_temp` schema name the SESSION metadata variants are built under (ADR-0042). An ephemeral\n * group's sync bookkeeping (cursor + tags) is scoped to the engine session by placing it in `pg_temp`\n * relations that die with the engine — the cursor's lifetime is mechanically tied to the TEMP cluster\n * whose rows it indexes. `pg_temp` is a per-session alias Postgres accepts in DML qualification (probed\n * on real PGlite), so the DML paths select these objects unchanged. Same relation NAMES as the durable\n * variants, distinguished by schema alone (maintainer ruling).\n */\nconst SESSION_METADATA_SCHEMA = \"pg_temp\";\n\nfunction buildSubscriptionsMetadata(schema: ReturnType<typeof pgSchema>) {\n return schema.table(\"subscriptions_metadata\", {\n key: text(\"key\").primaryKey(),\n // JSONB NOT NULL — round-trips as a parsed object (drizzle's jsonb codec), matching the raw path.\n shape_metadata: jsonb(\"shape_metadata\").$type<Record<string, ShapeSubscriptionState>>().notNull(),\n // The LSN is persisted as TEXT (a bigint has no JSON/portable-column form); callers `BigInt(...)` it.\n last_lsn: text(\"last_lsn\").notNull(),\n });\n}\n\nfunction buildShapeRowTags(schema: ReturnType<typeof pgSchema>) {\n return schema.table(\n \"shape_row_tags\",\n {\n shape_table: text(\"shape_table\").notNull(),\n pk_json: text(\"pk_json\").notNull(),\n tag: text(\"tag\").notNull(),\n },\n (t) => [\n primaryKey({ columns: [t.shape_table, t.pk_json, t.tag] }),\n index(\"shape_row_tags_shape_tag_idx\").on(t.shape_table, t.tag),\n ],\n );\n}\n\nconst cache = new Map<string, MetadataTables>();\n\n/** The (memoized) metadata-store `pgTable`s for a given metadata schema name. */\nexport function getMetadataTables(metadataSchema: string): MetadataTables {\n let tables = cache.get(metadataSchema);\n if (!tables) {\n const schema = pgSchema(metadataSchema);\n tables = {\n subscriptionsMetadata: buildSubscriptionsMetadata(schema),\n shapeRowTags: buildShapeRowTags(schema),\n };\n cache.set(metadataSchema, tables);\n }\n return tables;\n}\n\nlet sessionCache: MetadataTables | undefined;\n\n/**\n * The (memoized) SESSION metadata-store `pgTable`s (ADR-0042) — the same relation names as the durable\n * variants, built from the SAME column builders (ADR-0029 D3 single-source), but schema-qualified into\n * `pg_temp` so the DML lands in the engine's session-scoped TEMP relations. No schema parameter: `pg_temp`\n * is per-engine by construction, so a single memoized singleton serves every engine. The DDL that\n * PROVISIONS these tables uses the unqualified `CREATE TEMP TABLE` form (the TEMP keyword places the\n * relation in the session schema; a `pg_temp.x` DDL target is not portable), rendered from these SAME\n * definitions via `renderCreateTableSql({ temp: true })`.\n */\nexport function getSessionMetadataTables(): MetadataTables {\n if (!sessionCache) {\n const schema = pgSchema(SESSION_METADATA_SCHEMA);\n sessionCache = {\n subscriptionsMetadata: buildSubscriptionsMetadata(schema),\n shapeRowTags: buildShapeRowTags(schema),\n };\n }\n return sessionCache;\n}\n\n/**\n * Select the durable or SESSION metadata tables (ADR-0042). `sessionScoped` groups (ephemeral retention)\n * route their cursor + tag DML to the `pg_temp` variants; every other group keeps the durable tables. The\n * engine learns one storage-scope bit, not the retention model.\n */\nexport function pickMetadataTables(metadataSchema: string, sessionScoped: boolean): MetadataTables {\n return sessionScoped ? getSessionMetadataTables() : getMetadataTables(metadataSchema);\n}\n",
|
|
24
|
+
"import {\n and,\n desc,\n eq,\n exists,\n getColumns,\n gt,\n inArray,\n is,\n isNotNull,\n isNull,\n lt,\n ne,\n notExists,\n SQL,\n sql,\n} from \"drizzle-orm\";\nimport {\n alias,\n getTableConfig,\n getViewConfig,\n PgDialect,\n type AnyPgTable,\n type PgColumn,\n type PgInsertValue,\n} from \"drizzle-orm/pg-core\";\nimport { drizzle } from \"drizzle-orm/pglite\";\n\nimport {\n clearMutationRecoveryMarkerIfSettled,\n readMutationRecoveryRequired,\n writeMutationRecoveryRequired,\n} from \"./local-store\";\nimport {\n getJournalTable,\n getOverlayTable,\n getSyncedLocalTable,\n type JournalTable,\n type OverlayTable,\n} from \"./local-tables\";\n\n// Statements are AUTHORED as Drizzle builders over the journal/overlay/synced table objects\n// (rename-safe, typed, schema-qualification handled by the table objects) and rendered to\n// text+params here, because they EXECUTE through the caller's raw `MutationDb` seam — the one\n// connection the mutation runtime and its tests own (and mock). `drizzle.mock()` builds queries\n// without a connection; `queryDialect` renders standalone `sql` fragments the builders cannot\n// express (compound CTE shapes, derived-table wrappers).\nconst queryBuilder = drizzle.mock();\nconst queryDialect = new PgDialect();\n\n/**\n * Strip the two internal overlay columns that appear on _read_model views\n * (`overlay_kind`, `local_updated_at_us`) from any user-supplied input or\n * patch object before it is serialised into a mutation payload. Callers\n * that spread a view row directly into a create/update call would otherwise\n * hit `TypeError: Do not know how to serialize a BigInt` because\n * `local_updated_at_us` is stored as a native JS `bigint`.\n */\nfunction stripReadModelOverlayFields<T>(value: T): T {\n if (value === null || typeof value !== \"object\") return value;\n const obj = value as Record<string, unknown>;\n if (!(\"overlay_kind\" in obj) && !(\"local_updated_at_us\" in obj)) return value;\n const { overlay_kind: _ok, local_updated_at_us: _lu, ...rest } = obj;\n return rest as T;\n}\n\n/**\n * JSON replacer that serialises `bigint` values as strings. PostgreSQL\n * accepts string literals for BIGINT columns, and JSON has no native bigint\n * type, so this is the safest cross-boundary representation.\n */\nfunction bigintReplacer(_key: string, value: unknown): unknown {\n return typeof value === \"bigint\" ? String(value) : value;\n}\n\nfunction jsonStringifyPayload(value: unknown): string {\n return JSON.stringify(value, bigintReplacer);\n}\n\nimport type {\n BatchMutationAck,\n MutationAck,\n MutationDiagnostics,\n MutationRejection,\n SyncTableCreateInput,\n SyncTableEntry,\n SyncTableName,\n SyncTableRecord,\n SyncTableRegistry,\n SyncTableUpdateInput,\n WriteMode,\n} from \"@pgxsinkit/contracts\";\nimport {\n batchMutationErrorSchema,\n buildOverlayResolutionBarrier,\n fingerprintRegistry,\n getProjectedColumns as getProjectedTableColumns,\n getSyncRegistrySchema,\n maybeQuoteIdentifier,\n quoteIdentifier,\n resolveServerVersionColumnName,\n} from \"@pgxsinkit/contracts\";\n\nimport { syncDebug } from \"./debug\";\nimport {\n assertValidMutationTransition,\n classifyFailureStatus,\n DEFAULT_MAX_MUTATION_ATTEMPTS,\n type MutationStatus,\n} from \"./mutation-state\";\n\nexport type { MutationStatus } from \"./mutation-state\";\nexport type MutationKind = \"create\" | \"update\" | \"delete\";\n\n/**\n * The dynamic write-unit tag (ADR-0022 §2) a `transaction({ mode })` block stamps onto the mutations\n * authored within it: a shared `id` grouping the co-committed mutations, and the unit's `mode`. Persisted\n * on each journal row (`write_unit` / `write_mode`); absent for the default path, where the flusher derives\n * mode + unit from the table's static consistency group.\n */\nexport interface WriteUnit {\n id: string;\n mode: WriteMode;\n}\n\nexport type MutationBatchItem<TRegistry extends SyncTableRegistry> = {\n [TKey in SyncTableName<TRegistry>]:\n | {\n table: TKey;\n kind: \"create\";\n input: SyncTableCreateInput<TRegistry, TKey>;\n }\n | {\n table: TKey;\n kind: \"update\";\n entityKey: Record<string, string>;\n patch: SyncTableUpdateInput<TRegistry, TKey>;\n /**\n * A **blind** update (ADR-0022 addendum): plan a journal row ONLY — no local base row is required\n * and no optimistic overlay is written. Set exclusively by the transaction handle's `updateBlind`;\n * valid only when the write routes pessimistically (a `pessimistic` unit, or a statically-pessimistic\n * table), and rejected at enqueue otherwise. Absent/false for an ordinary update.\n */\n blind?: boolean;\n }\n | {\n table: TKey;\n kind: \"delete\";\n entityKey: Record<string, string>;\n };\n}[SyncTableName<TRegistry>];\n\nexport const DEFAULT_FLUSH_BATCH_SIZE = 100;\n\nexport interface MutationDetail {\n tableName: string;\n entityKey: Record<string, string>;\n mutationId: string;\n mutationSeq: number;\n mutationKind: MutationKind;\n status: MutationStatus;\n attemptCount: number;\n lastHttpStatus: number | null;\n lastError: string | null;\n conflictReason: string | null;\n nextRetryAtUs: string | null;\n serverUpdatedAtUs: string | null;\n updatedAtUs: string;\n /** Registry fingerprint (ADR-0004) the mutation was authored under, or null if unstamped. */\n registryVersion: string | null;\n}\n\nexport interface MutationDb {\n exec: (sql: string) => Promise<unknown>;\n query: <TRow extends Record<string, unknown> = Record<string, unknown>>(\n sql: string,\n params?: unknown[],\n ) => Promise<{ rows: TRow[] }>;\n}\n\nexport interface CreateMutationRuntimeOptions<TRegistry extends SyncTableRegistry> {\n db: MutationDb;\n registry: TRegistry;\n writeUrl: string;\n getAuthToken?: () => Promise<string | undefined>;\n /** Static headers added to every write request (e.g. a Supabase Cloud `apikey`); see {@link CreateSyncClientOptions.requestHeaders}. */\n requestHeaders?: Record<string, string>;\n /**\n * Registry fingerprint (ADR-0004) stamped onto each enqueued mutation as its\n * `registry_version`, so a version-boundary crossing is known before sending (ADR-0006).\n */\n registryVersion?: string;\n /**\n * Whether pgxsinkit owns the local schema (and therefore the `pgxsinkit_local_meta` table the durable\n * recovery-required marker lives in). Defaults to `true`. A caller-owned `pgliteInstance` boot sets this\n * `false`: the meta table may not exist, so the marker is never read/written and boot recovery falls back\n * to the legacy always-recover pass (proposal §1 caller-owned-PGlite constraint).\n */\n ownsMetaTable?: boolean;\n /**\n * Hard cap on send attempts before a still-failing mutation is quarantined\n * (ADR-0005 congestion policy). Defaults to {@link DEFAULT_MAX_MUTATION_ATTEMPTS}.\n */\n maxMutationAttempts?: number;\n /**\n * Max mutations drained per flush HTTP request; a flush loops slices until the journal is empty.\n * Defaults to {@link DEFAULT_FLUSH_BATCH_SIZE}. Primarily a test seam (a small value exercises the\n * multi-slice drain path without enqueueing hundreds of mutations).\n */\n flushBatchSize?: number;\n /**\n * Invoked after a flush whenever mutations transition to `quarantined` (terminal,\n * permanently rejected). Receives the newly-quarantined details so the app can surface\n * them, then either re-author + resubmit or roll back via {@link MutationRuntime.discardQuarantined}\n * (clears the kept overlay + quarantined journal rows, so the entity accepts new mutations again).\n * The library never silently drops these (ADR-0006 decision 4).\n */\n onQuarantine?: (quarantined: MutationDetail[]) => void | Promise<void>;\n /**\n * Invoked after a flush whenever mutations transition to `conflicted` — a stale write the\n * server declined under the `reject-if-stale` Conflict policy (ADR-0015). Distinct from\n * `onQuarantine` (structural rejection): the optimistic Overlay is KEPT, so the app surfaces a\n * resolution/diff UI and resolves each as a new write (or `discardConflict`s it). Never silent.\n */\n onConflict?: (conflicted: MutationDetail[]) => void | Promise<void>;\n /**\n * Invoked after an authoritative (pessimistic) flush whenever a write-unit was `rejected` (ADR-0022) —\n * a business decline the client could not evaluate locally (capacity/quota/uniqueness). The inverse of\n * `onConflict`: the optimistic Overlay was **auto-discarded** for every member of the unit, so the app\n * surfaces the typed reason (e.g. \"full\") rather than a resolve/diff UI. Never silent.\n */\n onReject?: (rejected: MutationDetail[]) => void | Promise<void>;\n /**\n * Invoked once per enqueue with the DISTINCT non-blind table keys of the planned batch (ADR-0039).\n * An ordinary optimistic `create`/`update`/`delete` is a reference to its target, and a reference\n * activates the target's lazy consistency group — the read path does this implicitly, the write path\n * did not. The client wires this to a fire-and-forget `ensureSynced`, so the group is open by the time\n * the echo returns. Purely-blind batches (only `updateBlind`) report nothing: a blind write is the\n * deliberate no-echo, no-activation write-only exception. Fire-and-forget from the runtime's view —\n * never awaited, and a throw here must never fail the enqueue (the runtime guards the call).\n */\n onOrdinaryEnqueue?: (tables: readonly string[]) => void;\n}\n\ninterface TableContext {\n key: string;\n entry: SyncTableEntry<AnyPgTable>;\n readModel: string;\n syncedTable: string;\n overlayTable: string;\n journalTable: string;\n journalSequence: string;\n pkColumnNames: string[];\n pkPropertyKeys: string[];\n /**\n * The Server version (ADR-0010) column name (e.g. `updated_at_us`) and its drizzle property key,\n * resolved from the table's managed fields. Used to capture the Base server version (ADR-0015) at\n * enqueue — the value the user's edit was authored against. `null` would mean no Server version,\n * which registry validation already forbids for a writable table.\n */\n serverVersionColumnName: string | null;\n serverVersionPropertyKey: string | null;\n /**\n * Property keys of the table's `nowMicroseconds` managed fields (governance), resolved generically\n * rather than by the `createdAtUs`/`updatedAtUs` naming convention. The optimistic overlay stamps\n * these client-side so a custom-named managed timestamp (e.g. a Server version not called\n * `updated_at_us`) is materialised correctly — closing the split interpreter between the generic\n * server applier (which reads governance) and the local path (ADR-0004).\n *\n * - `managedNowMicrosecondsPropertyKeys` — every `nowMicroseconds` field, stamped on create.\n * - `updateManagedNowMicrosecondsPropertyKeys` — those that apply on update, re-stamped each update.\n *\n * These augment, and never remove, the convention fill in `createOptimisticRecordFromContext`,\n * which remains the safety net for a `created_at_us`/`updated_at_us` column that carries a SQL\n * `DEFAULT` (unmaterialisable client-side) yet is not declared a managed field.\n */\n managedNowMicrosecondsPropertyKeys: string[];\n updateManagedNowMicrosecondsPropertyKeys: string[];\n /**\n * The table's `authClaim` managed fields that apply on create (governance), each with the JSON\n * claimPath it stamps from. The server stamps these from the verified request claims, so they are\n * stripped from the create input type and never sent in the flushed payload. But the optimistic\n * overlay still needs a value — such a column is typically `NOT NULL` (an owner/author/created_by) —\n * so the runtime fills it client-side from the decoded JWT claim at the same path (the same value the\n * server will stamp), so the local row renders attributed immediately and never flips on convergence.\n * (`auth.uid()` is just `claimPath: [\"sub\"]`, so this one path covers it.)\n */\n managedAuthClaimCreateFields: Array<{ propertyKey: string; claimPath: string[] }>;\n recordIncludesOverlayState: boolean;\n columns: Array<{\n propertyKey: string;\n column: ReturnType<typeof getProjectedTableColumns<AnyPgTable>>[number][\"column\"];\n }>;\n /**\n * The generated local relations as runtime Drizzle table objects (local-tables.ts), so the\n * runtime's statements are AUTHORED as tier-① builders while still EXECUTING through the raw\n * `MutationDb` seam. Journal fixed columns are camelCase-keyed; per-entry PK columns are keyed\n * by DB column name; overlay/synced columns are keyed by drizzle property key.\n */\n tables: {\n synced: AnyPgTable;\n overlay: OverlayTable;\n journal: JournalTable;\n };\n /** Overlay columns keyed by property key (`getColumns` memo — overlay keys are property keys, not DB names). */\n overlayColumnsByPropertyKey: Record<string, PgColumn>;\n /** Synced read-cache columns keyed by property key. */\n syncedColumnsByPropertyKey: Record<string, PgColumn>;\n /** The entry's PK columns ON THE OVERLAY, resolved by DB column name (ordered like `pkColumnNames`). */\n overlayPkColumns: PgColumn[];\n /** The entry's PK columns ON THE SYNCED table, resolved by DB column name (ordered like `pkColumnNames`). */\n syncedPkColumns: PgColumn[];\n /** The Server version column ON THE SYNCED table (ADR-0010), or null when the table declares none. */\n syncedServerVersionColumn: PgColumn | null;\n /**\n * Memoized render of the reconcile idle probe (the per-tick hot statement): built once per\n * context so every convergence tick pays only a plain `db.query` of a cached string.\n */\n reconcileIdleProbe?: { sql: string; params: unknown[] };\n}\n\n/**\n * The result of {@link MutationRuntime.runBootRecovery}, shaped to feed the `warmBoot` BootReport fields\n * directly (ADR-0034): whether the per-table recovery loop was skipped, whether recovery was required this\n * boot, how many writable journals were visited, and how many rows were lifted `sending → pending` (`null`\n * when the pass was legacy/uncounted, a real count on the marker-`true` path).\n */\nexport interface BootRecoveryOutcome {\n skipped: boolean;\n required: boolean;\n tablesVisited: number;\n rowsRecovered: number | null;\n}\n\nexport interface MutationRuntime<TRegistry extends SyncTableRegistry> {\n /** The registry fingerprint (ADR-0004) this runtime stamps onto enqueued mutations. */\n registryVersion: string;\n create: <TKey extends SyncTableName<TRegistry>>(\n table: TKey,\n input: SyncTableCreateInput<TRegistry, TKey>,\n ) => Promise<void>;\n update: <TKey extends SyncTableName<TRegistry>>(\n table: TKey,\n entityKey: Record<string, string>,\n patch: SyncTableUpdateInput<TRegistry, TKey>,\n ) => Promise<void>;\n delete: <TKey extends SyncTableName<TRegistry>>(table: TKey, entityKey: Record<string, string>) => Promise<void>;\n /**\n * Enqueue an atomic batch of mutations. An optional {@link WriteUnit} tags every row of the batch as one\n * dynamic write-unit (ADR-0022 §2) — the `transaction({ mode })` block passes it; the per-table\n * `create`/`update`/`delete` helpers do not (their write-mode comes from the static group at flush).\n */\n batch: (items: ReadonlyArray<MutationBatchItem<TRegistry>>, unit?: WriteUnit) => Promise<void>;\n /**\n * Discard a `conflicted` entity (ADR-0015): clear its conflicted journal entries and the kept\n * optimistic Overlay, so the Read model falls back to the synced (server) value. Use when the user\n * abandons their stale edit instead of resolving it as a new write. No-op for an entity with no\n * conflicted entry.\n */\n discardConflict: <TKey extends SyncTableName<TRegistry>>(\n table: TKey,\n entityKey: Record<string, string>,\n ) => Promise<void>;\n /**\n * Discard a `quarantined` entity (ADR-0006): clear its quarantined journal entries and the kept\n * optimistic Overlay, so the Read model falls back to the synced (server) value and the entity\n * accepts new mutations again. The rollback path for a permanently-rejected write (e.g. an RLS\n * policy denial routed to quarantine). Symmetric to {@link discardConflict}. No-op for an entity\n * with no quarantined entry; the overlay is kept when another still-owed write depends on it.\n */\n discardQuarantined: <TKey extends SyncTableName<TRegistry>>(\n table: TKey,\n entityKey: Record<string, string>,\n ) => Promise<void>;\n flush: (table?: SyncTableName<TRegistry>) => Promise<void>;\n /**\n * Flush one pessimistic write-unit (ADR-0022) to the authoritative endpoint and apply its per-mutation\n * result inline: `acked` clears via the synced echo, `conflicted` keeps the overlay (surfaced), and\n * `rejected` auto-discards the overlay for the whole unit (surfaced via `onReject`). A foreground\n * operation — it resolves once the server has decided. Throws on transport failure (the overlay is kept\n * for a retry). Returns the server acks. Used by the client `transaction({ mode: \"pessimistic\" })` block.\n */\n flushUnit: (unitId: string) => Promise<{ acks: MutationAck[] }>;\n reconcile: (table?: SyncTableName<TRegistry>) => Promise<void>;\n retryFailed: (table?: SyncTableName<TRegistry>) => Promise<void>;\n recoverSending: (table?: SyncTableName<TRegistry>) => Promise<void>;\n /**\n * Boot-time journal recovery driven by the durable recovery-required marker (proposal §1 / slice 2). The\n * internal boot entry point that decides — from the marker and the boot mode — whether the per-table\n * `sending → pending` recovery loop runs at all, and clears/initializes the marker afterwards. It NEVER\n * runs from a consumer call ({@link recoverSending} keeps today's exact per-table semantics and never\n * touches the marker); {@link BootRecoveryOutcome} feeds the `warmBoot` BootReport fields verbatim.\n *\n * - `ownsMetaTable: false` (caller-owned PGlite) → legacy always-recover, marker untouched.\n * - `restore: true` → legacy recovery + {@link quarantineRecovered} + self-verifying clear (marker ignored).\n * - marker `false` → skip the loop entirely.\n * - marker absent (legacy store) → one legacy recovery pass, then initialize the marker.\n * - marker `true` → the N per-table updates PLUS the self-verifying clear, wrapped in one transaction.\n */\n runBootRecovery: (opts: { ownsMetaTable: boolean; restore: boolean }) => Promise<BootRecoveryOutcome>;\n /**\n * Quarantine EVERY non-terminal journal row recovered from a backup (`pending`/`sending`/`failed` →\n * `quarantined`) — the restore-boot rule (ADR-0035 decision 6). Nothing recovered from a store backup\n * may ever auto-flush: the write path keeps `mutationId` in `operations_log` but never consults it, so\n * there is no dedupe ledger, and a replayed mutation would silently re-apply stale values over newer\n * writes on a last-write-wins table (and a replayed create collides on its PK). Terminal states\n * (`acked`/`conflicted`/`rejected`) are left untouched. Run ONCE, on the restore boot only, AFTER\n * `recoverSending` (which first lifts any `sending` back to `pending`); the app then inspects\n * `diagnostics()` and resolves each row via `discardQuarantined` (quarantine is terminal — \"release\"\n * means discard and re-author as a new mutation) before going online. A no-op on a clean journal.\n */\n quarantineRecovered: (table?: SyncTableName<TRegistry>) => Promise<void>;\n readMutationStats: (table?: SyncTableName<TRegistry>) => Promise<MutationDiagnostics>;\n readMutationDetails: (table?: SyncTableName<TRegistry>) => Promise<MutationDetail[]>;\n createOptimisticRecord: <TKey extends SyncTableName<TRegistry>>(\n table: TKey,\n input: SyncTableCreateInput<TRegistry, TKey>,\n ) => SyncTableRecord<TRegistry, TKey>;\n}\n\nexport function nowMicroseconds(): string {\n return (BigInt(Date.now()) * 1000n).toString();\n}\n\n/**\n * Best-effort decode of a JWT's claims payload, for stamping `authClaim` managed fields into the\n * optimistic overlay (the value the server will independently stamp from the same claim path). This is\n * **not** a verification — the token is trusted only for a local, optimistic projection that the server\n * re-stamps authoritatively on apply; a forged claim could never make the server attribute the row\n * differently. Returns `undefined` for a malformed token.\n */\nexport function decodeJwtClaims(token: string): Record<string, unknown> | undefined {\n const segments = token.split(\".\");\n if (segments.length < 2 || !segments[1]) {\n return undefined;\n }\n try {\n const normalized = segments[1].replace(/-/g, \"+\").replace(/_/g, \"/\");\n const padded = normalized.padEnd(normalized.length + ((4 - (normalized.length % 4)) % 4), \"=\");\n const binary = atob(padded);\n const bytes = Uint8Array.from(binary, (char) => char.charCodeAt(0));\n const payload = JSON.parse(new TextDecoder().decode(bytes)) as unknown;\n return typeof payload === \"object\" && payload !== null ? (payload as Record<string, unknown>) : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Read a claim at a JSON path out of a decoded claims object, returning it as a string (the form the\n * optimistic overlay column expects, mirroring the server's `jsonb #>>` text extraction). Returns\n * `undefined` if the path is absent or the leaf is not a string/number.\n */\nexport function readJwtClaimPath(claims: Record<string, unknown>, claimPath: string[]): string | undefined {\n let cursor: unknown = claims;\n for (const segment of claimPath) {\n if (typeof cursor !== \"object\" || cursor === null) {\n return undefined;\n }\n cursor = (cursor as Record<string, unknown>)[segment];\n }\n if (typeof cursor === \"string\") {\n return cursor;\n }\n return typeof cursor === \"number\" ? String(cursor) : undefined;\n}\n\nexport function computeBackoffDelayMs(attemptCount: number) {\n const exponent = Math.max(attemptCount - 1, 0);\n return Math.min(1000 * 2 ** exponent, 30_000);\n}\n\n/**\n * Retry delay with equal jitter around the {@link computeBackoffDelayMs} ceiling: half\n * the ceiling plus a random share of the other half. Spreads retries so a fleet of\n * clients does not stampede the server in lockstep after an outage (ADR-0005 congestion\n * policy). `random` is injectable for deterministic tests.\n */\nexport function computeRetryDelayMs(attemptCount: number, random: () => number = Math.random) {\n const ceiling = computeBackoffDelayMs(attemptCount);\n return Math.round(ceiling / 2 + random() * (ceiling / 2));\n}\n\nexport function computeNextRetryAtUs(nowUs: string, attemptCount: number, random: () => number = Math.random) {\n return (BigInt(nowUs) + BigInt(computeRetryDelayMs(attemptCount, random)) * 1000n).toString();\n}\n\nexport function createMutationRuntime<TRegistry extends SyncTableRegistry>(\n options: CreateMutationRuntimeOptions<TRegistry>,\n): MutationRuntime<TRegistry> {\n const resolveAuthToken = async () => {\n if (options.getAuthToken) {\n return await options.getAuthToken();\n }\n\n return undefined;\n };\n\n // The decoded JWT claims for stamping `authClaim` create-managed fields into the optimistic overlay\n // (the same value the server stamps from the same claim path). Resolved only when a create needs it\n // (a table with such a field), so tokenless registries never pay a token lookup.\n const resolveAuthClaims = async (): Promise<Record<string, unknown> | undefined> => {\n const token = await resolveAuthToken();\n return token ? decodeJwtClaims(token) : undefined;\n };\n\n const tableContexts = buildTableContexts(options.registry);\n const maxMutationAttempts = options.maxMutationAttempts ?? DEFAULT_MAX_MUTATION_ATTEMPTS;\n const flushBatchSize = options.flushBatchSize ?? DEFAULT_FLUSH_BATCH_SIZE;\n // The fingerprint (ADR-0004) stamped onto each enqueued mutation (ADR-0006). The runtime\n // owns the registry, so it derives this itself; an explicit override is honoured for tests.\n const registryVersion = options.registryVersion ?? fingerprintRegistry(options.registry);\n let flushQueue = Promise.resolve();\n\n // Whether pgxsinkit owns the local schema (and the `pgxsinkit_local_meta` table the durable\n // recovery-required marker lives in). A caller-owned PGlite boot sets this false, so the marker is never\n // touched and the SET/clear seams below are no-ops (proposal §1 caller-owned-PGlite constraint).\n const ownsMetaTable = options.ownsMetaTable ?? true;\n // Cached \"this epoch has already committed the marker `true`\" flag (slice 2). Marker-first ordering:\n // `ensureRecoveryMarker` awaits ONE marker upsert before the first `sending` transition of a dirty epoch,\n // then flips this true, so steady-state flushing pays zero extra crossings. Reset to false only after the\n // self-verifying clear proves no `sending` row remains (`settleRecoveryMarker` / boot recovery).\n let recoveryMarkerDirty = false;\n\n // In-flight mark-sending span counter (FIX 1 — the concurrent-`flushUnit` marker race). Bumped SYNCHRONOUSLY\n // (before any await) whenever a status-update call transitions a row to `sending`, and dropped in a `finally`\n // once that UPDATE has committed — so it brackets the span from \"marker decision\" to \"committed `sending`\n // row\". `settleRecoveryMarker` refuses to clear while any such span is open, so a concurrent pessimistic\n // sender (a `flushUnit` that does NOT ride `flushQueue`) that has passed the cached-dirty check but not yet\n // committed its `sending` UPDATE can never have the marker cleared out from under it.\n //\n // Soundness: EVERY pending→sending transition in existence flows through THIS one runtime on a single JS\n // thread (ADR-0002 single in-DB write path; one engine per store), so the counter fully orders every\n // \"marker-decision → commit\" span against every clear attempt; the durable guarded clear still protects\n // against already-committed rows. Why not the review's primary fix (BEGIN/COMMIT around marker + claim +\n // `sending`): it adds 3 crossings to every flush's hot path, and a single-crossing data-modifying CTE is\n // not expressible in drizzle-rc.4 — the counter costs ZERO crossings and is sound under the single-runtime\n // invariant.\n let markSendingInFlight = 0;\n const markSendingScope: MarkSendingScope = {\n enter: () => {\n markSendingInFlight += 1;\n },\n exit: () => {\n markSendingInFlight -= 1;\n },\n };\n\n /**\n * Marker-first SET (proposal §1 rule 1, corrected): commit the marker `true` BEFORE the first\n * pending→sending transition of a dirty epoch. Invoked from the ONE choke point (`applyMutationStatusUpdates`,\n * gated on a `sending` target) immediately before its UPDATE executes. The upsert auto-commits, so the\n * marker is durable before any `sending` row can commit — the invariant the whole slice protects.\n */\n const ensureRecoveryMarker = async () => {\n if (!ownsMetaTable || recoveryMarkerDirty) {\n return;\n }\n await writeMutationRecoveryRequired(options.db, options.registry, true);\n recoveryMarkerDirty = true;\n };\n\n /**\n * Self-verifying clear at a post-ack seam (in-flight `sending` count has dropped to zero after a flush).\n * Writes the marker `false` only when NOT EXISTS any `sending` row across every writable journal; on a\n * successful clear the epoch-dirty flag resets so the next dirty epoch re-commits the marker.\n */\n const settleRecoveryMarker = async () => {\n if (!ownsMetaTable) {\n return;\n }\n // FIX 1: do NOT attempt the guarded clear while a concurrent mark-sending span is open (between its marker\n // decision and its committed `sending` UPDATE). Clearing now could write `false` before that sender's\n // `sending` row commits, stranding it on a crash. Each sender settles at its OWN end, so the last\n // concurrent unit to close its span still performs the clear — a skipped clear just leaves the\n // conservative `true` for the next settle (or boot recovery) to clear.\n if (markSendingInFlight > 0) {\n return;\n }\n // FIX 1b — reset the epoch-dirty flag SYNCHRONOUSLY here, in the SAME continuation as the counter check and\n // BEFORE the clear's `db.query` is issued (nothing awaits between them: `clearMutationRecoveryMarkerIfSettled`\n // builds the statement synchronously and its first await is `db.query`). Do NOT touch the flag AFTER the\n // clear resolves — a sender that entered mid-clear may have legitimately re-set it `true`, and stomping it\n // back to `false` would reopen the hole.\n //\n // Soundness against a sender racing an IN-FLIGHT clear: every sender's `enter()` + dirty-read is synchronous,\n // so relative to this synchronous check-and-reset block it is either\n // (i) BEFORE it → `markSendingInFlight > 0` here → no clear is issued at all (the FIX 1 gate); or\n // (ii) AFTER it → the sender reads `recoveryMarkerDirty === false` → it awaits\n // `writeMutationRecoveryRequired(true)`, and PGlite's single-connection queue serializes that upsert\n // AFTER the already-issued clear → the marker is durably `true` again BEFORE the sender's `sending`\n // UPDATE (only issued once the marker await resolves) can commit. A crash between the rewrite and the\n // UPDATE leaves marker-`true`/no-row (conservative).\n // On a guard-blocked clear (a committed `sending` row made the UPDATE a no-op) the flag stays pessimistically\n // `false`, so the next sender writes a redundant `true` — one extra crossing on a rare path, harmless.\n recoveryMarkerDirty = false;\n await clearMutationRecoveryMarkerIfSettled(options.db, options.registry);\n };\n\n /** The `sending → pending` recovery UPDATE for one journal (shared by the public + boot recovery paths). */\n const buildRecoverSendingQuery = (journal: JournalTable, nowUs: string) =>\n queryBuilder\n .update(journal)\n .set({\n status: \"pending\",\n updatedAtUs: nowUs,\n sentAtUs: null,\n nextRetryAtUs: nowUs,\n lastError: null,\n lastHttpStatus: null,\n conflictReason: null,\n })\n .where(eq(journal.status, \"sending\"))\n .toSQL();\n\n const readAffectedRows = (result: unknown): number => (result as { affectedRows?: number }).affectedRows ?? 0;\n\n const getTableContext = (table: SyncTableName<TRegistry>) => {\n const context = tableContexts[table];\n\n if (!context) {\n throw new Error(`Unknown mutation table: ${String(table)}`);\n }\n\n return context;\n };\n\n const runInTransaction = async (operation: () => Promise<void>) => {\n await options.db.exec(\"BEGIN\");\n\n try {\n await operation();\n await options.db.exec(\"COMMIT\");\n } catch (error) {\n await options.db.exec(\"ROLLBACK\");\n throw error;\n }\n };\n\n const normalizeBatchItem = (\n item: MutationBatchItem<TRegistry>,\n order: number,\n claims: Record<string, unknown> | undefined,\n ): NormalizedBatchItem => {\n const context = getTableContext(item.table as SyncTableName<TRegistry>);\n const mutationId = globalThis.crypto.randomUUID();\n const nowUs = nowMicroseconds();\n\n switch (item.kind) {\n case \"create\": {\n const strippedInput = stripReadModelOverlayFields(item.input);\n const optimisticRecord = ensureRecord(createOptimisticRecordFromContext(context, strippedInput, claims));\n const entityKey = buildEntityKeyFromRecord(context, optimisticRecord);\n\n return {\n context,\n kind: \"create\",\n entityKey,\n entityKeyJson: serializeEntityKey(entityKey),\n optimisticRecord,\n input: strippedInput,\n mutationId,\n nowUs,\n order,\n };\n }\n case \"update\": {\n const entityKey = normalizeEntityKey(context, item.entityKey);\n const patch = ensureRecord(stripReadModelOverlayFields(item.patch));\n\n return {\n context,\n kind: \"update\",\n entityKey,\n entityKeyJson: serializeEntityKey(entityKey),\n patch,\n blind: item.blind ?? false,\n mutationId,\n nowUs,\n order,\n };\n }\n case \"delete\": {\n const entityKey = normalizeEntityKey(context, item.entityKey);\n\n return {\n context,\n kind: \"delete\",\n entityKey,\n entityKeyJson: serializeEntityKey(entityKey),\n mutationId,\n nowUs,\n order,\n };\n }\n }\n };\n\n const enqueueBatch = async (\n items: ReadonlyArray<MutationBatchItem<TRegistry>>,\n unit?: WriteUnit,\n ): Promise<string[]> => {\n if (items.length === 0) {\n return [];\n }\n\n // The distinct pessimistic write-unit ids this enqueue tagged — returned so the caller can\n // foreground-route them to the authoritative endpoint (ADR-0022). Empty for a purely optimistic batch.\n const pessimisticUnitIds = new Set<string>();\n\n // Resolve the decoded claims once per batch, but only if a create actually needs them (a target\n // table with an `authClaim` create-managed field). Avoids a token lookup for every other write.\n const needsAuthClaims = items.some(\n (item) =>\n item.kind === \"create\" &&\n getTableContext(item.table as SyncTableName<TRegistry>).managedAuthClaimCreateFields.length > 0,\n );\n const claims = needsAuthClaims ? await resolveAuthClaims() : undefined;\n\n const normalizedItems = items.map((item, index) => normalizeBatchItem(item, index, claims));\n\n // ADR-0039: report the DISTINCT non-blind table keys so the client can fire-and-forget activate\n // each target's lazy consistency group. A blind update plans a journal row only (no echo, no\n // activation — the write-only pattern), so it is never reported; create/delete are never blind.\n const ordinaryTables = new Set<string>();\n for (const item of normalizedItems) {\n if (item.kind === \"update\" && item.blind) {\n continue;\n }\n ordinaryTables.add(item.context.key);\n }\n if (ordinaryTables.size > 0 && options.onOrdinaryEnqueue) {\n try {\n options.onOrdinaryEnqueue([...ordinaryTables]);\n } catch {\n // A hook throw must never fail the enqueue (ADR-0039): the activation is a fire-and-forget\n // best-effort; the group self-heals on its next activation regardless.\n }\n }\n\n const batchGroups = new Map<string, { context: TableContext; items: NormalizedBatchItem[] }>();\n\n for (const item of normalizedItems) {\n const existing = batchGroups.get(item.context.key);\n\n if (existing) {\n existing.items.push(item);\n continue;\n }\n\n batchGroups.set(item.context.key, {\n context: item.context,\n items: [item],\n });\n }\n\n for (const { context, items: groupedItems } of batchGroups.values()) {\n groupedItems.sort((left, right) => left.order - right.order);\n const uniqueEntities = dedupeBatchEntities(groupedItems);\n const latestMutationStates = await readLatestMutationStates(options.db, context, uniqueEntities);\n const currentRecordStates = await readCurrentRecordStates(options.db, context, uniqueEntities);\n const entityStates = new Map<string, BatchEntityState>();\n\n for (const entity of uniqueEntities) {\n const latestState = latestMutationStates.get(entity.entityKeyJson);\n const currentState = currentRecordStates.get(entity.entityKeyJson);\n\n entityStates.set(entity.entityKeyJson, {\n entityKey: entity.entityKey,\n entityKeyJson: entity.entityKeyJson,\n record: currentState ? extractRecordFromState(context, currentState) : null,\n overlayKind: currentState?.overlayKind ?? null,\n localUpdatedAtUs: currentState?.localUpdatedAtUs ?? null,\n latestMutationSeq: latestState?.latestMutationSeq ?? null,\n latestMutationKind: latestState?.latestMutationKind ?? null,\n latestMutationStatus: latestState?.latestMutationStatus ?? null,\n });\n }\n\n const plannedMutations: PlannedMutationInsert[] = [];\n const plannedOverlays = new Map<string, PlannedOverlayUpsert>();\n\n for (const item of groupedItems) {\n const entityState = entityStates.get(item.entityKeyJson);\n\n if (!entityState) {\n throw new Error(`Missing batch state for table ${context.key}`);\n }\n\n switch (item.kind) {\n case \"create\": {\n if ((entityState.latestMutationSeq ?? 0) !== 0) {\n throw new Error(`${context.key} already has queued mutations`);\n }\n\n plannedMutations.push({\n mutationId: item.mutationId,\n entityKey: item.entityKey,\n entityKeyJson: item.entityKeyJson,\n mutationKind: \"create\",\n payloadJson: jsonStringifyPayload({\n kind: \"create\",\n value: item.input,\n }),\n nowUs: item.nowUs,\n // A create has no Base server version (ADR-0015): its conflict is a PK collision, a\n // separate concern from the stale-write check.\n baseServerVersion: null,\n });\n\n entityState.record = item.optimisticRecord;\n entityState.overlayKind = \"pending_create\";\n entityState.localUpdatedAtUs = item.nowUs;\n entityState.latestMutationSeq = (entityState.latestMutationSeq ?? 0) + 1;\n entityState.latestMutationKind = \"create\";\n entityState.latestMutationStatus = \"pending\";\n plannedOverlays.set(item.entityKeyJson, {\n entityKey: item.entityKey,\n record: item.optimisticRecord,\n overlayKind: \"pending_create\",\n localUpdatedAtUs: item.nowUs,\n });\n break;\n }\n case \"update\": {\n if (item.blind) {\n // ADR-0022 addendum — a BLIND update: the write target is excluded from the actor's read\n // shape (its rows never stream here), so there is no local base row to seed and no optimistic\n // state to show. It is meaningful ONLY when the write routes to the authoritative endpoint (the\n // /unit expander is authoritative): an optimistic-routed blind write has nothing to converge, so\n // it is rejected at enqueue. The `unit` fixes the route inside a `transaction` block; a plain\n // enqueue on a statically-pessimistic table earns its own pessimistic unit downstream.\n const routesPessimistic = unit ? unit.mode === \"pessimistic\" : context.entry.writeMode === \"pessimistic\";\n if (!routesPessimistic) {\n throw new Error(\n `${context.key}: updateBlind requires a pessimistic write unit — use transaction({ mode: \"pessimistic\" }) (an optimistic blind write has nothing to show and no base to converge)`,\n );\n }\n\n // KEEP the already-queued-for-deletion guard (journal-derived; needs no local record).\n if (entityState.latestMutationKind === \"delete\" && entityState.latestMutationStatus !== \"acked\") {\n throw new Error(`${context.key} is already queued for deletion`);\n }\n\n // Plan a journal row ONLY — no overlay, so nothing enters the read model and nothing can linger\n // there. `baseServerVersion: null`: the /unit expander is authoritative, there is no base to\n // capture. The `pessimistic-blind` marker keeps the row off the optimistic flusher and lets\n // reconcile retire it after ack WITHOUT a synced echo (there is no visible row to converge).\n plannedMutations.push({\n mutationId: item.mutationId,\n entityKey: item.entityKey,\n entityKeyJson: item.entityKeyJson,\n mutationKind: \"update\",\n payloadJson: jsonStringifyPayload({\n kind: \"update\",\n patch: item.patch,\n }),\n nowUs: item.nowUs,\n baseServerVersion: null,\n writeMode: \"pessimistic-blind\",\n });\n\n // Advance only the journal-derived tracking (no record/overlay): so a later same-batch item on\n // this entity chains in author order and sees the pending blind write.\n entityState.latestMutationSeq = (entityState.latestMutationSeq ?? 0) + 1;\n entityState.latestMutationKind = \"update\";\n entityState.latestMutationStatus = \"pending\";\n break;\n }\n\n if (!entityState.record) {\n throw new Error(`${context.key} not found in local read model`);\n }\n\n if (entityState.latestMutationKind === \"delete\" && entityState.latestMutationStatus !== \"acked\") {\n throw new Error(`${context.key} is already queued for deletion`);\n }\n\n // ADR-0015: capture the Base server version BEFORE the record is replaced by the\n // optimistic value below (which overwrites the Server version with the client clock).\n const updateBaseServerVersion = captureChainHeadBase(context, entityState);\n const overlayKind = entityState.overlayKind === \"pending_create\" ? \"pending_create\" : \"pending_update\";\n const optimisticRecord = ensureRecord(\n buildOptimisticRecord(\n context,\n {\n ...entityState.record,\n ...item.patch,\n // Re-stamp the on-update managed timestamp(s) generically (governance-driven) — for a\n // convention table this is exactly `updatedAtUs`, for a custom-named Server version\n // it is that column, so the optimistic row never carries a stale managed value.\n ...buildUpdateManagedNowStamp(context, item.nowUs),\n },\n {\n overlayKind,\n localUpdatedAtUs: item.nowUs,\n },\n ),\n );\n plannedMutations.push({\n mutationId: item.mutationId,\n entityKey: item.entityKey,\n entityKeyJson: item.entityKeyJson,\n mutationKind: \"update\",\n payloadJson: jsonStringifyPayload({\n kind: \"update\",\n patch: item.patch,\n }),\n nowUs: item.nowUs,\n baseServerVersion: updateBaseServerVersion,\n });\n\n entityState.record = optimisticRecord;\n entityState.overlayKind = overlayKind;\n entityState.localUpdatedAtUs = item.nowUs;\n entityState.latestMutationSeq = (entityState.latestMutationSeq ?? 0) + 1;\n entityState.latestMutationKind = \"update\";\n entityState.latestMutationStatus = \"pending\";\n plannedOverlays.set(item.entityKeyJson, {\n entityKey: item.entityKey,\n record: optimisticRecord,\n overlayKind,\n localUpdatedAtUs: item.nowUs,\n });\n break;\n }\n case \"delete\": {\n if (!entityState.record) {\n throw new Error(`${context.key} not found in local read model`);\n }\n\n if (entityState.latestMutationKind === \"delete\" && entityState.latestMutationStatus !== \"acked\") {\n throw new Error(`${context.key} is already queued for deletion`);\n }\n\n const deleteBaseServerVersion = captureChainHeadBase(context, entityState);\n plannedMutations.push({\n mutationId: item.mutationId,\n entityKey: item.entityKey,\n entityKeyJson: item.entityKeyJson,\n mutationKind: \"delete\",\n payloadJson: jsonStringifyPayload({\n kind: \"delete\",\n entityKey: item.entityKey,\n }),\n nowUs: item.nowUs,\n baseServerVersion: deleteBaseServerVersion,\n });\n\n entityState.overlayKind = \"pending_delete\";\n entityState.localUpdatedAtUs = item.nowUs;\n entityState.latestMutationSeq = (entityState.latestMutationSeq ?? 0) + 1;\n entityState.latestMutationKind = \"delete\";\n entityState.latestMutationStatus = \"pending\";\n plannedOverlays.set(item.entityKeyJson, {\n entityKey: item.entityKey,\n record: entityState.record,\n overlayKind: \"pending_delete\",\n localUpdatedAtUs: item.nowUs,\n });\n break;\n }\n }\n }\n\n // ADR-0022: an explicit unit (from a `transaction` block) tags the whole batch; otherwise a\n // statically-`pessimistic` table earns its own per-enqueue unit, so its writes route to the\n // authoritative endpoint too. An optimistic table with no explicit unit stays untagged.\n const effectiveUnit: WriteUnit | undefined =\n unit ??\n (context.entry.writeMode === \"pessimistic\"\n ? { id: globalThis.crypto.randomUUID(), mode: \"pessimistic\" }\n : undefined);\n if (effectiveUnit?.mode === \"pessimistic\") {\n pessimisticUnitIds.add(effectiveUnit.id);\n }\n await insertMutationsBulk(options.db, context, plannedMutations, registryVersion, effectiveUnit);\n await upsertOverlayRecordsBulk(options.db, context, [...plannedOverlays.values()]);\n }\n\n return [...pessimisticUnitIds];\n };\n\n const runFlush = async (table?: SyncTableName<TRegistry>) => {\n const affectedContexts = new Map<string, TableContext>();\n const quarantinedMutationIds = new Set<string>();\n const conflictedMutationIds = new Set<string>();\n let processedCount = 0;\n\n do {\n const batchResult = await flushBatch(\n options.db,\n tableContexts as Record<string, TableContext>,\n options.writeUrl,\n maxMutationAttempts,\n flushBatchSize,\n table,\n resolveAuthToken,\n options.requestHeaders,\n ensureRecoveryMarker,\n markSendingScope,\n );\n\n processedCount = batchResult.processedCount;\n\n for (const context of batchResult.affectedContexts) {\n affectedContexts.set(context.key, context);\n }\n\n for (const mutationId of batchResult.quarantinedMutationIds) {\n quarantinedMutationIds.add(mutationId);\n }\n\n for (const mutationId of batchResult.conflictedMutationIds) {\n conflictedMutationIds.add(mutationId);\n }\n } while (processedCount > 0);\n\n for (const context of affectedContexts.values()) {\n await reconcileTable(options.db, context);\n }\n\n // Post-ack seam (optimistic path): the drain loop above has settled every `sending` row this pass\n // produced (into acked/failed/quarantined/conflicted), so try the self-verifying clear — it writes the\n // marker `false` iff no `sending` row remains across any journal, resetting the epoch-dirty flag.\n await settleRecoveryMarker();\n\n // Surface newly-quarantined mutations after reconciliation so the app never has to\n // poll for permanently-rejected writes (ADR-0006 decision 4). Never silent loss.\n if (quarantinedMutationIds.size > 0 && options.onQuarantine) {\n const details = await readMutationDetailsForContexts(\n options.db,\n [...affectedContexts.values()],\n quarantinedMutationIds,\n );\n\n if (details.length > 0) {\n await options.onQuarantine(details);\n }\n }\n\n // Surface newly-conflicted (stale) writes (ADR-0015). The optimistic Overlay is kept, so the app\n // can show a resolution/diff UI and resolve each as a new write (or discard it). Never silent.\n if (conflictedMutationIds.size > 0 && options.onConflict) {\n const details = await readMutationDetailsForContexts(\n options.db,\n [...affectedContexts.values()],\n conflictedMutationIds,\n );\n\n if (details.length > 0) {\n await options.onConflict(details);\n }\n }\n };\n\n const runtime: MutationRuntime<TRegistry> = {\n registryVersion,\n create: async (table, input) => {\n let unitIds: string[] = [];\n await runInTransaction(async () => {\n unitIds = await enqueueBatch([{ table, kind: \"create\", input }]);\n });\n // A statically-`pessimistic` table foreground-routes its write to the authoritative endpoint\n // (ADR-0022) — the write is server-authoritative, so it is sent immediately, not left for the\n // optimistic convergence loop (which skips pessimistic rows).\n for (const unitId of unitIds) {\n await runtime.flushUnit(unitId);\n }\n },\n update: async (table, entityKeyInput, patch) => {\n let unitIds: string[] = [];\n await runInTransaction(async () => {\n unitIds = await enqueueBatch([{ table, kind: \"update\", entityKey: entityKeyInput, patch }]);\n });\n for (const unitId of unitIds) {\n await runtime.flushUnit(unitId);\n }\n },\n delete: async (table, entityKeyInput) => {\n let unitIds: string[] = [];\n await runInTransaction(async () => {\n unitIds = await enqueueBatch([{ table, kind: \"delete\", entityKey: entityKeyInput }]);\n });\n for (const unitId of unitIds) {\n await runtime.flushUnit(unitId);\n }\n },\n batch: async (items, unit) => {\n let unitIds: string[] = [];\n await runInTransaction(async () => {\n unitIds = await enqueueBatch(items, unit);\n });\n // An explicit unit (from a `transaction` block) is flushed by the caller; only foreground-route the\n // units a plain `batch()` generated for statically-pessimistic tables.\n if (!unit) {\n for (const unitId of unitIds) {\n await runtime.flushUnit(unitId);\n }\n }\n },\n discardConflict: async (table, entityKeyInput) => {\n const context = getTableContext(table);\n const entityKey = normalizeEntityKey(context, entityKeyInput);\n const entityKeyJson = serializeEntityKey(entityKey);\n\n // discardTerminalEntity owns its own transaction (like reconcileTable), so it is not wrapped.\n await discardTerminalEntity(options.db, context, entityKey, entityKeyJson, \"conflicted\");\n },\n discardQuarantined: async (table, entityKeyInput) => {\n const context = getTableContext(table);\n const entityKey = normalizeEntityKey(context, entityKeyInput);\n const entityKeyJson = serializeEntityKey(entityKey);\n\n // Symmetric to discardConflict — retire the entity's `quarantined` journal rows and clear the\n // kept overlay behind the same owed-guard, so a permanently-rejected write is a real rollback.\n await discardTerminalEntity(options.db, context, entityKey, entityKeyJson, \"quarantined\");\n },\n flush: async (table) => {\n const nextFlush = flushQueue.then(() => runFlush(table));\n flushQueue = nextFlush.catch(() => undefined);\n await nextFlush;\n },\n flushUnit: async (unitId) => {\n const contexts = Object.values(tableContexts).filter((context): context is TableContext => context != null);\n const unitRows = await readUnitPendingRows(options.db, contexts, unitId);\n if (unitRows.length === 0) {\n return { acks: [] };\n }\n\n // Prepare the unit's rows (entity key + envelope payload) and group them by table.\n const prepared: PreparedBatchRow[] = [];\n const byContext = new Map<string, PreparedBatchRow[]>();\n for (const row of unitRows) {\n const context = tableContexts[row.tableKey];\n if (!context) {\n continue;\n }\n const entityKey = JSON.parse(row.entityKeyJson) as Record<string, string>;\n const rawPayload = JSON.parse(row.payloadJson) as Record<string, unknown>;\n const preparedRow: PreparedBatchRow = {\n ...row,\n context,\n entityKey,\n envelopePayload:\n row.mutationKind === \"delete\"\n ? entityKey\n : toSqlColumnPayload(\n context,\n stripManagedFields(\n context,\n (rawPayload[\"value\"] ?? rawPayload[\"patch\"] ?? rawPayload) as Record<string, unknown>,\n row.mutationKind as \"create\" | \"update\",\n ),\n ),\n sqlTableName: context.entry.shape?.tableName ?? context.key,\n };\n prepared.push(preparedRow);\n const list = byContext.get(context.key);\n if (list) {\n list.push(preparedRow);\n } else {\n byContext.set(context.key, [preparedRow]);\n }\n }\n\n // Mark every member sending (persist the resolved Base server version, like the batch path).\n const sentAtUs = nowMicroseconds();\n for (const rows of byContext.values()) {\n await applyMutationStatusUpdates(\n options.db,\n rows[0]!.context,\n rows.map((row) => ({\n mutationId: row.mutationId,\n status: \"sending\" as const,\n attemptCount: row.attemptCount + 1,\n updatedAtUs: sentAtUs,\n sentAtUs,\n replaceSentAtUs: true,\n baseServerVersion: row.baseServerVersion,\n replaceBaseServerVersion: true,\n lastError: null,\n nextRetryAtUs: null,\n lastHttpStatus: null,\n conflictReason: null,\n })),\n ensureRecoveryMarker,\n markSendingScope,\n );\n }\n\n const mutations = prepared.map((row) => ({\n tableName: row.sqlTableName,\n entityKey: row.entityKey,\n mutationId: row.mutationId,\n mutationSeq: row.mutationSeq,\n kind: row.mutationKind as \"create\" | \"update\" | \"delete\",\n payload: row.envelopePayload,\n clientTimestampUs: sentAtUs,\n ...(row.baseServerVersion != null ? { baseServerVersion: row.baseServerVersion } : {}),\n }));\n\n const url = resolveAuthoritativeMutationUrl(options.writeUrl);\n let acksByMutationId: Map<string, BatchMutationAck[\"acks\"][number]>;\n\n try {\n const authToken = await options.getAuthToken?.();\n let response = await fetch(url, {\n method: \"POST\",\n headers: buildRequestHeaders(authToken, options.requestHeaders),\n body: jsonStringifyPayload({ writeUnit: unitId, mutations }),\n });\n\n if ([401, 403].includes(response.status) && options.getAuthToken) {\n response = await fetch(url, {\n method: \"POST\",\n headers: buildRequestHeaders(await options.getAuthToken(), options.requestHeaders),\n body: jsonStringifyPayload({ writeUnit: unitId, mutations }),\n });\n }\n\n if (!response.ok) {\n const text = await response.text();\n throw new MutationRequestError(\n text.length > 0 ? text : `Authoritative write responded with ${response.status}`,\n response.status,\n parseBatchRejections(text),\n );\n }\n\n const responseJson = (await response.json()) as BatchMutationAck;\n acksByMutationId = new Map(responseJson.acks.map((ack) => [ack.mutationId, ack]));\n } catch (error) {\n // A pessimistic write is foreground: it never reached the server (transport / non-2xx), so the\n // unit did not happen. Mark it failed — KEEPING the optimistic overlay so a retry can resend — and\n // rethrow so the caller surfaces it. There is no background retry for pessimistic units.\n const failedAtUs = nowMicroseconds();\n const httpStatus = error instanceof MutationRequestError ? error.status : null;\n const errorMessage = error instanceof Error ? error.message : \"Authoritative write failed\";\n for (const rows of byContext.values()) {\n await applyMutationStatusUpdates(\n options.db,\n rows[0]!.context,\n rows.map((row) => {\n const attemptCount = row.attemptCount + 1;\n const outcome = resolveBatchFailureOutcome(attemptCount, maxMutationAttempts, failedAtUs);\n return {\n mutationId: row.mutationId,\n status: outcome.status,\n attemptCount,\n updatedAtUs: failedAtUs,\n lastError: errorMessage,\n nextRetryAtUs: outcome.nextRetryAtUs,\n lastHttpStatus: httpStatus,\n conflictReason: null,\n };\n }),\n );\n }\n throw error;\n }\n\n // Apply each member's ack.\n const ackedAtUs = nowMicroseconds();\n const failedAtUs = nowMicroseconds();\n const rejectedIds = new Set<string>();\n const conflictedIds = new Set<string>();\n\n for (const rows of byContext.values()) {\n await applyMutationStatusUpdates(\n options.db,\n rows[0]!.context,\n rows.map((row) => {\n const ack = acksByMutationId.get(row.mutationId);\n\n if (ack?.status === \"rejected\") {\n // ADR-0022 §4: a business rejection. Terminal `rejected`; the overlay is auto-discarded below.\n rejectedIds.add(row.mutationId);\n return {\n mutationId: row.mutationId,\n status: \"rejected\" as const,\n attemptCount: row.attemptCount + 1,\n updatedAtUs: failedAtUs,\n lastError: ack.rejectionReason ?? \"Rejected by the authoritative endpoint\",\n nextRetryAtUs: null,\n lastHttpStatus: ack.httpStatus ?? 409,\n conflictReason: ack.rejectionReason ?? \"Rejected by the authoritative endpoint\",\n };\n }\n\n if (ack?.status === \"conflicted\") {\n // ADR-0015: a stale member — terminal `conflicted`, overlay KEPT (resolve as a new write).\n conflictedIds.add(row.mutationId);\n return {\n mutationId: row.mutationId,\n status: \"conflicted\" as const,\n attemptCount: row.attemptCount + 1,\n updatedAtUs: failedAtUs,\n serverUpdatedAtUs: ack.serverUpdatedAtUs ?? null,\n replaceServerUpdatedAtUs: true,\n lastError: ack.conflictReason ?? \"Stale write rejected (reject-if-stale)\",\n nextRetryAtUs: null,\n lastHttpStatus: ack.httpStatus ?? 409,\n conflictReason: ack.conflictReason ?? \"Stale write rejected (reject-if-stale)\",\n };\n }\n\n if (!ack || ack.status !== \"acked\") {\n const attemptCount = row.attemptCount + 1;\n const outcome = resolveFailureOutcome(\n ack?.httpStatus ?? null,\n attemptCount,\n maxMutationAttempts,\n failedAtUs,\n );\n return {\n mutationId: row.mutationId,\n status: outcome.status,\n attemptCount,\n updatedAtUs: failedAtUs,\n lastError: ack?.conflictReason ?? \"Authoritative write not acknowledged\",\n nextRetryAtUs: outcome.nextRetryAtUs,\n lastHttpStatus: ack?.httpStatus ?? null,\n conflictReason: null,\n };\n }\n\n return {\n mutationId: row.mutationId,\n status: \"acked\" as const,\n attemptCount: row.attemptCount + 1,\n updatedAtUs: ackedAtUs,\n ackedAtUs,\n replaceAckedAtUs: true,\n serverUpdatedAtUs: ack.serverUpdatedAtUs ?? null,\n replaceServerUpdatedAtUs: true,\n lastError: null,\n nextRetryAtUs: null,\n lastHttpStatus: row.mutationKind === \"delete\" ? 204 : 200,\n conflictReason: null,\n };\n }),\n );\n }\n\n // ADR-0022 §4: auto-discard the optimistic overlay for every rejected entity (the whole unit was\n // declined). The terminal `rejected` journal row is kept for diagnostics + `onReject`.\n for (const row of prepared) {\n if (rejectedIds.has(row.mutationId)) {\n await discardOverlayForSettledEntity(options.db, row.context, row.entityKey, row.entityKeyJson);\n }\n }\n\n const affectedContexts = [...byContext.keys()]\n .map((key) => tableContexts[key])\n .filter((context): context is TableContext => context != null);\n for (const context of affectedContexts) {\n await reconcileTable(options.db, context);\n }\n\n if (rejectedIds.size > 0 && options.onReject) {\n const details = await readMutationDetailsForContexts(options.db, affectedContexts, rejectedIds);\n if (details.length > 0) {\n await options.onReject(details);\n }\n }\n if (conflictedIds.size > 0 && options.onConflict) {\n const details = await readMutationDetailsForContexts(options.db, affectedContexts, conflictedIds);\n if (details.length > 0) {\n await options.onConflict(details);\n }\n }\n\n // Post-ack seam (pessimistic path): every member of the unit has left `sending`, so try the\n // self-verifying clear — it settles the marker to `false` iff no `sending` row remains anywhere.\n await settleRecoveryMarker();\n\n return { acks: [...acksByMutationId.values()] };\n },\n reconcile: async (table) => {\n const contexts = filterContexts(tableContexts, table);\n\n for (const context of contexts) {\n await reconcileTable(options.db, context);\n }\n },\n retryFailed: async (table) => {\n assertValidMutationTransition(\"failed\", \"pending\");\n const contexts = filterContexts(tableContexts, table);\n const nowUs = nowMicroseconds();\n\n for (const context of contexts) {\n const journal = context.tables.journal;\n const query = queryBuilder\n .update(journal)\n .set({ status: \"pending\", nextRetryAtUs: nowUs, updatedAtUs: nowUs, conflictReason: null })\n .where(eq(journal.status, \"failed\"))\n .toSQL();\n await options.db.query(query.sql, query.params as unknown[]);\n }\n },\n recoverSending: async (table) => {\n assertValidMutationTransition(\"sending\", \"pending\");\n const contexts = filterContexts(tableContexts, table);\n const nowUs = nowMicroseconds();\n\n for (const context of contexts) {\n const query = buildRecoverSendingQuery(context.tables.journal, nowUs);\n await options.db.query(query.sql, query.params as unknown[]);\n }\n },\n runBootRecovery: async ({ ownsMetaTable: bootOwnsMetaTable, restore }) => {\n assertValidMutationTransition(\"sending\", \"pending\");\n const contexts = filterContexts(tableContexts, undefined);\n const tablesVisited = contexts.length;\n\n // Caller-owned PGlite: the meta table may not exist, so never touch the marker — legacy always-recover.\n if (!bootOwnsMetaTable) {\n await runtime.recoverSending();\n return { skipped: false, required: true, tablesVisited, rowsRecovered: null };\n }\n\n // Restore boot ignores the marker entirely (proposal §1): legacy recovery lifts any `sending` back to\n // `pending`, quarantine parks every recovered non-terminal row, then the self-verifying clear settles\n // the marker (a clean marker in the backup must never bypass quarantine — quarantine ran first).\n if (restore) {\n await runtime.recoverSending();\n await runtime.quarantineRecovered();\n await settleRecoveryMarker();\n return { skipped: false, required: true, tablesVisited, rowsRecovered: null };\n }\n\n const marker = await readMutationRecoveryRequired(options.db, options.registry);\n\n // Marker `false`: a clean prior settle proved no `sending` row remains — skip the per-table loop.\n if (marker === false) {\n return { skipped: true, required: false, tablesVisited: 0, rowsRecovered: 0 };\n }\n\n // Marker absent (legacy/pre-feature store): one conservative recovery pass, then initialize the marker\n // (the pass just guaranteed no `sending` row remains, so an unconditional `false` is correct).\n if (marker === null) {\n await runtime.recoverSending();\n await writeMutationRecoveryRequired(options.db, options.registry, false);\n recoveryMarkerDirty = false;\n return { skipped: false, required: true, tablesVisited, rowsRecovered: null };\n }\n\n // Marker `true`: a crash may have left committed `sending` rows. Run the N per-table updates PLUS the\n // self-verifying clear atomically (a correctness upgrade over today's un-wrapped loop), counting the\n // rows lifted `sending → pending` from each UPDATE's affected-row count.\n const nowUs = nowMicroseconds();\n let rowsRecovered = 0;\n await runInTransaction(async () => {\n for (const context of contexts) {\n const query = buildRecoverSendingQuery(context.tables.journal, nowUs);\n const result = await options.db.query(query.sql, query.params as unknown[]);\n rowsRecovered += readAffectedRows(result);\n }\n await clearMutationRecoveryMarkerIfSettled(options.db, options.registry);\n });\n recoveryMarkerDirty = false;\n return { skipped: false, required: true, tablesVisited, rowsRecovered };\n },\n quarantineRecovered: async (table) => {\n // The restore-boot quarantine (ADR-0035 decision 6): every non-terminal recovered row is parked in the\n // terminal `quarantined` state so NOTHING recovered from a backup auto-flushes (no dedupe ledger →\n // unsafe replay). `pending -> quarantined` is a restore-only edge (see mutation-state.ts); `sending`\n // and `failed` already reach quarantine. Assert all three edges up front so a future transition-table\n // change that breaks restore fails loudly here rather than silently skipping the quarantine.\n assertValidMutationTransition(\"pending\", \"quarantined\");\n assertValidMutationTransition(\"sending\", \"quarantined\");\n assertValidMutationTransition(\"failed\", \"quarantined\");\n const contexts = filterContexts(tableContexts, table);\n const nowUs = nowMicroseconds();\n\n for (const context of contexts) {\n const journal = context.tables.journal;\n const query = queryBuilder\n .update(journal)\n .set({\n status: \"quarantined\",\n updatedAtUs: nowUs,\n // Terminal: never retried, so clear the retry cursor and name restore as the cause on the row so\n // an inspecting app can tell a restore-quarantined write from a server-rejected one.\n nextRetryAtUs: null,\n lastError: \"Quarantined on restore: recovered from a store backup, not replayed (ADR-0035).\",\n conflictReason: null,\n })\n .where(inArray(journal.status, [\"pending\", \"sending\", \"failed\"]))\n .toSQL();\n await options.db.query(query.sql, query.params as unknown[]);\n }\n },\n readMutationStats: async (table) => {\n const contexts = filterContexts(tableContexts, table);\n const totals: MutationDiagnostics = {\n pendingCount: 0,\n sendingCount: 0,\n failedCount: 0,\n quarantinedCount: 0,\n conflictedCount: 0,\n rejectedCount: 0,\n ackedCount: 0,\n };\n\n for (const context of contexts) {\n const journal = context.tables.journal;\n // Drizzle has no `FILTER` operator (tier ②): each aggregate is a typed `sql` fragment over the\n // journal `status` column object with a bound status literal, aliased to the exact camelCase row\n // key the totals below read (the raw seam returns rows UNMAPPED, so aliases are load-bearing).\n const filteredCount = (status: MutationStatus, columnAlias: string) =>\n sql<number>`count(*) filter (where ${journal.status} = ${status})::int`.as(columnAlias);\n const query = queryBuilder\n .select({\n pendingCount: filteredCount(\"pending\", \"pendingCount\"),\n sendingCount: filteredCount(\"sending\", \"sendingCount\"),\n failedCount: filteredCount(\"failed\", \"failedCount\"),\n quarantinedCount: filteredCount(\"quarantined\", \"quarantinedCount\"),\n conflictedCount: filteredCount(\"conflicted\", \"conflictedCount\"),\n rejectedCount: filteredCount(\"rejected\", \"rejectedCount\"),\n ackedCount: filteredCount(\"acked\", \"ackedCount\"),\n })\n .from(journal)\n .toSQL();\n const result = await options.db.query<MutationDiagnostics & Record<string, unknown>>(\n query.sql,\n query.params as unknown[],\n );\n\n const row = result.rows[0];\n if (!row) {\n continue;\n }\n\n totals.pendingCount += row.pendingCount;\n totals.sendingCount += row.sendingCount;\n totals.failedCount += row.failedCount;\n totals.quarantinedCount += row.quarantinedCount;\n totals.conflictedCount += row.conflictedCount;\n totals.rejectedCount += row.rejectedCount;\n totals.ackedCount += row.ackedCount;\n }\n\n return totals;\n },\n readMutationDetails: async (table) => {\n const contexts = filterContexts(tableContexts, table);\n return readMutationDetailsForContexts(options.db, contexts);\n },\n createOptimisticRecord: (table, input) => {\n const context = getTableContext(table);\n return createOptimisticRecordFromContext(context, input);\n },\n };\n\n return runtime;\n}\n\n/**\n * Read journal entries across the given contexts as {@link MutationDetail}s, newest first.\n * Shared by the public `readMutationDetails` and the flush path's quarantine surfacing,\n * optionally narrowed to a set of mutation ids.\n */\nasync function readMutationDetailsForContexts(\n db: MutationDb,\n contexts: TableContext[],\n mutationIds?: ReadonlySet<string>,\n): Promise<MutationDetail[]> {\n const rows: MutationDetail[] = [];\n\n for (const context of contexts) {\n const journal = context.tables.journal;\n // The raw seam returns rows UNMAPPED (no drizzle result mapping), so every field is aliased\n // explicitly to its camelCase row key, and the `_us` bigints keep their `::text` casts.\n const query = queryBuilder\n .select({\n mutationId: sql<string>`${journal.mutationId}`.as(\"mutationId\"),\n entityKeyJson: sql<string>`${journal.entityKeyJson}`.as(\"entityKeyJson\"),\n mutationSeq: sql<number>`${journal.mutationSeq}`.as(\"mutationSeq\"),\n mutationKind: sql<MutationKind>`${journal.mutationKind}`.as(\"mutationKind\"),\n status: journal.status,\n attemptCount: sql<number>`${journal.attemptCount}`.as(\"attemptCount\"),\n lastHttpStatus: sql<number | null>`${journal.lastHttpStatus}`.as(\"lastHttpStatus\"),\n lastError: sql<string | null>`${journal.lastError}`.as(\"lastError\"),\n conflictReason: sql<string | null>`${journal.conflictReason}`.as(\"conflictReason\"),\n nextRetryAtUs: sql<string | null>`${journal.nextRetryAtUs}::text`.as(\"nextRetryAtUs\"),\n serverUpdatedAtUs: sql<string | null>`${journal.serverUpdatedAtUs}::text`.as(\"serverUpdatedAtUs\"),\n updatedAtUs: sql<string>`${journal.updatedAtUs}::text`.as(\"updatedAtUs\"),\n registryVersion: sql<string | null>`${journal.registryVersion}`.as(\"registryVersion\"),\n })\n .from(journal)\n .orderBy(desc(journal.updatedAtUs), desc(journal.mutationSeq))\n .toSQL();\n const result = await db.query<MutationDetailRow>(query.sql, query.params as unknown[]);\n\n for (const row of result.rows) {\n if (mutationIds && !mutationIds.has(row.mutationId)) {\n continue;\n }\n\n rows.push({\n tableName: context.key,\n entityKey: JSON.parse(row.entityKeyJson) as Record<string, string>,\n mutationId: row.mutationId,\n mutationSeq: row.mutationSeq,\n mutationKind: row.mutationKind,\n status: row.status,\n attemptCount: row.attemptCount,\n lastHttpStatus: row.lastHttpStatus,\n lastError: row.lastError,\n conflictReason: row.conflictReason,\n nextRetryAtUs: row.nextRetryAtUs,\n serverUpdatedAtUs: row.serverUpdatedAtUs,\n updatedAtUs: row.updatedAtUs,\n registryVersion: row.registryVersion,\n });\n }\n }\n\n return rows.sort((left, right) => Number(right.updatedAtUs) - Number(left.updatedAtUs));\n}\n\ninterface MutationRow extends Record<string, unknown> {\n mutationId: string;\n entityKeyJson: string;\n mutationSeq: number;\n mutationKind: MutationKind;\n status: MutationStatus;\n payloadJson: string;\n attemptCount: number;\n lastHttpStatus: number | null;\n lastError: string | null;\n conflictReason: string | null;\n nextRetryAtUs: string | null;\n serverUpdatedAtUs: string | null;\n registryVersion: string | null;\n}\n\ninterface MutationDetailRow extends Record<string, unknown> {\n mutationId: string;\n entityKeyJson: string;\n mutationSeq: number;\n mutationKind: MutationKind;\n status: MutationStatus;\n attemptCount: number;\n lastHttpStatus: number | null;\n lastError: string | null;\n conflictReason: string | null;\n nextRetryAtUs: string | null;\n serverUpdatedAtUs: string | null;\n updatedAtUs: string;\n registryVersion: string | null;\n}\n\ninterface CurrentRecordStateRow extends Record<string, unknown> {\n overlayKind: string;\n localUpdatedAtUs: string;\n latestMutationSeq: number | null;\n latestMutationKind: MutationKind | null;\n latestMutationStatus: MutationStatus | null;\n}\n\ninterface BatchLatestMutationStateRow extends Record<string, unknown> {\n entityKeyJson: string;\n latestMutationSeq: number | null;\n latestMutationKind: MutationKind | null;\n latestMutationStatus: MutationStatus | null;\n}\n\ninterface BatchCurrentRecordStateRow extends Record<string, unknown> {\n entityKeyJson: string;\n overlayKind: string;\n localUpdatedAtUs: string;\n}\n\ninterface BatchEntityRef {\n entityKey: Record<string, string>;\n entityKeyJson: string;\n}\n\ninterface PlannedMutationInsert {\n mutationId: string;\n entityKey: Record<string, string>;\n entityKeyJson: string;\n mutationKind: MutationKind;\n payloadJson: string;\n nowUs: string;\n /**\n * The Base server version (ADR-0015) stamped at enqueue: the synced Server version the user saw,\n * for a **chain head** (the first staged write on the entity). `null` for a `create` (no base) and\n * for a **chained** write — the latter resolves its base at flush from its acked predecessor\n * (readPendingBatchRows), by Per-entity flush serialization (ADR-0014).\n */\n baseServerVersion: string | null;\n /**\n * A per-row `write_mode` override (ADR-0022 addendum). Left unset for an ordinary row, which inherits the\n * unit's mode at insert. A blind update sets `\"pessimistic-blind\"` so the row is flushed only by its unit's\n * foreground path (never the optimistic batch) and retires from the journal without a synced echo.\n */\n writeMode?: string | null;\n}\n\ninterface PlannedOverlayUpsert {\n entityKey: Record<string, string>;\n record: Record<string, unknown>;\n overlayKind: string;\n localUpdatedAtUs: string;\n}\n\ninterface BatchEntityState {\n entityKey: Record<string, string>;\n entityKeyJson: string;\n record: Record<string, unknown> | null;\n overlayKind: string | null;\n localUpdatedAtUs: string | null;\n latestMutationSeq: number | null;\n latestMutationKind: MutationKind | null;\n latestMutationStatus: MutationStatus | null;\n}\n\ntype NormalizedBatchItem =\n | {\n context: TableContext;\n kind: \"create\";\n entityKey: Record<string, string>;\n entityKeyJson: string;\n optimisticRecord: Record<string, unknown>;\n input: unknown;\n mutationId: string;\n nowUs: string;\n order: number;\n }\n | {\n context: TableContext;\n kind: \"update\";\n entityKey: Record<string, string>;\n entityKeyJson: string;\n patch: Record<string, unknown>;\n /** A blind update (ADR-0022 addendum): journal-only, no base-row presence check, no overlay. */\n blind: boolean;\n mutationId: string;\n nowUs: string;\n order: number;\n }\n | {\n context: TableContext;\n kind: \"delete\";\n entityKey: Record<string, string>;\n entityKeyJson: string;\n mutationId: string;\n nowUs: string;\n order: number;\n };\n\n/**\n * The Base server version (ADR-0015) to stamp at enqueue for an update/delete. Only a **chain head**\n * — the first staged write on the entity (no earlier unresolved mutation) — captures an enqueue-time\n * base: the synced Server version the user's edit was authored against, so a genuine external write\n * between view and apply is caught. A **chained** write (an earlier same-entity mutation is still\n * owed) returns `null` here; it resolves its base at flush from its acked predecessor, so an entity's\n * own successive edits never self-conflict (decision 2).\n */\nfunction captureChainHeadBase(context: TableContext, entityState: BatchEntityState): string | null {\n if ((entityState.latestMutationSeq ?? 0) !== 0) {\n return null;\n }\n\n if (!context.serverVersionPropertyKey || !entityState.record) {\n return null;\n }\n\n // The Server version is a bigint count of microseconds, surfaced as a string/number/bigint\n // depending on the read path. Anything else (null/object) means no observable base.\n const raw = entityState.record[context.serverVersionPropertyKey];\n if (typeof raw === \"string\" || typeof raw === \"number\" || typeof raw === \"bigint\") {\n return String(raw);\n }\n\n return null;\n}\n\nfunction buildTableContexts<TRegistry extends SyncTableRegistry>(registry: TRegistry) {\n const localSchema = getSyncRegistrySchema(registry);\n\n return Object.fromEntries(\n Object.entries(registry)\n .filter(([, entry]) => entry.mode !== \"readonly\")\n .map(([key, entry]) => [key, buildTableContext(registry, key, entry, localSchema)]),\n ) as Partial<Record<SyncTableName<TRegistry>, TableContext>>;\n}\n\nfunction buildTableContext<TRegistry extends SyncTableRegistry>(\n registry: TRegistry,\n key: string,\n entry: SyncTableEntry<AnyPgTable>,\n localSchema: string,\n): TableContext {\n if (!entry.clientProjection?.overlayTable || !entry.clientProjection.journalTable) {\n throw new Error(`overlay and journal tables are required for writable table ${key}`);\n }\n\n const columns = getProjectedTableColumns(entry).map(({ propertyKey, column }) => ({\n propertyKey,\n column,\n }));\n\n const pkPropertyKeys = entry.primaryKey.columns.map((columnName) => {\n const column = columns.find((candidate) => candidate.column.name === columnName);\n\n if (!column) {\n throw new Error(`Primary key column ${columnName} was not found on table ${key}`);\n }\n\n return column.propertyKey;\n });\n\n const serverVersionColumnName = resolveServerVersionColumnName(entry) ?? null;\n const serverVersionPropertyKey = serverVersionColumnName\n ? (columns.find((candidate) => candidate.column.name === serverVersionColumnName)?.propertyKey ?? null)\n : null;\n\n // Resolve the `nowMicroseconds` managed fields generically from governance, not by property name.\n // `field.column` is a drizzle property key, but tolerate a column-name declaration too.\n const resolveManagedPropertyKey = (fieldColumn: string): string | undefined =>\n columns.find((candidate) => candidate.propertyKey === fieldColumn || candidate.column.name === fieldColumn)\n ?.propertyKey;\n const nowMicrosecondsManagedFields = (entry.governance?.managedFields ?? []).filter(\n (field) => field.strategy === \"nowMicroseconds\",\n );\n const managedNowMicrosecondsPropertyKeys = nowMicrosecondsManagedFields\n .map((field) => resolveManagedPropertyKey(field.column as string))\n .filter((propertyKey): propertyKey is string => propertyKey !== undefined);\n const updateManagedNowMicrosecondsPropertyKeys = nowMicrosecondsManagedFields\n .filter((field) => field.applyOn.includes(\"update\"))\n .map((field) => resolveManagedPropertyKey(field.column as string))\n .filter((propertyKey): propertyKey is string => propertyKey !== undefined);\n\n const managedAuthClaimCreateFields = (entry.governance?.managedFields ?? [])\n .filter((field) => field.strategy === \"authClaim\" && field.applyOn.includes(\"create\"))\n .flatMap((field) => {\n const propertyKey = resolveManagedPropertyKey(field.column as string);\n return propertyKey && field.claimPath ? [{ propertyKey, claimPath: field.claimPath }] : [];\n });\n\n // The generated local relations as runtime Drizzle objects (memoized per registry+key in\n // local-tables.ts), plus name-resolved column handles the statement authors below need:\n // overlay/synced columns are keyed by PROPERTY key, so PK columns (a DB-column-name concept,\n // ADR-0012) are resolved once here by matching `.name`.\n const tables = {\n synced: getSyncedLocalTable(registry, key as string & keyof TRegistry),\n overlay: getOverlayTable(registry, key as string & keyof TRegistry),\n journal: getJournalTable(registry, key as string & keyof TRegistry),\n };\n const overlayColumnsByPropertyKey = getColumns(tables.overlay) as Record<string, PgColumn>;\n const syncedColumnsByPropertyKey = getColumns(tables.synced) as Record<string, PgColumn>;\n const resolvePkColumns = (columnsByKey: Record<string, PgColumn>, relation: string) =>\n entry.primaryKey.columns.map((columnName) => {\n const column = Object.values(columnsByKey).find((candidate) => candidate.name === columnName);\n if (!column) {\n throw new Error(`Primary key column ${columnName} was not found on the ${relation} table for ${key}`);\n }\n return column;\n });\n const syncedServerVersionColumn = serverVersionColumnName\n ? (Object.values(syncedColumnsByPropertyKey).find((candidate) => candidate.name === serverVersionColumnName) ??\n null)\n : null;\n\n return {\n key,\n entry,\n readModel: qualifyLocalIdentifier(\n localSchema,\n entry.view != null\n ? getViewConfig(entry.view).name\n : (entry.clientProjection?.syncedTable ?? getTableConfig(entry.table).name),\n ),\n syncedTable: qualifyLocalIdentifier(\n localSchema,\n entry.clientProjection?.syncedTable ?? getTableConfig(entry.table).name,\n ),\n overlayTable: qualifyLocalIdentifier(localSchema, entry.clientProjection.overlayTable),\n journalTable: qualifyLocalIdentifier(localSchema, entry.clientProjection.journalTable),\n journalSequence: qualifyLocalIdentifier(localSchema, buildJournalSequenceName(entry.clientProjection.journalTable)),\n pkColumnNames: [...entry.primaryKey.columns],\n pkPropertyKeys,\n serverVersionColumnName,\n serverVersionPropertyKey,\n managedNowMicrosecondsPropertyKeys,\n updateManagedNowMicrosecondsPropertyKeys,\n managedAuthClaimCreateFields,\n recordIncludesOverlayState: \"overlayTable\" in (entry.clientProjection ?? {}),\n columns,\n tables,\n overlayColumnsByPropertyKey,\n syncedColumnsByPropertyKey,\n overlayPkColumns: resolvePkColumns(overlayColumnsByPropertyKey, \"overlay\"),\n syncedPkColumns: resolvePkColumns(syncedColumnsByPropertyKey, \"synced\"),\n syncedServerVersionColumn,\n };\n}\n\nfunction filterContexts<TRegistry extends SyncTableRegistry>(\n contexts: Partial<Record<SyncTableName<TRegistry>, TableContext>>,\n table?: SyncTableName<TRegistry>,\n) {\n if (table) {\n const context = contexts[table];\n return context ? [context] : [];\n }\n\n return Object.values(contexts).filter((context): context is TableContext => context !== undefined);\n}\n\n/**\n * Materialise a column's default into a concrete JS value for the optimistic overlay\n * row. The overlay INSERT writes an explicit value for every projected column (an\n * omitted column becomes a literal `NULL`, which overrides any table-level DEFAULT), so\n * a column declared `NOT NULL DEFAULT <x>` that the caller omits would violate the\n * overlay's NOT NULL constraint unless we fill the default here — mirroring what the\n * authoritative server applies on the base table.\n *\n * Only values we can produce client-side are materialised: a value-returning `defaultFn`\n * (e.g. `$defaultFn`) or a literal `.default(value)`. SQL-expression defaults\n * (`.default(sql\\`…\\`)`, `defaultRandom()`, `defaultNow()`) cannot be evaluated without\n * the database, so they are left to the server (the column is then expected to be either\n * caller-supplied or nullable in the optimistic row).\n */\nfunction materializeColumnDefault(column: TableContext[\"columns\"][number][\"column\"]): {\n ok: boolean;\n value?: unknown;\n} {\n if (!column.hasDefault) {\n return { ok: false };\n }\n\n if (typeof column.defaultFn === \"function\") {\n const produced = column.defaultFn();\n return is(produced, SQL) ? { ok: false } : { ok: true, value: produced };\n }\n\n if (column.default !== undefined && !is(column.default, SQL)) {\n return { ok: true, value: column.default };\n }\n\n return { ok: false };\n}\n\nfunction createOptimisticRecordFromContext<TCreate, TRecord>(\n context: TableContext,\n input: TCreate,\n claims?: Record<string, unknown>,\n): TRecord {\n const record = {\n ...(isRecord(input) ? input : {}),\n };\n const nowUs = nowMicroseconds();\n\n // Stamp `authClaim` create-managed fields (owner/author/created_by) from the decoded claim at the\n // field's path, so the optimistic overlay row is attributed locally and satisfies the column's NOT\n // NULL — the server independently stamps the same claim on apply, so the value never flips on\n // convergence. (`auth.uid()` is just `claimPath: [\"sub\"]`.)\n if (claims != null) {\n for (const { propertyKey, claimPath } of context.managedAuthClaimCreateFields) {\n if (record[propertyKey] === undefined) {\n const value = readJwtClaimPath(claims, claimPath);\n if (value !== undefined) {\n record[propertyKey] = value;\n }\n }\n }\n }\n\n if (hasProperty(context, \"createdAtUs\") && record[\"createdAtUs\"] === undefined) {\n record[\"createdAtUs\"] = nowUs;\n }\n\n if (hasProperty(context, \"updatedAtUs\") && record[\"updatedAtUs\"] === undefined) {\n record[\"updatedAtUs\"] = nowUs;\n }\n\n // Generic managed-timestamp fill (governance-driven): stamp any `nowMicroseconds` managed field the\n // convention block above did not — e.g. a Server version column not named `updated_at_us`. Additive\n // and idempotent, so convention tables are unaffected (their fields are already filled).\n for (const propertyKey of context.managedNowMicrosecondsPropertyKeys) {\n if (record[propertyKey] === undefined) {\n record[propertyKey] = nowUs;\n }\n }\n\n for (const { propertyKey, column } of context.columns) {\n if (record[propertyKey] !== undefined) {\n continue;\n }\n\n const materialized = materializeColumnDefault(column);\n if (materialized.ok) {\n record[propertyKey] = materialized.value;\n }\n }\n\n return buildOptimisticRecord(context, record, {\n overlayKind: \"pending_create\",\n localUpdatedAtUs: nowUs,\n }) as TRecord;\n}\n\n/**\n * Stamp every on-update `nowMicroseconds` managed field with `nowUs` (governance-driven, ADR-0004),\n * keyed by drizzle property key. For a convention table this is exactly `{ updatedAtUs: nowUs }`; for\n * a custom-named Server version it targets that column — so the local optimistic path never assumes\n * the demo naming the generic server applier does not.\n */\nfunction buildUpdateManagedNowStamp(context: TableContext, nowUs: string): Record<string, string> {\n return Object.fromEntries(\n context.updateManagedNowMicrosecondsPropertyKeys.map((propertyKey) => [propertyKey, nowUs]),\n );\n}\n\nfunction buildOptimisticRecord(\n context: TableContext,\n record: Record<string, unknown>,\n options: {\n overlayKind: string;\n localUpdatedAtUs: string;\n },\n) {\n if (!context.recordIncludesOverlayState) {\n return record;\n }\n\n return {\n ...record,\n overlayKind: options.overlayKind,\n localUpdatedAtUs: options.localUpdatedAtUs,\n };\n}\n\nfunction buildEntityKeyFromRecord(context: TableContext, record: unknown) {\n const recordObject = ensureRecord(record);\n return normalizeEntityKey(\n context,\n Object.fromEntries(context.pkPropertyKeys.map((propertyKey) => [propertyKey, String(recordObject[propertyKey])])),\n );\n}\n\nfunction normalizeEntityKey(context: TableContext, input: Record<string, string>) {\n // The public API accepts the identity by drizzle property name (ergonomics); past this\n // boundary the canonical Entity identity is column-keyed (ADR-0012), matching the\n // journal/overlay PK columns, entity_key_json, and the applier's `v_entity_key->>'<column>'`.\n // pkPropertyKeys[i] ↔ pkColumnNames[i] by construction (buildTableContext), so we map once here.\n return Object.fromEntries(\n context.pkPropertyKeys.map((propertyKey, index) => {\n const value = input[propertyKey];\n\n if (value === undefined) {\n throw new Error(`Missing entity key property ${propertyKey} for table ${context.key}`);\n }\n\n return [context.pkColumnNames[index]!, String(value)];\n }),\n );\n}\n\nfunction serializeEntityKey(entityKey: Record<string, string>) {\n return JSON.stringify(entityKey);\n}\n\nfunction dedupeBatchEntities(items: ReadonlyArray<NormalizedBatchItem>): BatchEntityRef[] {\n const entities = new Map<string, BatchEntityRef>();\n\n for (const item of items) {\n if (!entities.has(item.entityKeyJson)) {\n entities.set(item.entityKeyJson, {\n entityKey: item.entityKey,\n entityKeyJson: item.entityKeyJson,\n });\n }\n }\n\n return [...entities.values()];\n}\n\nasync function readLatestMutationStates(\n db: MutationDb,\n context: TableContext,\n entities: ReadonlyArray<BatchEntityRef>,\n) {\n if (entities.length === 0) {\n return new Map<string, BatchLatestMutationStateRow>();\n }\n\n // The old VALUES-CTE + LEFT-JOIN-back-to-input existed only to emit null rows for entities with\n // no journal history; the caller reads via `map.get(...) ?? null`, so a missing key is equivalent.\n const journal = context.tables.journal;\n const query = queryBuilder\n .selectDistinctOn([journal.entityKeyJson], {\n entityKeyJson: sql<string>`${journal.entityKeyJson}`.as(\"entityKeyJson\"),\n latestMutationSeq: sql<number>`${journal.mutationSeq}`.as(\"latestMutationSeq\"),\n latestMutationKind: sql<MutationKind>`${journal.mutationKind}`.as(\"latestMutationKind\"),\n latestMutationStatus: sql<MutationStatus>`${journal.status}`.as(\"latestMutationStatus\"),\n })\n .from(journal)\n .where(\n inArray(\n journal.entityKeyJson,\n entities.map((entity) => entity.entityKeyJson),\n ),\n )\n .orderBy(journal.entityKeyJson, desc(journal.mutationSeq))\n .toSQL();\n const result = await db.query<BatchLatestMutationStateRow>(query.sql, query.params as unknown[]);\n\n return new Map(result.rows.map((row) => [row.entityKeyJson, row]));\n}\n\nasync function readCurrentRecordStates(db: MutationDb, context: TableContext, entities: ReadonlyArray<BatchEntityRef>) {\n if (entities.length === 0) {\n return new Map<string, BatchCurrentRecordStateRow>();\n }\n\n // Tier ②: the overlay-∪-synced shape over an input VALUES table. The input CTE carries each\n // entity's `entity_key_json` alongside its PK values (the caller maps rows back by that JSON), so\n // it cannot be a plain builder select; every identifier still comes from the table objects /\n // `sql.identifier`, and every value is a bound (cast-typed) param.\n const overlay = context.tables.overlay;\n const synced = context.tables.synced;\n const inputCte = buildEntityInputCte(context, entities);\n const overlaySelectColumns = buildProjectedSelectColumns(context, context.overlayColumnsByPropertyKey);\n const syncedSelectColumns = buildProjectedSelectColumns(context, context.syncedColumnsByPropertyKey);\n const inputOverlayJoin = buildEntityInputJoin(context.pkColumnNames, context.overlayPkColumns);\n const inputSyncedJoin = buildEntityInputJoin(context.pkColumnNames, context.syncedPkColumns);\n const syncedUpdatedAtColumn = context.syncedColumnsByPropertyKey[\"updatedAtUs\"];\n const syncedLocalUpdated =\n hasProperty(context, \"updatedAtUs\") && syncedUpdatedAtColumn\n ? sql`${syncedUpdatedAtColumn}::text AS \"localUpdatedAtUs\"`\n : sql`'0' AS \"localUpdatedAtUs\"`;\n\n const query = queryDialect.sqlToQuery(sql`\n WITH ${inputCte},\n overlay_rows AS (\n SELECT\n input.entity_key_json AS \"entityKeyJson\",\n ${overlaySelectColumns},\n ${overlay.overlayKind} AS \"overlayKind\",\n ${overlay.localUpdatedAtUs}::text AS \"localUpdatedAtUs\"\n FROM input_entities AS input\n JOIN ${overlay}\n ON ${inputOverlayJoin}\n ),\n synced_rows AS (\n SELECT\n input.entity_key_json AS \"entityKeyJson\",\n ${syncedSelectColumns},\n ${\"synced\"} AS \"overlayKind\",\n ${syncedLocalUpdated}\n FROM input_entities AS input\n JOIN ${synced}\n ON ${inputSyncedJoin}\n WHERE NOT EXISTS (\n SELECT 1\n FROM ${overlay}\n WHERE ${inputOverlayJoin}\n )\n )\n SELECT *\n FROM overlay_rows\n UNION ALL\n SELECT *\n FROM synced_rows\n `);\n const result = await db.query<BatchCurrentRecordStateRow>(query.sql, query.params as unknown[]);\n\n return new Map(result.rows.map((row) => [row.entityKeyJson, row]));\n}\n\nasync function insertMutationsBulk(\n db: MutationDb,\n context: TableContext,\n rows: ReadonlyArray<PlannedMutationInsert>,\n registryVersion: string | null,\n unit?: WriteUnit,\n) {\n if (rows.length === 0) {\n return;\n }\n\n // ADR-0022: a dynamic write-unit tags every row of the batch with one shared unit id + mode; the\n // default path leaves both NULL (the flusher derives mode/unit from the static group). A blind row\n // carries its own `write_mode` override (`pessimistic-blind`), so the mode is resolved per row.\n const writeUnit = unit?.id ?? null;\n const journal = context.tables.journal;\n // `mutationSeq` is intentionally omitted: the generated journal DDL carries\n // `mutation_seq ... DEFAULT nextval(<journal sequence>)`, so the DB default assigns it — drizzle\n // renders `default` for every column a row does not provide.\n const values = rows.map((row) => ({\n mutationId: row.mutationId,\n ...Object.fromEntries(context.pkColumnNames.map((columnName) => [columnName, row.entityKey[columnName]])),\n entityKeyJson: row.entityKeyJson,\n mutationKind: row.mutationKind,\n status: \"pending\",\n registryVersion,\n baseServerVersion: row.baseServerVersion,\n payloadJson: row.payloadJson,\n enqueuedAtUs: row.nowUs,\n nextRetryAtUs: row.nowUs,\n updatedAtUs: row.nowUs,\n writeUnit,\n writeMode: row.writeMode ?? unit?.mode ?? null,\n }));\n\n const query = queryBuilder\n .insert(journal)\n .values(values as PgInsertValue<JournalTable>[])\n .toSQL();\n await db.query(query.sql, query.params as unknown[]);\n\n // Lifecycle origin: the moment each mutation is first staged into the journal. Correlates by id with\n // the later \"board-write sending\"/\"board-write acks\" lines (staged → sent → acked, per id).\n for (const row of rows) {\n syncDebug(\"mutation staged\", { mutationId: row.mutationId, table: context.key });\n }\n}\n\nasync function upsertOverlayRecordsBulk(\n db: MutationDb,\n context: TableContext,\n rows: ReadonlyArray<PlannedOverlayUpsert>,\n) {\n if (rows.length === 0) {\n return;\n }\n\n const overlay = context.tables.overlay;\n const values = rows.map((row) => ({\n ...Object.fromEntries(context.columns.map(({ propertyKey }) => [propertyKey, row.record[propertyKey] ?? null])),\n overlayKind: row.overlayKind,\n localUpdatedAtUs: row.localUpdatedAtUs,\n }));\n // Every inserted column (the projection + the two overlay columns) takes its EXCLUDED value on\n // conflict — the fixed alias PostgreSQL defines for the proposed row; its column names are the\n // table's own, so they come from the column objects via `sql.identifier`.\n const excludedSet = Object.fromEntries([\n ...context.columns.map(({ propertyKey, column }) => [propertyKey, sql`excluded.${sql.identifier(column.name)}`]),\n [\"overlayKind\", sql`excluded.${sql.identifier(overlay.overlayKind.name)}`],\n [\"localUpdatedAtUs\", sql`excluded.${sql.identifier(overlay.localUpdatedAtUs.name)}`],\n ]) as Record<string, SQL>;\n\n const query = queryBuilder\n .insert(overlay)\n .values(values as PgInsertValue<OverlayTable>[])\n .onConflictDoUpdate({ target: context.overlayPkColumns, set: excludedSet })\n .toSQL();\n await db.query(query.sql, query.params as unknown[]);\n}\n\n/**\n * The batch-input CTE as a typed fragment: `input_entities (entity_key_json, <pks…>) AS (VALUES …)`\n * with every value a bound param, cast to its PK column's type (an untyped VALUES column would\n * otherwise default to text and break the join against a uuid/int PK).\n */\nfunction buildEntityInputCte(context: TableContext, entities: ReadonlyArray<BatchEntityRef>): SQL {\n const columnNames = [\"entity_key_json\", ...context.pkColumnNames];\n const tuples = entities.map((entity) => {\n const values = [\n sql`${entity.entityKeyJson}`,\n ...context.pkColumnNames.map((columnName) => {\n const columnEntry = context.columns.find(({ column }) => column.name === columnName);\n const castSuffix = columnEntry ? resolveInputCastSuffix(columnEntry.column.columnType) : \"\";\n // The cast keyword is a FIXED type suffix selected from the closed switch below — never\n // derived from user data — so `sql.raw` is safe here; the value itself is a bound param.\n return castSuffix\n ? sql`${entity.entityKey[columnName]}${sql.raw(castSuffix)}`\n : sql`${entity.entityKey[columnName]}`;\n }),\n ];\n return sql`(${sql.join(values, sql`, `)})`;\n });\n\n return sql`input_entities (${sql.join(\n columnNames.map((columnName) => sql.identifier(columnName)),\n sql`, `,\n )}) AS (VALUES ${sql.join(tuples, sql`, `)})`;\n}\n\nfunction resolveInputCastSuffix(columnType: string): string {\n switch (columnType) {\n case \"PgUUID\":\n return \"::uuid\";\n case \"PgBigInt64\":\n case \"PgBigInt53\":\n return \"::bigint\";\n case \"PgInteger\":\n case \"PgSerial\":\n case \"PgSmallInt\":\n return \"::int\";\n case \"PgBoolean\":\n return \"::boolean\";\n case \"PgTimestamp\":\n case \"PgTimestampString\":\n return \"::timestamp\";\n default:\n return \"\";\n }\n}\n\n/**\n * The projected columns of one branch (overlay or synced) as select-list fragments, aliased to\n * their camelCase property keys — the raw seam returns rows unmapped, so the aliases ARE the row\n * keys — with `::text` casts on the bigint columns (matching how the runtime reads them).\n */\nfunction buildProjectedSelectColumns(context: TableContext, columnsByPropertyKey: Record<string, PgColumn>): SQL {\n return sql.join(\n context.columns.map(({ propertyKey, column }) => {\n const target = columnsByPropertyKey[propertyKey];\n if (!target) {\n throw new Error(`Projected column ${propertyKey} was not found on the local tables for ${context.key}`);\n }\n if (column.columnType === \"PgBigInt64\" || column.columnType === \"PgBigInt53\") {\n return sql`${target}::text AS ${sql.identifier(propertyKey)}`;\n }\n return sql`${target} AS ${sql.identifier(propertyKey)}`;\n }),\n sql`, `,\n );\n}\n\n/** PK equality between a branch table's columns and the `input` CTE, as a typed fragment. */\nfunction buildEntityInputJoin(pkColumnNames: string[], pkColumns: PgColumn[]): SQL {\n return sql.join(\n pkColumnNames.map((columnName, index) => sql`${pkColumns[index]!} = input.${sql.identifier(columnName)}`),\n sql` AND `,\n );\n}\n\n// ---------------------------------------------------------------------------\n// Batch flush — sends one send-eligible slice of pending mutations across all\n// target tables in a single POST /api/mutations call. The public flush()\n// wrapper loops until no more eligible rows remain.\n// ---------------------------------------------------------------------------\n\ninterface PendingBatchRow extends MutationRow {\n tableKey: string;\n enqueuedAtUs: string;\n /** The resolved Base server version (ADR-0015), or null when the table predates the policy. */\n baseServerVersion: string | null;\n}\n\ninterface PreparedBatchRow extends PendingBatchRow {\n context: TableContext;\n entityKey: Record<string, string>;\n envelopePayload: Record<string, unknown>;\n sqlTableName: string;\n}\n\ninterface FlushBatchResult {\n processedCount: number;\n affectedContexts: TableContext[];\n /** Mutation ids that transitioned to `quarantined` in this slice (ADR-0006), for surfacing. */\n quarantinedMutationIds: string[];\n /** Mutation ids that transitioned to `conflicted` in this slice (ADR-0015), for surfacing. */\n conflictedMutationIds: string[];\n}\n\n/**\n * Runtime-scoped enter/exit seam for the in-flight mark-sending span counter (FIX 1). Threaded into\n * `applyMutationStatusUpdates` so the free function can bracket a `sending` transition against the runtime's\n * `settleRecoveryMarker`, which the free function cannot otherwise see. `enter` is called synchronously before\n * the marker await; `exit` in a `finally` after the `sending` UPDATE commits.\n */\ninterface MarkSendingScope {\n enter: () => void;\n exit: () => void;\n}\n\ninterface MutationStatusUpdate {\n mutationId: string;\n status: MutationStatus;\n attemptCount: number;\n updatedAtUs: string;\n sentAtUs?: string | null;\n replaceSentAtUs?: boolean;\n ackedAtUs?: string | null;\n replaceAckedAtUs?: boolean;\n serverUpdatedAtUs?: string | null;\n replaceServerUpdatedAtUs?: boolean;\n baseServerVersion?: string | null;\n replaceBaseServerVersion?: boolean;\n lastError?: string | null;\n nextRetryAtUs?: string | null;\n lastHttpStatus?: number | null;\n conflictReason?: string | null;\n}\n\n/**\n * The resolved Base server version (ADR-0015) for a row at flush. A **chain head** already carries\n * `base_server_version` (stamped at enqueue), so COALESCE returns it untouched — keeping the\n * enqueue-time base means a genuine external write between view and apply is still caught. A\n * **chained** write has NULL there; it resolves to its **acked predecessor's** Server version (by\n * Per-entity flush serialization the predecessor is already acked when this row flushes), falling\n * back to the entity's current synced version once that predecessor has been reconciled away. Either\n * fallback yields the entity's own latest server state, so its own chain never self-conflicts.\n */\nfunction buildResolvedBaseServerVersion(context: TableContext): SQL {\n const journal = context.tables.journal;\n const synced = context.tables.synced;\n const pred = alias(journal, \"pred\");\n const predecessor = queryBuilder\n .select({ value: sql`MAX(${pred.serverUpdatedAtUs})` })\n .from(pred)\n .where(\n and(\n eq(pred.entityKeyJson, journal.entityKeyJson),\n lt(pred.mutationSeq, journal.mutationSeq),\n eq(pred.status, \"acked\"),\n ),\n );\n\n if (!context.syncedServerVersionColumn) {\n return sql`COALESCE(${journal.baseServerVersion}, ${predecessor})::text`;\n }\n\n const syncedFallback = queryBuilder\n .select({ value: sql`${context.syncedServerVersionColumn}` })\n .from(synced)\n .where(\n and(\n ...context.pkColumnNames.map((columnName, index) => eq(context.syncedPkColumns[index]!, journal[columnName]!)),\n ),\n );\n\n return sql`COALESCE(${journal.baseServerVersion}, ${predecessor}, ${syncedFallback})::text`;\n}\n\n/**\n * One table's send-eligible journal rows as a builder select with the shared {@link PendingBatchRow}\n * projection — the aliases ARE the row keys (raw seam), `tableKey` rides as a bound param, and the\n * resolved Base server version (ADR-0015) is the typed COALESCE fragment above.\n */\nfunction buildPendingRowsProjection(context: TableContext) {\n const journal = context.tables.journal;\n return {\n tableKey: sql<string>`${context.key}`.as(\"tableKey\"),\n mutationId: sql<string>`${journal.mutationId}`.as(\"mutationId\"),\n entityKeyJson: sql<string>`${journal.entityKeyJson}`.as(\"entityKeyJson\"),\n mutationSeq: sql<number>`${journal.mutationSeq}`.as(\"mutationSeq\"),\n mutationKind: sql<MutationKind>`${journal.mutationKind}`.as(\"mutationKind\"),\n status: journal.status,\n payloadJson: sql<string>`${journal.payloadJson}`.as(\"payloadJson\"),\n attemptCount: sql<number>`${journal.attemptCount}`.as(\"attemptCount\"),\n lastHttpStatus: sql<number | null>`${journal.lastHttpStatus}`.as(\"lastHttpStatus\"),\n lastError: sql<string | null>`${journal.lastError}`.as(\"lastError\"),\n conflictReason: sql<string | null>`${journal.conflictReason}`.as(\"conflictReason\"),\n nextRetryAtUs: sql<string | null>`${journal.nextRetryAtUs}::text`.as(\"nextRetryAtUs\"),\n serverUpdatedAtUs: sql<string | null>`${journal.serverUpdatedAtUs}::text`.as(\"serverUpdatedAtUs\"),\n baseServerVersion: buildResolvedBaseServerVersion(context).as(\"baseServerVersion\"),\n enqueuedAtUs: sql<string>`${journal.enqueuedAtUs}::text`.as(\"enqueuedAtUs\"),\n };\n}\n\nasync function readPendingBatchRows(db: MutationDb, contexts: TableContext[], nowUs: string, batchSize: number) {\n if (contexts.length === 0) {\n return [] as PendingBatchRow[];\n }\n\n const branches = contexts.map((context) => {\n const journal = context.tables.journal;\n const earlier = alias(journal, \"earlier\");\n return queryBuilder\n .select(buildPendingRowsProjection(context))\n .from(journal)\n .where(\n and(\n inArray(journal.status, [\"pending\", \"failed\"]),\n // ADR-0022: pessimistic rows are flushed by the authoritative unit path (flushUnit), never the\n // optimistic batch — exclude them here so a tagged write is never optimistically sent. The\n // `NOT LIKE 'pessimistic%'` also excludes a `pessimistic-blind` row (ADR-0022 addendum), which\n // belongs to its unit's foreground flush too.\n sql`COALESCE(${journal.writeMode}, '') NOT LIKE 'pessimistic%'`,\n sql`COALESCE(${journal.nextRetryAtUs}, 0) <= ${nowUs}::bigint`,\n notExists(\n queryBuilder\n .select({ one: sql`1` })\n .from(earlier)\n .where(\n and(\n eq(earlier.entityKeyJson, journal.entityKeyJson),\n lt(earlier.mutationSeq, journal.mutationSeq),\n // A still-unresolved earlier mutation blocks later same-entity ones so the\n // server applies them in author order. The quarantined status is included: a\n // later mutation must not flush past a prerequisite the server permanently\n // rejected (it would itself fail); resolving the quarantine unblocks the queue.\n inArray(earlier.status, [\"pending\", \"failed\", \"sending\", \"quarantined\"]),\n ),\n ),\n ),\n ),\n );\n });\n\n // The union rides inside a derived table because the outer ORDER BY casts the (text) output\n // columns — a set operation's own ORDER BY may only name plain output columns. The `pending`\n // alias and its two quoted output-column names are fixed by the projection above, not data.\n const query = queryDialect.sqlToQuery(\n sql`SELECT * FROM (${sql.join(branches, sql` UNION ALL `)}) AS pending ORDER BY pending.\"enqueuedAtUs\"::bigint ASC, pending.\"mutationSeq\" ASC LIMIT ${batchSize}`,\n );\n const result = await db.query<PendingBatchRow>(query.sql, query.params as unknown[]);\n\n return result.rows;\n}\n\n/**\n * Read one pessimistic write-unit's send-eligible rows (ADR-0022) across every table, ordered by author\n * sequence. Unlike {@link readPendingBatchRows} it has no per-entity ordering gate: a unit is enqueued and\n * sent atomically, so its members go together.\n */\nasync function readUnitPendingRows(\n db: MutationDb,\n contexts: TableContext[],\n unitId: string,\n): Promise<PendingBatchRow[]> {\n if (contexts.length === 0) {\n return [];\n }\n\n const branches = contexts.map((context) => {\n const journal = context.tables.journal;\n return queryBuilder\n .select(buildPendingRowsProjection(context))\n .from(journal)\n .where(and(eq(journal.writeUnit, unitId), inArray(journal.status, [\"pending\", \"failed\"])));\n });\n\n const query = queryDialect.sqlToQuery(\n sql`SELECT * FROM (${sql.join(branches, sql` UNION ALL `)}) AS unit ORDER BY unit.\"mutationSeq\" ASC`,\n );\n const result = await db.query<PendingBatchRow>(query.sql, query.params as unknown[]);\n\n return result.rows;\n}\n\nasync function flushBatch(\n db: MutationDb,\n tableContexts: Record<string, TableContext>,\n batchWriteUrl: string,\n maxAttempts: number,\n batchSize: number,\n tableFilter?: string,\n getAuthToken?: () => Promise<string | undefined>,\n requestHeaders?: Record<string, string>,\n ensureRecoveryMarker?: () => Promise<void>,\n markSendingScope?: MarkSendingScope,\n): Promise<FlushBatchResult> {\n const contexts = filterContexts(tableContexts, tableFilter);\n const nowUs = nowMicroseconds();\n const quarantinedMutationIds: string[] = [];\n const conflictedMutationIds: string[] = [];\n\n // Collect send-eligible mutations across all target tables.\n const pendingRows = await readPendingBatchRows(db, contexts, nowUs, batchSize);\n const pending: PreparedBatchRow[] = [];\n const pendingByTable = new Map<string, PreparedBatchRow[]>();\n\n for (const row of pendingRows) {\n const context = tableContexts[row.tableKey];\n\n if (!context) {\n continue;\n }\n\n const entityKey = JSON.parse(row.entityKeyJson) as Record<string, string>;\n const rawPayload = JSON.parse(row.payloadJson) as Record<string, unknown>;\n const preparedRow: PreparedBatchRow = {\n ...row,\n context,\n entityKey,\n envelopePayload:\n row.mutationKind === \"delete\"\n ? entityKey\n : toSqlColumnPayload(\n context,\n stripManagedFields(\n context,\n (rawPayload[\"value\"] ?? rawPayload[\"patch\"] ?? rawPayload) as Record<string, unknown>,\n row.mutationKind as \"create\" | \"update\",\n ),\n ),\n sqlTableName: context.entry.shape?.tableName ?? context.key,\n };\n\n pending.push(preparedRow);\n\n const existingTableRows = pendingByTable.get(context.key);\n\n if (existingTableRows) {\n existingTableRows.push(preparedRow);\n } else {\n pendingByTable.set(context.key, [preparedRow]);\n }\n }\n\n if (pending.length === 0) {\n // If a write just enqueued and requested a pass, but this flush sees nothing, the pass raced the\n // journal commit (or everything is already in-flight/backed-off) — the write then waits for a\n // later pass. Worth seeing explicitly when chasing flush latency.\n syncDebug(\"flushBatch: no send-eligible mutations this pass\");\n return {\n processedCount: 0,\n affectedContexts: [],\n quarantinedMutationIds,\n conflictedMutationIds,\n };\n }\n\n syncDebug(\"flushBatch sending to board-write\", { count: pending.length });\n\n // Mark all as sending.\n const sentAtUs = nowMicroseconds();\n\n for (const rows of pendingByTable.values()) {\n await applyMutationStatusUpdates(\n db,\n rows[0]!.context,\n rows.map((row) => ({\n mutationId: row.mutationId,\n status: \"sending\",\n attemptCount: row.attemptCount + 1,\n updatedAtUs: sentAtUs,\n sentAtUs,\n replaceSentAtUs: true,\n // Persist the resolved Base server version (ADR-0015) so a chained write's flush-resolved\n // base is durable and matches exactly what the envelope carries to the server.\n baseServerVersion: row.baseServerVersion,\n replaceBaseServerVersion: true,\n lastError: null,\n nextRetryAtUs: null,\n lastHttpStatus: null,\n conflictReason: null,\n })),\n ensureRecoveryMarker,\n markSendingScope,\n );\n }\n\n const mutations = pending.map((row) => {\n return {\n tableName: row.sqlTableName,\n entityKey: row.entityKey,\n mutationId: row.mutationId,\n mutationSeq: row.mutationSeq,\n kind: row.mutationKind as \"create\" | \"update\" | \"delete\",\n payload: row.envelopePayload,\n clientTimestampUs: sentAtUs,\n // ADR-0015: carry the resolved Base server version so the applier can detect a stale write.\n // Omitted for a create / a table that predates the policy (null) — then no stale check runs.\n ...(row.baseServerVersion != null ? { baseServerVersion: row.baseServerVersion } : {}),\n };\n });\n\n let responseOk = false;\n let acksByMutationId: Map<string, BatchMutationAck[\"acks\"][number]> = new Map();\n const batchMutationUrl = resolveBatchMutationUrl(batchWriteUrl);\n\n try {\n // Resolve the auth token and the network round-trip separately: in the board, `getAuthToken` calls\n // `supabase.auth.getSession()` per send, which can itself stall (token refresh) and would otherwise\n // be invisibly folded into \"the write was slow\".\n const authStart = typeof performance !== \"undefined\" ? performance.now() : Date.now();\n const authToken = await getAuthToken?.();\n const fetchStart = typeof performance !== \"undefined\" ? performance.now() : Date.now();\n syncDebug(\"board-write auth token resolved\", { ms: Math.round(fetchStart - authStart) });\n\n let response = await fetch(batchMutationUrl, {\n method: \"POST\",\n headers: buildRequestHeaders(authToken, requestHeaders),\n body: jsonStringifyPayload({ mutations }),\n });\n\n if ([401, 403].includes(response.status) && getAuthToken) {\n response = await fetch(batchMutationUrl, {\n method: \"POST\",\n headers: buildRequestHeaders(await getAuthToken(), requestHeaders),\n body: jsonStringifyPayload({ mutations }),\n });\n }\n\n const fetchEnd = typeof performance !== \"undefined\" ? performance.now() : Date.now();\n syncDebug(\"board-write responded\", { status: response.status, ms: Math.round(fetchEnd - fetchStart) });\n\n if (response.ok) {\n const responseJson = (await response.json()) as BatchMutationAck;\n responseOk = true;\n acksByMutationId = new Map(responseJson.acks.map((ack) => [ack.mutationId, ack]));\n syncDebug(\"board-write acks\", {\n acks: responseJson.acks.map((ack) => `${ack.mutationId.slice(0, 8)}:${ack.status}`),\n });\n } else {\n const text = await response.text();\n throw new MutationRequestError(\n text.length > 0 ? text : `Bulk write responded with ${response.status}`,\n response.status,\n parseBatchRejections(text),\n );\n }\n } catch (error) {\n const failedAtUs = nowMicroseconds();\n const httpStatus = error instanceof MutationRequestError ? error.status : null;\n const errorMessage = error instanceof Error ? error.message : \"Unknown batch write failure\";\n // The server attributed the failure to specific mutations (a structural validation\n // rejection of an atomic batch). When present, we quarantine exactly those and leave the\n // innocent siblings immediately retryable; absent (transport / 5xx / auth / malformed\n // envelope), the whole batch stays retryable under the shared attempt cap.\n const rejectionById =\n error instanceof MutationRequestError && error.rejections\n ? new Map(error.rejections.map((rejection) => [rejection.mutationId, rejection]))\n : null;\n\n for (const rows of pendingByTable.values()) {\n await applyMutationStatusUpdates(\n db,\n rows[0]!.context,\n rows.map((row) => {\n const attemptCount = row.attemptCount + 1;\n\n if (rejectionById) {\n const rejection = rejectionById.get(row.mutationId);\n\n if (rejection) {\n // Named as the cause: terminal quarantine (it will never succeed unchanged).\n quarantinedMutationIds.push(row.mutationId);\n return {\n mutationId: row.mutationId,\n status: \"quarantined\" as const,\n attemptCount,\n updatedAtUs: failedAtUs,\n lastError: rejection.reason,\n nextRetryAtUs: null,\n lastHttpStatus: httpStatus,\n conflictReason: rejection.reason,\n };\n }\n\n // Innocent sibling: nothing was applied (atomic batch), so make it immediately\n // retryable — no backoff (the fault was the now-quarantined mutation, not\n // congestion) — and the next flush proceeds without the poison.\n return {\n mutationId: row.mutationId,\n status: \"failed\" as const,\n attemptCount,\n updatedAtUs: failedAtUs,\n lastError: \"Batch rejected due to a sibling mutation; retrying without it\",\n nextRetryAtUs: null,\n lastHttpStatus: httpStatus,\n conflictReason: null,\n };\n }\n\n // Unattributed batch-level failure: stays retryable with jittered backoff; only the\n // hard attempt cap escalates to terminal quarantined. A structural 4xx is NOT\n // quarantined here (a stray 404/413/malformed envelope would otherwise permanently\n // kill unrelated valid writes).\n const outcome = resolveBatchFailureOutcome(attemptCount, maxAttempts, failedAtUs);\n\n if (outcome.status === \"quarantined\") {\n quarantinedMutationIds.push(row.mutationId);\n }\n\n return {\n mutationId: row.mutationId,\n status: outcome.status,\n attemptCount,\n updatedAtUs: failedAtUs,\n lastError: errorMessage,\n nextRetryAtUs: outcome.nextRetryAtUs,\n lastHttpStatus: httpStatus,\n conflictReason: null,\n };\n }),\n );\n }\n\n return {\n processedCount: pending.length,\n affectedContexts: [...new Set(pending.map((row) => row.context))],\n quarantinedMutationIds,\n conflictedMutationIds,\n };\n }\n\n if (!responseOk) {\n return {\n processedCount: pending.length,\n affectedContexts: [...new Set(pending.map((row) => row.context))],\n quarantinedMutationIds,\n conflictedMutationIds,\n };\n }\n\n // Apply per-mutation ack results.\n const ackedAtUs = nowMicroseconds();\n const failedAtUs = nowMicroseconds();\n\n for (const rows of pendingByTable.values()) {\n await applyMutationStatusUpdates(\n db,\n rows[0]!.context,\n rows.map((row) => {\n const ack = acksByMutationId.get(row.mutationId);\n\n if (ack && ack.status === \"conflicted\") {\n // ADR-0015: a stale write the reject-if-stale policy declined. Move to the terminal\n // `conflicted` status — NOT a failure (never retried as-is, the base is still stale) — and\n // KEEP the optimistic Overlay (reconcile only clears acked rows, so the user's edit stays\n // visible). The server's current Server version rides on the journal row for the diff UI.\n conflictedMutationIds.push(row.mutationId);\n return {\n mutationId: row.mutationId,\n status: \"conflicted\" as const,\n attemptCount: row.attemptCount + 1,\n updatedAtUs: failedAtUs,\n serverUpdatedAtUs: ack.serverUpdatedAtUs ?? null,\n replaceServerUpdatedAtUs: true,\n lastError: ack.conflictReason ?? \"Stale write rejected (reject-if-stale)\",\n nextRetryAtUs: null,\n lastHttpStatus: ack.httpStatus ?? 409,\n conflictReason: ack.conflictReason ?? \"Stale write rejected (reject-if-stale)\",\n };\n }\n\n if (!ack || ack.status !== \"acked\") {\n const attemptCount = row.attemptCount + 1;\n const httpStatus = ack?.httpStatus ?? null;\n const outcome = resolveFailureOutcome(httpStatus, attemptCount, maxAttempts, failedAtUs);\n\n if (outcome.status === \"quarantined\") {\n quarantinedMutationIds.push(row.mutationId);\n }\n\n return {\n mutationId: row.mutationId,\n status: outcome.status,\n attemptCount,\n updatedAtUs: failedAtUs,\n lastError: ack?.conflictReason ?? \"Batch mutation not acknowledged\",\n nextRetryAtUs: outcome.nextRetryAtUs,\n lastHttpStatus: httpStatus,\n conflictReason: ack?.conflictReason ?? null,\n };\n }\n\n if (row.mutationKind === \"delete\") {\n return {\n mutationId: row.mutationId,\n status: \"acked\",\n attemptCount: row.attemptCount + 1,\n updatedAtUs: ackedAtUs,\n ackedAtUs,\n replaceAckedAtUs: true,\n lastError: null,\n nextRetryAtUs: null,\n lastHttpStatus: 204,\n conflictReason: null,\n };\n }\n\n return {\n mutationId: row.mutationId,\n status: \"acked\",\n attemptCount: row.attemptCount + 1,\n updatedAtUs: ackedAtUs,\n ackedAtUs,\n replaceAckedAtUs: true,\n serverUpdatedAtUs: ack.serverUpdatedAtUs ?? null,\n replaceServerUpdatedAtUs: true,\n lastError: null,\n nextRetryAtUs: null,\n lastHttpStatus: 200,\n conflictReason: null,\n };\n }),\n );\n }\n\n return {\n processedCount: pending.length,\n affectedContexts: [...new Set(pending.map((row) => row.context))],\n quarantinedMutationIds,\n conflictedMutationIds,\n };\n}\n\n/**\n * Resolve a flush failure into the durable journal outcome (ADR-0006). A structural\n * rejection ({@link classifyFailureStatus}) or hitting the hard attempt cap ends the\n * retry loop with a terminal `quarantined` (no `next_retry_at_us`); otherwise the\n * mutation stays `failed` with a jittered backoff (ADR-0005 congestion policy).\n */\nfunction resolveFailureOutcome(\n httpStatus: number | null,\n attemptCount: number,\n maxAttempts: number,\n failedAtUs: string,\n): { status: \"failed\" | \"quarantined\"; nextRetryAtUs: string | null } {\n if (classifyFailureStatus(httpStatus) === \"quarantined\" || attemptCount >= maxAttempts) {\n return { status: \"quarantined\", nextRetryAtUs: null };\n }\n\n return { status: \"failed\", nextRetryAtUs: computeNextRetryAtUs(failedAtUs, attemptCount) };\n}\n\n/**\n * Resolve a *batch-level* failure — the whole POST failed (transport error, 5xx, auth, or a\n * non-2xx the server did not attribute to a specific mutation). Unlike a per-mutation ack\n * rejection, the fault cannot be pinned on any one mutation, so a structural 4xx must NOT\n * quarantine the batch (a stray 404/413/malformed envelope would permanently kill unrelated\n * valid offline writes). These failures stay retryable `failed` with jittered backoff; only\n * the hard attempt cap escalates to terminal `quarantined`.\n */\nfunction resolveBatchFailureOutcome(\n attemptCount: number,\n maxAttempts: number,\n failedAtUs: string,\n): { status: \"failed\" | \"quarantined\"; nextRetryAtUs: string | null } {\n if (attemptCount >= maxAttempts) {\n return { status: \"quarantined\", nextRetryAtUs: null };\n }\n\n return { status: \"failed\", nextRetryAtUs: computeNextRetryAtUs(failedAtUs, attemptCount) };\n}\n\nfunction resolveBatchMutationUrl(batchWriteUrl: string): string {\n const trimmed = batchWriteUrl.replace(/\\/+$/, \"\");\n\n if (trimmed.endsWith(\"/mutations\")) {\n return trimmed;\n }\n\n return `${trimmed}/mutations`;\n}\n\n/** The authoritative (pessimistic) write endpoint (ADR-0022): the batch URL with `/unit` appended. */\nfunction resolveAuthoritativeMutationUrl(batchWriteUrl: string): string {\n return `${resolveBatchMutationUrl(batchWriteUrl)}/unit`;\n}\n\nfunction stripManagedFields(\n context: TableContext,\n payload: Record<string, unknown>,\n operation: \"create\" | \"update\",\n): Record<string, unknown> {\n const managedColumns = new Set<string>();\n\n for (const mf of context.entry.governance?.managedFields ?? []) {\n if (mf.applyOn.includes(operation)) {\n managedColumns.add(mf.column);\n }\n }\n\n if (managedColumns.size === 0) return payload;\n\n return Object.fromEntries(Object.entries(payload).filter(([key]) => !managedColumns.has(key)));\n}\n\nfunction toSqlColumnPayload(context: TableContext, payload: Record<string, unknown>): Record<string, unknown> {\n const normalized: Record<string, unknown> = {};\n\n for (const { propertyKey, column } of context.columns) {\n const columnName = column.name;\n\n if (Object.prototype.hasOwnProperty.call(payload, columnName)) {\n normalized[columnName] = payload[columnName];\n continue;\n }\n\n if (Object.prototype.hasOwnProperty.call(payload, propertyKey)) {\n normalized[columnName] = payload[propertyKey];\n }\n }\n\n return normalized;\n}\n\n/**\n * Discard a terminal-state entity: clear its journal rows in the given terminal status\n * (`conflicted` — ADR-0015; or `quarantined` — ADR-0006) and its kept optimistic Overlay row, so the\n * Read model falls back to the synced (server) value. The overlay is removed only when no OTHER journal\n * row still owes the entity (a pending/sending/failed/acked write), mirroring reconcileTable's\n * overlay-clear guard — so a discard never strips an overlay another un-resolved write still depends\n * on. Both public discards (`discardConflict`, `discardQuarantined`) are this one body parameterized by\n * the terminal status they retire; owning its own transaction (like reconcileTable), it is not wrapped.\n */\nasync function discardTerminalEntity(\n db: MutationDb,\n context: TableContext,\n entityKey: Record<string, string>,\n entityKeyJson: string,\n terminalStatus: \"conflicted\" | \"quarantined\",\n) {\n await db.exec(\"BEGIN\");\n\n try {\n const journal = context.tables.journal;\n const clearQuery = queryBuilder\n .delete(journal)\n .where(and(eq(journal.status, terminalStatus), eq(journal.entityKeyJson, entityKeyJson)))\n .toSQL();\n await db.query(clearQuery.sql, clearQuery.params as unknown[]);\n\n // Clear the kept overlay only when no journal row still owes this entity — so a discard never\n // strips an overlay another un-resolved write (e.g. a resolution already enqueued) depends on.\n const overlayQuery = buildOverlayDiscardQuery(context, entityKey, entityKeyJson);\n await db.query(overlayQuery.sql, overlayQuery.params as unknown[]);\n\n await db.exec(\"COMMIT\");\n } catch (error) {\n await db.exec(\"ROLLBACK\");\n throw error;\n }\n}\n\n/**\n * The shared overlay-discard statement: delete the entity's overlay row unless a journal row still\n * owes the entity — `owedStatuses` narrows which journal rows count as \"owed\" (all of them for a\n * conflict discard; only the un-sent pending/sending/failed set for a settled-unit discard).\n */\nfunction buildOverlayDiscardQuery(\n context: TableContext,\n entityKey: Record<string, string>,\n entityKeyJson: string,\n owedStatuses?: MutationStatus[],\n) {\n const overlay = context.tables.overlay;\n const journal = context.tables.journal;\n const owed = queryBuilder\n .select({ one: sql`1` })\n .from(journal)\n .where(\n owedStatuses\n ? and(eq(journal.entityKeyJson, entityKeyJson), inArray(journal.status, owedStatuses))\n : eq(journal.entityKeyJson, entityKeyJson),\n );\n\n return queryBuilder\n .delete(overlay)\n .where(\n and(\n ...context.pkColumnNames.map((columnName, index) =>\n eq(context.overlayPkColumns[index]!, entityKey[columnName]),\n ),\n notExists(owed),\n ),\n )\n .toSQL();\n}\n\n/**\n * Auto-discard the optimistic overlay for an entity whose pessimistic write-unit the authoritative endpoint\n * `rejected` (ADR-0022 §4). Unlike {@link discardTerminalEntity} this KEEPS the terminal `rejected` journal\n * row (for diagnostics + `onReject`); it only clears the overlay, and only when no still-owed\n * (`pending`/`sending`/`failed`) journal row depends on it — so a later un-sent write never loses its overlay.\n */\nasync function discardOverlayForSettledEntity(\n db: MutationDb,\n context: TableContext,\n entityKey: Record<string, string>,\n entityKeyJson: string,\n) {\n const query = buildOverlayDiscardQuery(context, entityKey, entityKeyJson, [\"pending\", \"sending\", \"failed\"]);\n await db.query(query.sql, query.params as unknown[]);\n}\n\nasync function reconcileTable(db: MutationDb, context: TableContext) {\n // Idle fast-path. Reconcile only retires/clears journal rows in a terminal-clearable state — 'acked'\n // (clear the overlay once the echo lands) or 'conflicted' (retire once a later write resolved it). When\n // none exist — the steady state of an idle entity set — all three statements below are no-ops, so skip\n // the whole transaction. This matters because the convergence driver runs reconcile for EVERY writable\n // table on its interval (default 1.5s), and each CTE pays full PGlite plan+execute cost even against an\n // empty journal: left unguarded it is the dominant idle-CPU cost. The real-time cleanup path is the\n // <table>_reconcile_on_sync trigger; this bulk pass is a fallback, so skipping it when there is nothing\n // to clear changes no outcome. The guard is a single existence probe over the (small, usually empty)\n // journal.\n const journal = context.tables.journal;\n const overlay = context.tables.overlay;\n const synced = context.tables.synced;\n // This is the idle-CPU hot statement (it runs for every writable table on every convergence\n // tick), so the rendered text+params are memoized per context — each tick pays only a plain\n // `db.query` of a cached string, and it stays OUTSIDE any transaction (no BEGIN on the idle path).\n let idleProbe = context.reconcileIdleProbe;\n if (!idleProbe) {\n const probeQuery = queryDialect.sqlToQuery(\n sql`SELECT ${exists(\n queryBuilder\n .select({ one: sql`1` })\n .from(journal)\n .where(inArray(journal.status, [\"acked\", \"conflicted\"])),\n )} AS \"hasWork\"`,\n );\n idleProbe = { sql: probeQuery.sql, params: probeQuery.params as unknown[] };\n context.reconcileIdleProbe = idleProbe;\n }\n const work = await db.query<{ hasWork: boolean }>(idleProbe.sql, idleProbe.params);\n if (work.rows[0]?.hasWork !== true) {\n return;\n }\n\n // The Convergence barrier (ADR-0010) gates the acked-row clearing below; the synced-table trigger\n // handles real-time cleanup, and this is the bulk recovery/fallback path that runs after every flush.\n await db.exec(\"BEGIN\");\n\n try {\n // ADR-0015: retire a terminal `conflicted` row once the user has RESOLVED it — i.e. a LATER write\n // on the same entity has been acked (resolution is an ordinary new mutation). Without this, the old\n // conflicted row lingers forever: `<table>_sync_state.conflict_state` keeps surfacing the resolved\n // conflict and `diagnostics().conflictedCount` never drops. Run before the acked-clear below so the\n // resolving row is still present to supersede it. (`discardConflict` is the explicit throw-away path.)\n // Drizzle DELETE has no USING; the resolver leg is the equivalent EXISTS semi-join.\n const resolver = alias(journal, \"resolver\");\n const retireQuery = queryBuilder\n .delete(journal)\n .where(\n and(\n eq(journal.status, \"conflicted\"),\n exists(\n queryBuilder\n .select({ one: sql`1` })\n .from(resolver)\n .where(\n and(\n eq(resolver.entityKeyJson, journal.entityKeyJson),\n gt(resolver.mutationSeq, journal.mutationSeq),\n eq(resolver.status, \"acked\"),\n ),\n ),\n ),\n ),\n )\n .toSQL();\n await db.query(retireQuery.sql, retireQuery.params as unknown[]);\n\n // ADR-0022 addendum — retire an acked `pessimistic-blind` row with NO echo barrier. A blind update's\n // write target is excluded from this actor's read shape, so no synced echo will ever land for it and no\n // overlay was ever planned: the standard acked-clear below (gated on a synced row reaching the acked\n // version) would keep it forever. Nothing local converges for these rows, so once the authoritative unit\n // acked them there is nothing left to do but drop the journal row. Crash-safe: any later reconcile tick\n // clears a blind row the foreground flushUnit didn't survive to reconcile.\n const blindRetireQuery = queryBuilder\n .delete(journal)\n .where(and(eq(journal.status, \"acked\"), eq(journal.writeMode, \"pessimistic-blind\")))\n .toSQL();\n await db.query(blindRetireQuery.sql, blindRetireQuery.params as unknown[]);\n\n // Clear acknowledged non-delete mutations + matching overlays. ADR-0010: gated by the\n // Convergence barrier (same predicate as the trigger) — the acked write clears only once the\n // synced echo's Server version has reached its acked version. Joining the synced table makes\n // the comparison possible (and means an un-synced acked write is held until its echo lands).\n // Drizzle authoring: DELETE..USING becomes the equivalent EXISTS semi-join, chained through a\n // data-modifying CTE (both sub-statements see the same statement-start snapshot, exactly like\n // the USING form). The barrier predicate stays the shared contracts helper (single authority\n // with the trigger); it renders against the tables' own names, which is how drizzle references\n // their columns here (no aliases on a DELETE target).\n const barrier = sql.raw(\n buildOverlayResolutionBarrier(context.entry, {\n journalAlias: quoteIdentifier(getTableConfig(journal).name),\n syncedAlias: quoteIdentifier(getTableConfig(synced).name),\n }),\n );\n const clearedJournal = queryBuilder.$with(\"cleared_journal\").as(\n queryBuilder\n .delete(journal)\n .where(\n and(\n eq(journal.status, \"acked\"),\n isNotNull(journal.serverUpdatedAtUs),\n ne(journal.mutationKind, \"delete\"),\n exists(\n queryBuilder\n .select({ one: sql`1` })\n .from(synced)\n .where(\n and(\n ...context.pkColumnNames.map((columnName, index) =>\n eq(context.syncedPkColumns[index]!, journal[columnName]!),\n ),\n barrier,\n ),\n ),\n ),\n ),\n )\n .returning(\n Object.fromEntries([\n [\"entity_key_json\", journal.entityKeyJson],\n ...context.pkColumnNames.map((columnName) => [columnName, journal[columnName]!]),\n ]),\n ),\n );\n const clearedJournalColumns = clearedJournal as unknown as Record<string, PgColumn>;\n const ackedClearQuery = queryBuilder\n .with(clearedJournal)\n .delete(overlay)\n .where(\n exists(\n queryBuilder\n .select({ one: sql`1` })\n .from(clearedJournal)\n .where(\n and(\n ...context.pkColumnNames.map((columnName, index) =>\n eq(context.overlayPkColumns[index]!, clearedJournalColumns[columnName]!),\n ),\n notExists(\n queryBuilder\n .select({ one: sql`1` })\n .from(journal)\n .where(\n and(\n eq(journal.entityKeyJson, clearedJournalColumns[\"entity_key_json\"]!),\n inArray(journal.status, [\"pending\", \"sending\", \"failed\"]),\n ),\n ),\n ),\n ),\n ),\n ),\n )\n .toSQL();\n await db.query(ackedClearQuery.sql, ackedClearQuery.params as unknown[]);\n\n // Clear acknowledged delete mutations where synced row is absent\n // Single compound CTE — PGlite does not support multi-statement query().\n const clearableEntities = queryBuilder.$with(\"clearable_entities\").as(\n queryBuilder\n .selectDistinct(\n Object.fromEntries([\n [\"entity_key_json\", journal.entityKeyJson],\n ...context.pkColumnNames.map((columnName) => [columnName, journal[columnName]!]),\n ]),\n )\n .from(journal)\n .leftJoin(\n synced,\n and(\n ...context.pkColumnNames.map((columnName, index) =>\n eq(context.syncedPkColumns[index]!, journal[columnName]!),\n ),\n ),\n )\n .where(\n and(eq(journal.status, \"acked\"), eq(journal.mutationKind, \"delete\"), isNull(context.syncedPkColumns[0]!)),\n ),\n );\n const clearableEntityColumns = clearableEntities as unknown as Record<string, PgColumn>;\n const deletedOverlay = queryBuilder.$with(\"deleted_overlay\").as(\n queryBuilder.delete(overlay).where(\n exists(\n queryBuilder\n .select({ one: sql`1` })\n .from(clearableEntities)\n .where(\n and(\n ...context.pkColumnNames.map((columnName, index) =>\n eq(context.overlayPkColumns[index]!, clearableEntityColumns[columnName]!),\n ),\n ),\n ),\n ),\n ),\n );\n const deleteClearQuery = queryBuilder\n .with(clearableEntities, deletedOverlay)\n .delete(journal)\n .where(\n and(\n eq(journal.status, \"acked\"),\n eq(journal.mutationKind, \"delete\"),\n exists(\n queryBuilder\n .select({ one: sql`1` })\n .from(clearableEntities)\n .where(\n and(\n ...context.pkColumnNames.map((columnName) =>\n eq(journal[columnName]!, clearableEntityColumns[columnName]!),\n ),\n ),\n ),\n ),\n ),\n )\n .toSQL();\n await db.query(deleteClearQuery.sql, deleteClearQuery.params as unknown[]);\n await db.exec(\"COMMIT\");\n } catch (error) {\n await db.exec(\"ROLLBACK\");\n throw error;\n }\n}\n\nfunction buildRequestHeaders(bearerToken?: string, requestHeaders?: Record<string, string>): Record<string, string> {\n // Static headers first so the toolkit-owned Content-Type/Authorization always win.\n return {\n ...(requestHeaders ?? {}),\n \"Content-Type\": \"application/json\",\n ...(bearerToken ? { Authorization: `Bearer ${bearerToken}` } : {}),\n };\n}\n\nasync function applyMutationStatusUpdates(\n db: MutationDb,\n context: TableContext,\n updates: MutationStatusUpdate[],\n onBeforeMarkSending?: () => Promise<void>,\n markSendingScope?: MarkSendingScope,\n) {\n if (updates.length === 0) {\n return;\n }\n\n // Marker-first choke point (slice 2): this is the ONE code path every pending→sending transition flows\n // through (optimistic `flushBatch` + pessimistic `flushUnit`). When any update targets `sending`, commit\n // the durable recovery-required marker BEFORE the transition's UPDATE executes, so a committed `sending`\n // row can never coexist with a `false` marker. Non-`sending` transitions (ack/fail/quarantine) never fire it.\n const marksSending = updates.some((update) => update.status === \"sending\");\n // FIX 1: open the in-flight mark-sending span SYNCHRONOUSLY (before the marker await below), so a concurrent\n // `settleRecoveryMarker` cannot clear the marker between this call's marker decision and its committed\n // `sending` UPDATE. Closed in the `finally` once the UPDATE has committed.\n if (marksSending) markSendingScope?.enter();\n try {\n if (onBeforeMarkSending && marksSending) {\n await onBeforeMarkSending();\n }\n await execMutationStatusUpdates(db, context, updates);\n } finally {\n if (marksSending) markSendingScope?.exit();\n }\n}\n\n/** The bare status-update UPDATE (no marker/counter concerns) — split so `applyMutationStatusUpdates` can\n * bracket it with the mark-sending span in a `finally` (FIX 1). */\nasync function execMutationStatusUpdates(db: MutationDb, context: TableContext, updates: MutationStatusUpdate[]) {\n // Tier ②: `update().from(<VALUES>)`. Every value is a bound param with the same cast as before;\n // the `updates` alias and its column list are fixed by this function (not derived from data), so\n // the alias-qualified references in SET/WHERE are fixed template text, while the journal side of\n // each CASE interpolates the column objects.\n const journal = context.tables.journal;\n const tuples = updates.map(\n (update) =>\n sql`(${update.mutationId}, ${update.status}, ${update.attemptCount}::int, ${update.updatedAtUs}::bigint, ${\n update.sentAtUs ?? null\n }::bigint, ${update.replaceSentAtUs ?? false}::boolean, ${update.ackedAtUs ?? null}::bigint, ${\n update.replaceAckedAtUs ?? false\n }::boolean, ${update.serverUpdatedAtUs ?? null}::bigint, ${update.replaceServerUpdatedAtUs ?? false}::boolean, ${\n update.baseServerVersion ?? null\n }::bigint, ${update.replaceBaseServerVersion ?? false}::boolean, ${update.lastError ?? null}, ${\n update.nextRetryAtUs ?? null\n }::bigint, ${update.lastHttpStatus ?? null}::int, ${update.conflictReason ?? null})`,\n );\n const updatesTable = sql`(VALUES ${sql.join(\n tuples,\n sql`, `,\n )}) AS updates (mutation_id, status, attempt_count, updated_at_us, sent_at_us, replace_sent_at_us, acked_at_us, replace_acked_at_us, server_updated_at_us, replace_server_updated_at_us, base_server_version, replace_base_server_version, last_error, next_retry_at_us, last_http_status, conflict_reason)`;\n\n const query = queryBuilder\n .update(journal)\n .set({\n status: sql`updates.status`,\n attemptCount: sql`updates.attempt_count`,\n updatedAtUs: sql`updates.updated_at_us::bigint`,\n sentAtUs: sql`CASE WHEN updates.replace_sent_at_us THEN updates.sent_at_us::bigint ELSE ${journal.sentAtUs} END`,\n ackedAtUs: sql`CASE WHEN updates.replace_acked_at_us THEN updates.acked_at_us::bigint ELSE ${journal.ackedAtUs} END`,\n serverUpdatedAtUs: sql`CASE WHEN updates.replace_server_updated_at_us THEN updates.server_updated_at_us::bigint ELSE ${journal.serverUpdatedAtUs} END`,\n baseServerVersion: sql`CASE WHEN updates.replace_base_server_version THEN updates.base_server_version::bigint ELSE ${journal.baseServerVersion} END`,\n lastError: sql`updates.last_error`,\n nextRetryAtUs: sql`updates.next_retry_at_us::bigint`,\n lastHttpStatus: sql`updates.last_http_status`,\n conflictReason: sql`updates.conflict_reason`,\n })\n .from(updatesTable)\n .where(eq(journal.mutationId, sql`updates.mutation_id::uuid`))\n .toSQL();\n await db.query(query.sql, query.params as unknown[]);\n}\n\nfunction qualifyLocalIdentifier(schemaName: string, tableName: string) {\n if (schemaName === \"public\") {\n // Quote-when-needed: a reserved-word or mixed-case table name (e.g. `group`)\n // MUST be quoted or the generated SQL fails to parse (ADR-0004). Normal names\n // stay bare, so existing generated SQL is unchanged.\n return maybeQuoteIdentifier(tableName);\n }\n\n return `${quoteIdentifier(schemaName)}.${quoteIdentifier(tableName)}`;\n}\n\nfunction buildJournalSequenceName(journalTable: string) {\n return `${journalTable}_mutation_seq`;\n}\n\nfunction hasProperty(context: TableContext, propertyKey: string) {\n return context.columns.some((column) => column.propertyKey === propertyKey);\n}\n\nfunction ensureRecord(value: unknown) {\n if (!isRecord(value)) {\n throw new Error(\"Mutation runtime expected a record payload\");\n }\n\n return value;\n}\n\nfunction extractRecordFromState(context: TableContext, state: CurrentRecordStateRow | BatchCurrentRecordStateRow) {\n return Object.fromEntries(context.columns.map(({ propertyKey }) => [propertyKey, state[propertyKey] ?? null]));\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null;\n}\n\nclass MutationRequestError extends Error {\n readonly status: number;\n /** Per-mutation attribution the server returned for a structural rejection, or null. */\n readonly rejections: MutationRejection[] | null;\n\n constructor(message: string, status: number, rejections: MutationRejection[] | null = null) {\n super(message);\n this.name = \"MutationRequestError\";\n this.status = status;\n this.rejections = rejections;\n }\n}\n\n/**\n * Extract per-mutation attribution from a non-2xx batch-write body. The server names the\n * offending mutations on a structural (validation) rejection; an absent, non-JSON, or\n * empty-`rejections` body yields null, so the failure is treated as non-attributable\n * (whole batch stays retryable).\n */\nfunction parseBatchRejections(body: string): MutationRejection[] | null {\n if (body.length === 0) {\n return null;\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(body);\n } catch {\n return null;\n }\n\n const result = batchMutationErrorSchema.safeParse(parsed);\n const rejections = result.success ? result.data.rejections : undefined;\n return rejections && rejections.length > 0 ? rejections : null;\n}\n",
|
|
25
25
|
"/**\n * The mutation-journal state machine (ADR-0005, extended by ADR-0006).\n *\n * The runtime is large; previously the legal status transitions were implicit,\n * scattered across SQL writes. This is the one named place that defines them, so the\n * rules are testable and a future change extends a single table. ADR-0006 splits the\n * old single `failed` into transient (retryable `failed`) and permanent (`quarantined`).\n */\n\nexport type MutationStatus = \"pending\" | \"sending\" | \"acked\" | \"failed\" | \"quarantined\" | \"conflicted\" | \"rejected\";\n\n/**\n * Legal transitions. `acked` is terminal at the journal level — it is cleared by\n * reconciliation once the synced echo reaches the acknowledged server timestamp, not\n * by another status transition. `quarantined` is terminal too: the server will never\n * accept the mutation as-is, so it is surfaced (callback + diagnostics), never retried.\n * `conflicted` (ADR-0015) is likewise terminal but a *different* outcome: the write was\n * well-formed but **stale** (an external write interleaved) and the table's `reject-if-stale`\n * policy declined it. The optimistic Overlay is KEPT (the user's edit is not lost) and the\n * conflict is surfaced via `onConflict`; resolution is an ordinary NEW mutation, and `discard`\n * clears the overlay + this entry. It is never retried as-is (the base would still be stale).\n * `rejected` (ADR-0022) is terminal as well, and the inverse of `conflicted` on disposition: the\n * authoritative endpoint declined the whole pessimistic write-**unit** for a business reason (a\n * capacity/quota/uniqueness rule the client could not evaluate locally), so the optimistic Overlay\n * is **auto-discarded** for every member of the unit and the typed reason is surfaced via `onReject`.\n * Never retried (the server's answer is authoritative).\n *\n * - `pending -> sending` a flush claims the row and posts it.\n * - `sending -> acked` the server acknowledged the mutation.\n * - `sending -> failed` transient transport/server error (network, 5xx, …).\n * - `sending -> quarantined` structural 4xx rejection the server will never accept.\n * - `sending -> conflicted` a stale write the reject-if-stale policy declined (ADR-0015).\n * - `sending -> rejected` a business rejection from the authoritative endpoint (ADR-0022).\n * - `sending -> pending` recoverSending re-queues an in-flight row on startup.\n * - `pending -> quarantined` a RESTORE boot quarantines every non-terminal row recovered from a\n * backup (ADR-0035 decision 6). A `pending` row is normally only ever claimed (`-> sending`), but a\n * store restored from a backup must NOT auto-flush anything it recovered — the write path has no\n * `mutationId` dedupe ledger, so replaying a recovered `pending`/`sending`/`failed` mutation is unsafe\n * (silent last-write-wins reverts, create PK collisions). Restore is therefore the ONE producer of this\n * edge; ordinary boots never move a `pending` row straight to `quarantined`.\n * - `failed -> pending` retryFailed re-queues a failed row.\n * - `failed -> quarantined` the hard max-attempts cap is reached; stop retrying (also the restore\n * quarantine of a recovered `failed` row, ADR-0035 decision 6 — the edge already existed).\n */\nexport const MUTATION_TRANSITIONS = {\n // `pending -> quarantined` exists ONLY for the restore-boot quarantine (ADR-0035 decision 6); the normal\n // flush path only ever claims a pending row (`-> sending`).\n pending: [\"sending\", \"quarantined\"],\n sending: [\"acked\", \"failed\", \"quarantined\", \"conflicted\", \"rejected\", \"pending\"],\n failed: [\"pending\", \"quarantined\"],\n quarantined: [],\n conflicted: [],\n rejected: [],\n acked: [],\n} as const satisfies Record<MutationStatus, readonly MutationStatus[]>;\n\nexport function isValidMutationTransition(from: MutationStatus, to: MutationStatus): boolean {\n return (MUTATION_TRANSITIONS[from] as readonly MutationStatus[]).includes(to);\n}\n\nexport function assertValidMutationTransition(from: MutationStatus, to: MutationStatus): void {\n if (!isValidMutationTransition(from, to)) {\n throw new Error(`Illegal mutation-journal transition: ${from} -> ${to}`);\n }\n}\n\n/**\n * The hard cap on send attempts (ADR-0005 congestion policy). A mutation that has\n * failed this many times — even with transient-looking errors — is given up on and\n * quarantined, so a permanently-unreachable server never produces an unbounded retry\n * loop. The consumer can raise/lower it via `createSyncClient({ maxMutationAttempts })`.\n */\nexport const DEFAULT_MAX_MUTATION_ATTEMPTS = 10;\n\n/**\n * 4xx statuses that are nonetheless transient: auth (the runtime refreshes the token and\n * retries), request-timeout, too-early, and rate-limit. Everything else in the 4xx range\n * is treated as a structural rejection the server will never accept as-is.\n */\nconst TRANSIENT_CLIENT_ERROR_STATUSES: ReadonlySet<number> = new Set([401, 403, 408, 425, 429]);\n\n/**\n * Classify a flush failure into its durable journal state (ADR-0006 decision 4):\n * - `quarantined` (terminal): a structural 4xx rejection — retrying is pointless, so it\n * is surfaced rather than retry-looped (the silent-data-loss case the runtime *can*\n * catch at send time).\n * - `failed` (retryable): network/transport (no status), any 5xx, or a transient 4xx.\n */\nexport function classifyFailureStatus(httpStatus: number | null | undefined): \"failed\" | \"quarantined\" {\n if (httpStatus == null) {\n return \"failed\";\n }\n\n if (httpStatus >= 400 && httpStatus < 500 && !TRANSIENT_CLIENT_ERROR_STATUSES.has(httpStatus)) {\n return \"quarantined\";\n }\n\n return \"failed\";\n}\n",
|
|
26
|
+
"// The registry-wide reactive mutation-status API (warm-persisted-store-startup slice 4 / proposal §5,\n// option 1). `client.mutations.*` lets a consumer render a global sync indicator or diagnostics screen with\n// ONE subscription over the `pgxsinkit_all_mutations` view (schema.ts) instead of one live query per writable\n// journal — the O(writable-table) fan-out the proposal set out to remove.\n//\n// It is a FACTORY over the two seams BOTH client modes already share — `subscribeLiveRows` (in-process over\n// `pglite.live`; worker-attached over the bridge) and a one-shot `query` (in-process `pglite.query`;\n// worker-attached the `rawQuery` RPC) — so the worker bridge needs ZERO protocol change. Every runtime query\n// is Drizzle-built over `getAllMutationsView` (tier ①); consumers never touch generated journal relation\n// names.\n\nimport { and, desc, eq, inArray, sql } from \"drizzle-orm\";\nimport { drizzle } from \"drizzle-orm/pglite\";\n\nimport type { MutationSummary, SyncTableName, SyncTableRegistry } from \"@pgxsinkit/contracts\";\n\nimport { getAllMutationsView } from \"./local-tables\";\nimport type { MutationDetail, MutationKind } from \"./mutation\";\nimport type { MutationStatus } from \"./mutation-state\";\n\n// Re-export the detail shape under the summary-API name. The list/subscribe detail rows ARE\n// {@link MutationDetail} (it already carries `tableName` + the parsed `entityKey`), reused verbatim.\nexport type { MutationDetail } from \"./mutation\";\nexport type MutationSummaryDetail = MutationDetail;\n\n/**\n * Build-only Drizzle (compiles to SQL via `.toSQL()`; never executes) — same mock seam mutation.ts uses.\n * Lazily constructed: some unit suites mock `drizzle-orm/pglite`, so `drizzle.mock` is unavailable at module\n * load; a lazy builder is only reached when a real query is actually authored (never in those mocked boots).\n */\nlet queryBuilderInstance: ReturnType<typeof drizzle.mock> | undefined;\nfunction queryBuilder(): ReturnType<typeof drizzle.mock> {\n return (queryBuilderInstance ??= drizzle.mock());\n}\n\n/** Optional filters for {@link MutationsApi.list} / {@link MutationsApi.subscribe}. */\nexport interface MutationListOptions<TRegistry extends SyncTableRegistry> {\n /** Restrict to one registry table key (the `table_key` column). */\n table?: SyncTableName<TRegistry>;\n /**\n * Restrict to one entity — matched on the serialized `entity_key_json` (`JSON.stringify(entityKey)`),\n * byte-for-byte against the enqueue-time serialization. For a COMPOSITE key, pass the properties in the\n * same order pgxsinkit serialized them (a key taken from a returned {@link MutationSummaryDetail} or the\n * write API round-trips correctly; a hand-built object with a different property order silently matches\n * nothing).\n */\n entityKey?: Record<string, string>;\n /** Restrict to a set of journal statuses. */\n statuses?: readonly MutationStatus[];\n /** Cap the returned rows (applied after the `enqueued_at_us` ordering). */\n limit?: number;\n}\n\n/** A handle to a live summary subscription: the initial summary plus an idempotent unsubscribe. */\nexport interface MutationSummarySubscription {\n initial: MutationSummary;\n unsubscribe: () => void;\n}\n\n/** A handle to a live detail subscription: the initial ordered rows plus an idempotent unsubscribe. */\nexport interface MutationListSubscription {\n initial: MutationSummaryDetail[];\n unsubscribe: () => void;\n}\n\n/**\n * The registry-wide reactive mutation-status surface (`client.mutations`), identical on the in-process and\n * worker-attached client. Consumers NEVER touch the generated journal relation names — everything routes\n * through the `pgxsinkit_all_mutations` view.\n *\n * The `summary` is cheap enough to mount PERMANENTLY (one fingerprinted registration regardless of subscriber\n * count — ADR-0040 dedup gives one shared rerun per journal write, not N). Full `list`/`subscribe` detail\n * subscriptions should stay route- or feature-scoped.\n */\nexport interface MutationsApi<TRegistry extends SyncTableRegistry> {\n /** One-shot per-status counts across every writable journal (absent statuses = 0). */\n summary(): Promise<MutationSummary>;\n /**\n * Live per-status counts: `listener` fires on every change, the initial summary is on the returned handle\n * (matching `subscribeLiveRows`' initial-via-return / changes-via-callback split). One registration\n * regardless of subscriber count. Cheap to mount permanently.\n */\n subscribeSummary(listener: (summary: MutationSummary) => void): Promise<MutationSummarySubscription>;\n /** One-shot normalized detail rows, filtered by {@link MutationListOptions}, ordered newest-first by `enqueued_at_us`. */\n list(options?: MutationListOptions<TRegistry>): Promise<MutationSummaryDetail[]>;\n /**\n * Live normalized detail rows (same filters/ordering as {@link list}). Route/feature-scoped: a detail\n * subscription reruns the union SELECT on each relevant write — cheap for a scoped view, but prefer the\n * summary for anything mounted app-wide.\n */\n subscribe(\n options: MutationListOptions<TRegistry>,\n listener: (rows: MutationSummaryDetail[]) => void,\n ): Promise<MutationListSubscription>;\n}\n\n/** The row shape the raw seams return for the summary aggregate (unmapped, keyed by output column name). */\ninterface SummaryRow extends Record<string, unknown> {\n status: string;\n count: number | string;\n}\n\n/** The row shape the raw seams return for a detail query (unmapped, keyed by the select's aliases). */\ninterface DetailRow extends Record<string, unknown> {\n tableName: string;\n entityKeyJson: string;\n mutationId: string;\n mutationSeq: number | string;\n mutationKind: MutationKind;\n status: MutationStatus;\n attemptCount: number | string;\n lastHttpStatus: number | null;\n lastError: string | null;\n conflictReason: string | null;\n nextRetryAtUs: string | null;\n serverUpdatedAtUs: string | null;\n updatedAtUs: string;\n registryVersion: string | null;\n}\n\n/** The seams the factory needs — shared verbatim by both client modes (zero worker-protocol change). */\nexport interface MutationsApiDeps<TRegistry extends SyncTableRegistry> {\n registry: TRegistry;\n subscribeLiveRows: <TRow extends Record<string, unknown>>(\n input: { sql: string; params: readonly unknown[] },\n onRows: (rows: TRow[]) => void,\n ) => Promise<{ initialRows: TRow[]; unsubscribe: () => void }>;\n /** One-shot query seam (in-process `pglite.query`; worker-attached the `rawQuery` RPC). Rows are UNMAPPED. */\n query: (sql: string, params?: unknown[]) => Promise<{ rows: Record<string, unknown>[] }>;\n}\n\nconst STATUS_TO_SUMMARY_KEY: Record<MutationStatus, keyof MutationSummary> = {\n pending: \"pendingCount\",\n sending: \"sendingCount\",\n acked: \"ackedCount\",\n failed: \"failedCount\",\n quarantined: \"quarantinedCount\",\n conflicted: \"conflictedCount\",\n rejected: \"rejectedCount\",\n};\n\nfunction emptySummary(): MutationSummary {\n return {\n pendingCount: 0,\n sendingCount: 0,\n ackedCount: 0,\n failedCount: 0,\n rejectedCount: 0,\n conflictedCount: 0,\n quarantinedCount: 0,\n unsettledCount: 0,\n settledCount: 0,\n };\n}\n\n/** Fold `{status, count}` aggregate rows into the summary shape (absent statuses = 0; derive the totals). */\nfunction foldSummary(rows: readonly SummaryRow[]): MutationSummary {\n const summary = emptySummary();\n for (const row of rows) {\n const key = STATUS_TO_SUMMARY_KEY[row.status as MutationStatus];\n if (key) {\n summary[key] = Number(row.count);\n }\n }\n // See MutationSummary's JSDoc (FIX 3): `conflicted` AND `quarantined` are journal-terminal but user-UNSETTLED\n // (overlay kept, entity blocked, `destroy()` refuses them, reconciliation counts them owed), so both join\n // pending/sending/failed. `settledCount` is the truly-done complement — `acked` + `rejected` only.\n summary.unsettledCount =\n summary.pendingCount +\n summary.sendingCount +\n summary.failedCount +\n summary.conflictedCount +\n summary.quarantinedCount;\n summary.settledCount = summary.ackedCount + summary.rejectedCount;\n return summary;\n}\n\nfunction mapDetailRow(row: DetailRow): MutationSummaryDetail {\n return {\n tableName: row.tableName,\n entityKey: JSON.parse(row.entityKeyJson) as Record<string, string>,\n mutationId: row.mutationId,\n mutationSeq: Number(row.mutationSeq),\n mutationKind: row.mutationKind,\n status: row.status,\n attemptCount: Number(row.attemptCount),\n lastHttpStatus: row.lastHttpStatus,\n lastError: row.lastError,\n conflictReason: row.conflictReason,\n nextRetryAtUs: row.nextRetryAtUs,\n serverUpdatedAtUs: row.serverUpdatedAtUs,\n updatedAtUs: row.updatedAtUs,\n registryVersion: row.registryVersion,\n };\n}\n\n/** Does the registry declare ≥1 writable table (a journal to union → the view is emitted)? */\nfunction hasWritableTable(registry: SyncTableRegistry): boolean {\n return Object.values(registry).some((entry) => entry.mode !== \"readonly\" && entry.clientProjection?.journalTable);\n}\n\n/** The `SELECT status, count(*) … GROUP BY status` aggregate over the view (tier ①). */\nfunction buildSummarySql(registry: SyncTableRegistry): { sql: string; params: unknown[] } {\n const view = getAllMutationsView(registry);\n return queryBuilder()\n .select({ status: view.status, count: sql<number>`count(*)::int`.as(\"count\") })\n .from(view)\n .groupBy(view.status)\n .toSQL();\n}\n\n/**\n * The filtered detail SELECT over the view (tier ①). Every column is aliased to its camelCase key (the raw\n * seams return rows UNMAPPED), mirroring `readMutationDetailsForContexts`, plus the `table_key`. Ordered\n * newest-first by `enqueued_at_us` — the per-journal `mutation_seq` is NOT globally ordered, so it is never\n * used across tables.\n */\nfunction buildDetailSql<TRegistry extends SyncTableRegistry>(\n registry: TRegistry,\n options: MutationListOptions<TRegistry> | undefined,\n): { sql: string; params: unknown[] } {\n const view = getAllMutationsView(registry);\n const conditions = [];\n if (options?.table != null) {\n conditions.push(eq(view.tableKey, options.table));\n }\n if (options?.entityKey != null) {\n conditions.push(eq(view.entityKeyJson, JSON.stringify(options.entityKey)));\n }\n if (options?.statuses != null && options.statuses.length > 0) {\n conditions.push(inArray(view.status, options.statuses as string[]));\n }\n\n const base = queryBuilder()\n .select({\n tableName: sql<string>`${view.tableKey}`.as(\"tableName\"),\n entityKeyJson: sql<string>`${view.entityKeyJson}`.as(\"entityKeyJson\"),\n mutationId: sql<string>`${view.mutationId}`.as(\"mutationId\"),\n mutationSeq: sql<number>`${view.mutationSeq}`.as(\"mutationSeq\"),\n mutationKind: sql<MutationKind>`${view.mutationKind}`.as(\"mutationKind\"),\n status: sql<MutationStatus>`${view.status}`.as(\"status\"),\n attemptCount: sql<number>`${view.attemptCount}`.as(\"attemptCount\"),\n lastHttpStatus: sql<number | null>`${view.lastHttpStatus}`.as(\"lastHttpStatus\"),\n lastError: sql<string | null>`${view.lastError}`.as(\"lastError\"),\n conflictReason: sql<string | null>`${view.conflictReason}`.as(\"conflictReason\"),\n nextRetryAtUs: sql<string | null>`${view.nextRetryAtUs}::text`.as(\"nextRetryAtUs\"),\n serverUpdatedAtUs: sql<string | null>`${view.serverUpdatedAtUs}::text`.as(\"serverUpdatedAtUs\"),\n updatedAtUs: sql<string>`${view.updatedAtUs}::text`.as(\"updatedAtUs\"),\n registryVersion: sql<string | null>`${view.registryVersion}`.as(\"registryVersion\"),\n })\n .from(view)\n .where(conditions.length > 0 ? and(...conditions) : undefined)\n // `mutation_id` tiebreak: mutations enqueued in the same microsecond (e.g. a multi-table batch) must not\n // shuffle relative order between live-query reruns.\n .orderBy(desc(view.enqueuedAtUs), desc(view.mutationId));\n\n return (options?.limit != null ? base.limit(options.limit) : base).toSQL();\n}\n\n/**\n * Build the `client.mutations` API over the shared seams. Implemented ONCE — both client modes pass their own\n * `subscribeLiveRows` + one-shot `query`, so semantics are identical and the worker bridge is untouched. A\n * registry with NO writable table emits no view, so the API short-circuits to empty shapes WITHOUT touching\n * the (absent) view — derived from the registry, never a runtime probe.\n */\nexport function createMutationsApi<TRegistry extends SyncTableRegistry>(\n deps: MutationsApiDeps<TRegistry>,\n): MutationsApi<TRegistry> {\n const { registry, subscribeLiveRows, query } = deps;\n const writable = hasWritableTable(registry);\n\n return {\n summary: async () => {\n if (!writable) {\n return emptySummary();\n }\n const built = buildSummarySql(registry);\n const { rows } = await query(built.sql, built.params);\n return foldSummary(rows as SummaryRow[]);\n },\n subscribeSummary: async (listener) => {\n if (!writable) {\n return { initial: emptySummary(), unsubscribe: () => {} };\n }\n const built = buildSummarySql(registry);\n const subscription = await subscribeLiveRows<SummaryRow>({ sql: built.sql, params: built.params }, (rows) =>\n listener(foldSummary(rows)),\n );\n return { initial: foldSummary(subscription.initialRows), unsubscribe: subscription.unsubscribe };\n },\n list: async (options) => {\n if (!writable) {\n return [];\n }\n const built = buildDetailSql(registry, options);\n const { rows } = await query(built.sql, built.params);\n return (rows as DetailRow[]).map(mapDetailRow);\n },\n subscribe: async (options, listener) => {\n if (!writable) {\n return { initial: [], unsubscribe: () => {} };\n }\n const built = buildDetailSql(registry, options);\n const subscription = await subscribeLiveRows<DetailRow>({ sql: built.sql, params: built.params }, (rows) =>\n listener(rows.map(mapDetailRow)),\n );\n return { initial: subscription.initialRows.map(mapDetailRow), unsubscribe: subscription.unsubscribe };\n },\n };\n}\n",
|
|
26
27
|
"import type { ExternalHeadersRecord, ShapeStreamOptions } from \"@electric-sql/client\";\n\n/** The per-shape error handler shape Electric expects (`ShapeStreamOptions.onError`). */\ntype ShapeStreamErrorHandler = NonNullable<ShapeStreamOptions[\"onError\"]>;\n\n/**\n * Read-path identity (ADR-0013). The two ingress points must share **one** token lifecycle: the\n * write path already calls `getAuthToken` fresh on every flush, so the read path must too — never\n * freezing a JWT at boot, which wedges a long-lived offline-first session the instant the token\n * expires.\n *\n * `buildAuthShapeHeaders` returns the read-path `Authorization` header as an **async function**.\n * Electric resolves header-value functions on every request *and every retry*\n * (`ExternalHeadersRecord` allows `string | (() => string | Promise<string>)`), so each shape fetch\n * presents a fresh token. This is the client mirror of ADR-0003's server-side one-identity decision.\n *\n * The provider contract (documented in `docs/architecture.md`): `getAuthToken` is now called per\n * request by both paths and **must be refresh-deduping** — return the cached valid token and refresh\n * single-flight, so an N-shape consistency group does not trigger N refreshes.\n */\n/**\n * Build the read-path shape headers: the optional async `Authorization` (per ADR-0013) **plus** any\n * caller-supplied static `requestHeaders`. The static headers are spread first so the toolkit-owned\n * `Authorization` always wins; they exist for deployment-gateway credentials the toolkit is otherwise\n * agnostic about — e.g. a Supabase `apikey` header the platform function gateway expects. Emitted\n * whenever *either* a token provider or static headers are present, so a credential-only consumer\n * (no per-request token) still sends its headers.\n */\nexport function buildShapeHeaders(input: {\n getAuthToken?: () => Promise<string | undefined>;\n requestHeaders?: Record<string, string>;\n}): ExternalHeadersRecord {\n const headers: ExternalHeadersRecord = { ...(input.requestHeaders ?? {}) };\n const getAuthToken = input.getAuthToken;\n if (getAuthToken) {\n // Resolved per request: a fresh token each time, never one captured at boot. An absent token\n // yields an empty value (unauthenticated) rather than the literal string `Bearer undefined`.\n headers[\"Authorization\"] = async () => {\n const token = await getAuthToken();\n return token ? `Bearer ${token}` : \"\";\n };\n }\n return headers;\n}\n\n/** Token-only convenience over {@link buildShapeHeaders}; retained for callers that pass a provider. */\nexport function buildAuthShapeHeaders(\n getAuthToken: () => Promise<string | undefined>,\n requestHeaders?: Record<string, string>,\n): ExternalHeadersRecord {\n return buildShapeHeaders({ getAuthToken, ...(requestHeaders ? { requestHeaders } : {}) });\n}\n\n/** HTTP statuses that mean \"the credential is the problem\" — re-auth, never give up (ADR-0013). */\nconst AUTH_ERROR_STATUSES = new Set([401, 403]);\n\n/** Read the duck-typed numeric `status` off an Electric `FetchError`, or `undefined` for a plain error. */\nfunction readErrorStatus(error: unknown): number | undefined {\n if (typeof error !== \"object\" || error === null || !(\"status\" in error)) {\n return undefined;\n }\n const status = (error as { status: unknown }).status;\n return typeof status === \"number\" ? status : undefined;\n}\n\n/**\n * True when the error is an auth failure (Electric's `FetchError` with a 401/403 `status`). We read\n * the documented `status` field rather than `instanceof FetchError`: the experimental and client\n * packages can resolve to *different* `@electric-sql/client` copies, so an `instanceof` against one\n * copy can miss a `FetchError` thrown from the other. A duck-typed numeric `status` is robust and\n * carries no false positives — a plain network/`Error` has no numeric `status`.\n */\nfunction isAuthError(error: unknown): boolean {\n const status = readErrorStatus(error);\n return status !== undefined && AUTH_ERROR_STATUSES.has(status);\n}\n\n/**\n * Whether a non-auth read-stream error is worth retrying (#4): a transient transport fault — a 5xx,\n * a 429 rate-limit, or a network error with no HTTP status. A genuine non-auth 4xx (400/404/409/…)\n * is structural: retrying re-fails, so we stop. (401/403 are handled separately as auth.)\n */\nfunction isRetryableStreamError(error: unknown): boolean {\n const status = readErrorStatus(error);\n if (status === undefined) {\n return true; // network/transport error — retry with Electric's backoff\n }\n return status >= 500 || status === 429;\n}\n\n/**\n * The per-shape `ShapeStreamOptions.onError` handler for the read path. It is the only place that can\n * request a retry (the `MultiShapeStream.subscribe` `onError` is notification-only), so it owns BOTH\n * read-path identity (ADR-0013) and read-stream error surfacing (#4):\n *\n * - **auth (401/403)** → `onAuthError` + return `{}` (retry): Electric re-issues the request,\n * re-resolving the async Authorization header ({@link buildAuthShapeHeaders}) for a *fresh* token.\n * Never return `void` here — that stops the stream permanently, wrong for offline-first: a dead\n * session must keep retrying (jittered backoff bounds the cost) so sync resumes the instant re-auth\n * makes the token valid again. The optional `onAuthError` surfaces a distinct \"re-login\" status.\n * - **any other error** → `onReadStreamError` (so the runtime can move to a `degraded` status instead\n * of silently believing the read path is live), then retry transient faults ({@link\n * isRetryableStreamError}: 5xx/429/network → `{}`) or stop a structural 4xx (return `undefined`). A\n * later successful fetch (`onSyncActivity`) clears the degraded status back to live.\n */\nexport function createShapeErrorHandler(\n options: { onAuthError?: () => void; onReadStreamError?: (error: Error) => void } = {},\n): ShapeStreamErrorHandler {\n return (error: Error) => {\n if (isAuthError(error)) {\n options.onAuthError?.();\n return {}; // retry → re-resolves the async Authorization header for a fresh token\n }\n options.onReadStreamError?.(error);\n return isRetryableStreamError(error) ? {} : undefined;\n };\n}\n",
|
|
27
|
-
"import type { ExternalHeadersRecord } from \"@electric-sql/client\";\nimport type { PGliteInterface } from \"@electric-sql/pglite\";\n\nimport {\n type Retention,\n type SubscriptionTiming,\n type SyncConfigInput,\n type SyncTableRegistry,\n type TableSpecInput,\n} from \"@pgxsinkit/contracts\";\n\nimport type { BootStampCollector, GroupBootStamp } from \"./boot-report\";\nimport type { SyncNamespaceObj } from \"./sync\";\nimport { createShapeErrorHandler } from \"./sync-auth\";\n\nexport interface ShapeSyncSpec {\n electricUrl: string;\n tableName: string;\n schema?: string;\n shapeKey: string;\n primaryKey: string[];\n electricTable?: string;\n /**\n * Consistency group (ADR-0009 decision 2). Specs sharing a group sync on one `MultiShapeStream`\n * and commit atomically. Absent → the table is its own singleton group keyed by its `shapeKey`.\n */\n consistencyGroup?: string;\n /**\n * Subscription timing (ADR-0021). Absent → `eager`. A `lazy` spec's group is held out of the eager\n * boot set and started on demand via {@link StartConfiguredSyncResult.ensureGroupStarted}. A group's\n * members all agree (registry-validated), so the group's timing is any member's.\n */\n subscription?: SubscriptionTiming;\n /**\n * Retention (ADR-0021). Absent → `persistent`. Only a `persistent` `lazy` group is promoted to the\n * eager set on activation (its activation is permanent across boots); an `ephemeral` group's activation\n * is session-scoped by construction, so it is never promoted/persisted.\n */\n retention?: Retention;\n}\n\nexport interface ConfiguredShapeSyncSpec extends ShapeSyncSpec {\n key: string;\n}\n\nexport interface StartConfiguredSyncOptions {\n syncConfig: SyncConfigInput;\n /**\n * The sync registry (ADR-0029 D1): the engine's sole per-table spec source. Each shape's `tableKey`\n * (its `syncConfig` table key) resolves against it for the local table, PKs, apply strategy, and\n * column types — no table-scoped fact is threaded from `syncConfig` into the engine.\n */\n registry: SyncTableRegistry;\n /**\n * Shape request headers shared by every member shape. Values may be async functions resolved per\n * request (ADR-0013) — the read-path `Authorization` token is one such function.\n */\n shapeHeaders?: ExternalHeadersRecord;\n onInitialSync?: () => void;\n onTableInitialSync?: (tableKey: string) => void;\n /**\n * Fresh-store prefetch overlap (ADR-0032 S4). When present, every EAGER group starts its shape streams\n * and buffers their catch-up into the memory inbox immediately, gating all commits until this promise\n * resolves — so the network catch-up overlaps the local boot phases (schema/journal/reconcile) instead\n * of running after them. Set ONLY by `createSyncClient` on a provably-fresh store (its `freshStore`\n * hint); absent → the sequential path. Passed straight through to the engine's `syncShapesToTables`.\n */\n dbReady?: Promise<void>;\n /** Commit-level error surfacing (ADR-0009 decision 5): a sync commit exhausted its retries. */\n onSyncError?: (error: Error) => void;\n /**\n * Notified when a shape hits an auth error (401/403) and the read path is retrying for a fresh\n * token (ADR-0013 Phase 3). The runtime surfaces a distinct `auth-needed` status from this.\n */\n onAuthError?: () => void;\n /**\n * Notified when a shape hits a NON-auth stream error (#4): a transient 5xx/429/network (retried) or\n * a structural 4xx (stops the stream). The runtime surfaces a `degraded` status from this so it\n * never silently believes the read path is live while it has actually stalled.\n */\n onReadStreamError?: (error: Error) => void;\n /**\n * Notified when a shape successfully delivers a batch — i.e. a fetch just succeeded (ADR-0013\n * Phase 3). The runtime uses this to clear an `auth-needed`/`degraded` status once sync resumes.\n */\n onSyncActivity?: () => void;\n /**\n * Consistency-group keys of `lazy` groups that were activated on a previous boot and persisted their\n * activation flag (ADR-0021 §2 — `lazy + persistent` promotion). These join the eager boot set as if\n * they were declared `eager`, so a once-activated durable lazy group resumes without re-evaluation.\n * Computed by the caller from the local meta table (the sync engine does no DB read of its own).\n */\n promotedGroups?: ReadonlySet<string>;\n /**\n * Invoked when a `persistent` `lazy` group is activated on demand (not promoted at boot), so the\n * caller can persist its activation flag for the next boot (ADR-0021 §2). Never fired for an\n * `ephemeral` group (its activation is session-scoped and leaves no durable trace).\n */\n onLazyActivated?: (groupKey: string) => void;\n /**\n * Invoked exactly once per consistency group the moment it becomes up-to-date (ADR-0032 decision 6 —\n * per-group readiness). Fires for eager, promoted, and on-demand `lazy` groups alike, so a client can\n * surface progressive per-group paint (and the worker bridge can fan a `groupReady` event to tabs)\n * without the all-eager-groups `onInitialSync` gate. The matching promise is {@link StartConfiguredSyncResult.groupReady}.\n */\n onGroupReady?: (groupKey: string) => void;\n /**\n * Boot observability (ADR-0034): opens a per-group accumulator (rows/requests/fetch/apply wall) for each\n * EAGER + PROMOTED boot group, stamped by the engine as the group's stream chain delivers and applies. A\n * lazy on-demand start gets none — so a lazily-activated-later group never enters (or mutates) the report.\n * Absent → no boot instrumentation.\n */\n bootCollector?: BootStampCollector;\n}\n\n// The engine is reached through the `electric` namespace the client attaches post-create (ADR-0032 S1) —\n// a plain property carrying the sync entry points, no longer a create-time PGlite extension.\ntype SyncEnginePGlite = PGliteInterface & { electric: SyncNamespaceObj };\n\nexport interface ShapeSyncResult {\n unsubscribe: () => void;\n readonly isUpToDate: boolean;\n}\n\nexport interface StartConfiguredSyncResult {\n unsubscribe: () => void;\n tables: Record<string, ShapeSyncResult>;\n /**\n * Start a `lazy` consistency group (ADR-0021) held out of the eager boot set. Idempotent and\n * single-flight: concurrent calls share one start; a started, unknown, or eager group resolves\n * immediately. Resolves once the group's initial sync completes — the seam the live-query layer\n * calls on first reference to a lazy table. After it resolves, the group's member `tables` entries\n * report `isUpToDate` live.\n */\n ensureGroupStarted: (groupKey: string) => Promise<void>;\n /**\n * Stop a group's stream and return it to dormant (ADR-0021 §2): tear down its live subscription and\n * clear the runtime so {@link isTableStarted} reports false again and a later {@link ensureGroupStarted}\n * re-subscribes from scratch — the inverse of an on-demand activation. Used by the client's `desync`\n * to halt a lazy group before truncating its read cache. A no-op for an unknown or never-started group.\n * The temp cluster of an `ephemeral` group is NOT dropped here (that is the deferred idle-eviction); the\n * cluster simply stops being fed.\n */\n stopGroup: (groupKey: string) => void;\n /** The consistency-group key a table belongs to — maps a queried table to its {@link ensureGroupStarted}. */\n groupKeyForTable: (tableKey: string) => string | undefined;\n /**\n * Whether a table's consistency group has started and completed its initial sync, so its reads are\n * hydrated (ADR-0021). False for a `lazy` group still held out of the boot set. Drives the read-path\n * tripwire — a lazy relation read while this is false would return empty/stale rows.\n */\n isTableStarted: (tableKey: string) => boolean;\n /**\n * A promise that resolves the moment the given consistency group is up-to-date (ADR-0032 decision 6).\n * Resolves immediately for an already-ready group; stays pending for a `lazy` group until it is\n * activated (via {@link ensureGroupStarted}) and catches up. An unknown group resolves immediately\n * (nothing to await). Per-group readiness the client re-exposes as `client.groupReady(table)`.\n */\n groupReady: (groupKey: string) => Promise<void>;\n /** Whether the given consistency group has completed its initial sync (synchronous peek at {@link groupReady}). */\n isGroupReady: (groupKey: string) => boolean;\n /** Every consistency-group key this config declares — the domain of {@link groupReady}/{@link isGroupReady}. */\n groupKeys: () => string[];\n}\n\nexport function buildShapeUrl(electricUrl: string, table: string) {\n const url = new URL(electricUrl);\n url.searchParams.set(\"table\", table);\n return url.toString();\n}\n\nexport function buildShapeConfig(input: ShapeSyncSpec) {\n return {\n shape: {\n // The ingress `table` param carries the unique `shapeKey` — the proxy resolves the shape by it and\n // maps it to the physical Electric table on egress (so a read projection and its owner, which share\n // a physical table, stay distinguishable). `table` below is the LOCAL PGlite apply target.\n url: buildShapeUrl(input.electricUrl, input.shapeKey),\n },\n table: input.tableName,\n ...(input.schema !== undefined ? { schema: input.schema } : {}),\n primaryKey: [...input.primaryKey],\n shapeKey: input.shapeKey,\n };\n}\n\nexport function buildConfiguredShapeSpecs(input: SyncConfigInput): ConfiguredShapeSyncSpec[] {\n return Object.entries(input.tables)\n .filter(([, table]) => table.mode !== \"writeonly\")\n .map(([key, table]) => buildConfiguredShapeSpec(input.electricUrl, input.localSchema, key, table));\n}\n\n/**\n * One consistency group's runtime: its specs, the subscription timing its members agree on, and its\n * live stream once started (`null` while a `lazy` group is still held). `startPromise` makes start\n * single-flight so concurrent on-demand triggers share one subscription.\n */\ninterface GroupRuntime {\n groupKey: string;\n specs: ConfiguredShapeSyncSpec[];\n subscription: SubscriptionTiming;\n retention: Retention;\n result: ShapeSyncResult | null;\n startPromise: Promise<void> | null;\n}\n\nexport async function startConfiguredSync(\n pg: SyncEnginePGlite,\n input: StartConfiguredSyncOptions,\n): Promise<StartConfiguredSyncResult> {\n const specs = buildConfiguredShapeSpecs(input.syncConfig);\n\n // Bucket specs into consistency groups (ADR-0009 decision 2). Each group is one MultiShapeStream\n // committed atomically; an ungrouped table is its own singleton group keyed by its shapeKey. A group\n // carries the subscription timing its members agree on (ADR-0021; registry validation guarantees\n // agreement, so the first member's value is the group's): `eager` groups start at boot, `lazy` groups\n // are held until ensureGroupStarted (the on-demand / live-query interception seam).\n const groups = new Map<string, GroupRuntime>();\n const groupKeyByTable = new Map<string, string>();\n for (const spec of specs) {\n const groupKey = groupSubscriptionKey(spec);\n groupKeyByTable.set(spec.key, groupKey);\n const existing = groups.get(groupKey);\n if (existing) {\n existing.specs.push(spec);\n } else {\n groups.set(groupKey, {\n groupKey,\n specs: [spec],\n subscription: spec.subscription ?? \"eager\",\n retention: spec.retention ?? \"persistent\",\n result: null,\n startPromise: null,\n });\n }\n }\n\n // Per-group readiness (ADR-0032 decision 6): one deferred per group, created up front so a caller can\n // await ANY group — eager or still-dormant lazy — before it has started. Resolved once (idempotent) the\n // moment the group reports up-to-date; a never-activated lazy group's promise simply stays pending.\n interface GroupReadyDeferred {\n promise: Promise<void>;\n resolve: () => void;\n ready: boolean;\n }\n const groupReadyState = new Map<string, GroupReadyDeferred>();\n for (const groupKey of groups.keys()) {\n let resolve!: () => void;\n const promise = new Promise<void>((r) => {\n resolve = r;\n });\n groupReadyState.set(groupKey, { promise, resolve, ready: false });\n }\n const markGroupReady = (groupKey: string) => {\n const state = groupReadyState.get(groupKey);\n if (!state || state.ready) return;\n state.ready = true;\n state.resolve();\n input.onGroupReady?.(groupKey);\n };\n\n // A `lazy` group activated on a previous boot (ADR-0021 §2 `lazy + persistent` promotion) is treated\n // as eager this boot: its activation is permanent, so it joins the boot set and resumes like any durable\n // table — no per-session re-evaluation, no half-lazy.\n const promotedGroups = input.promotedGroups ?? new Set<string>();\n const isEagerAtBoot = (group: GroupRuntime) => group.subscription !== \"lazy\" || promotedGroups.has(group.groupKey);\n\n // Boot readiness (`onInitialSync`) waits only for the boot (eager + promoted) groups to catch up; a lazy\n // group started later via ensureGroupStarted signals its members' `onTableInitialSync` but never the gate.\n const eagerGroups = [...groups.values()].filter(isEagerAtBoot);\n let pendingBootGroups = eagerGroups.length;\n let bootSignalled = false;\n const signalBootIfReady = () => {\n if (!bootSignalled && pendingBootGroups <= 0) {\n bootSignalled = true;\n input.onInitialSync?.();\n }\n };\n\n // Start one group's stream, single-flight: a started group resolves immediately; an in-flight start\n // is shared. `countsTowardBoot` is true only for the eager boot starts.\n const startGroup = (group: GroupRuntime, countsTowardBoot: boolean): Promise<void> => {\n if (group.result) {\n return Promise.resolve();\n }\n if (group.startPromise) {\n return group.startPromise;\n }\n // Boot observability (ADR-0034): open an accumulator for a BOOT group only (eager + promoted); an\n // on-demand lazy start (`countsTowardBoot === false`) gets none, so it never enters the report.\n const bootStamp: GroupBootStamp | undefined =\n countsTowardBoot && input.bootCollector\n ? input.bootCollector.beginGroup(group.groupKey, group.specs.length)\n : undefined;\n group.startPromise = startGroupSync(pg, {\n groupKey: group.groupKey,\n specs: group.specs,\n registry: input.registry,\n ...(bootStamp ? { bootStamp } : {}),\n // The prefetch overlap (ADR-0032 S4) applies ONLY to the eager BOOT starts: a fresh store's eager\n // groups are genuinely new, so buffering their catch-up behind the commit gate is safe. An on-demand\n // `lazy` start happens post-boot on an already-provisioned store (which may even be RESUMING persisted\n // subscription state), so it must take the exact sequential path — never the fresh-store overlap.\n ...(countsTowardBoot && input.dbReady ? { dbReady: input.dbReady } : {}),\n ...(input.shapeHeaders ? { headers: input.shapeHeaders } : {}),\n ...(input.onSyncError ? { onSyncError: input.onSyncError } : {}),\n ...(input.onAuthError ? { onAuthError: input.onAuthError } : {}),\n ...(input.onReadStreamError ? { onReadStreamError: input.onReadStreamError } : {}),\n ...(input.onSyncActivity ? { onSyncActivity: input.onSyncActivity } : {}),\n onGroupInitialSync: () => {\n // The group is up-to-date as a unit; signal each member table, mark the group ready (per-group\n // readiness, ADR-0032 decision 6), then (for an eager group only) advance the boot gate once\n // every eager group is caught up.\n for (const spec of group.specs) {\n input.onTableInitialSync?.(spec.key);\n }\n // Boot observability (ADR-0034): stamp readyAtMs and freeze the accumulator at the group's ready edge,\n // so later live traffic never mutates a finalized report.\n bootStamp?.markReady();\n markGroupReady(group.groupKey);\n if (countsTowardBoot) {\n pendingBootGroups -= 1;\n signalBootIfReady();\n }\n },\n }).then((result) => {\n group.result = result;\n // A `persistent` `lazy` group activated on demand (not a boot start) persists its activation, so the\n // next boot promotes it to eager (ADR-0021 §2). `ephemeral` activation is session-scoped — never persisted.\n if (!countsTowardBoot && group.subscription === \"lazy\" && group.retention === \"persistent\") {\n input.onLazyActivated?.(group.groupKey);\n }\n });\n return group.startPromise;\n };\n\n // Each member table exposes a per-table view backed by its group's runtime: up-to-date exactly when\n // the group is (false until a lazy group is started), and unsubscribing it tears down the group.\n const tables: Record<string, ShapeSyncResult> = {};\n for (const [tableKey, groupKey] of groupKeyByTable) {\n const group = groups.get(groupKey)!;\n tables[tableKey] = {\n unsubscribe: () => group.result?.unsubscribe(),\n get isUpToDate() {\n return group.result?.isUpToDate ?? false;\n },\n };\n }\n\n // Start the eager groups at boot; lazy groups wait for ensureGroupStarted. `signalBootIfReady` after\n // the await covers a config with no eager groups (boot is trivially complete).\n await Promise.all(eagerGroups.map((group) => startGroup(group, true)));\n signalBootIfReady();\n\n return {\n unsubscribe: () => {\n // Unsubscribe per group (not per table) so a multi-table group's stream is torn down once.\n for (const group of groups.values()) {\n group.result?.unsubscribe();\n }\n },\n tables,\n ensureGroupStarted: (groupKey) => {\n const group = groups.get(groupKey);\n return group ? startGroup(group, false) : Promise.resolve();\n },\n stopGroup: (groupKey) => {\n const group = groups.get(groupKey);\n if (!group) return;\n // Tear down the live stream and clear the runtime so the group is dormant again: `isTableStarted`\n // reports false and `ensureGroupStarted` re-runs `startGroupSync` (its `group.result`/`startPromise`\n // short-circuits no longer apply) on the next reference.\n group.result?.unsubscribe();\n group.result = null;\n group.startPromise = null;\n // Return the group's readiness to pending: a stopped group is dormant again, so `groupReady` for a\n // later re-activation must re-await its fresh catch-up rather than resolve on the stale deferred.\n if (groupReadyState.get(groupKey)?.ready) {\n let resolve!: () => void;\n const promise = new Promise<void>((r) => {\n resolve = r;\n });\n groupReadyState.set(groupKey, { promise, resolve, ready: false });\n }\n },\n groupKeyForTable: (tableKey) => groupKeyByTable.get(tableKey),\n isTableStarted: (tableKey) => {\n const groupKey = groupKeyByTable.get(tableKey);\n if (groupKey == null) return false;\n return groups.get(groupKey)?.result != null;\n },\n // An unknown group key has nothing to await, so its readiness resolves immediately (never blocks).\n groupReady: (groupKey) => groupReadyState.get(groupKey)?.promise ?? Promise.resolve(),\n isGroupReady: (groupKey) => groupReadyState.get(groupKey)?.ready ?? true,\n groupKeys: () => [...groups.keys()],\n };\n}\n\ninterface StartGroupSyncOptions {\n groupKey: string;\n specs: ConfiguredShapeSyncSpec[];\n registry: SyncTableRegistry;\n headers?: ExternalHeadersRecord;\n /** Fresh-store prefetch overlap gate (ADR-0032 S4) — forwarded to the engine's `syncShapesToTables`. */\n dbReady?: Promise<void>;\n /** Boot observability (ADR-0034): the group's accumulator, stamped by the engine on delivery/apply. */\n bootStamp?: GroupBootStamp;\n onGroupInitialSync?: () => void;\n onSyncError?: (error: Error) => void;\n onAuthError?: () => void;\n onReadStreamError?: (error: Error) => void;\n onSyncActivity?: () => void;\n}\n\n/**\n * Sync one consistency group on a single `MultiShapeStream` (ADR-0009 decision 2). All member\n * shapes share the group's subscription key and commit atomically at a shared LSN frontier; each\n * shape keeps its own apply strategy and column types (resolved per-shape inside the engine).\n */\nexport async function startGroupSync(pg: SyncEnginePGlite, input: StartGroupSyncOptions) {\n const shapeHeaders = input.headers && Object.keys(input.headers).length > 0 ? input.headers : undefined;\n\n // The per-shape onError owns read-path auth recovery (ADR-0013 Phase 2: a 401/403 retries with a\n // fresh token) AND read-stream error surfacing (#4: a non-auth error moves the runtime to\n // `degraded`, retrying transient 5xx/429/network and stopping a structural 4xx).\n const onError = createShapeErrorHandler({\n ...(input.onAuthError ? { onAuthError: input.onAuthError } : {}),\n ...(input.onReadStreamError ? { onReadStreamError: input.onReadStreamError } : {}),\n });\n\n const shapes = Object.fromEntries(\n input.specs.map((spec) => [\n spec.key,\n {\n shape: {\n // Ingress `table` = the unique `shapeKey` (proxy maps it to the physical table on egress).\n url: buildShapeUrl(spec.electricUrl, spec.shapeKey),\n ...(shapeHeaders ? { headers: shapeHeaders } : {}),\n onError,\n },\n // ADR-0029 D1: the registry table key is the engine's sole per-table spec — the local apply\n // target, PKs, strategy, and column types all derive from `(registry, tableKey)`. The\n // `syncConfig` table key IS the registry key, so the spec's `key` is the `tableKey`.\n tableKey: spec.key,\n },\n ]),\n );\n\n return getElectricNamespace(pg).syncShapesToTables({\n key: input.groupKey,\n registry: input.registry,\n shapes,\n ...(input.dbReady ? { dbReady: input.dbReady } : {}),\n ...(input.bootStamp ? { bootStamp: input.bootStamp } : {}),\n ...(input.onGroupInitialSync ? { onInitialSync: input.onGroupInitialSync } : {}),\n ...(input.onSyncError ? { onSyncError: input.onSyncError } : {}),\n ...(input.onSyncActivity ? { onSyncActivity: input.onSyncActivity } : {}),\n });\n}\n\nfunction getElectricNamespace(pg: SyncEnginePGlite) {\n return pg.electric;\n}\n\nfunction buildConfiguredShapeSpec(\n electricUrl: string,\n localSchema: string | undefined,\n key: string,\n table: TableSpecInput,\n): ConfiguredShapeSyncSpec {\n if (table.shape === undefined) {\n throw new Error(`shape is required for synced table ${key}`);\n }\n\n return {\n key,\n electricUrl,\n tableName: table.clientProjection?.syncedTable ?? table.shape.tableName,\n // ADR-0021 §3: an ephemeral table's cluster is `TEMP` (bare names in `pg_temp`), so the row-applier\n // must target the unqualified name (resolved via search_path) — omit the schema for it.\n ...(localSchema && table.retention !== \"ephemeral\" ? { schema: localSchema } : {}),\n shapeKey: table.shape.shapeKey,\n primaryKey: [...(table.clientProjection?.localPrimaryKey?.columns ?? table.primaryKey.columns)],\n electricTable: table.shape.electricTable ?? table.shape.tableName,\n ...(table.consistencyGroup ? { consistencyGroup: table.consistencyGroup } : {}),\n ...(table.subscription ? { subscription: table.subscription } : {}),\n ...(table.retention ? { retention: table.retention } : {}),\n };\n}\n\n/**\n * The subscription key for a spec's consistency group (ADR-0009 decision 2): the explicit\n * `consistencyGroup` when set, else the table's own `shapeKey` (a singleton group). One persisted\n * subscription-state row exists per group key, so subscription reset enumerates these.\n */\nexport function groupSubscriptionKey(spec: Pick<ConfiguredShapeSyncSpec, \"consistencyGroup\" | \"shapeKey\">): string {\n return spec.consistencyGroup ?? spec.shapeKey;\n}\n",
|
|
28
|
-
"// Started life as a copy of @electric-sql/pglite-sync (Apache-2.0, © ElectricSQL — see NOTICE).\n// Fully internalized (ADR-0009); upstream compatibility is an explicit anti-goal (ADR-0028) — evolve freely.\nimport type { EventMessage, MovePattern, Row } from \"@electric-sql/client\";\nimport { isChangeMessage, isControlMessage } from \"@electric-sql/client\";\nimport type { ChangeMessage, ShapeStreamOptions } from \"@electric-sql/client\";\nimport { MultiShapeStream } from \"@electric-sql/experimental\";\nimport type { PGliteInterface } from \"@electric-sql/pglite\";\nimport { sql } from \"drizzle-orm\";\nimport { getTableConfig } from \"drizzle-orm/pg-core\";\n\nimport { type ApplyStrategy, classifyTableApplyStrategy } from \"@pgxsinkit/contracts\";\n\nimport { instrumentShapeFetch, syncDebug } from \"../debug\";\nimport { type ApplyTarget, resolveApplyTarget } from \"../local-tables\";\nimport { computeRetryDelayMs } from \"../mutation\";\nimport {\n applyBulkDeletesToTable,\n applyBulkUpdatesToTable,\n applyInsertsToTable,\n applyMessagesToTableWithCopy,\n applyMessagesToTableWithJson,\n applyUpsertsToTable,\n} from \"./apply\";\nimport { drizzleOverPg } from \"./drizzle-executor\";\nimport {\n NUDGE_HOLD_GRACE_MS,\n NUDGE_MAX_ROUNDS,\n NUDGE_ROUND_GRACE_MS,\n NUDGE_ROUND_WAIT_MS,\n withNudgeBuster,\n} from \"./nudge\";\nimport { foldChangeBatch, ShapeInbox } from \"./shape-inbox\";\nimport {\n deleteSubscriptionState,\n getSubscriptionState,\n migrateSubscriptionMetadataTables,\n type SubscriptionState,\n updateSubscriptionState,\n} from \"./subscription-state\";\nimport {\n addShapeRowTags,\n applyShapeMoveOut,\n applyShapeTagSync,\n assertValidMetadataSchema,\n clearShapeTags,\n DEFAULT_METADATA_SCHEMA,\n shapeTableId,\n} from \"./tags\";\nimport {\n DEFAULT_MAX_COMMIT_RETRIES,\n type ElectricSyncOptions,\n type InitialInsertMethod,\n type InsertChangeMessage,\n type Lsn,\n type SyncShapesToTablesOptions,\n type SyncShapesToTablesResult,\n type SyncShapeToTableOptions,\n type SyncShapeToTableResult,\n} from \"./types\";\n\nexport * from \"./types\";\n\n/**\n * Replication-stream headers Electric attaches to change messages but does not\n * declare on its `Header` type: `lsn` orders changes within the stream and\n * `last` marks the final change of an LSN. Single choke point for these\n * protocol assumptions.\n */\n/**\n * Maps the statically-resolved {@link ApplyStrategy} (ADR-0009 decision 3) onto the engine's\n * initial-backfill apply path. Undefined (no registry-supplied strategy) defaults to `copy`:\n * the COPY TEXT serializer round-trips every built-in type, so it is the safe no-brainer bootstrap.\n */\nfunction applyStrategyToInsertMethod(strategy: ApplyStrategy | undefined): InitialInsertMethod {\n switch (strategy) {\n case \"json\":\n return \"json\";\n case \"insert\":\n return \"insert\";\n default:\n return \"copy\";\n }\n}\n\nfunction readReplicationHeaders(headers: ChangeMessage[\"headers\"]): { lsn: bigint; isLastOfLsn: boolean } {\n const rawLsn: unknown = headers[\"lsn\"];\n\n return {\n lsn: typeof rawLsn === \"string\" ? BigInt(rawLsn) : BigInt(0),\n isLastOfLsn: headers[\"last\"] === true,\n };\n}\n\n/**\n * Electric's tagged-subquery `EventMessage` (ADR-0023) — `headers.event` is `move-out` | `move-in`,\n * carrying `patterns`. It is neither a change nor a control message, so `@electric-sql/client` exposes\n * no guard; we detect it by the `event` header. `MultiShapeStream` adds `.shape` like every message.\n */\ntype ShapeEventMessage = EventMessage & { shape: string };\n\nfunction isEventMessage(message: unknown): message is ShapeEventMessage {\n return (\n typeof message === \"object\" &&\n message !== null &&\n typeof (message as { headers?: { event?: unknown } }).headers?.event === \"string\"\n );\n}\n\n/**\n * Construct the pgxsinkit sync engine over an ALREADY-created PGlite instance (ADR-0032 S1). The engine\n * is a plain module — not a create-time PGlite extension — so it demands only the minimal surface it\n * actually uses: a {@link PGliteInterface} (it runs its metadata DDL + apply commits through `pg.transaction`\n * / `pg.query` / `pg.exec`; it does NOT touch the `live` extension). It returns the `namespace` object (the\n * local-bookkeeping + shape-sync entry points the client attaches as `pg.electric`) plus an explicit\n * `close()` — the teardown the former extension's `close` hook ran when PGlite closed, now invoked\n * explicitly by the owner at the same moment (see `createSyncClient`'s `stop`/`destroy`).\n */\nexport async function createSyncEngine(pg: PGliteInterface, options?: ElectricSyncOptions) {\n const debug = options?.debug ?? false;\n // pgxsinkit-owned metadata namespace (ADR-0009 decision 6): this is our local bookkeeping (the\n // subscription-state table) and the sync-origin GUC (`<schema>.syncing`), not Electric's — so it\n // lives under our own schema, renamed from the upstream `electric` default.\n const metadataSchema = options?.metadataSchema ?? DEFAULT_METADATA_SCHEMA;\n // The schema name reaches raw GUC + DDL identifier positions below (no quoted-identifier form exists\n // there), so validate it at construction rather than trust caller input in those raw spots.\n assertValidMetadataSchema(metadataSchema);\n const streams: Array<{\n stream: MultiShapeStream<Record<string, Row<unknown>>>;\n aborter: AbortController;\n }> = [];\n\n const getShapeOptions = (shapes: SyncShapesToTablesOptions[\"shapes\"], shapeName: string) => {\n const shape = shapes[shapeName];\n if (!shape) {\n throw new Error(`Missing shape options for ${shapeName}`);\n }\n return shape;\n };\n\n const shapePerTableLock = new Map<string, void>();\n\n // Memoize the metadata DDL as a PROMISE, not a boolean: concurrent eager groups (`shape-sync.ts`\n // starts them with `Promise.all`) both call `initMetadataTables`, and a boolean set BEFORE the async\n // migration completed let the second caller return early and query the metadata tables before the DDL\n // had run. Storing the in-flight promise makes every concurrent caller await the same single migration.\n // Cleared on rejection so a transient DDL failure can be retried by a later start rather than caching a\n // rejected promise forever.\n let initMetadataTablesPromise: Promise<void> | undefined;\n const initMetadataTables = (): Promise<void> => {\n if (!initMetadataTablesPromise) {\n initMetadataTablesPromise = migrateSubscriptionMetadataTables({\n pg,\n metadataSchema,\n }).catch((error: unknown) => {\n initMetadataTablesPromise = undefined;\n throw error;\n });\n }\n return initMetadataTablesPromise;\n };\n\n const syncShapesToTables = async ({\n key,\n registry,\n shapes,\n initialInsertMethod,\n onInitialSync,\n onError,\n onSyncError,\n onSyncActivity,\n dbReady,\n bootStamp,\n maxCommitRetries = DEFAULT_MAX_COMMIT_RETRIES,\n commitRetryDelayMs = computeRetryDelayMs,\n }: SyncShapesToTablesOptions): Promise<SyncShapesToTablesResult> => {\n let unsubscribed = false;\n // Fresh-store prefetch overlap (ADR-0032 S4): the caller proved the store fresh and handed a `dbReady`\n // gate, so start the streams and buffer their catch-up into the memory inbox NOW — before the local\n // store's schema/journal/reconcile finish — and defer every DB touch (metadata DDL, the first commit)\n // until the gate lifts. Without it, the exact sequential path: init the metadata tables up front.\n const overlap = dbReady != null;\n if (!overlap) {\n await initMetadataTables();\n }\n\n // Resolve each shape's apply target ONCE at subscribe time (ADR-0029 D1/D2): the real projected\n // synced table, its columns, PKs, and model-derived types — the engine's per-message work is then a\n // pure builder over these resolved objects, never a per-message re-derivation or catalog probe.\n const targets = new Map<string, ApplyTarget>(\n Object.entries(shapes).map(([shapeName, shapeOptions]) => [\n shapeName,\n resolveApplyTarget(registry, shapeOptions.tableKey),\n ]),\n );\n const getTarget = (shapeName: string): ApplyTarget => {\n const target = targets.get(shapeName);\n if (!target) {\n throw new Error(`Missing apply target for ${shapeName}`);\n }\n return target;\n };\n // The synced table's physical identity — the per-table lock key and the tag-store `shape_table` key.\n const tableIdentity = (target: ApplyTarget) => {\n const { name, schema } = getTableConfig(target.table);\n return shapeTableId(schema, name);\n };\n\n Object.entries(shapes)\n .filter(([, shape]) => !shape.onMustRefetch)\n .forEach(([, shape]) => {\n if (shapePerTableLock.has(shape.tableKey)) {\n throw new Error(\"Already syncing shape for table \" + shape.tableKey);\n }\n shapePerTableLock.set(shape.tableKey);\n });\n\n let subState: SubscriptionState | null = null;\n\n // On the overlap path the store is provably fresh (the `freshStore` gate), so it carries no persisted\n // subscription state — AND its metadata tables do not exist yet (their DDL is deferred to the gate).\n // Skip the read entirely: `subState` stays null, so the group is (correctly) a new subscription.\n if (key !== null && !overlap) {\n subState = await getSubscriptionState({\n pg,\n metadataSchema,\n subscriptionKey: key,\n });\n if (debug && subState) {\n console.log(\"resuming from subscription state\", subState);\n }\n }\n\n const isNewSubscription = subState === null;\n\n // Each shape resolves its own apply method (ADR-0009 decisions 2 + 3 / ADR-0029 D1): an explicit\n // per-shape `initialInsertMethod` override wins, else the group-level default, else the registry's\n // build-time classification of the entry. So a consistency group with mixed column profiles applies\n // each table on its correct path.\n const shapeInsertMethod = new Map<string, InitialInsertMethod>(\n Object.entries(shapes).map(([shapeName, shapeOptions]) => {\n // Strategy precedence (ADR-0009 decisions 2+3 / ADR-0029 D1): an explicit per-shape override,\n // then the group-level default, then the registry's build-time classification of the entry.\n const entry = registry[shapeOptions.tableKey]!;\n const method =\n shapeOptions.initialInsertMethod ??\n initialInsertMethod ??\n applyStrategyToInsertMethod(classifyTableApplyStrategy(entry));\n return [shapeName, method];\n }),\n );\n\n // `useInsert` is per-shape, not shared: in a multi-shape group, one shape finishing its bulk\n // backfill must not flip every other shape onto plain `INSERT`. A shape uses its bulk path only\n // on a fresh subscription with a non-`insert` method; a resume starts already in insert mode.\n const useInsert = new Map<string, boolean>(\n Object.keys(shapes).map((shapeName) => [\n shapeName,\n !isNewSubscription || shapeInsertMethod.get(shapeName) === \"insert\",\n ]),\n );\n let onInitialSyncCalled = false;\n\n const maybeSignalInitialSync = () => {\n if (onInitialSync && !onInitialSyncCalled && multiShapeStream.isUpToDate) {\n onInitialSync();\n onInitialSyncCalled = true;\n }\n };\n\n // The Shape inbox (ADR-0014 / ISS-06): the pure, in-memory buffer + complete-LSN frontier for\n // this group's shapes. The engine keeps the commit queue, the apply, and the truncate set.\n const inbox = new ShapeInbox(Object.keys(shapes));\n\n // Live-tail sibling nudge (ADR-0031): a per-shape one-shot cache-buster token. The watchdog (below)\n // sets a token just before nudging a lagging sibling; `withNudgeBuster` (wrapping each shape's\n // fetchClient) consumes it on the sibling's next non-live catch-up so a CDN HIT cannot return the same\n // stale watermark and defeat the nudge. Empty on the steady path → the wrapper is a straight passthrough.\n const nudgeBusters = new Map<string, string>();\n\n const truncateNeeded = new Set<string>();\n // The committed frontier is a *running* variable, advanced after each successful commit — not\n // the boot-time `const` the upstream engine never advanced (which forced redundant empty\n // re-commits). `degraded` latches once commits exhaust their retries (ADR-0009 decision 5).\n let committedLsn: Lsn = subState?.last_lsn ?? BigInt(-1);\n let degraded = false;\n // Single-flight commit queue: at most one commit runs at a time; messages buffered while one\n // is in flight coalesce into the next run (re-armed via `commitRerun`).\n let commitInFlight: Promise<void> | null = null;\n let commitRerun = false;\n\n const aborter = new AbortController();\n Object.values(shapes)\n .filter((shapeOptions) => !!shapeOptions.shape.signal)\n .forEach((shapeOptions) => {\n shapeOptions.shape.signal!.addEventListener(\"abort\", () => aborter.abort(), {\n once: true,\n });\n });\n\n const multiShapeOptions: Record<string, ShapeStreamOptions<Row<unknown>>> = {};\n for (const [shapeName, shapeOptions] of Object.entries(shapes)) {\n const shapeMetadata = subState?.shape_metadata[shapeName];\n const streamOptions: ShapeStreamOptions<Row<unknown>> = {\n ...shapeOptions.shape,\n signal: aborter.signal,\n // Instrument every ShapeStream HTTP request (the read-path long-poll/catch-up) when debug is on;\n // a passthrough otherwise (see instrumentShapeFetch). Wraps any existing fetchClient rather than\n // replacing it, so auth/header injection on the shape's own fetchClient still runs. `withNudgeBuster`\n // is the OUTER wrapper (ADR-0031 live-tail nudge): it stamps the cache-buster onto the URL BEFORE\n // instrumentation runs, so the debug rail logs the busted URL (`BUSTED`) that actually hits the wire.\n fetchClient: withNudgeBuster(instrumentShapeFetch(shapeOptions.shape.fetchClient), nudgeBusters, shapeName),\n };\n\n if (shapeMetadata) {\n streamOptions.offset = shapeMetadata.offset;\n streamOptions.handle = shapeMetadata.handle;\n }\n\n multiShapeOptions[shapeName] = streamOptions;\n }\n\n const multiShapeStream = new MultiShapeStream<Record<string, Row<unknown>>>({\n shapes: multiShapeOptions,\n });\n\n // The commit gate (ADR-0032 S4). Open immediately on the sequential path; held closed on the overlap\n // path until `dbReady` resolves, so NOTHING writes to PGlite before the local schema exists. The inbox\n // is pure memory, so buffering catch-up behind this closed gate is safe — the only DB-bound work\n // (metadata DDL, then commits) waits for the gate.\n let dbGateOpen = !overlap;\n if (overlap) {\n // The streams' network side is starting now (subscribe below triggers the first fetch), overlapping\n // the caller's local boot phases. Name the shapes so the overlap is measurable on the boot rail.\n syncDebug(\"boot shape prefetch start\", { shapes: Object.keys(shapes) });\n }\n\n const getShapeStream = (shapeName: string) => {\n const stream = multiShapeStream.shapes[shapeName];\n if (!stream) {\n throw new Error(`Missing stream for ${shapeName}`);\n }\n return stream;\n };\n\n const insertMethods = {\n json: applyMessagesToTableWithJson,\n copy: applyMessagesToTableWithCopy,\n insert: applyInsertsToTable,\n } as const;\n\n // Apply everything buffered up to `targetLsn` in a single transaction, retrying with jittered\n // backoff on failure. Returns `true` once applied (and advances the running committed frontier);\n // returns `false` without advancing if the engine unsubscribed mid-flight or the commit\n // exhausted its retries (→ `degraded` + `onSyncError`, ADR-0009 decision 5). The drained\n // messages and the truncate snapshot are held across retries so a transient failure loses\n // nothing; the read cache never advances past an unapplied commit.\n const commitUpToLsn = async (targetLsn: Lsn): Promise<boolean> => {\n // PEEK (not drain) the buffered batch: it stays in the inbox until the transaction below actually\n // succeeds, and is only then ACKed (removed). A commit that exhausts its retries (→ `degraded`)\n // therefore HOLDS the drained batch in the buffer instead of losing it (ADR-0009 decision 5) — and\n // `enqueueCommit` refuses to run any newer commit while degraded, so a later LSN can never apply\n // over this held, unapplied batch. Recovery is a restart/refetch: the persisted offset was not\n // advanced, so the held batch re-streams from the same frontier.\n const messagesToCommit = inbox.peekUpTo(targetLsn);\n\n // Record every shape's reset epoch AT PEEK TIME (synchronously with the peeks, before the async\n // transaction). If a must-refetch + re-snapshot bumps a shape's epoch mid-commit, the acks below\n // skip that shape so its post-reset rebuild survives rather than being deleted/spliced away — see\n // ShapeInbox.ackUpTo / ackMoveOuts / ackMoveIns.\n const epochsAtPeek = inbox.snapshotEpochs();\n\n // Capture, per shape, whether it is still accepting snapshot (LSN-0) rows AT PEEK TIME. A shape in\n // snapshot acceptance (post-reset re-snapshot, or a brand-new shape before its first real lsn) can\n // have the SAME snapshot rows double-delivered by the racing recovery fetch loops — possibly across\n // separate commits — so its inserts are applied idempotently (upsert) rather than as plain\n // collision-surfacing inserts. Once a real lsn re-arms the dedup, this is false and the live-tail\n // plain-INSERT invariant (a genuine PK collision must surface, ADR-0014) is back in force.\n const snapshotModeAtPeek = new Map<string, boolean>(\n Object.keys(shapes).map((shapeName) => [shapeName, inbox.acceptsSnapshotRowsFor(shapeName)]),\n );\n\n // Snapshot the truncate set so a retried transaction still truncates; the per-shape flag is\n // cleared only once the commit has succeeded.\n const shapesToTruncate = new Set(truncateNeeded);\n\n // Peek the buffered tagged-subquery move-outs (ADR-0023) the same way: held in the buffer so a\n // retried/degraded commit still has them, ACKed only on success (by the exact peeked count, so a\n // move-out that arrived during a coalescing commit is not dropped).\n const moveOutsToCommit = new Map<string, MovePattern[][]>();\n // Peek the buffered tagged-subquery move-ins (ADR-0024) identically: a move-in snapshot row carries\n // no LSN; it is applied idempotently in the commit transaction and ACKed only on success.\n const moveInsToCommit = new Map<string, ChangeMessage<Row<unknown>>[]>();\n for (const shapeName of Object.keys(shapes)) {\n const pendingOut = inbox.peekMoveOuts(shapeName);\n if (pendingOut.length > 0) {\n moveOutsToCommit.set(shapeName, pendingOut);\n }\n const pendingIn = inbox.peekMoveIns(shapeName);\n if (pendingIn.length > 0) {\n moveInsToCommit.set(shapeName, pendingIn);\n }\n }\n\n const runCommit = () =>\n pg.transaction(async (tx) => {\n if (debug) {\n console.time(\"commit\");\n }\n\n // Tier ③ (ADR-0028 allow-list): a `SET LOCAL` GUC — the sync-origin `<schema>.syncing` flag\n // the apply trigger reads to distinguish streamed server truth from local writes. GUCs have\n // no tier-①/② builder form; the schema identifier is fixed at engine construction.\n await tx.exec(`SET LOCAL ${metadataSchema}.syncing = true;`);\n\n for (const [shapeName, initialMessages] of messagesToCommit.entries()) {\n const shape = getShapeOptions(shapes, shapeName);\n const target = getTarget(shapeName);\n const shapeMethod = shapeInsertMethod.get(shapeName)!;\n let messages = initialMessages;\n\n // ADR-0023: the shape's tag store key (synced table, schema-qualified).\n const shapeTable = tableIdentity(target);\n\n if (shapesToTruncate.has(shapeName)) {\n if (debug) {\n console.log(\"truncating table\", shapeTable);\n }\n if (shape.onMustRefetch) {\n await shape.onMustRefetch(drizzleOverPg(tx));\n } else {\n // ADR-0029 D4: a must-refetch wipe is engine cache maintenance, not server truth — so it\n // TRUNCATEs (tier ②; `TRUNCATE` has no Drizzle builder, the table object is interpolated)\n // rather than reacting via the per-row reconcile trigger. Correctness rides the reconcile\n // loop; TRUNCATE is O(1) and the re-snapshot inserts still fire the trigger.\n await drizzleOverPg(tx).execute(sql`TRUNCATE ${target.table}`);\n }\n // The re-snapshot rebuilds tags from scratch, so drop this shape's stale tag-set too\n // (ADR-0023 Slice 2: a must-refetch/rebuild must not leave orphan tags).\n await clearShapeTags({ pg: tx, metadataSchema, shapeTable });\n }\n\n // ADR-0024: this shape's buffered move-in snapshot rows (a row ENTERING the shape). Their\n // tags are UNIONED first (a move-in adds a reason, it must not clear an independent grant's\n // tag) — and a regular change for the same row in this batch then authoritatively replaces\n // below, so union-then-replace converges either way.\n const moveInMessages = moveInsToCommit.get(shapeName) ?? [];\n if (moveInMessages.length > 0) {\n await addShapeRowTags({\n pg: tx,\n metadataSchema,\n shapeTable,\n messages: moveInMessages,\n primaryKey: target.primaryKey,\n });\n }\n\n // Maintain the tag-set from the RAW drained batch (ADR-0023) — before the data apply and\n // the move-out eviction, so an add-then-remove within one commit resolves correctly. Uses\n // `initialMessages` (the full batch) since the insert/fold split below reduces `messages`.\n await applyShapeTagSync({\n pg: tx,\n metadataSchema,\n shapeTable,\n messages: initialMessages,\n primaryKey: target.primaryKey,\n });\n\n // ADR-0024: apply the move-in rows idempotently BEFORE the change fold, so a same-commit\n // update to a just-moved-in row lands on a present row. Upsert (not plain INSERT) because the\n // row may already be present via another grant or be re-delivered on a resume.\n if (moveInMessages.length > 0) {\n await applyUpsertsToTable({\n pg: tx,\n target,\n messages: moveInMessages,\n debug,\n });\n }\n\n if (!useInsert.get(shapeName)) {\n const initialInserts: InsertChangeMessage[] = [];\n const remainingMessages: ChangeMessage<Row<unknown>>[] = [];\n let foundNonInsert = false;\n for (const message of messages) {\n if (!foundNonInsert && message.headers.operation === \"insert\") {\n initialInserts.push(message as InsertChangeMessage);\n } else {\n foundNonInsert = true;\n remainingMessages.push(message);\n }\n }\n if (initialInserts.length > 0 && shapeMethod === \"copy\") {\n remainingMessages.unshift(initialInserts.pop()!);\n }\n messages = remainingMessages;\n\n if (initialInserts.length > 0) {\n await insertMethods[shapeMethod]({\n pg: tx,\n target,\n messages: initialInserts,\n debug,\n });\n\n useInsert.set(shapeName, true);\n }\n }\n\n // ADR-0014 Phase 3: fold this shape's drained batch to one net op per PK, then apply\n // three bulk statements in the order DELETE → INSERT → UPDATE. A re-created PK's delete\n // must precede its insert; every other PK lands in exactly one statement, so the rest of\n // the order is irrelevant within the (atomic) commit. The fold collapses same-PK runs, so\n // no bulk statement ever holds two rows for one PK — closing the `UPDATE … FROM` /\n // `json_to_recordset` join hazard (which would use one arbitrary matching row) by\n // construction. This replaces the previous one-SQL-statement-per-row steady-state loop.\n if (messages.length > 0) {\n const folded = foldChangeBatch(messages);\n\n if (folded.deletes.length > 0) {\n await applyBulkDeletesToTable({\n pg: tx,\n target,\n messages: folded.deletes,\n debug,\n });\n }\n if (folded.inserts.length > 0) {\n if (snapshotModeAtPeek.get(shapeName)) {\n // Snapshot-acceptance mode (post-reset re-snapshot / pre-first-lsn): the racing recovery\n // loops can re-deliver these exact snapshot rows, possibly in a later commit after this\n // shape's TRUNCATE flag has been consumed — so apply them idempotently (upsert), the same\n // posture as a move-in, rather than failing the commit on a PK collision.\n await applyUpsertsToTable({\n pg: tx,\n target,\n messages: folded.inserts,\n debug,\n });\n } else {\n await applyInsertsToTable({\n pg: tx,\n target,\n messages: folded.inserts,\n debug,\n });\n }\n }\n if (folded.updates.length > 0) {\n await applyBulkUpdatesToTable({\n pg: tx,\n target,\n messages: folded.updates,\n debug,\n });\n }\n }\n\n // ADR-0023: after the data + tag state is current, apply this shape's buffered move-outs —\n // withdraw the revoked tag and evict any row left with no tag (via the bulk-delete path, so\n // the reconcile trigger fires and the read model converges).\n const patternSets = moveOutsToCommit.get(shapeName);\n if (patternSets) {\n await applyShapeMoveOut({\n pg: tx,\n metadataSchema,\n shapeTable,\n target,\n patternSets,\n debug,\n });\n }\n }\n\n if (key) {\n await updateSubscriptionState({\n pg: tx,\n metadataSchema,\n subscriptionKey: key,\n shapeMetadata: Object.fromEntries(\n Object.keys(shapes).map((shapeName) => {\n const stream = getShapeStream(shapeName);\n return [\n shapeName,\n {\n handle: stream.shapeHandle!,\n offset: stream.lastOffset,\n },\n ];\n }),\n ),\n lastLsn: targetLsn,\n debug,\n });\n }\n\n // If we unsubscribed while this commit was in flight, discard it rather than persist\n // work during teardown. PGlite's `transaction()` skips its COMMIT once `tx.rollback()`\n // has closed the tx, so this rolls back both the applied rows and the subscription-state\n // advance; the (un-advanced) persisted offset means a later resume re-streams this batch.\n if (unsubscribed) {\n await tx.rollback();\n }\n });\n\n for (let attempt = 1; ; attempt++) {\n if (unsubscribed) {\n return false;\n }\n try {\n await runCommit();\n if (unsubscribed) {\n // The commit rolled itself back on unsubscribe (see runCommit); do not advance the\n // committed frontier, ACK the peeked buffer, or clear truncate flags for discarded work.\n return false;\n }\n committedLsn = targetLsn;\n // The transaction committed — now (and only now) remove the peeked batch from the inbox, passing\n // the peek-time epochs so a shape reset mid-commit is skipped (its rebuild survives). Move-outs/\n // move-ins are ACKed by the exact peeked count so anything that arrived during a coalescing\n // commit survives for the next run.\n inbox.ackUpTo(targetLsn, epochsAtPeek);\n for (const [shapeName, patternSets] of moveOutsToCommit) {\n inbox.ackMoveOuts(shapeName, patternSets.length, epochsAtPeek.get(shapeName) ?? inbox.epochFor(shapeName));\n }\n for (const [shapeName, moveInMessages] of moveInsToCommit) {\n inbox.ackMoveIns(\n shapeName,\n moveInMessages.length,\n epochsAtPeek.get(shapeName) ?? inbox.epochFor(shapeName),\n );\n }\n for (const shapeName of shapesToTruncate) {\n truncateNeeded.delete(shapeName);\n }\n if (debug) console.timeEnd(\"commit\");\n maybeSignalInitialSync();\n return true;\n } catch (error) {\n if (unsubscribed) {\n return false;\n }\n if (attempt >= maxCommitRetries) {\n degraded = true;\n onSyncError?.(error instanceof Error ? error : new Error(String(error)));\n return false;\n }\n await new Promise((resolve) => setTimeout(resolve, commitRetryDelayMs(attempt)));\n }\n }\n };\n\n const lowestCompleteLsn = (): Lsn => inbox.lowestCompleteLsn();\n\n // ─── Live-tail sibling nudge (ADR-0031 live-tail completion) ──────────────────────────────────────\n // The catch-up alignment (ADR-0031 in shape-inbox.ts) fixed this class of stall at BOOT: quiet shapes'\n // stale cached watermarks no longer hold a busy shape's backfill. On the LIVE tail the same shape holds\n // recur — a change batch lands on a busy shape at LSN L, but the group commits only at the min effective\n // frontier, so the batch stays buffered until every quiet sibling's PARKED long-poll returns a fresh\n // `global_last_seen_lsn` (~41s on Electric Cloud). This watchdog closes that live-tail gap: when a batch\n // is gated (its `batchMaxLsn > committedLsn`), it nudges each lagging sibling — aborting its parked poll\n // and forcing an immediate NON-live catch-up (`forceDisconnectAndRefresh`), which returns a fresh\n // watermark in ~sub-second. The group frontier then reaches L and the normal commit path (driven by the\n // up-to-date arrivals, NOT by this watchdog) fires. Atomicity is untouched: commits still happen only at\n // the group min frontier. The one-shot cache-buster (`nudgeBusters` + `withNudgeBuster`) defends each\n // nudged catch-up against a CDN HIT that would echo the stale watermark. Bounded to NUDGE_MAX_ROUNDS so a\n // genuinely-dead or still-legitimately-polling sibling degrades to the old wait-out-the-poll behavior\n // rather than a refresh storm.\n const nudgeInFlight = new Map<string, Promise<void>>();\n let nudgeTargetLsn: Lsn = BigInt(-1);\n let nudgeWatchdogRunning = false;\n\n // Void-called from the subscribe callback (never awaited — it must not backpressure the stream). Raises\n // the shared target and, if not already running, runs bounded rounds until the frontier reaches it, the\n // group tears down / degrades / re-closes its gate, or the rounds exhaust. Single-flight: a concurrent\n // gated batch just raises `nudgeTargetLsn` and returns. Wrapped so it can never throw unhandled.\n const runNudgeWatchdog = async (targetLsn: Lsn): Promise<void> => {\n if (targetLsn > nudgeTargetLsn) {\n nudgeTargetLsn = targetLsn;\n }\n if (nudgeWatchdogRunning) {\n return;\n }\n nudgeWatchdogRunning = true;\n try {\n // Pre-alignment (boot catch-up, before ADR-0031 lays the commit floors) the nudge is pure noise:\n // the alignment itself will commit the gated backfill the moment every shape reports, and firing\n // busted catch-ups mid-boot only contends with the boot requests. The floors survive later resets,\n // so this gate closes exactly once — the live tail is always past it.\n if (inbox.alignedFloor() < BigInt(0)) {\n return;\n }\n // Resolved / torn-down / gated-shut → nothing to nudge; the up-to-date arrival itself runs the\n // commit, so the watchdog never commits.\n const resolvedOrStopped = (): boolean =>\n unsubscribed || degraded || !dbGateOpen || lowestCompleteLsn() >= nudgeTargetLsn;\n\n // Hold-persistence grace: a cross-shape transaction's sibling halves arrive milliseconds apart,\n // so EVERY grouped commit passes through a transient held instant — nudging on it would abort\n // the sibling poll that is about to deliver the other half (the sync-e2e regression). Only a\n // hold that survives this grace is a real quiet-sibling park worth nudging.\n for (let waited = 0; waited < NUDGE_HOLD_GRACE_MS; waited += NUDGE_ROUND_GRACE_MS) {\n await new Promise((resolve) => setTimeout(resolve, NUDGE_ROUND_GRACE_MS));\n if (resolvedOrStopped()) {\n return;\n }\n }\n\n for (let round = 1; round <= NUDGE_MAX_ROUNDS; round++) {\n if (resolvedOrStopped()) {\n return;\n }\n for (const shapeName of Object.keys(shapes)) {\n // A shape still catching up advances on its own — only nudge one already in its live tail.\n if (!inbox.hasReportedUpToDate(shapeName)) continue;\n if (inbox.effectiveLsnFor(shapeName) >= nudgeTargetLsn) continue;\n if (nudgeInFlight.has(shapeName)) continue;\n // `forceDisconnectAndRefresh` is declared on the real ShapeStream, but a mocked/typed surface may\n // omit it — reach it structurally and skip (with a rail line) when absent.\n const stream = getShapeStream(shapeName) as { forceDisconnectAndRefresh?: () => Promise<void> };\n if (typeof stream.forceDisconnectAndRefresh !== \"function\") {\n syncDebug(\"live-tail sibling nudge unavailable\", { shape: shapeName });\n continue;\n }\n // Arm the one-shot cache-buster BEFORE the refresh so the forced catch-up carries it.\n nudgeBusters.set(shapeName, crypto.randomUUID());\n syncDebug(\"live-tail sibling nudge\", { shape: shapeName, target: String(nudgeTargetLsn), round });\n const refresh = stream\n .forceDisconnectAndRefresh()\n .catch((err: unknown) =>\n syncDebug(\"live-tail sibling nudge failed\", { shape: shapeName, error: String(err) }),\n )\n .finally(() => {\n nudgeInFlight.delete(shapeName);\n });\n nudgeInFlight.set(shapeName, refresh);\n }\n // Nothing to nudge and nothing in flight → exit QUIETLY (no exhaustion line). This is the routine\n // pre-alignment case: a gated batch during catch-up has siblings that have not yet reported\n // up-to-date, and those advance on their own — spinning the remaining rounds would only delay-loop\n // and print a misleading \"exhausted\" line on every boot rail. The \"held by group frontier\" line\n // already told the story.\n if (nudgeInFlight.size === 0) {\n return;\n }\n // Wait for this round's forced catch-ups to actually land and advance the frontier. The refresh\n // promises settle before the refreshed response does (measured), so awaiting them alone would\n // re-nudge into still-in-flight requests — poll the frontier instead, bounded per round, and\n // break out the moment the target is reached.\n await Promise.all([...nudgeInFlight.values()]);\n for (let waited = 0; waited < NUDGE_ROUND_WAIT_MS; waited += NUDGE_ROUND_GRACE_MS) {\n await new Promise((resolve) => setTimeout(resolve, NUDGE_ROUND_GRACE_MS));\n if (resolvedOrStopped()) {\n return;\n }\n }\n }\n // Rounds exhausted and the frontier is still short: a sibling is dead or genuinely mid-poll. Degrade\n // to the old behavior (wait out its live long-poll) rather than nudge forever.\n syncDebug(\"live-tail nudge exhausted; waiting on sibling live polls\", {\n target: String(nudgeTargetLsn),\n frontier: String(lowestCompleteLsn()),\n });\n } catch (err) {\n syncDebug(\"live-tail nudge watchdog error\", { error: String(err) });\n } finally {\n nudgeWatchdogRunning = false;\n }\n };\n\n // Drain buffered changes up to the current complete frontier, one commit at a time, looping\n // while fresh messages keep arriving (so commits coalesce). Returns early on `degraded` — a held\n // commit is not retried here; recovery is a later message/refetch or a restart.\n const runCommitLoop = async (): Promise<void> => {\n do {\n commitRerun = false;\n const target = lowestCompleteLsn();\n const isCommitNeeded = target > committedLsn;\n const isMustRefetchAndCatchingUp = target >= committedLsn && truncateNeeded.size > 0;\n // A buffered move-out (ADR-0023) or move-in (ADR-0024) must be committed even if no change\n // advanced the frontier — the revocation/grant has to land. Their `up-to-date` normally advances\n // `target`, but don't rely on that (move/event messages carry no LSN).\n const hasPendingMoves = target >= committedLsn && (inbox.hasPendingMoveOuts() || inbox.hasPendingMoveIns());\n // ADR-0031: a LATE-arriving change at or below an already-committed target must still commit. The\n // aligned commit floor lets `ingestChange` accept a change below the floor (its dedup frontier is\n // the raw `completeLsns`, unmoved by the floor), so such a change can land AFTER the group frontier\n // has already reached — or passed — its LSN, where no frontier advance would trigger a commit for\n // it. Committing at `target === committedLsn` is safe: it mirrors the moves path, which already\n // calls `commitUpToLsn(target)` with no frontier advance. (At `target > committedLsn` this overlaps\n // `isCommitNeeded` — harmless; the expression stays simple.)\n const hasLateArrivals = target >= committedLsn && inbox.hasBufferedChangesAtOrBelow(target);\n if (isCommitNeeded || isMustRefetchAndCatchingUp || hasPendingMoves || hasLateArrivals) {\n const applied = await commitUpToLsn(target);\n if (!applied) {\n return;\n }\n } else {\n maybeSignalInitialSync();\n }\n } while (commitRerun);\n };\n\n // Single-flight: at most one commit loop runs. A message arriving while one is running buffers\n // synchronously (above) and re-arms the loop via `commitRerun`; `commitInFlight` is cleared\n // inside the same async body — before its promise resolves — so an enqueue can never observe a\n // stale in-flight handle and resolve without committing its messages.\n const enqueueCommit = (): Promise<void> => {\n // ADR-0009 decision 5: once a commit exhausts its retries the engine latches `degraded` and\n // REFUSES to run any further commit. `commitUpToLsn` peeks (never drains) the buffer, so the\n // unapplied batch is still held; refusing later commits guarantees a newer LSN can never apply\n // over that held batch (the divergence the destructive drain allowed). The buffer keeps\n // accumulating incoming messages harmlessly; recovery is a restart/refetch, which re-streams the\n // held frontier because the persisted offset was never advanced. Note the commit-await backpressure\n // is intentionally absent while degraded — the inbox grows at the stream's rate until recovery,\n // which is the accepted cost of ADR-0009's documented \"hold the buffer\" posture.\n if (degraded) {\n return commitInFlight ?? Promise.resolve();\n }\n if (commitInFlight) {\n commitRerun = true;\n return commitInFlight;\n }\n commitInFlight = (async () => {\n try {\n await runCommitLoop();\n } finally {\n commitInFlight = null;\n }\n })();\n return commitInFlight;\n };\n\n multiShapeStream.subscribe(async (messages) => {\n if (unsubscribed) {\n return;\n }\n // A delivered batch means a fetch just succeeded — the read path is alive (ADR-0013 Phase 3),\n // so the runtime can clear an auth-needed status once a fresh token starts working again.\n onSyncActivity?.();\n if (debug) {\n console.log(\"received messages\", messages.length);\n }\n // Receive-path latency probe: a batch carrying real change rows is the moment Electric delivered\n // a write to this subscriber (the writer's own echo, or another browser's edit fanning in). The\n // gap from here to the commit finishing is the local apply cost.\n const changeCount = messages.reduce((n, message) => (isChangeMessage(message) ? n + 1 : n), 0);\n if (changeCount > 0) {\n syncDebug(\"sync received change batch from Electric\", { changes: changeCount });\n }\n // Boot observability (ADR-0034): one delivery = one shape-stream response. Records the fetch (network)\n // gap since the last settle plus this batch's request + change-row counts. No-op post-ready (frozen).\n bootStamp?.onBatchDelivered(changeCount);\n const commitStartedAt = typeof performance !== \"undefined\" ? performance.now() : Date.now();\n\n // The max LSN over the change rows this batch COMPLETED (routed to `ingestChange` with `isLastOfLsn`;\n // move-in rows carry no lsn and are excluded). It is what the batch needs the group frontier to reach\n // to actually commit — the truth test for the \"applied\" vs \"held\" rail line below. -1 if none.\n let batchMaxLsn: Lsn = BigInt(-1);\n\n messages.forEach((message) => {\n if (isChangeMessage(message)) {\n // A tagged-subquery MOVE-IN row (ADR-0024): an existing row ENTERING the shape because a grant\n // was added. Electric delivers it as a snapshot insert flagged `is_move_in` with NO `lsn`/`last`\n // (it is not a replication-stream change), so the `ingestChange` dedup — which floors a missing\n // lsn to 0 — would treat it as already-seen and drop it once the frontier passed 0. Route it to\n // its own buffer, applied idempotently at the next commit (the trailing `up-to-date`).\n if (message.headers[\"is_move_in\"] === true) {\n inbox.ingestMoveIn(message.shape, message);\n } else {\n const { lsn, isLastOfLsn } = readReplicationHeaders(message.headers);\n inbox.ingestChange(message.shape, message, lsn, isLastOfLsn);\n if (isLastOfLsn && lsn > batchMaxLsn) {\n batchMaxLsn = lsn;\n }\n }\n } else if (isControlMessage(message)) {\n switch (message.headers.control) {\n case \"up-to-date\": {\n if (debug) {\n console.log(\"received up-to-date\", message);\n }\n if (typeof message.headers.global_last_seen_lsn !== \"string\") {\n throw new Error(\"global_last_seen_lsn is not a string\");\n }\n // ADR-0031: `ingestUpToDate` returns true ONLY on the transition where this control message\n // completed the group (every shape has now reported up-to-date) and the inbox aligned the\n // commit floors. Surface that single moment on the debug rail so a \"stale board at load that\n // rearranges itself\" symptom is diagnosable — the floor it aligned to is the group head.\n if (inbox.ingestUpToDate(message.shape, BigInt(message.headers.global_last_seen_lsn))) {\n syncDebug(\"catch-up watermark aligned\", { floor: String(inbox.alignedFloor()) });\n }\n break;\n }\n case \"must-refetch\": {\n if (debug) {\n console.log(\"received must-refetch\", message);\n }\n // Surface the expired-handle / rewind event on the syncDebug rail too (the legacy `debug`\n // option only console.logs it): must-refetch is the trigger for the truncate + re-snapshot\n // recovery, so it must be visible when diagnosing a convergence loss in a live app.\n syncDebug(\"must-refetch received\", { shape: message.shape });\n inbox.resetShape(message.shape);\n truncateNeeded.add(message.shape);\n break;\n }\n }\n } else if (isEventMessage(message)) {\n // ADR-0023: a tagged-subquery move-out — a grant was revoked, so the rows it kept in the shape\n // must be evicted. Buffer the patterns; the eviction runs in the next commit (decision 3).\n // `MultiShapeStream`'s callback type does not declare `EventMessage` (the prior guards narrow\n // `message` to `never` here), so reach the runtime-present event through an explicit cast.\n const eventMessage = message as unknown as ShapeEventMessage;\n if (eventMessage.headers.event === \"move-out\") {\n if (debug) {\n console.log(\"received move-out\", eventMessage);\n }\n inbox.ingestMoveOut(eventMessage.shape, eventMessage.headers.patterns);\n }\n // A `move-in` EventMessage (ADR-0024) needs no action here: its newly-matched rows arrive in the\n // same batch as snapshot inserts flagged `is_move_in`, which the change branch routes to the\n // move-in buffer. The event's `patterns` are redundant with those inserts' `tags`.\n }\n });\n\n // Buffering above is synchronous. On the overlap path, while the commit gate is still closed the\n // batch stays in the memory inbox (its LSN frontier + catch-up watermarks still advance from the\n // ingest above) and the callback returns WITHOUT awaiting a commit — so the stream keeps fetching\n // catch-up and does not stall behind the local boot phases. Once the gate lifts, the deferred commit\n // train (below) drains everything buffered. On the sequential path the gate is already open, so this\n // is the unchanged path: enqueue the single-flight commit and await it (the natural backpressure that\n // bounds the buffer — replacing the old fire-and-forget commit + `setTimeout(0)` race).\n if (dbGateOpen) {\n const applyStartedAt = typeof performance !== \"undefined\" ? performance.now() : Date.now();\n await enqueueCommit();\n // Boot observability (ADR-0034): the apply (commit-into-PGlite) wall for this delivery.\n bootStamp?.onApply((typeof performance !== \"undefined\" ? performance.now() : Date.now()) - applyStartedAt);\n if (changeCount > 0) {\n // Truthful rail (ADR-0031): the \"applied\" line only fires when this batch's completed changes\n // actually landed (its `batchMaxLsn` is at or below the advanced `committedLsn`). Otherwise the\n // group frontier had not reached them — the batch is BUFFERED behind a quiet sibling's watermark —\n // so say so, and kick the live-tail sibling nudge to shorten that hold (void: never backpressure\n // the stream).\n if (batchMaxLsn <= committedLsn) {\n const elapsed = (typeof performance !== \"undefined\" ? performance.now() : Date.now()) - commitStartedAt;\n syncDebug(\"sync applied change batch to local store\", { changes: changeCount, ms: Math.round(elapsed) });\n } else {\n syncDebug(\"sync change batch held by group frontier\", {\n changes: changeCount,\n heldLsn: String(batchMaxLsn),\n frontier: String(lowestCompleteLsn()),\n });\n void runNudgeWatchdog(batchMaxLsn);\n }\n }\n }\n }, onError);\n\n // Fresh-store prefetch overlap (ADR-0032 S4): the moment the caller signals the local store is ready\n // (schema exec + journal recovery + store-version reconcile done), run the deferred metadata DDL, open\n // the commit gate, and drain everything the streams buffered during the window in one commit train. The\n // ADR-0031 catch-up watermarks were aligned by the ingests above as the up-to-dates arrived, so this\n // drain commits to the aligned floor and `onInitialSync` fires exactly as on the sequential path.\n if (overlap) {\n void dbReady!.then(async () => {\n if (unsubscribed) {\n return;\n }\n // The metadata tables' DDL was deferred past the gate (the store had no schema when the streams\n // started); create them now, before the first commit needs the subscription-state table.\n await initMetadataTables();\n dbGateOpen = true;\n syncDebug(\"boot commits opened\");\n // Boot observability (ADR-0034): on the overlap path the buffered catch-up drains here (not in a\n // subscribe callback), so stamp the drain's apply wall into the group's accumulator.\n const drainStartedAt = typeof performance !== \"undefined\" ? performance.now() : Date.now();\n await enqueueCommit();\n bootStamp?.onApply((typeof performance !== \"undefined\" ? performance.now() : Date.now()) - drainStartedAt);\n });\n }\n\n streams.push({\n stream: multiShapeStream,\n aborter,\n });\n\n const unsubscribe = () => {\n if (debug) {\n console.log(\"unsubscribing\");\n }\n unsubscribed = true;\n multiShapeStream.unsubscribeAll();\n aborter.abort();\n for (const shape of Object.values(shapes)) {\n shapePerTableLock.delete(shape.tableKey);\n }\n };\n\n return {\n unsubscribe,\n get isUpToDate() {\n // Never report up-to-date while a commit is pending or after going degraded (ADR-0009\n // decision 5): the read cache must not claim to match the server on an unapplied commit. Nor while\n // the overlap commit gate is still closed (ADR-0032 S4): the stream may already be `isUpToDate` on\n // the network side while its catch-up is still buffered, unapplied, in the memory inbox.\n return dbGateOpen && !degraded && commitInFlight === null && multiShapeStream.isUpToDate;\n },\n streams: Object.fromEntries(\n Object.keys(shapes).map((shapeName) => [shapeName, getShapeStream(shapeName)]),\n ) as SyncShapesToTablesResult[\"streams\"],\n };\n };\n\n const syncShapeToTable = async (options: SyncShapeToTableOptions): Promise<SyncShapeToTableResult> => {\n // ADR-0029 D6: thin sugar over the group form, forwarding the same entry-based options. The\n // per-shape `initialInsertMethod` (if any) rides through; the group form resolves the backfill\n // strategy from the registry entry when it is absent.\n const multiShapeSub = await syncShapesToTables({\n registry: options.registry,\n shapes: {\n shape: {\n shape: options.shape,\n tableKey: options.tableKey,\n onMustRefetch: options.onMustRefetch,\n ...(options.initialInsertMethod ? { initialInsertMethod: options.initialInsertMethod } : {}),\n },\n },\n key: options.shapeKey,\n onInitialSync: options.onInitialSync,\n onError: options.onError,\n onSyncError: options.onSyncError,\n maxCommitRetries: options.maxCommitRetries,\n commitRetryDelayMs: options.commitRetryDelayMs,\n });\n\n return {\n unsubscribe: multiShapeSub.unsubscribe,\n get isUpToDate() {\n return multiShapeSub.isUpToDate;\n },\n stream: (() => {\n const stream = multiShapeSub.streams[\"shape\"];\n if (!stream) {\n throw new Error(\"Missing stream for shape\");\n }\n return stream;\n })() as SyncShapeToTableResult[\"stream\"],\n };\n };\n\n const deleteSubscription = async (key: string) => {\n await deleteSubscriptionState({\n pg,\n metadataSchema,\n subscriptionKey: key,\n });\n };\n\n const namespaceObj = {\n initMetadataTables,\n syncShapesToTables,\n syncShapeToTable,\n deleteSubscription,\n };\n\n const close = async () => {\n for (const { stream, aborter } of streams) {\n stream.unsubscribeAll();\n aborter.abort();\n }\n };\n\n return {\n namespace: namespaceObj,\n close,\n };\n}\n\n/**\n * The pgxsinkit sync engine handle: the {@link SyncNamespaceObj} the client attaches as `pg.electric`,\n * plus the explicit `close()` teardown. Derived from {@link createSyncEngine}'s real return so the type\n * follows the object.\n */\nexport type SyncEngine = Awaited<ReturnType<typeof createSyncEngine>>;\nexport type SyncNamespaceObj = SyncEngine[\"namespace\"];\n\nexport type PGliteWithSync = PGliteInterface & {\n sync: SyncNamespaceObj;\n};\n",
|
|
28
|
+
"import type { ExternalHeadersRecord } from \"@electric-sql/client\";\nimport type { PGliteInterface } from \"@electric-sql/pglite\";\n\nimport {\n type Retention,\n type SubscriptionTiming,\n type SyncConfigInput,\n type SyncTableRegistry,\n type TableSpecInput,\n} from \"@pgxsinkit/contracts\";\n\nimport type { BootStampCollector, GroupBootStamp } from \"./boot-report\";\nimport type { SyncNamespaceObj } from \"./sync\";\nimport { createShapeErrorHandler } from \"./sync-auth\";\n\nexport interface ShapeSyncSpec {\n electricUrl: string;\n tableName: string;\n schema?: string;\n shapeKey: string;\n primaryKey: string[];\n electricTable?: string;\n /**\n * Consistency group (ADR-0009 decision 2). Specs sharing a group sync on one `MultiShapeStream`\n * and commit atomically. Absent → the table is its own singleton group keyed by its `shapeKey`.\n */\n consistencyGroup?: string;\n /**\n * Subscription timing (ADR-0021). Absent → `eager`. A `lazy` spec's group is held out of the eager\n * boot set and started on demand via {@link StartConfiguredSyncResult.ensureGroupStarted}. A group's\n * members all agree (registry-validated), so the group's timing is any member's.\n */\n subscription?: SubscriptionTiming;\n /**\n * Retention (ADR-0021). Absent → `persistent`. Only a `persistent` `lazy` group is promoted to the\n * eager set on activation (its activation is permanent across boots); an `ephemeral` group's activation\n * is session-scoped by construction, so it is never promoted/persisted.\n */\n retention?: Retention;\n}\n\nexport interface ConfiguredShapeSyncSpec extends ShapeSyncSpec {\n key: string;\n}\n\nexport interface StartConfiguredSyncOptions {\n syncConfig: SyncConfigInput;\n /**\n * The sync registry (ADR-0029 D1): the engine's sole per-table spec source. Each shape's `tableKey`\n * (its `syncConfig` table key) resolves against it for the local table, PKs, apply strategy, and\n * column types — no table-scoped fact is threaded from `syncConfig` into the engine.\n */\n registry: SyncTableRegistry;\n /**\n * Shape request headers shared by every member shape. Values may be async functions resolved per\n * request (ADR-0013) — the read-path `Authorization` token is one such function.\n */\n shapeHeaders?: ExternalHeadersRecord;\n onInitialSync?: () => void;\n onTableInitialSync?: (tableKey: string) => void;\n /**\n * Fresh-store prefetch overlap (ADR-0032 S4). When present, every EAGER group starts its shape streams\n * and buffers their catch-up into the memory inbox immediately, gating all commits until this promise\n * resolves — so the network catch-up overlaps the local boot phases (schema/journal/reconcile) instead\n * of running after them. Set ONLY by `createSyncClient` on a provably-fresh store (its `freshStore`\n * hint); absent → the sequential path. Passed straight through to the engine's `syncShapesToTables`.\n */\n dbReady?: Promise<void>;\n /** Commit-level error surfacing (ADR-0009 decision 5): a sync commit exhausted its retries. */\n onSyncError?: (error: Error) => void;\n /**\n * Notified when a shape hits an auth error (401/403) and the read path is retrying for a fresh\n * token (ADR-0013 Phase 3). The runtime surfaces a distinct `auth-needed` status from this.\n */\n onAuthError?: () => void;\n /**\n * Notified when a shape hits a NON-auth stream error (#4): a transient 5xx/429/network (retried) or\n * a structural 4xx (stops the stream). The runtime surfaces a `degraded` status from this so it\n * never silently believes the read path is live while it has actually stalled.\n */\n onReadStreamError?: (error: Error) => void;\n /**\n * Notified when a shape successfully delivers a batch — i.e. a fetch just succeeded (ADR-0013\n * Phase 3). The runtime uses this to clear an `auth-needed`/`degraded` status once sync resumes.\n */\n onSyncActivity?: () => void;\n /**\n * Consistency-group keys of `lazy` groups that were activated on a previous boot and persisted their\n * activation flag (ADR-0021 §2 — `lazy + persistent` promotion). These join the eager boot set as if\n * they were declared `eager`, so a once-activated durable lazy group resumes without re-evaluation.\n * Computed by the caller from the local meta table (the sync engine does no DB read of its own).\n */\n promotedGroups?: ReadonlySet<string>;\n /**\n * Invoked when a `persistent` `lazy` group is activated on demand (not promoted at boot), so the\n * caller can persist its activation flag for the next boot (ADR-0021 §2). Never fired for an\n * `ephemeral` group (its activation is session-scoped and leaves no durable trace).\n */\n onLazyActivated?: (groupKey: string) => void;\n /**\n * Invoked exactly once per consistency group the moment it becomes up-to-date (ADR-0032 decision 6 —\n * per-group readiness). Fires for eager, promoted, and on-demand `lazy` groups alike, so a client can\n * surface progressive per-group paint (and the worker bridge can fan a `groupReady` event to tabs)\n * without the all-eager-groups `onInitialSync` gate. The matching promise is {@link StartConfiguredSyncResult.groupReady}.\n */\n onGroupReady?: (groupKey: string) => void;\n /**\n * Boot observability (ADR-0034): opens a per-group accumulator (rows/requests/fetch/apply wall) for each\n * EAGER + PROMOTED boot group, stamped by the engine as the group's stream chain delivers and applies. A\n * lazy on-demand start gets none — so a lazily-activated-later group never enters (or mutates) the report.\n * Absent → no boot instrumentation.\n */\n bootCollector?: BootStampCollector;\n}\n\n// The engine is reached through the `electric` namespace the client attaches post-create (ADR-0032 S1) —\n// a plain property carrying the sync entry points, no longer a create-time PGlite extension.\ntype SyncEnginePGlite = PGliteInterface & { electric: SyncNamespaceObj };\n\nexport interface ShapeSyncResult {\n unsubscribe: () => void;\n readonly isUpToDate: boolean;\n}\n\nexport interface StartConfiguredSyncResult {\n unsubscribe: () => void;\n tables: Record<string, ShapeSyncResult>;\n /**\n * Start a `lazy` consistency group (ADR-0021) held out of the eager boot set. Idempotent and\n * single-flight: concurrent calls share one start; a started, unknown, or eager group resolves\n * immediately. Resolves once the group's initial sync completes — the seam the live-query layer\n * calls on first reference to a lazy table. After it resolves, the group's member `tables` entries\n * report `isUpToDate` live.\n */\n ensureGroupStarted: (groupKey: string) => Promise<void>;\n /**\n * Stop a group's stream and return it to dormant (ADR-0021 §2): tear down its live subscription and\n * clear the runtime so {@link isTableStarted} reports false again and a later {@link ensureGroupStarted}\n * re-subscribes from scratch — the inverse of an on-demand activation. Used by the client's `desync`\n * to halt a lazy group before truncating its read cache. A no-op for an unknown or never-started group.\n * The temp cluster of an `ephemeral` group is NOT dropped here (that is the deferred idle-eviction); the\n * cluster simply stops being fed.\n */\n stopGroup: (groupKey: string) => void;\n /** The consistency-group key a table belongs to — maps a queried table to its {@link ensureGroupStarted}. */\n groupKeyForTable: (tableKey: string) => string | undefined;\n /**\n * Whether a table's consistency group has started and completed its initial sync, so its reads are\n * hydrated (ADR-0021). False for a `lazy` group still held out of the boot set. Drives the read-path\n * tripwire — a lazy relation read while this is false would return empty/stale rows.\n */\n isTableStarted: (tableKey: string) => boolean;\n /**\n * A promise that resolves the moment the given consistency group is up-to-date (ADR-0032 decision 6).\n * Resolves immediately for an already-ready group; stays pending for a `lazy` group until it is\n * activated (via {@link ensureGroupStarted}) and catches up. An unknown group resolves immediately\n * (nothing to await). Per-group readiness the client re-exposes as `client.groupReady(table)`.\n */\n groupReady: (groupKey: string) => Promise<void>;\n /** Whether the given consistency group has completed its initial sync (synchronous peek at {@link groupReady}). */\n isGroupReady: (groupKey: string) => boolean;\n /** Every consistency-group key this config declares — the domain of {@link groupReady}/{@link isGroupReady}. */\n groupKeys: () => string[];\n}\n\nexport function buildShapeUrl(electricUrl: string, table: string) {\n const url = new URL(electricUrl);\n url.searchParams.set(\"table\", table);\n return url.toString();\n}\n\nexport function buildShapeConfig(input: ShapeSyncSpec) {\n return {\n shape: {\n // The ingress `table` param carries the unique `shapeKey` — the proxy resolves the shape by it and\n // maps it to the physical Electric table on egress (so a read projection and its owner, which share\n // a physical table, stay distinguishable). `table` below is the LOCAL PGlite apply target.\n url: buildShapeUrl(input.electricUrl, input.shapeKey),\n },\n table: input.tableName,\n ...(input.schema !== undefined ? { schema: input.schema } : {}),\n primaryKey: [...input.primaryKey],\n shapeKey: input.shapeKey,\n };\n}\n\nexport function buildConfiguredShapeSpecs(input: SyncConfigInput): ConfiguredShapeSyncSpec[] {\n return Object.entries(input.tables)\n .filter(([, table]) => table.mode !== \"writeonly\")\n .map(([key, table]) => buildConfiguredShapeSpec(input.electricUrl, input.localSchema, key, table));\n}\n\n/**\n * One consistency group's runtime: its specs, the subscription timing its members agree on, and its\n * live stream once started (`null` while a `lazy` group is still held). `startPromise` makes start\n * single-flight so concurrent on-demand triggers share one subscription.\n */\ninterface GroupRuntime {\n groupKey: string;\n specs: ConfiguredShapeSyncSpec[];\n subscription: SubscriptionTiming;\n retention: Retention;\n result: ShapeSyncResult | null;\n startPromise: Promise<void> | null;\n}\n\nexport async function startConfiguredSync(\n pg: SyncEnginePGlite,\n input: StartConfiguredSyncOptions,\n): Promise<StartConfiguredSyncResult> {\n const specs = buildConfiguredShapeSpecs(input.syncConfig);\n\n // Bucket specs into consistency groups (ADR-0009 decision 2). Each group is one MultiShapeStream\n // committed atomically; an ungrouped table is its own singleton group keyed by its shapeKey. A group\n // carries the subscription timing its members agree on (ADR-0021; registry validation guarantees\n // agreement, so the first member's value is the group's): `eager` groups start at boot, `lazy` groups\n // are held until ensureGroupStarted (the on-demand / live-query interception seam).\n const groups = new Map<string, GroupRuntime>();\n const groupKeyByTable = new Map<string, string>();\n for (const spec of specs) {\n const groupKey = groupSubscriptionKey(spec);\n groupKeyByTable.set(spec.key, groupKey);\n const existing = groups.get(groupKey);\n if (existing) {\n existing.specs.push(spec);\n } else {\n groups.set(groupKey, {\n groupKey,\n specs: [spec],\n subscription: spec.subscription ?? \"eager\",\n retention: spec.retention ?? \"persistent\",\n result: null,\n startPromise: null,\n });\n }\n }\n\n // Per-group readiness (ADR-0032 decision 6): one deferred per group, created up front so a caller can\n // await ANY group — eager or still-dormant lazy — before it has started. Resolved once (idempotent) the\n // moment the group reports up-to-date; a never-activated lazy group's promise simply stays pending.\n interface GroupReadyDeferred {\n promise: Promise<void>;\n resolve: () => void;\n ready: boolean;\n }\n const groupReadyState = new Map<string, GroupReadyDeferred>();\n for (const groupKey of groups.keys()) {\n let resolve!: () => void;\n const promise = new Promise<void>((r) => {\n resolve = r;\n });\n groupReadyState.set(groupKey, { promise, resolve, ready: false });\n }\n const markGroupReady = (groupKey: string) => {\n const state = groupReadyState.get(groupKey);\n if (!state || state.ready) return;\n state.ready = true;\n state.resolve();\n input.onGroupReady?.(groupKey);\n };\n\n // A `lazy` group activated on a previous boot (ADR-0021 §2 `lazy + persistent` promotion) is treated\n // as eager this boot: its activation is permanent, so it joins the boot set and resumes like any durable\n // table — no per-session re-evaluation, no half-lazy.\n const promotedGroups = input.promotedGroups ?? new Set<string>();\n const isEagerAtBoot = (group: GroupRuntime) => group.subscription !== \"lazy\" || promotedGroups.has(group.groupKey);\n\n // Boot readiness (`onInitialSync`) waits only for the boot (eager + promoted) groups to catch up; a lazy\n // group started later via ensureGroupStarted signals its members' `onTableInitialSync` but never the gate.\n const eagerGroups = [...groups.values()].filter(isEagerAtBoot);\n let pendingBootGroups = eagerGroups.length;\n let bootSignalled = false;\n const signalBootIfReady = () => {\n if (!bootSignalled && pendingBootGroups <= 0) {\n bootSignalled = true;\n input.onInitialSync?.();\n }\n };\n\n // Start one group's stream, single-flight: a started group resolves immediately; an in-flight start\n // is shared. `countsTowardBoot` is true only for the eager boot starts.\n const startGroup = (group: GroupRuntime, countsTowardBoot: boolean): Promise<void> => {\n if (group.result) {\n return Promise.resolve();\n }\n if (group.startPromise) {\n return group.startPromise;\n }\n // Boot observability (ADR-0034): open an accumulator for a BOOT group only (eager + promoted); an\n // on-demand lazy start (`countsTowardBoot === false`) gets none, so it never enters the report.\n const bootStamp: GroupBootStamp | undefined =\n countsTowardBoot && input.bootCollector\n ? input.bootCollector.beginGroup(group.groupKey, group.specs.length)\n : undefined;\n group.startPromise = startGroupSync(pg, {\n groupKey: group.groupKey,\n specs: group.specs,\n registry: input.registry,\n // ADR-0042: an ephemeral group's cursor + tags are session-scoped (stored in `pg_temp`), so a warm\n // engine restart re-streams the shape from scratch rather than resuming a stale durable cursor over\n // the recreated-empty TEMP cluster. The engine learns only this one storage-scope bit.\n ...(group.retention === \"ephemeral\" ? { sessionScoped: true } : {}),\n ...(bootStamp ? { bootStamp } : {}),\n // The prefetch overlap (ADR-0032 S4) applies ONLY to the eager BOOT starts: a fresh store's eager\n // groups are genuinely new, so buffering their catch-up behind the commit gate is safe. An on-demand\n // `lazy` start happens post-boot on an already-provisioned store (which may even be RESUMING persisted\n // subscription state), so it must take the exact sequential path — never the fresh-store overlap.\n ...(countsTowardBoot && input.dbReady ? { dbReady: input.dbReady } : {}),\n ...(input.shapeHeaders ? { headers: input.shapeHeaders } : {}),\n ...(input.onSyncError ? { onSyncError: input.onSyncError } : {}),\n ...(input.onAuthError ? { onAuthError: input.onAuthError } : {}),\n ...(input.onReadStreamError ? { onReadStreamError: input.onReadStreamError } : {}),\n ...(input.onSyncActivity ? { onSyncActivity: input.onSyncActivity } : {}),\n onGroupInitialSync: () => {\n // The group is up-to-date as a unit; signal each member table, mark the group ready (per-group\n // readiness, ADR-0032 decision 6), then (for an eager group only) advance the boot gate once\n // every eager group is caught up.\n for (const spec of group.specs) {\n input.onTableInitialSync?.(spec.key);\n }\n // Boot observability (ADR-0034): stamp readyAtMs and freeze the accumulator at the group's ready edge,\n // so later live traffic never mutates a finalized report.\n bootStamp?.markReady();\n markGroupReady(group.groupKey);\n if (countsTowardBoot) {\n pendingBootGroups -= 1;\n signalBootIfReady();\n }\n },\n }).then((result) => {\n group.result = result;\n // A `persistent` `lazy` group activated on demand (not a boot start) persists its activation, so the\n // next boot promotes it to eager (ADR-0021 §2). `ephemeral` activation is session-scoped — never persisted.\n if (!countsTowardBoot && group.subscription === \"lazy\" && group.retention === \"persistent\") {\n input.onLazyActivated?.(group.groupKey);\n }\n });\n return group.startPromise;\n };\n\n // Each member table exposes a per-table view backed by its group's runtime: up-to-date exactly when\n // the group is (false until a lazy group is started), and unsubscribing it tears down the group.\n const tables: Record<string, ShapeSyncResult> = {};\n for (const [tableKey, groupKey] of groupKeyByTable) {\n const group = groups.get(groupKey)!;\n tables[tableKey] = {\n unsubscribe: () => group.result?.unsubscribe(),\n get isUpToDate() {\n return group.result?.isUpToDate ?? false;\n },\n };\n }\n\n // Start the eager groups at boot; lazy groups wait for ensureGroupStarted. `signalBootIfReady` after\n // the await covers a config with no eager groups (boot is trivially complete).\n await Promise.all(eagerGroups.map((group) => startGroup(group, true)));\n signalBootIfReady();\n\n return {\n unsubscribe: () => {\n // Unsubscribe per group (not per table) so a multi-table group's stream is torn down once.\n for (const group of groups.values()) {\n group.result?.unsubscribe();\n }\n },\n tables,\n ensureGroupStarted: (groupKey) => {\n const group = groups.get(groupKey);\n return group ? startGroup(group, false) : Promise.resolve();\n },\n stopGroup: (groupKey) => {\n const group = groups.get(groupKey);\n if (!group) return;\n // Tear down the live stream and clear the runtime so the group is dormant again: `isTableStarted`\n // reports false and `ensureGroupStarted` re-runs `startGroupSync` (its `group.result`/`startPromise`\n // short-circuits no longer apply) on the next reference.\n group.result?.unsubscribe();\n group.result = null;\n group.startPromise = null;\n // Return the group's readiness to pending: a stopped group is dormant again, so `groupReady` for a\n // later re-activation must re-await its fresh catch-up rather than resolve on the stale deferred.\n if (groupReadyState.get(groupKey)?.ready) {\n let resolve!: () => void;\n const promise = new Promise<void>((r) => {\n resolve = r;\n });\n groupReadyState.set(groupKey, { promise, resolve, ready: false });\n }\n },\n groupKeyForTable: (tableKey) => groupKeyByTable.get(tableKey),\n isTableStarted: (tableKey) => {\n const groupKey = groupKeyByTable.get(tableKey);\n if (groupKey == null) return false;\n return groups.get(groupKey)?.result != null;\n },\n // An unknown group key has nothing to await, so its readiness resolves immediately (never blocks).\n groupReady: (groupKey) => groupReadyState.get(groupKey)?.promise ?? Promise.resolve(),\n isGroupReady: (groupKey) => groupReadyState.get(groupKey)?.ready ?? true,\n groupKeys: () => [...groups.keys()],\n };\n}\n\ninterface StartGroupSyncOptions {\n groupKey: string;\n specs: ConfiguredShapeSyncSpec[];\n registry: SyncTableRegistry;\n /**\n * ADR-0042: the group's retention is `ephemeral`, so its sync bookkeeping (cursor + tags) is session-\n * scoped — the engine stores it in `pg_temp` relations that die with the engine. Forwarded straight to\n * the engine's `syncShapesToTables`; absent/`false` for a persistent group (byte-identical storage).\n */\n sessionScoped?: boolean;\n headers?: ExternalHeadersRecord;\n /** Fresh-store prefetch overlap gate (ADR-0032 S4) — forwarded to the engine's `syncShapesToTables`. */\n dbReady?: Promise<void>;\n /** Boot observability (ADR-0034): the group's accumulator, stamped by the engine on delivery/apply. */\n bootStamp?: GroupBootStamp;\n onGroupInitialSync?: () => void;\n onSyncError?: (error: Error) => void;\n onAuthError?: () => void;\n onReadStreamError?: (error: Error) => void;\n onSyncActivity?: () => void;\n}\n\n/**\n * Sync one consistency group on a single `MultiShapeStream` (ADR-0009 decision 2). All member\n * shapes share the group's subscription key and commit atomically at a shared LSN frontier; each\n * shape keeps its own apply strategy and column types (resolved per-shape inside the engine).\n */\nexport async function startGroupSync(pg: SyncEnginePGlite, input: StartGroupSyncOptions) {\n const shapeHeaders = input.headers && Object.keys(input.headers).length > 0 ? input.headers : undefined;\n\n // The per-shape onError owns read-path auth recovery (ADR-0013 Phase 2: a 401/403 retries with a\n // fresh token) AND read-stream error surfacing (#4: a non-auth error moves the runtime to\n // `degraded`, retrying transient 5xx/429/network and stopping a structural 4xx).\n const onError = createShapeErrorHandler({\n ...(input.onAuthError ? { onAuthError: input.onAuthError } : {}),\n ...(input.onReadStreamError ? { onReadStreamError: input.onReadStreamError } : {}),\n });\n\n const shapes = Object.fromEntries(\n input.specs.map((spec) => [\n spec.key,\n {\n shape: {\n // Ingress `table` = the unique `shapeKey` (proxy maps it to the physical table on egress).\n url: buildShapeUrl(spec.electricUrl, spec.shapeKey),\n ...(shapeHeaders ? { headers: shapeHeaders } : {}),\n onError,\n },\n // ADR-0029 D1: the registry table key is the engine's sole per-table spec — the local apply\n // target, PKs, strategy, and column types all derive from `(registry, tableKey)`. The\n // `syncConfig` table key IS the registry key, so the spec's `key` is the `tableKey`.\n tableKey: spec.key,\n },\n ]),\n );\n\n return getElectricNamespace(pg).syncShapesToTables({\n key: input.groupKey,\n registry: input.registry,\n shapes,\n ...(input.sessionScoped ? { sessionScoped: input.sessionScoped } : {}),\n ...(input.dbReady ? { dbReady: input.dbReady } : {}),\n ...(input.bootStamp ? { bootStamp: input.bootStamp } : {}),\n ...(input.onGroupInitialSync ? { onInitialSync: input.onGroupInitialSync } : {}),\n ...(input.onSyncError ? { onSyncError: input.onSyncError } : {}),\n ...(input.onSyncActivity ? { onSyncActivity: input.onSyncActivity } : {}),\n });\n}\n\nfunction getElectricNamespace(pg: SyncEnginePGlite) {\n return pg.electric;\n}\n\nfunction buildConfiguredShapeSpec(\n electricUrl: string,\n localSchema: string | undefined,\n key: string,\n table: TableSpecInput,\n): ConfiguredShapeSyncSpec {\n if (table.shape === undefined) {\n throw new Error(`shape is required for synced table ${key}`);\n }\n\n return {\n key,\n electricUrl,\n tableName: table.clientProjection?.syncedTable ?? table.shape.tableName,\n // ADR-0021 §3: an ephemeral table's cluster is `TEMP` (bare names in `pg_temp`), so the row-applier\n // must target the unqualified name (resolved via search_path) — omit the schema for it.\n ...(localSchema && table.retention !== \"ephemeral\" ? { schema: localSchema } : {}),\n shapeKey: table.shape.shapeKey,\n primaryKey: [...(table.clientProjection?.localPrimaryKey?.columns ?? table.primaryKey.columns)],\n electricTable: table.shape.electricTable ?? table.shape.tableName,\n ...(table.consistencyGroup ? { consistencyGroup: table.consistencyGroup } : {}),\n ...(table.subscription ? { subscription: table.subscription } : {}),\n ...(table.retention ? { retention: table.retention } : {}),\n };\n}\n\n/**\n * The subscription key for a spec's consistency group (ADR-0009 decision 2): the explicit\n * `consistencyGroup` when set, else the table's own `shapeKey` (a singleton group). One persisted\n * subscription-state row exists per group key, so subscription reset enumerates these.\n */\nexport function groupSubscriptionKey(spec: Pick<ConfiguredShapeSyncSpec, \"consistencyGroup\" | \"shapeKey\">): string {\n return spec.consistencyGroup ?? spec.shapeKey;\n}\n",
|
|
29
|
+
"// Started life as a copy of @electric-sql/pglite-sync (Apache-2.0, © ElectricSQL — see NOTICE).\n// Fully internalized (ADR-0009); upstream compatibility is an explicit anti-goal (ADR-0028) — evolve freely.\nimport type { EventMessage, MovePattern, Row } from \"@electric-sql/client\";\nimport { isChangeMessage, isControlMessage } from \"@electric-sql/client\";\nimport type { ChangeMessage, ShapeStreamOptions } from \"@electric-sql/client\";\nimport { MultiShapeStream } from \"@electric-sql/experimental\";\nimport type { PGliteInterface } from \"@electric-sql/pglite\";\nimport { sql } from \"drizzle-orm\";\nimport { getTableConfig } from \"drizzle-orm/pg-core\";\n\nimport { type ApplyStrategy, classifyTableApplyStrategy } from \"@pgxsinkit/contracts\";\n\nimport { instrumentShapeFetch, syncDebug } from \"../debug\";\nimport { type ApplyTarget, resolveApplyTarget } from \"../local-tables\";\nimport { computeRetryDelayMs } from \"../mutation\";\nimport {\n applyBulkDeletesToTable,\n applyBulkUpdatesToTable,\n applyInsertsToTable,\n applyMessagesToTableWithCopy,\n applyMessagesToTableWithJson,\n applyUpsertsToTable,\n} from \"./apply\";\nimport { drizzleOverPg } from \"./drizzle-executor\";\nimport {\n NUDGE_HOLD_GRACE_MS,\n NUDGE_MAX_ROUNDS,\n NUDGE_ROUND_GRACE_MS,\n NUDGE_ROUND_WAIT_MS,\n withNudgeBuster,\n} from \"./nudge\";\nimport { foldChangeBatch, ShapeInbox } from \"./shape-inbox\";\nimport {\n deleteSubscriptionState,\n getSubscriptionState,\n migrateSubscriptionMetadataTables,\n type SubscriptionState,\n updateSubscriptionState,\n} from \"./subscription-state\";\nimport {\n addShapeRowTags,\n applyShapeMoveOut,\n applyShapeTagSync,\n assertValidMetadataSchema,\n clearShapeTags,\n DEFAULT_METADATA_SCHEMA,\n shapeTableId,\n} from \"./tags\";\nimport {\n DEFAULT_MAX_COMMIT_RETRIES,\n type ElectricSyncOptions,\n type InitialInsertMethod,\n type InsertChangeMessage,\n type Lsn,\n type SyncShapesToTablesOptions,\n type SyncShapesToTablesResult,\n type SyncShapeToTableOptions,\n type SyncShapeToTableResult,\n} from \"./types\";\n\nexport * from \"./types\";\n\n/**\n * Replication-stream headers Electric attaches to change messages but does not\n * declare on its `Header` type: `lsn` orders changes within the stream and\n * `last` marks the final change of an LSN. Single choke point for these\n * protocol assumptions.\n */\n/**\n * Maps the statically-resolved {@link ApplyStrategy} (ADR-0009 decision 3) onto the engine's\n * initial-backfill apply path. Undefined (no registry-supplied strategy) defaults to `copy`:\n * the COPY TEXT serializer round-trips every built-in type, so it is the safe no-brainer bootstrap.\n */\nfunction applyStrategyToInsertMethod(strategy: ApplyStrategy | undefined): InitialInsertMethod {\n switch (strategy) {\n case \"json\":\n return \"json\";\n case \"insert\":\n return \"insert\";\n default:\n return \"copy\";\n }\n}\n\nfunction readReplicationHeaders(headers: ChangeMessage[\"headers\"]): { lsn: bigint; isLastOfLsn: boolean } {\n const rawLsn: unknown = headers[\"lsn\"];\n\n return {\n lsn: typeof rawLsn === \"string\" ? BigInt(rawLsn) : BigInt(0),\n isLastOfLsn: headers[\"last\"] === true,\n };\n}\n\n/**\n * Electric's tagged-subquery `EventMessage` (ADR-0023) — `headers.event` is `move-out` | `move-in`,\n * carrying `patterns`. It is neither a change nor a control message, so `@electric-sql/client` exposes\n * no guard; we detect it by the `event` header. `MultiShapeStream` adds `.shape` like every message.\n */\ntype ShapeEventMessage = EventMessage & { shape: string };\n\nfunction isEventMessage(message: unknown): message is ShapeEventMessage {\n return (\n typeof message === \"object\" &&\n message !== null &&\n typeof (message as { headers?: { event?: unknown } }).headers?.event === \"string\"\n );\n}\n\n/**\n * Construct the pgxsinkit sync engine over an ALREADY-created PGlite instance (ADR-0032 S1). The engine\n * is a plain module — not a create-time PGlite extension — so it demands only the minimal surface it\n * actually uses: a {@link PGliteInterface} (it runs its metadata DDL + apply commits through `pg.transaction`\n * / `pg.query` / `pg.exec`; it does NOT touch the `live` extension). It returns the `namespace` object (the\n * local-bookkeeping + shape-sync entry points the client attaches as `pg.electric`) plus an explicit\n * `close()` — the teardown the former extension's `close` hook ran when PGlite closed, now invoked\n * explicitly by the owner at the same moment (see `createSyncClient`'s `stop`/`destroy`).\n */\nexport async function createSyncEngine(pg: PGliteInterface, options?: ElectricSyncOptions) {\n const debug = options?.debug ?? false;\n // pgxsinkit-owned metadata namespace (ADR-0009 decision 6): this is our local bookkeeping (the\n // subscription-state table) and the sync-origin GUC (`<schema>.syncing`), not Electric's — so it\n // lives under our own schema, renamed from the upstream `electric` default.\n const metadataSchema = options?.metadataSchema ?? DEFAULT_METADATA_SCHEMA;\n // The schema name reaches raw GUC + DDL identifier positions below (no quoted-identifier form exists\n // there), so validate it at construction rather than trust caller input in those raw spots.\n assertValidMetadataSchema(metadataSchema);\n const streams: Array<{\n stream: MultiShapeStream<Record<string, Row<unknown>>>;\n aborter: AbortController;\n }> = [];\n\n const getShapeOptions = (shapes: SyncShapesToTablesOptions[\"shapes\"], shapeName: string) => {\n const shape = shapes[shapeName];\n if (!shape) {\n throw new Error(`Missing shape options for ${shapeName}`);\n }\n return shape;\n };\n\n const shapePerTableLock = new Map<string, void>();\n\n // Memoize the metadata DDL as a PROMISE, not a boolean: concurrent eager groups (`shape-sync.ts`\n // starts them with `Promise.all`) both call `initMetadataTables`, and a boolean set BEFORE the async\n // migration completed let the second caller return early and query the metadata tables before the DDL\n // had run. Storing the in-flight promise makes every concurrent caller await the same single migration.\n // Cleared on rejection so a transient DDL failure can be retried by a later start rather than caching a\n // rejected promise forever.\n let initMetadataTablesPromise: Promise<void> | undefined;\n const initMetadataTables = (): Promise<void> => {\n if (!initMetadataTablesPromise) {\n initMetadataTablesPromise = migrateSubscriptionMetadataTables({\n pg,\n metadataSchema,\n }).catch((error: unknown) => {\n initMetadataTablesPromise = undefined;\n throw error;\n });\n }\n return initMetadataTablesPromise;\n };\n\n const syncShapesToTables = async ({\n key,\n registry,\n shapes,\n sessionScoped = false,\n initialInsertMethod,\n onInitialSync,\n onError,\n onSyncError,\n onSyncActivity,\n dbReady,\n bootStamp,\n maxCommitRetries = DEFAULT_MAX_COMMIT_RETRIES,\n commitRetryDelayMs = computeRetryDelayMs,\n }: SyncShapesToTablesOptions): Promise<SyncShapesToTablesResult> => {\n let unsubscribed = false;\n // Fresh-store prefetch overlap (ADR-0032 S4): the caller proved the store fresh and handed a `dbReady`\n // gate, so start the streams and buffer their catch-up into the memory inbox NOW — before the local\n // store's schema/journal/reconcile finish — and defer every DB touch (metadata DDL, the first commit)\n // until the gate lifts. Without it, the exact sequential path: init the metadata tables up front.\n const overlap = dbReady != null;\n if (!overlap) {\n await initMetadataTables();\n }\n\n // Resolve each shape's apply target ONCE at subscribe time (ADR-0029 D1/D2): the real projected\n // synced table, its columns, PKs, and model-derived types — the engine's per-message work is then a\n // pure builder over these resolved objects, never a per-message re-derivation or catalog probe.\n const targets = new Map<string, ApplyTarget>(\n Object.entries(shapes).map(([shapeName, shapeOptions]) => [\n shapeName,\n resolveApplyTarget(registry, shapeOptions.tableKey),\n ]),\n );\n const getTarget = (shapeName: string): ApplyTarget => {\n const target = targets.get(shapeName);\n if (!target) {\n throw new Error(`Missing apply target for ${shapeName}`);\n }\n return target;\n };\n // The synced table's physical identity — the per-table lock key and the tag-store `shape_table` key.\n const tableIdentity = (target: ApplyTarget) => {\n const { name, schema } = getTableConfig(target.table);\n return shapeTableId(schema, name);\n };\n\n Object.entries(shapes)\n .filter(([, shape]) => !shape.onMustRefetch)\n .forEach(([, shape]) => {\n if (shapePerTableLock.has(shape.tableKey)) {\n throw new Error(\"Already syncing shape for table \" + shape.tableKey);\n }\n shapePerTableLock.set(shape.tableKey);\n });\n\n let subState: SubscriptionState | null = null;\n\n // On the overlap path the store is provably fresh (the `freshStore` gate), so it carries no persisted\n // subscription state — AND its metadata tables do not exist yet (their DDL is deferred to the gate).\n // Skip the read entirely: `subState` stays null, so the group is (correctly) a new subscription.\n if (key !== null && !overlap) {\n subState = await getSubscriptionState({\n pg,\n metadataSchema,\n subscriptionKey: key,\n sessionScoped,\n });\n if (debug && subState) {\n console.log(\"resuming from subscription state\", subState);\n }\n }\n\n const isNewSubscription = subState === null;\n\n // Each shape resolves its own apply method (ADR-0009 decisions 2 + 3 / ADR-0029 D1): an explicit\n // per-shape `initialInsertMethod` override wins, else the group-level default, else the registry's\n // build-time classification of the entry. So a consistency group with mixed column profiles applies\n // each table on its correct path.\n const shapeInsertMethod = new Map<string, InitialInsertMethod>(\n Object.entries(shapes).map(([shapeName, shapeOptions]) => {\n // Strategy precedence (ADR-0009 decisions 2+3 / ADR-0029 D1): an explicit per-shape override,\n // then the group-level default, then the registry's build-time classification of the entry.\n const entry = registry[shapeOptions.tableKey]!;\n const method =\n shapeOptions.initialInsertMethod ??\n initialInsertMethod ??\n applyStrategyToInsertMethod(classifyTableApplyStrategy(entry));\n return [shapeName, method];\n }),\n );\n\n // `useInsert` is per-shape, not shared: in a multi-shape group, one shape finishing its bulk\n // backfill must not flip every other shape onto plain `INSERT`. A shape uses its bulk path only\n // on a fresh subscription with a non-`insert` method; a resume starts already in insert mode.\n const useInsert = new Map<string, boolean>(\n Object.keys(shapes).map((shapeName) => [\n shapeName,\n !isNewSubscription || shapeInsertMethod.get(shapeName) === \"insert\",\n ]),\n );\n let onInitialSyncCalled = false;\n\n const maybeSignalInitialSync = () => {\n if (onInitialSync && !onInitialSyncCalled && multiShapeStream.isUpToDate) {\n onInitialSync();\n onInitialSyncCalled = true;\n }\n };\n\n // The Shape inbox (ADR-0014 / ISS-06): the pure, in-memory buffer + complete-LSN frontier for\n // this group's shapes. The engine keeps the commit queue, the apply, and the truncate set.\n const inbox = new ShapeInbox(Object.keys(shapes));\n\n // Live-tail sibling nudge (ADR-0031): a per-shape one-shot cache-buster token. The watchdog (below)\n // sets a token just before nudging a lagging sibling; `withNudgeBuster` (wrapping each shape's\n // fetchClient) consumes it on the sibling's next non-live catch-up so a CDN HIT cannot return the same\n // stale watermark and defeat the nudge. Empty on the steady path → the wrapper is a straight passthrough.\n const nudgeBusters = new Map<string, string>();\n\n const truncateNeeded = new Set<string>();\n // The committed frontier is a *running* variable, advanced after each successful commit — not\n // the boot-time `const` the upstream engine never advanced (which forced redundant empty\n // re-commits). `degraded` latches once commits exhaust their retries (ADR-0009 decision 5).\n let committedLsn: Lsn = subState?.last_lsn ?? BigInt(-1);\n let degraded = false;\n // Single-flight commit queue: at most one commit runs at a time; messages buffered while one\n // is in flight coalesce into the next run (re-armed via `commitRerun`).\n let commitInFlight: Promise<void> | null = null;\n let commitRerun = false;\n\n const aborter = new AbortController();\n Object.values(shapes)\n .filter((shapeOptions) => !!shapeOptions.shape.signal)\n .forEach((shapeOptions) => {\n shapeOptions.shape.signal!.addEventListener(\"abort\", () => aborter.abort(), {\n once: true,\n });\n });\n\n const multiShapeOptions: Record<string, ShapeStreamOptions<Row<unknown>>> = {};\n for (const [shapeName, shapeOptions] of Object.entries(shapes)) {\n const shapeMetadata = subState?.shape_metadata[shapeName];\n const streamOptions: ShapeStreamOptions<Row<unknown>> = {\n ...shapeOptions.shape,\n signal: aborter.signal,\n // Instrument every ShapeStream HTTP request (the read-path long-poll/catch-up) when debug is on;\n // a passthrough otherwise (see instrumentShapeFetch). Wraps any existing fetchClient rather than\n // replacing it, so auth/header injection on the shape's own fetchClient still runs. `withNudgeBuster`\n // is the OUTER wrapper (ADR-0031 live-tail nudge): it stamps the cache-buster onto the URL BEFORE\n // instrumentation runs, so the debug rail logs the busted URL (`BUSTED`) that actually hits the wire.\n fetchClient: withNudgeBuster(instrumentShapeFetch(shapeOptions.shape.fetchClient), nudgeBusters, shapeName),\n };\n\n if (shapeMetadata) {\n streamOptions.offset = shapeMetadata.offset;\n streamOptions.handle = shapeMetadata.handle;\n }\n\n multiShapeOptions[shapeName] = streamOptions;\n }\n\n const multiShapeStream = new MultiShapeStream<Record<string, Row<unknown>>>({\n shapes: multiShapeOptions,\n });\n\n // The commit gate (ADR-0032 S4). Open immediately on the sequential path; held closed on the overlap\n // path until `dbReady` resolves, so NOTHING writes to PGlite before the local schema exists. The inbox\n // is pure memory, so buffering catch-up behind this closed gate is safe — the only DB-bound work\n // (metadata DDL, then commits) waits for the gate.\n let dbGateOpen = !overlap;\n if (overlap) {\n // The streams' network side is starting now (subscribe below triggers the first fetch), overlapping\n // the caller's local boot phases. Name the shapes so the overlap is measurable on the boot rail.\n syncDebug(\"boot shape prefetch start\", { shapes: Object.keys(shapes) });\n }\n\n const getShapeStream = (shapeName: string) => {\n const stream = multiShapeStream.shapes[shapeName];\n if (!stream) {\n throw new Error(`Missing stream for ${shapeName}`);\n }\n return stream;\n };\n\n const insertMethods = {\n json: applyMessagesToTableWithJson,\n copy: applyMessagesToTableWithCopy,\n insert: applyInsertsToTable,\n } as const;\n\n // Apply everything buffered up to `targetLsn` in a single transaction, retrying with jittered\n // backoff on failure. Returns `true` once applied (and advances the running committed frontier);\n // returns `false` without advancing if the engine unsubscribed mid-flight or the commit\n // exhausted its retries (→ `degraded` + `onSyncError`, ADR-0009 decision 5). The drained\n // messages and the truncate snapshot are held across retries so a transient failure loses\n // nothing; the read cache never advances past an unapplied commit.\n const commitUpToLsn = async (targetLsn: Lsn): Promise<boolean> => {\n // PEEK (not drain) the buffered batch: it stays in the inbox until the transaction below actually\n // succeeds, and is only then ACKed (removed). A commit that exhausts its retries (→ `degraded`)\n // therefore HOLDS the drained batch in the buffer instead of losing it (ADR-0009 decision 5) — and\n // `enqueueCommit` refuses to run any newer commit while degraded, so a later LSN can never apply\n // over this held, unapplied batch. Recovery is a restart/refetch: the persisted offset was not\n // advanced, so the held batch re-streams from the same frontier.\n const messagesToCommit = inbox.peekUpTo(targetLsn);\n\n // Record every shape's reset epoch AT PEEK TIME (synchronously with the peeks, before the async\n // transaction). If a must-refetch + re-snapshot bumps a shape's epoch mid-commit, the acks below\n // skip that shape so its post-reset rebuild survives rather than being deleted/spliced away — see\n // ShapeInbox.ackUpTo / ackMoveOuts / ackMoveIns.\n const epochsAtPeek = inbox.snapshotEpochs();\n\n // Capture, per shape, whether it is still accepting snapshot (LSN-0) rows AT PEEK TIME. A shape in\n // snapshot acceptance (post-reset re-snapshot, or a brand-new shape before its first real lsn) can\n // have the SAME snapshot rows double-delivered by the racing recovery fetch loops — possibly across\n // separate commits — so its inserts are applied idempotently (upsert) rather than as plain\n // collision-surfacing inserts. Once a real lsn re-arms the dedup, this is false and the live-tail\n // plain-INSERT invariant (a genuine PK collision must surface, ADR-0014) is back in force.\n const snapshotModeAtPeek = new Map<string, boolean>(\n Object.keys(shapes).map((shapeName) => [shapeName, inbox.acceptsSnapshotRowsFor(shapeName)]),\n );\n\n // Snapshot the truncate set so a retried transaction still truncates; the per-shape flag is\n // cleared only once the commit has succeeded.\n const shapesToTruncate = new Set(truncateNeeded);\n\n // Peek the buffered tagged-subquery move-outs (ADR-0023) the same way: held in the buffer so a\n // retried/degraded commit still has them, ACKed only on success (by the exact peeked count, so a\n // move-out that arrived during a coalescing commit is not dropped).\n const moveOutsToCommit = new Map<string, MovePattern[][]>();\n // Peek the buffered tagged-subquery move-ins (ADR-0024) identically: a move-in snapshot row carries\n // no LSN; it is applied idempotently in the commit transaction and ACKed only on success.\n const moveInsToCommit = new Map<string, ChangeMessage<Row<unknown>>[]>();\n for (const shapeName of Object.keys(shapes)) {\n const pendingOut = inbox.peekMoveOuts(shapeName);\n if (pendingOut.length > 0) {\n moveOutsToCommit.set(shapeName, pendingOut);\n }\n const pendingIn = inbox.peekMoveIns(shapeName);\n if (pendingIn.length > 0) {\n moveInsToCommit.set(shapeName, pendingIn);\n }\n }\n\n const runCommit = () =>\n pg.transaction(async (tx) => {\n if (debug) {\n console.time(\"commit\");\n }\n\n // Tier ③ (ADR-0028 allow-list): a `SET LOCAL` GUC — the sync-origin `<schema>.syncing` flag\n // the apply trigger reads to distinguish streamed server truth from local writes. GUCs have\n // no tier-①/② builder form; the schema identifier is fixed at engine construction.\n await tx.exec(`SET LOCAL ${metadataSchema}.syncing = true;`);\n\n for (const [shapeName, initialMessages] of messagesToCommit.entries()) {\n const shape = getShapeOptions(shapes, shapeName);\n const target = getTarget(shapeName);\n const shapeMethod = shapeInsertMethod.get(shapeName)!;\n let messages = initialMessages;\n\n // ADR-0023: the shape's tag store key (synced table, schema-qualified).\n const shapeTable = tableIdentity(target);\n\n if (shapesToTruncate.has(shapeName)) {\n if (debug) {\n console.log(\"truncating table\", shapeTable);\n }\n if (shape.onMustRefetch) {\n await shape.onMustRefetch(drizzleOverPg(tx));\n } else {\n // ADR-0029 D4: a must-refetch wipe is engine cache maintenance, not server truth — so it\n // TRUNCATEs (tier ②; `TRUNCATE` has no Drizzle builder, the table object is interpolated)\n // rather than reacting via the per-row reconcile trigger. Correctness rides the reconcile\n // loop; TRUNCATE is O(1) and the re-snapshot inserts still fire the trigger.\n await drizzleOverPg(tx).execute(sql`TRUNCATE ${target.table}`);\n }\n // The re-snapshot rebuilds tags from scratch, so drop this shape's stale tag-set too\n // (ADR-0023 Slice 2: a must-refetch/rebuild must not leave orphan tags).\n await clearShapeTags({ pg: tx, metadataSchema, shapeTable, sessionScoped });\n }\n\n // ADR-0024: this shape's buffered move-in snapshot rows (a row ENTERING the shape). Their\n // tags are UNIONED first (a move-in adds a reason, it must not clear an independent grant's\n // tag) — and a regular change for the same row in this batch then authoritatively replaces\n // below, so union-then-replace converges either way.\n const moveInMessages = moveInsToCommit.get(shapeName) ?? [];\n if (moveInMessages.length > 0) {\n await addShapeRowTags({\n pg: tx,\n metadataSchema,\n shapeTable,\n messages: moveInMessages,\n primaryKey: target.primaryKey,\n sessionScoped,\n });\n }\n\n // Maintain the tag-set from the RAW drained batch (ADR-0023) — before the data apply and\n // the move-out eviction, so an add-then-remove within one commit resolves correctly. Uses\n // `initialMessages` (the full batch) since the insert/fold split below reduces `messages`.\n await applyShapeTagSync({\n pg: tx,\n metadataSchema,\n shapeTable,\n messages: initialMessages,\n primaryKey: target.primaryKey,\n sessionScoped,\n });\n\n // ADR-0024: apply the move-in rows idempotently BEFORE the change fold, so a same-commit\n // update to a just-moved-in row lands on a present row. Upsert (not plain INSERT) because the\n // row may already be present via another grant or be re-delivered on a resume.\n if (moveInMessages.length > 0) {\n await applyUpsertsToTable({\n pg: tx,\n target,\n messages: moveInMessages,\n debug,\n });\n }\n\n if (!useInsert.get(shapeName)) {\n const initialInserts: InsertChangeMessage[] = [];\n const remainingMessages: ChangeMessage<Row<unknown>>[] = [];\n let foundNonInsert = false;\n for (const message of messages) {\n if (!foundNonInsert && message.headers.operation === \"insert\") {\n initialInserts.push(message as InsertChangeMessage);\n } else {\n foundNonInsert = true;\n remainingMessages.push(message);\n }\n }\n if (initialInserts.length > 0 && shapeMethod === \"copy\") {\n remainingMessages.unshift(initialInserts.pop()!);\n }\n messages = remainingMessages;\n\n if (initialInserts.length > 0) {\n await insertMethods[shapeMethod]({\n pg: tx,\n target,\n messages: initialInserts,\n debug,\n });\n\n useInsert.set(shapeName, true);\n }\n }\n\n // ADR-0014 Phase 3: fold this shape's drained batch to one net op per PK, then apply\n // three bulk statements in the order DELETE → INSERT → UPDATE. A re-created PK's delete\n // must precede its insert; every other PK lands in exactly one statement, so the rest of\n // the order is irrelevant within the (atomic) commit. The fold collapses same-PK runs, so\n // no bulk statement ever holds two rows for one PK — closing the `UPDATE … FROM` /\n // `json_to_recordset` join hazard (which would use one arbitrary matching row) by\n // construction. This replaces the previous one-SQL-statement-per-row steady-state loop.\n if (messages.length > 0) {\n const folded = foldChangeBatch(messages);\n\n if (folded.deletes.length > 0) {\n await applyBulkDeletesToTable({\n pg: tx,\n target,\n messages: folded.deletes,\n debug,\n });\n }\n if (folded.inserts.length > 0) {\n if (snapshotModeAtPeek.get(shapeName)) {\n // Snapshot-acceptance mode (post-reset re-snapshot / pre-first-lsn): the racing recovery\n // loops can re-deliver these exact snapshot rows, possibly in a later commit after this\n // shape's TRUNCATE flag has been consumed — so apply them idempotently (upsert), the same\n // posture as a move-in, rather than failing the commit on a PK collision.\n await applyUpsertsToTable({\n pg: tx,\n target,\n messages: folded.inserts,\n debug,\n });\n } else {\n await applyInsertsToTable({\n pg: tx,\n target,\n messages: folded.inserts,\n debug,\n });\n }\n }\n if (folded.updates.length > 0) {\n await applyBulkUpdatesToTable({\n pg: tx,\n target,\n messages: folded.updates,\n debug,\n });\n }\n }\n\n // ADR-0023: after the data + tag state is current, apply this shape's buffered move-outs —\n // withdraw the revoked tag and evict any row left with no tag (via the bulk-delete path, so\n // the reconcile trigger fires and the read model converges).\n const patternSets = moveOutsToCommit.get(shapeName);\n if (patternSets) {\n await applyShapeMoveOut({\n pg: tx,\n metadataSchema,\n shapeTable,\n target,\n patternSets,\n debug,\n sessionScoped,\n });\n }\n }\n\n if (key) {\n await updateSubscriptionState({\n pg: tx,\n metadataSchema,\n subscriptionKey: key,\n sessionScoped,\n shapeMetadata: Object.fromEntries(\n Object.keys(shapes).map((shapeName) => {\n const stream = getShapeStream(shapeName);\n return [\n shapeName,\n {\n handle: stream.shapeHandle!,\n offset: stream.lastOffset,\n },\n ];\n }),\n ),\n lastLsn: targetLsn,\n debug,\n });\n }\n\n // If we unsubscribed while this commit was in flight, discard it rather than persist\n // work during teardown. PGlite's `transaction()` skips its COMMIT once `tx.rollback()`\n // has closed the tx, so this rolls back both the applied rows and the subscription-state\n // advance; the (un-advanced) persisted offset means a later resume re-streams this batch.\n if (unsubscribed) {\n await tx.rollback();\n }\n });\n\n for (let attempt = 1; ; attempt++) {\n if (unsubscribed) {\n return false;\n }\n try {\n await runCommit();\n if (unsubscribed) {\n // The commit rolled itself back on unsubscribe (see runCommit); do not advance the\n // committed frontier, ACK the peeked buffer, or clear truncate flags for discarded work.\n return false;\n }\n committedLsn = targetLsn;\n // The transaction committed — now (and only now) remove the peeked batch from the inbox, passing\n // the peek-time epochs so a shape reset mid-commit is skipped (its rebuild survives). Move-outs/\n // move-ins are ACKed by the exact peeked count so anything that arrived during a coalescing\n // commit survives for the next run.\n inbox.ackUpTo(targetLsn, epochsAtPeek);\n for (const [shapeName, patternSets] of moveOutsToCommit) {\n inbox.ackMoveOuts(shapeName, patternSets.length, epochsAtPeek.get(shapeName) ?? inbox.epochFor(shapeName));\n }\n for (const [shapeName, moveInMessages] of moveInsToCommit) {\n inbox.ackMoveIns(\n shapeName,\n moveInMessages.length,\n epochsAtPeek.get(shapeName) ?? inbox.epochFor(shapeName),\n );\n }\n for (const shapeName of shapesToTruncate) {\n truncateNeeded.delete(shapeName);\n }\n if (debug) console.timeEnd(\"commit\");\n maybeSignalInitialSync();\n return true;\n } catch (error) {\n if (unsubscribed) {\n return false;\n }\n if (attempt >= maxCommitRetries) {\n degraded = true;\n onSyncError?.(error instanceof Error ? error : new Error(String(error)));\n return false;\n }\n await new Promise((resolve) => setTimeout(resolve, commitRetryDelayMs(attempt)));\n }\n }\n };\n\n const lowestCompleteLsn = (): Lsn => inbox.lowestCompleteLsn();\n\n // ─── Live-tail sibling nudge (ADR-0031 live-tail completion) ──────────────────────────────────────\n // The catch-up alignment (ADR-0031 in shape-inbox.ts) fixed this class of stall at BOOT: quiet shapes'\n // stale cached watermarks no longer hold a busy shape's backfill. On the LIVE tail the same shape holds\n // recur — a change batch lands on a busy shape at LSN L, but the group commits only at the min effective\n // frontier, so the batch stays buffered until every quiet sibling's PARKED long-poll returns a fresh\n // `global_last_seen_lsn` (~41s on Electric Cloud). This watchdog closes that live-tail gap: when a batch\n // is gated (its `batchMaxLsn > committedLsn`), it nudges each lagging sibling — aborting its parked poll\n // and forcing an immediate NON-live catch-up (`forceDisconnectAndRefresh`), which returns a fresh\n // watermark in ~sub-second. The group frontier then reaches L and the normal commit path (driven by the\n // up-to-date arrivals, NOT by this watchdog) fires. Atomicity is untouched: commits still happen only at\n // the group min frontier. The one-shot cache-buster (`nudgeBusters` + `withNudgeBuster`) defends each\n // nudged catch-up against a CDN HIT that would echo the stale watermark. Bounded to NUDGE_MAX_ROUNDS so a\n // genuinely-dead or still-legitimately-polling sibling degrades to the old wait-out-the-poll behavior\n // rather than a refresh storm.\n const nudgeInFlight = new Map<string, Promise<void>>();\n let nudgeTargetLsn: Lsn = BigInt(-1);\n let nudgeWatchdogRunning = false;\n\n // Void-called from the subscribe callback (never awaited — it must not backpressure the stream). Raises\n // the shared target and, if not already running, runs bounded rounds until the frontier reaches it, the\n // group tears down / degrades / re-closes its gate, or the rounds exhaust. Single-flight: a concurrent\n // gated batch just raises `nudgeTargetLsn` and returns. Wrapped so it can never throw unhandled.\n const runNudgeWatchdog = async (targetLsn: Lsn): Promise<void> => {\n if (targetLsn > nudgeTargetLsn) {\n nudgeTargetLsn = targetLsn;\n }\n if (nudgeWatchdogRunning) {\n return;\n }\n nudgeWatchdogRunning = true;\n try {\n // Pre-alignment (boot catch-up, before ADR-0031 lays the commit floors) the nudge is pure noise:\n // the alignment itself will commit the gated backfill the moment every shape reports, and firing\n // busted catch-ups mid-boot only contends with the boot requests. The floors survive later resets,\n // so this gate closes exactly once — the live tail is always past it.\n if (inbox.alignedFloor() < BigInt(0)) {\n return;\n }\n // Resolved / torn-down / gated-shut → nothing to nudge; the up-to-date arrival itself runs the\n // commit, so the watchdog never commits.\n const resolvedOrStopped = (): boolean =>\n unsubscribed || degraded || !dbGateOpen || lowestCompleteLsn() >= nudgeTargetLsn;\n\n // Hold-persistence grace: a cross-shape transaction's sibling halves arrive milliseconds apart,\n // so EVERY grouped commit passes through a transient held instant — nudging on it would abort\n // the sibling poll that is about to deliver the other half (the sync-e2e regression). Only a\n // hold that survives this grace is a real quiet-sibling park worth nudging.\n for (let waited = 0; waited < NUDGE_HOLD_GRACE_MS; waited += NUDGE_ROUND_GRACE_MS) {\n await new Promise((resolve) => setTimeout(resolve, NUDGE_ROUND_GRACE_MS));\n if (resolvedOrStopped()) {\n return;\n }\n }\n\n for (let round = 1; round <= NUDGE_MAX_ROUNDS; round++) {\n if (resolvedOrStopped()) {\n return;\n }\n for (const shapeName of Object.keys(shapes)) {\n // A shape still catching up advances on its own — only nudge one already in its live tail.\n if (!inbox.hasReportedUpToDate(shapeName)) continue;\n if (inbox.effectiveLsnFor(shapeName) >= nudgeTargetLsn) continue;\n if (nudgeInFlight.has(shapeName)) continue;\n // `forceDisconnectAndRefresh` is declared on the real ShapeStream, but a mocked/typed surface may\n // omit it — reach it structurally and skip (with a rail line) when absent.\n const stream = getShapeStream(shapeName) as { forceDisconnectAndRefresh?: () => Promise<void> };\n if (typeof stream.forceDisconnectAndRefresh !== \"function\") {\n syncDebug(\"live-tail sibling nudge unavailable\", { shape: shapeName });\n continue;\n }\n // Arm the one-shot cache-buster BEFORE the refresh so the forced catch-up carries it.\n nudgeBusters.set(shapeName, crypto.randomUUID());\n syncDebug(\"live-tail sibling nudge\", { shape: shapeName, target: String(nudgeTargetLsn), round });\n const refresh = stream\n .forceDisconnectAndRefresh()\n .catch((err: unknown) =>\n syncDebug(\"live-tail sibling nudge failed\", { shape: shapeName, error: String(err) }),\n )\n .finally(() => {\n nudgeInFlight.delete(shapeName);\n });\n nudgeInFlight.set(shapeName, refresh);\n }\n // Nothing to nudge and nothing in flight → exit QUIETLY (no exhaustion line). This is the routine\n // pre-alignment case: a gated batch during catch-up has siblings that have not yet reported\n // up-to-date, and those advance on their own — spinning the remaining rounds would only delay-loop\n // and print a misleading \"exhausted\" line on every boot rail. The \"held by group frontier\" line\n // already told the story.\n if (nudgeInFlight.size === 0) {\n return;\n }\n // Wait for this round's forced catch-ups to actually land and advance the frontier. The refresh\n // promises settle before the refreshed response does (measured), so awaiting them alone would\n // re-nudge into still-in-flight requests — poll the frontier instead, bounded per round, and\n // break out the moment the target is reached.\n await Promise.all([...nudgeInFlight.values()]);\n for (let waited = 0; waited < NUDGE_ROUND_WAIT_MS; waited += NUDGE_ROUND_GRACE_MS) {\n await new Promise((resolve) => setTimeout(resolve, NUDGE_ROUND_GRACE_MS));\n if (resolvedOrStopped()) {\n return;\n }\n }\n }\n // Rounds exhausted and the frontier is still short: a sibling is dead or genuinely mid-poll. Degrade\n // to the old behavior (wait out its live long-poll) rather than nudge forever.\n syncDebug(\"live-tail nudge exhausted; waiting on sibling live polls\", {\n target: String(nudgeTargetLsn),\n frontier: String(lowestCompleteLsn()),\n });\n } catch (err) {\n syncDebug(\"live-tail nudge watchdog error\", { error: String(err) });\n } finally {\n nudgeWatchdogRunning = false;\n }\n };\n\n // Drain buffered changes up to the current complete frontier, one commit at a time, looping\n // while fresh messages keep arriving (so commits coalesce). Returns early on `degraded` — a held\n // commit is not retried here; recovery is a later message/refetch or a restart.\n const runCommitLoop = async (): Promise<void> => {\n do {\n commitRerun = false;\n const target = lowestCompleteLsn();\n const isCommitNeeded = target > committedLsn;\n const isMustRefetchAndCatchingUp = target >= committedLsn && truncateNeeded.size > 0;\n // A buffered move-out (ADR-0023) or move-in (ADR-0024) must be committed even if no change\n // advanced the frontier — the revocation/grant has to land. Their `up-to-date` normally advances\n // `target`, but don't rely on that (move/event messages carry no LSN).\n const hasPendingMoves = target >= committedLsn && (inbox.hasPendingMoveOuts() || inbox.hasPendingMoveIns());\n // ADR-0031: a LATE-arriving change at or below an already-committed target must still commit. The\n // aligned commit floor lets `ingestChange` accept a change below the floor (its dedup frontier is\n // the raw `completeLsns`, unmoved by the floor), so such a change can land AFTER the group frontier\n // has already reached — or passed — its LSN, where no frontier advance would trigger a commit for\n // it. Committing at `target === committedLsn` is safe: it mirrors the moves path, which already\n // calls `commitUpToLsn(target)` with no frontier advance. (At `target > committedLsn` this overlaps\n // `isCommitNeeded` — harmless; the expression stays simple.)\n const hasLateArrivals = target >= committedLsn && inbox.hasBufferedChangesAtOrBelow(target);\n if (isCommitNeeded || isMustRefetchAndCatchingUp || hasPendingMoves || hasLateArrivals) {\n const applied = await commitUpToLsn(target);\n if (!applied) {\n return;\n }\n } else {\n maybeSignalInitialSync();\n }\n } while (commitRerun);\n };\n\n // Single-flight: at most one commit loop runs. A message arriving while one is running buffers\n // synchronously (above) and re-arms the loop via `commitRerun`; `commitInFlight` is cleared\n // inside the same async body — before its promise resolves — so an enqueue can never observe a\n // stale in-flight handle and resolve without committing its messages.\n const enqueueCommit = (): Promise<void> => {\n // ADR-0009 decision 5: once a commit exhausts its retries the engine latches `degraded` and\n // REFUSES to run any further commit. `commitUpToLsn` peeks (never drains) the buffer, so the\n // unapplied batch is still held; refusing later commits guarantees a newer LSN can never apply\n // over that held batch (the divergence the destructive drain allowed). The buffer keeps\n // accumulating incoming messages harmlessly; recovery is a restart/refetch, which re-streams the\n // held frontier because the persisted offset was never advanced. Note the commit-await backpressure\n // is intentionally absent while degraded — the inbox grows at the stream's rate until recovery,\n // which is the accepted cost of ADR-0009's documented \"hold the buffer\" posture.\n if (degraded) {\n return commitInFlight ?? Promise.resolve();\n }\n if (commitInFlight) {\n commitRerun = true;\n return commitInFlight;\n }\n commitInFlight = (async () => {\n try {\n await runCommitLoop();\n } finally {\n commitInFlight = null;\n }\n })();\n return commitInFlight;\n };\n\n multiShapeStream.subscribe(async (messages) => {\n if (unsubscribed) {\n return;\n }\n // A delivered batch means a fetch just succeeded — the read path is alive (ADR-0013 Phase 3),\n // so the runtime can clear an auth-needed status once a fresh token starts working again.\n onSyncActivity?.();\n if (debug) {\n console.log(\"received messages\", messages.length);\n }\n // Receive-path latency probe: a batch carrying real change rows is the moment Electric delivered\n // a write to this subscriber (the writer's own echo, or another browser's edit fanning in). The\n // gap from here to the commit finishing is the local apply cost.\n const changeCount = messages.reduce((n, message) => (isChangeMessage(message) ? n + 1 : n), 0);\n if (changeCount > 0) {\n syncDebug(\"sync received change batch from Electric\", { changes: changeCount });\n }\n // Boot observability (ADR-0034): one delivery = one shape-stream response. Records the fetch (network)\n // gap since the last settle plus this batch's request + change-row counts. No-op post-ready (frozen).\n bootStamp?.onBatchDelivered(changeCount);\n const commitStartedAt = typeof performance !== \"undefined\" ? performance.now() : Date.now();\n\n // The max LSN over the change rows this batch COMPLETED (routed to `ingestChange` with `isLastOfLsn`;\n // move-in rows carry no lsn and are excluded). It is what the batch needs the group frontier to reach\n // to actually commit — the truth test for the \"applied\" vs \"held\" rail line below. -1 if none.\n let batchMaxLsn: Lsn = BigInt(-1);\n\n messages.forEach((message) => {\n if (isChangeMessage(message)) {\n // A tagged-subquery MOVE-IN row (ADR-0024): an existing row ENTERING the shape because a grant\n // was added. Electric delivers it as a snapshot insert flagged `is_move_in` with NO `lsn`/`last`\n // (it is not a replication-stream change), so the `ingestChange` dedup — which floors a missing\n // lsn to 0 — would treat it as already-seen and drop it once the frontier passed 0. Route it to\n // its own buffer, applied idempotently at the next commit (the trailing `up-to-date`).\n if (message.headers[\"is_move_in\"] === true) {\n inbox.ingestMoveIn(message.shape, message);\n } else {\n const { lsn, isLastOfLsn } = readReplicationHeaders(message.headers);\n inbox.ingestChange(message.shape, message, lsn, isLastOfLsn);\n if (isLastOfLsn && lsn > batchMaxLsn) {\n batchMaxLsn = lsn;\n }\n }\n } else if (isControlMessage(message)) {\n switch (message.headers.control) {\n case \"up-to-date\": {\n if (debug) {\n console.log(\"received up-to-date\", message);\n }\n if (typeof message.headers.global_last_seen_lsn !== \"string\") {\n throw new Error(\"global_last_seen_lsn is not a string\");\n }\n // ADR-0031: `ingestUpToDate` returns true ONLY on the transition where this control message\n // completed the group (every shape has now reported up-to-date) and the inbox aligned the\n // commit floors. Surface that single moment on the debug rail so a \"stale board at load that\n // rearranges itself\" symptom is diagnosable — the floor it aligned to is the group head.\n if (inbox.ingestUpToDate(message.shape, BigInt(message.headers.global_last_seen_lsn))) {\n syncDebug(\"catch-up watermark aligned\", { floor: String(inbox.alignedFloor()) });\n }\n break;\n }\n case \"must-refetch\": {\n if (debug) {\n console.log(\"received must-refetch\", message);\n }\n // Surface the expired-handle / rewind event on the syncDebug rail too (the legacy `debug`\n // option only console.logs it): must-refetch is the trigger for the truncate + re-snapshot\n // recovery, so it must be visible when diagnosing a convergence loss in a live app.\n syncDebug(\"must-refetch received\", { shape: message.shape });\n inbox.resetShape(message.shape);\n truncateNeeded.add(message.shape);\n break;\n }\n }\n } else if (isEventMessage(message)) {\n // ADR-0023: a tagged-subquery move-out — a grant was revoked, so the rows it kept in the shape\n // must be evicted. Buffer the patterns; the eviction runs in the next commit (decision 3).\n // `MultiShapeStream`'s callback type does not declare `EventMessage` (the prior guards narrow\n // `message` to `never` here), so reach the runtime-present event through an explicit cast.\n const eventMessage = message as unknown as ShapeEventMessage;\n if (eventMessage.headers.event === \"move-out\") {\n if (debug) {\n console.log(\"received move-out\", eventMessage);\n }\n inbox.ingestMoveOut(eventMessage.shape, eventMessage.headers.patterns);\n }\n // A `move-in` EventMessage (ADR-0024) needs no action here: its newly-matched rows arrive in the\n // same batch as snapshot inserts flagged `is_move_in`, which the change branch routes to the\n // move-in buffer. The event's `patterns` are redundant with those inserts' `tags`.\n }\n });\n\n // Buffering above is synchronous. On the overlap path, while the commit gate is still closed the\n // batch stays in the memory inbox (its LSN frontier + catch-up watermarks still advance from the\n // ingest above) and the callback returns WITHOUT awaiting a commit — so the stream keeps fetching\n // catch-up and does not stall behind the local boot phases. Once the gate lifts, the deferred commit\n // train (below) drains everything buffered. On the sequential path the gate is already open, so this\n // is the unchanged path: enqueue the single-flight commit and await it (the natural backpressure that\n // bounds the buffer — replacing the old fire-and-forget commit + `setTimeout(0)` race).\n if (dbGateOpen) {\n const applyStartedAt = typeof performance !== \"undefined\" ? performance.now() : Date.now();\n await enqueueCommit();\n // Boot observability (ADR-0034): the apply (commit-into-PGlite) wall for this delivery.\n bootStamp?.onApply((typeof performance !== \"undefined\" ? performance.now() : Date.now()) - applyStartedAt);\n if (changeCount > 0) {\n // Truthful rail (ADR-0031): the \"applied\" line only fires when this batch's completed changes\n // actually landed (its `batchMaxLsn` is at or below the advanced `committedLsn`). Otherwise the\n // group frontier had not reached them — the batch is BUFFERED behind a quiet sibling's watermark —\n // so say so, and kick the live-tail sibling nudge to shorten that hold (void: never backpressure\n // the stream).\n if (batchMaxLsn <= committedLsn) {\n const elapsed = (typeof performance !== \"undefined\" ? performance.now() : Date.now()) - commitStartedAt;\n syncDebug(\"sync applied change batch to local store\", { changes: changeCount, ms: Math.round(elapsed) });\n } else {\n syncDebug(\"sync change batch held by group frontier\", {\n changes: changeCount,\n heldLsn: String(batchMaxLsn),\n frontier: String(lowestCompleteLsn()),\n });\n void runNudgeWatchdog(batchMaxLsn);\n }\n }\n }\n }, onError);\n\n // Fresh-store prefetch overlap (ADR-0032 S4): the moment the caller signals the local store is ready\n // (schema exec + journal recovery + store-version reconcile done), run the deferred metadata DDL, open\n // the commit gate, and drain everything the streams buffered during the window in one commit train. The\n // ADR-0031 catch-up watermarks were aligned by the ingests above as the up-to-dates arrived, so this\n // drain commits to the aligned floor and `onInitialSync` fires exactly as on the sequential path.\n if (overlap) {\n void dbReady!.then(async () => {\n if (unsubscribed) {\n return;\n }\n // The metadata tables' DDL was deferred past the gate (the store had no schema when the streams\n // started); create them now, before the first commit needs the subscription-state table.\n await initMetadataTables();\n dbGateOpen = true;\n syncDebug(\"boot commits opened\");\n // Boot observability (ADR-0034): on the overlap path the buffered catch-up drains here (not in a\n // subscribe callback), so stamp the drain's apply wall into the group's accumulator.\n const drainStartedAt = typeof performance !== \"undefined\" ? performance.now() : Date.now();\n await enqueueCommit();\n bootStamp?.onApply((typeof performance !== \"undefined\" ? performance.now() : Date.now()) - drainStartedAt);\n });\n }\n\n streams.push({\n stream: multiShapeStream,\n aborter,\n });\n\n const unsubscribe = () => {\n if (debug) {\n console.log(\"unsubscribing\");\n }\n unsubscribed = true;\n multiShapeStream.unsubscribeAll();\n aborter.abort();\n for (const shape of Object.values(shapes)) {\n shapePerTableLock.delete(shape.tableKey);\n }\n };\n\n return {\n unsubscribe,\n get isUpToDate() {\n // Never report up-to-date while a commit is pending or after going degraded (ADR-0009\n // decision 5): the read cache must not claim to match the server on an unapplied commit. Nor while\n // the overlap commit gate is still closed (ADR-0032 S4): the stream may already be `isUpToDate` on\n // the network side while its catch-up is still buffered, unapplied, in the memory inbox.\n return dbGateOpen && !degraded && commitInFlight === null && multiShapeStream.isUpToDate;\n },\n streams: Object.fromEntries(\n Object.keys(shapes).map((shapeName) => [shapeName, getShapeStream(shapeName)]),\n ) as SyncShapesToTablesResult[\"streams\"],\n };\n };\n\n const syncShapeToTable = async (options: SyncShapeToTableOptions): Promise<SyncShapeToTableResult> => {\n // ADR-0029 D6: thin sugar over the group form, forwarding the same entry-based options. The\n // per-shape `initialInsertMethod` (if any) rides through; the group form resolves the backfill\n // strategy from the registry entry when it is absent.\n const multiShapeSub = await syncShapesToTables({\n registry: options.registry,\n shapes: {\n shape: {\n shape: options.shape,\n tableKey: options.tableKey,\n onMustRefetch: options.onMustRefetch,\n ...(options.initialInsertMethod ? { initialInsertMethod: options.initialInsertMethod } : {}),\n },\n },\n key: options.shapeKey,\n ...(options.sessionScoped ? { sessionScoped: options.sessionScoped } : {}),\n onInitialSync: options.onInitialSync,\n onError: options.onError,\n onSyncError: options.onSyncError,\n maxCommitRetries: options.maxCommitRetries,\n commitRetryDelayMs: options.commitRetryDelayMs,\n });\n\n return {\n unsubscribe: multiShapeSub.unsubscribe,\n get isUpToDate() {\n return multiShapeSub.isUpToDate;\n },\n stream: (() => {\n const stream = multiShapeSub.streams[\"shape\"];\n if (!stream) {\n throw new Error(\"Missing stream for shape\");\n }\n return stream;\n })() as SyncShapeToTableResult[\"stream\"],\n };\n };\n\n const deleteSubscription = async (key: string) => {\n // ADR-0042: the scope-blind delete now also touches `pg_temp.subscriptions_metadata`, which does NOT\n // exist until the (per-engine, memoized) metadata migration has run — so a warm-store reset that fires\n // before any group started (nothing else triggered `initMetadataTables` yet) would hit 42P01. Ensure the\n // provisioning first; the promise is memoized/idempotent, so on the normal path (a group already\n // started) this is a no-op await on the resolved init promise.\n await initMetadataTables();\n await deleteSubscriptionState({\n pg,\n metadataSchema,\n subscriptionKey: key,\n });\n };\n\n const namespaceObj = {\n initMetadataTables,\n syncShapesToTables,\n syncShapeToTable,\n deleteSubscription,\n };\n\n const close = async () => {\n for (const { stream, aborter } of streams) {\n stream.unsubscribeAll();\n aborter.abort();\n }\n };\n\n return {\n namespace: namespaceObj,\n close,\n };\n}\n\n/**\n * The pgxsinkit sync engine handle: the {@link SyncNamespaceObj} the client attaches as `pg.electric`,\n * plus the explicit `close()` teardown. Derived from {@link createSyncEngine}'s real return so the type\n * follows the object.\n */\nexport type SyncEngine = Awaited<ReturnType<typeof createSyncEngine>>;\nexport type SyncNamespaceObj = SyncEngine[\"namespace\"];\n\nexport type PGliteWithSync = PGliteInterface & {\n sync: SyncNamespaceObj;\n};\n",
|
|
29
30
|
"// Live-tail sibling nudge (ADR-0031 live-tail completion). The engine commits a consistency group\n// atomically at the group's lowest effective frontier (the MIN over per-shape `max(rawFrontier,\n// commitFloor)`; see shape-inbox.ts). On the LIVE tail, when a change batch arrives on a busy shape at\n// LSN L, a quiet sibling shape's frontier only advances when its parked long-poll returns — up to ~41s on\n// Electric Cloud — so the busy shape's batch stays buffered, unapplied, for that whole hold. The nudge\n// aborts those parked polls and forces an immediate NON-live catch-up on each lagging sibling, which\n// returns a fresh `global_last_seen_lsn` in ~sub-second; the group frontier then reaches L and the batch\n// commits. Commit atomicity is untouched — commits still fire only at the group min frontier — this only\n// shortens how long a gated batch waits for its siblings' watermarks.\n//\n// This module holds the two pieces that are pure and side-effect-free (so a plain unit test can exercise\n// them without dragging PGlite/Electric in through the engine module): the bounded-round constants and the\n// one-shot cache-buster fetch wrapper. The stateful, per-group watchdog itself lives in the engine's\n// per-group scope (index.ts), where it can read the inbox frontiers and reach the live shape streams.\n\n/**\n * How long a hold must PERSIST before the first nudge round fires. A cross-shape transaction's halves\n * arrive milliseconds apart even on a healthy stack, so every grouped commit passes through a\n * transient \"held\" instant — nudging on it immediately ABORTS the sibling's long-poll that was about\n * to deliver the other half, turning a millisecond hold into an abort/refetch disruption loop\n * (regression caught by the sync-e2e integration lane on local Electric). A hold that outlives this\n * grace is the real thing: a quiet sibling parked in a multi-second poll. On Electric Cloud this adds\n * ~1s to a path that saves ~40s; on local stacks it means the nudge simply never fires.\n */\nexport const NUDGE_HOLD_GRACE_MS = 1_000;\n\n/**\n * Max nudge rounds before a dead / genuinely-still-polling sibling degrades back to the old behavior\n * (wait out its live long-poll) instead of being nudged forever — so a stuck sibling never becomes a\n * refresh storm.\n */\nexport const NUDGE_MAX_ROUNDS = 3;\n\n/**\n * Polling step while waiting for a nudge round's forced catch-ups to advance the group frontier. The\n * `forceDisconnectAndRefresh()` promise settles BEFORE the refreshed catch-up response lands (field\n * measurement: round 2 fired ~750ms into round 1's still-in-flight requests when the wait keyed off that\n * promise alone), so the watchdog instead polls the frontier at this step, up to\n * {@link NUDGE_ROUND_WAIT_MS} per round, breaking out the moment the target is reached.\n */\nexport const NUDGE_ROUND_GRACE_MS = 100;\n\n/**\n * Max wait per nudge round for the forced catch-ups to return and advance the frontier. A nudged\n * catch-up measures ~0.9–1.4s through a warm deployed edge proxy but >3.5s against a cold one — and\n * a next round's refresh ABORTS a still-in-flight round (the abort-and-reconnect is the mechanism),\n * so an early re-nudge throws away an almost-done response. The wait therefore covers the cold-edge\n * tail; worst case to exhaustion stays NUDGE_MAX_ROUNDS × this ≈ 12s, still far under a ~41s hold.\n */\nexport const NUDGE_ROUND_WAIT_MS = 4_000;\n\n/** The request URL of a `fetch` first argument, in any of its accepted forms; undefined if unreadable. */\nfunction requestUrl(input: Parameters<typeof fetch>[0]): string | undefined {\n if (typeof input === \"string\") return input;\n if (input instanceof URL) return input.toString();\n if (typeof input === \"object\" && input !== null && \"url\" in input) {\n return (input as { url: string }).url;\n }\n return undefined;\n}\n\n/**\n * Wrap a `fetchClient` so a pending one-shot nudge token defeats the CDN on the nudged sibling's catch-up.\n *\n * A nudge's `forceDisconnectAndRefresh` issues a NON-live catch-up (Electric sets `canLongPoll: false`),\n * which is CDN-cacheable — a HIT would return the SAME stale watermark that made the sibling lag, defeating\n * the nudge. So the watchdog drops a per-shape token into `nudgeBusters` just before it nudges; this wrapper\n * consumes that token on the sibling's next NON-live request, appending `cache-buster=<token>` to force a\n * CDN miss. It is one-shot (the token is deleted on use) and skips LIVE (`live=true`) long-polls — the token\n * is meant for the catch-up that follows the aborted poll, not the poll itself, which is left to be retained\n * for that catch-up. An already-present `cache-buster` param is overwritten. When no token is pending this is\n * a straight passthrough, so the off-path pays only this closure.\n *\n * Exported for unit testing; composed in the engine as the OUTER wrapper around `instrumentShapeFetch`, so\n * the buster stamps the URL BEFORE instrumentation logs it (the debug rail then shows `BUSTED`).\n */\nexport function withNudgeBuster(\n fetchClient: typeof fetch,\n nudgeBusters: Map<string, string>,\n shapeName: string,\n): typeof fetch {\n const wrapped = (input: Parameters<typeof fetch>[0], init?: Parameters<typeof fetch>[1]): Promise<Response> => {\n const token = nudgeBusters.get(shapeName);\n if (token === undefined) {\n return fetchClient(input, init);\n }\n const raw = requestUrl(input);\n if (raw === undefined) {\n return fetchClient(input, init);\n }\n const url = new URL(raw);\n // A live long-poll is the parked request the nudge aborts, not the catch-up that carries the fresh\n // watermark — leave it (and the token) untouched so the token lands on the following catch-up.\n if (url.searchParams.get(\"live\") === \"true\") {\n return fetchClient(input, init);\n }\n // One-shot: consume the token and stamp this catch-up URL (set overwrites any existing param).\n nudgeBusters.delete(shapeName);\n url.searchParams.set(\"cache-buster\", token);\n const busted = url.toString();\n if (typeof input === \"string\" || input instanceof URL) {\n return fetchClient(busted, init);\n }\n // A Request carries method/headers/body that must survive the URL swap — rebuild from it.\n return fetchClient(new Request(busted, input), init);\n };\n // `typeof fetch` (Bun's global) carries a `preconnect` member the wrapper neither has nor needs — the\n // ShapeStream only ever invokes fetchClient as a plain fetch — so the shape-compatible cast is safe.\n return wrapped as typeof fetch;\n}\n",
|
|
30
31
|
"import type { ChangeMessage, MovePattern, Row } from \"@electric-sql/client\";\n\nimport type { InsertChangeMessage, Lsn } from \"./types\";\n\n/**\n * The Shape inbox (ADR-0014 / ISS-06): the pure, in-memory staging buffer between a shape's\n * Electric subscription and the Sync applier. It buffers each shape's change messages keyed by\n * LSN, tracks each shape's complete-LSN frontier, and drains everything up to a target LSN for the\n * applier to write. No database I/O lives here — that is exactly what makes it (and the ADR-0014\n * per-PK fold that will live here) property-testable against an ordered per-row apply oracle.\n *\n * One inbox owns all shapes in a consistency group; the group commits atomically at the lowest\n * complete frontier across its shapes ({@link lowestCompleteLsn}). `must-refetch` truncation stays\n * with the applier (the inbox only drops the affected shape's buffer via {@link resetShape}).\n *\n * COMMIT WATERMARK vs DEDUP FRONTIER (ADR-0031) — the load-bearing separation. Two per-shape LSNs live\n * here and they are deliberately NOT the same number:\n *\n * - {@link completeLsns} — the SOLE dedup threshold. {@link ingestChange} drops any change at or below\n * it as already-seen. Nothing else may narrow what the inbox accepts; a change below a shape's floor\n * (below) but above its raw frontier is still buffered, never dropped.\n * - {@link commitFloors} — a per-shape COMMIT watermark laid down once per catch-up completion (see\n * {@link ingestUpToDate}'s alignment). It only ever RAISES a shape's effective commit frontier in\n * {@link lowestCompleteLsn}; it never gates ingestion.\n *\n * Why the two must be separate: Electric's catch-up (non-live) shape responses are CDN-cacheable\n * (`s-maxage`, `stale-while-revalidate`), and the `up-to-date` control message — with its\n * `global_last_seen_lsn` watermark — rides INSIDE that cached body. So a quiet shape's cached catch-up\n * can assert a STALE watermark (captured before a busy sibling shape's newer writes), which drags the\n * group min-frontier below changes already delivered on the busy shape, holding them buffered until the\n * quiet shape's first LIVE long-poll returns a fresh watermark (~tens of seconds on Electric Cloud). The\n * alignment lifts the commit floors to the freshest ASSERTED global head so those changes commit at\n * catch-up completion — while the dedup frontier stays put, so a late sub-floor change from a shape whose\n * cached catch-up omitted it is still ingested and committed rather than dropped.\n */\nexport class ShapeInbox {\n // Per shape: buffered change messages keyed by their LSN, kept in arrival order within an LSN.\n private readonly changes = new Map<string, Map<Lsn, ChangeMessage<Row<unknown>>[]>>();\n // Per shape: the highest LSN known complete (every change at or below it has been received).\n private readonly completeLsns = new Map<string, Lsn>();\n // Per shape: buffered `move-out` events (ADR-0023), one pattern set per event. The event carries no\n // LSN, so it cannot key `changes`; it is drained and applied at the next commit (the `up-to-date`\n // that follows it), in the same transaction as that frontier's changes.\n private readonly moveOuts = new Map<string, MovePattern[][]>();\n // Per shape: buffered `move-in` snapshot rows (ADR-0024). A move-in row (`is_move_in`) is a row\n // ENTERING the shape; Electric delivers it as a snapshot insert with NO `lsn`/`last`, so it cannot\n // key `changes` either (and the change dedup, which floors a missing lsn to 0, would drop it once the\n // frontier passed 0). Drained and applied — idempotently — at the next commit, like the move-outs.\n private readonly moveIns = new Map<string, ChangeMessage<Row<unknown>>[]>();\n // Per shape: a reset epoch, bumped every time {@link resetShape} rewinds a shape (must-refetch). The\n // commit path records each shape's epoch at PEEK time and passes it back to the acks; an ack no-ops for\n // any shape whose epoch has since changed. This closes the mid-commit-reset hole: if a must-refetch +\n // re-snapshot arrives for shape B WHILE a commit that peeked B is in flight, B's frontier is rewound and\n // its buffers replaced with post-reset content; without the epoch guard the succeeding commit's\n // `ackUpTo`/`ackMove*` would delete/splice that never-peeked post-reset content, leaving B truncated-empty.\n private readonly epochs = new Map<string, number>();\n // Per shape: whether a snapshot (LSN-0) row is currently accepted PAST the dedup frontier. Set on\n // registration and every {@link resetShape} (must-refetch); re-armed (cleared) the first time a change\n // with a REAL lsn (> 0) is ingested for the shape. Invariant: after a reset — and on a brand-new shape\n // before any real replication LSN has been seen — a re-snapshot's rows are floored to LSN 0, yet the\n // frontier may already sit at a large LSN (a racing bare `up-to-date` advanced it before the rows\n // landed). The LSN-0 dedup ({@link ingestChange}) would then drop the whole re-snapshot. So while this\n // flag is set, LSN-0 rows bypass the dedup; the first real lsn (> 0) proves the stream has moved past\n // the snapshot into the live tail, and re-arms the dedup. The re-snapshot's rows reaching the applier\n // is what keeps the reconcile loop — the completeness guarantee (ADR-0029 D4) — whole.\n private readonly snapshotAccepted = new Map<string, boolean>();\n // Per shape: whether this shape has reported `up-to-date` at least once since registration / its last\n // {@link resetShape}. Set true in {@link ingestUpToDate} even when the reported watermark does NOT\n // advance the frontier (a stale cached watermark still means \"this shape has completed a catch-up and\n // asserted a global head\"). The catch-up alignment (ADR-0031) fires only once EVERY shape in the group\n // has reported up-to-date — i.e. once the whole group has a first asserted global head to align to.\n private readonly upToDateSeen = new Map<string, boolean>();\n // Per shape: the watermark (`global_last_seen_lsn`) this shape MOST RECENTLY reported via\n // {@link ingestUpToDate}, recorded unconditionally — even a stale cached watermark that does not\n // advance {@link completeLsns}. This is the input to the group-max alignment: the freshest asserted\n // global head across the group is `max` over these REPORTED watermarks (NOT over the frontiers — a\n // frontier can sit ahead of every reported watermark mid-live-batch; see {@link ingestUpToDate}).\n private readonly lastUpToDateLsn = new Map<string, Lsn>();\n // Per shape: the COMMIT floor (ADR-0031) — a watermark that only ever RAISES this shape's effective\n // commit frontier in {@link lowestCompleteLsn}, never its dedup threshold. Laid down once per catch-up\n // completion by the alignment in {@link ingestUpToDate}. Deliberately NOT reset by {@link resetShape}:\n // floors are monotonic, so a reset shape keeps its old floor (its buffer is empty anyway) until the\n // next group-wide realignment lifts it. Default -1 = no floor.\n private readonly commitFloors = new Map<string, Lsn>();\n // Whether the one-time catch-up commit-floor alignment (ADR-0031) has already run for the current\n // registration/reset generation. False at construction; set true when the alignment lays down floors in\n // {@link ingestUpToDate}; reset to false by {@link resetShape} so a must-refetch re-catch-up realigns\n // the group once every shape has completed again (a reset shape re-streams a fresh — possibly cached —\n // catch-up, so the group needs a fresh asserted global head to align to).\n private aligned = false;\n // The freshest asserted global head the last alignment aligned to (`max` over reported watermarks) —\n // surfaced on the debug rail by the caller as the `floor` of the `catch-up watermark aligned` line.\n private lastAlignedFloor: Lsn = BigInt(-1);\n\n constructor(shapeNames: Iterable<string>) {\n for (const shapeName of shapeNames) {\n this.changes.set(shapeName, new Map());\n this.completeLsns.set(shapeName, BigInt(-1));\n this.moveOuts.set(shapeName, []);\n this.moveIns.set(shapeName, []);\n this.epochs.set(shapeName, 0);\n this.snapshotAccepted.set(shapeName, true);\n this.upToDateSeen.set(shapeName, false);\n this.lastUpToDateLsn.set(shapeName, BigInt(-1));\n this.commitFloors.set(shapeName, BigInt(-1));\n }\n }\n\n /**\n * Whether the shape is still accepting snapshot (LSN-0) rows past the dedup frontier — true from\n * registration / the last {@link resetShape} until the first real-lsn change re-armed the dedup. The\n * commit path reads this to apply such rows idempotently (the racing recovery loops can double-deliver\n * them), consistent with the move-in upsert path, rather than as a plain collision-surfacing insert.\n */\n acceptsSnapshotRowsFor(shapeName: string): boolean {\n return this.snapshotAccepted.get(shapeName) === true;\n }\n\n /** The complete-LSN frontier for one shape (the already-seen dedup threshold). */\n completeLsnFor(shapeName: string): Lsn {\n return this.completeLsns.get(shapeName) ?? BigInt(-1);\n }\n\n /**\n * The shape's current reset epoch. The commit path snapshots this for every peeked shape and passes it\n * back to the acks, which no-op for any shape whose epoch changed (a mid-commit {@link resetShape}) so\n * the reset's own truncate+rebuild path owns that shape's post-reset state.\n */\n epochFor(shapeName: string): number {\n return this.epochs.get(shapeName) ?? 0;\n }\n\n /**\n * Buffer a change message. A message at or below the shape's current complete frontier is\n * already-seen and dropped. `isLastOfLsn` advances the frontier to this LSN.\n */\n ingestChange(shapeName: string, message: ChangeMessage<Row<unknown>>, lsn: Lsn, isLastOfLsn: boolean): void {\n // A real replication lsn (> 0) proves the stream has moved past the snapshot into the live tail:\n // re-arm the LSN-0 dedup for this shape (see {@link snapshotAccepted}).\n if (lsn > BigInt(0)) {\n this.snapshotAccepted.set(shapeName, false);\n }\n // A snapshot (LSN-0) row while snapshot acceptance is open bypasses the dedup even if the frontier\n // has advanced past 0 — otherwise a re-snapshot delivered AFTER a racing `up-to-date` (which pushed\n // the frontier to a large LSN) would be dropped wholesale, truncating the shape to empty. It still\n // buffers at LSN 0 (and does not advance the frontier), so drains/acks/truncate are unchanged.\n const acceptSnapshotRow = lsn === BigInt(0) && this.acceptsSnapshotRowsFor(shapeName);\n if (!acceptSnapshotRow && lsn <= this.completeLsnFor(shapeName)) {\n return;\n }\n\n const shapeChanges = this.changes.get(shapeName);\n if (!shapeChanges) {\n return;\n }\n\n let lsnMessages = shapeChanges.get(lsn);\n if (!lsnMessages) {\n lsnMessages = [];\n shapeChanges.set(lsn, lsnMessages);\n }\n lsnMessages.push(message);\n\n if (isLastOfLsn) {\n this.completeLsns.set(shapeName, lsn);\n }\n }\n\n /** The commit floor (ADR-0031) for one shape — the aligned watermark; -1 when no floor has been laid. */\n commitFloorFor(shapeName: string): Lsn {\n return this.commitFloors.get(shapeName) ?? BigInt(-1);\n }\n\n /**\n * A shape's EFFECTIVE complete frontier (ADR-0031): `max(completeLsnFor(shape), commitFloorFor(shape))` —\n * the raw dedup frontier raised by any aligned commit floor. This is the exact per-shape quantity\n * {@link lowestCompleteLsn} minimizes over (both go through here, so the two definitions cannot drift),\n * and the input the live-tail sibling nudge reads to decide which siblings still lag a target LSN.\n */\n effectiveLsnFor(shapeName: string): Lsn {\n const raw = this.completeLsnFor(shapeName);\n const floor = this.commitFloorFor(shapeName);\n return raw > floor ? raw : floor;\n }\n\n /**\n * Whether this shape has reported `up-to-date` at least once since registration / its last\n * {@link resetShape} — the {@link upToDateSeen} flag. The live-tail sibling nudge (ADR-0031) reads this:\n * a shape still catching up advances on its own, so only a shape already in its live tail is ever nudged.\n */\n hasReportedUpToDate(shapeName: string): boolean {\n return this.upToDateSeen.get(shapeName) === true;\n }\n\n /** The freshest asserted global head the last catch-up alignment aligned to (ADR-0031); -1 if never aligned. */\n alignedFloor(): Lsn {\n return this.lastAlignedFloor;\n }\n\n /**\n * Advance the frontier on an `up-to-date` control message (carries no buffered change) AND run the\n * one-time catch-up commit-floor alignment (ADR-0031) once the whole group has reported up-to-date.\n *\n * Returns `true` iff THIS call performed the alignment (the caller emits a single diagnostic line on\n * that transition); `false` on every other call.\n */\n ingestUpToDate(shapeName: string, globalLastSeenLsn: Lsn): boolean {\n // Record the report unconditionally: this shape has now completed a catch-up and asserted a global\n // head, and this is the watermark to align to — even if it is stale (below the frontier) and so does\n // NOT advance the dedup frontier below. Both facts feed the alignment; neither is the frontier.\n this.upToDateSeen.set(shapeName, true);\n this.lastUpToDateLsn.set(shapeName, globalLastSeenLsn);\n\n // The existing conditional frontier advance is UNCHANGED: a watermark only advances the dedup frontier\n // when it is strictly ahead of it. A stale cached watermark leaves the frontier where it was.\n if (globalLastSeenLsn > this.completeLsnFor(shapeName)) {\n this.completeLsns.set(shapeName, globalLastSeenLsn);\n }\n\n // Catch-up commit-floor alignment (ADR-0031), one-time per registration/reset generation: once EVERY\n // shape in the group has reported up-to-date, lift each shape's commit floor to the freshest asserted\n // global head. That is `max` over the REPORTED watermarks ({@link lastUpToDateLsn}) — deliberately NOT\n // over the frontiers ({@link completeLsns}). A frontier can be ahead of every reported watermark when a\n // live change batch is in flight and its sibling shapes' halves have not arrived yet; aligning floors\n // to such a frontier would commit one shape's half of a cross-shape transaction ahead of the other's\n // (a torn write). The freshest asserted global head is a watermark every shape has been told is\n // complete, so aligning to it can never tear a transaction that is still assembling above it.\n if (!this.aligned) {\n let everySeen = true;\n for (const seen of this.upToDateSeen.values()) {\n if (!seen) {\n everySeen = false;\n break;\n }\n }\n if (everySeen) {\n let groupMax: Lsn = BigInt(-1);\n for (const reported of this.lastUpToDateLsn.values()) {\n if (reported > groupMax) {\n groupMax = reported;\n }\n }\n for (const shape of this.commitFloors.keys()) {\n const existing = this.commitFloorFor(shape);\n this.commitFloors.set(shape, groupMax > existing ? groupMax : existing);\n }\n this.aligned = true;\n this.lastAlignedFloor = groupMax;\n return true;\n }\n }\n return false;\n }\n\n /** Buffer a `move-out` event's patterns for a shape (ADR-0023); applied at the next commit. */\n ingestMoveOut(shapeName: string, patterns: MovePattern[]): void {\n this.moveOuts.get(shapeName)?.push(patterns);\n }\n\n /** Remove and return a shape's buffered `move-out` pattern sets (one per event), in arrival order. */\n drainMoveOuts(shapeName: string): MovePattern[][] {\n const pending = this.moveOuts.get(shapeName) ?? [];\n this.moveOuts.set(shapeName, []);\n return pending;\n }\n\n /**\n * Peek — WITHOUT removing — a shape's buffered `move-out` pattern sets (a copy, arrival order). Pairs\n * with {@link ackMoveOuts}: the commit path peeks, applies inside its transaction, and acks (removes)\n * only after the transaction succeeds — so a failed/degraded commit (ADR-0009 decision 5) leaves the\n * revocations buffered rather than silently losing them.\n */\n peekMoveOuts(shapeName: string): MovePattern[][] {\n return [...(this.moveOuts.get(shapeName) ?? [])];\n }\n\n /**\n * Remove the first `count` buffered `move-out` pattern sets for a shape (call only after the commit\n * that consumed a matching {@link peekMoveOuts} of that many entries succeeded). Removing exactly the\n * peeked count — not clear-all — keeps any move-out that arrived DURING the commit (coalescing path)\n * buffered for the next run. `epochAtPeek` is the shape's {@link epochFor} captured at peek time: if a\n * {@link resetShape} bumped it since, the peeked entries no longer exist (the array was replaced), so\n * this no-ops rather than splicing the post-reset replacement.\n */\n ackMoveOuts(shapeName: string, count: number, epochAtPeek: number): void {\n if (this.epochFor(shapeName) !== epochAtPeek) {\n return;\n }\n this.moveOuts.get(shapeName)?.splice(0, count);\n }\n\n /** Whether any shape has a buffered `move-out` awaiting a commit. */\n hasPendingMoveOuts(): boolean {\n for (const pending of this.moveOuts.values()) {\n if (pending.length > 0) return true;\n }\n return false;\n }\n\n /** Buffer a `move-in` snapshot row for a shape (ADR-0024); applied idempotently at the next commit. */\n ingestMoveIn(shapeName: string, message: ChangeMessage<Row<unknown>>): void {\n this.moveIns.get(shapeName)?.push(message);\n }\n\n /** Remove and return a shape's buffered `move-in` snapshot rows, in arrival order. */\n drainMoveIns(shapeName: string): ChangeMessage<Row<unknown>>[] {\n const pending = this.moveIns.get(shapeName) ?? [];\n this.moveIns.set(shapeName, []);\n return pending;\n }\n\n /** Peek — WITHOUT removing — a shape's buffered `move-in` snapshot rows (a copy, arrival order). See {@link peekMoveOuts}. */\n peekMoveIns(shapeName: string): ChangeMessage<Row<unknown>>[] {\n return [...(this.moveIns.get(shapeName) ?? [])];\n }\n\n /**\n * Remove the first `count` buffered `move-in` snapshot rows for a shape (post-commit ack; see\n * {@link ackMoveOuts}). No-ops if `epochAtPeek` no longer matches the shape's current epoch (a\n * mid-commit {@link resetShape}), so the post-reset replacement rows survive.\n */\n ackMoveIns(shapeName: string, count: number, epochAtPeek: number): void {\n if (this.epochFor(shapeName) !== epochAtPeek) {\n return;\n }\n this.moveIns.get(shapeName)?.splice(0, count);\n }\n\n /** Whether any shape has a buffered `move-in` awaiting a commit. */\n hasPendingMoveIns(): boolean {\n for (const pending of this.moveIns.values()) {\n if (pending.length > 0) return true;\n }\n return false;\n }\n\n /** Reset a shape on `must-refetch`: drop its buffer and rewind its frontier (the applier truncates). */\n resetShape(shapeName: string): void {\n this.changes.get(shapeName)?.clear();\n this.completeLsns.set(shapeName, BigInt(-1));\n this.moveOuts.set(shapeName, []);\n this.moveIns.set(shapeName, []);\n // Re-open snapshot acceptance: the re-snapshot's LSN-0 rows must survive the dedup even if a racing\n // `up-to-date` advances the rewound frontier again before they arrive (see {@link snapshotAccepted}).\n this.snapshotAccepted.set(shapeName, true);\n // ADR-0031: this shape must re-report up-to-date before it counts toward the group again, and its\n // last reported watermark is void (it re-streams a fresh — possibly cached — catch-up). Clear the\n // group's aligned flag so the whole group realigns once every shape has completed again. The commit\n // floor is NOT cleared: floors are monotonic (the buffer is empty post-reset anyway), so the shape\n // keeps its old floor until realignment lifts it.\n this.upToDateSeen.set(shapeName, false);\n this.lastUpToDateLsn.set(shapeName, BigInt(-1));\n this.aligned = false;\n // Bump the epoch so any in-flight commit that peeked this shape BEFORE the reset skips its acks — the\n // post-reset buffers just installed above must survive to be committed on the follow-up pass.\n this.epochs.set(shapeName, this.epochFor(shapeName) + 1);\n }\n\n /**\n * The lowest EFFECTIVE complete frontier across all shapes — the atomic group commit target. A shape's\n * effective frontier is `max(completeLsnFor(shape), commitFloorFor(shape))` (ADR-0031): the raw dedup\n * frontier, raised by any aligned commit floor. Aligning the floors up to the freshest asserted global\n * head lets a group whose quiet shapes reported a STALE cached catch-up watermark still commit a busy\n * shape's delivered changes at catch-up completion, instead of holding them until the quiet shapes'\n * first live long-poll. The floor never narrows what {@link ingestChange} accepts (that remains the raw\n * {@link completeLsns}), so a late sub-floor change is still ingested and then committed.\n */\n lowestCompleteLsn(): Lsn {\n let minimum: Lsn | null = null;\n for (const shapeName of this.completeLsns.keys()) {\n const effective = this.effectiveLsnFor(shapeName);\n if (minimum === null || effective < minimum) {\n minimum = effective;\n }\n }\n return minimum ?? BigInt(-1);\n }\n\n /**\n * Whether any shape has a buffered change entry at an LSN at or below `targetLsn` (ADR-0031). The commit\n * loop uses this to fire a commit for a LATE-arriving change that lands at or below an already-committed\n * target — possible exactly because the aligned commit floor lets {@link ingestChange} accept a change\n * below the floor while the group frontier already sits at (or above) it, so no new frontier advance\n * would otherwise trigger a commit for it.\n */\n hasBufferedChangesAtOrBelow(targetLsn: Lsn): boolean {\n for (const shapeChanges of this.changes.values()) {\n for (const lsn of shapeChanges.keys()) {\n if (lsn <= targetLsn) {\n return true;\n }\n }\n }\n return false;\n }\n\n /**\n * Peek — WITHOUT removing — every buffered change at or below `targetLsn`, per shape, in buffered-LSN\n * order. The returned map has an entry for every shape (an empty array where nothing peeked). Pairs\n * with {@link ackUpTo}: the commit path peeks, writes the batch inside its transaction, and acks\n * (removes) only after the transaction succeeds — so a failed/degraded commit (ADR-0009 decision 5)\n * holds the batch in the buffer rather than dropping it, and a newer LSN can never land over it.\n */\n peekUpTo(targetLsn: Lsn): Map<string, ChangeMessage<Row<unknown>>[]> {\n const peeked = new Map<string, ChangeMessage<Row<unknown>>[]>();\n\n for (const [shapeName, shapeChanges] of this.changes.entries()) {\n const messages: ChangeMessage<Row<unknown>>[] = [];\n for (const lsn of [...shapeChanges.keys()]) {\n if (lsn <= targetLsn) {\n for (const message of shapeChanges.get(lsn)!) {\n messages.push(message);\n }\n }\n }\n peeked.set(shapeName, messages);\n }\n\n return peeked;\n }\n\n /**\n * Remove every buffered change at or below `targetLsn` (call only after the commit that consumed a\n * matching {@link peekUpTo} succeeded). `epochsAtPeek` maps each shape to its {@link epochFor} captured\n * at peek time; a shape whose epoch has since changed is **skipped entirely**.\n *\n * The epoch guard is load-bearing under a frontier REWIND. In the steady state, the frontier only\n * advances, so nothing new at or below `targetLsn` can be buffered between peek and ack. But a mid-commit\n * {@link resetShape} (must-refetch) rewinds a shape's frontier to -1 and lets its re-snapshot buffer at\n * LSN 0 — content that was NOT in this commit's peek. Deleting it here (LSN 0 ≤ `targetLsn`) would drop\n * the rebuild; the epoch bump makes this no-op for that shape so the reset's own rebuild path owns it.\n */\n ackUpTo(targetLsn: Lsn, epochsAtPeek: Map<string, number>): void {\n for (const [shapeName, shapeChanges] of this.changes.entries()) {\n const peekEpoch = epochsAtPeek.get(shapeName);\n if (peekEpoch !== undefined && this.epochFor(shapeName) !== peekEpoch) {\n continue;\n }\n for (const lsn of [...shapeChanges.keys()]) {\n if (lsn <= targetLsn) {\n shapeChanges.delete(lsn);\n }\n }\n }\n }\n\n /** Snapshot every shape's current {@link epochFor} — captured at peek time and passed to the acks. */\n snapshotEpochs(): Map<string, number> {\n return new Map([...this.epochs.keys()].map((shapeName) => [shapeName, this.epochFor(shapeName)]));\n }\n\n /**\n * Remove and return every buffered change at or below `targetLsn`, per shape, in buffered-LSN order\n * ({@link peekUpTo} then {@link ackUpTo}). The returned map has an entry for every shape (an empty\n * array where nothing drained).\n */\n drainUpTo(targetLsn: Lsn): Map<string, ChangeMessage<Row<unknown>>[]> {\n const epochsAtPeek = this.snapshotEpochs();\n const drained = this.peekUpTo(targetLsn);\n this.ackUpTo(targetLsn, epochsAtPeek);\n return drained;\n }\n}\n\ntype Operation = \"insert\" | \"update\" | \"delete\";\n\n/**\n * A drained shape batch folded to **one net operation per primary key** (ADR-0014 decision 1).\n * Each PK appears in at most one of `inserts`/`updates`, and at most once in `deletes` — except a\n * *re-created* PK (`[delete, insert]`), which appears in both `deletes` and `inserts` so the bulk\n * apply clears the pre-existing row before inserting the new one. The Sync applier therefore runs\n * three bulk statements **in the order `deletes → inserts → updates`** (Phase 3): that ordering is\n * what makes a re-create safe, and every other PK is touched by exactly one statement, so the rest\n * of the order is irrelevant within the atomic commit.\n */\nexport interface FoldedShapeBatch {\n /** PKs to delete — net-`delete` keys, plus the clearing delete of each re-created key. */\n deletes: ChangeMessage<Row<unknown>>[];\n /** Full rows to insert — net-`insert` keys, plus each re-created key's new row (merged values). */\n inserts: InsertChangeMessage[];\n /** Merged partial updates — net-`update` keys (carry the PK plus the union of updated columns). */\n updates: ChangeMessage<Row<unknown>>[];\n}\n\n/** Clone a representative message, overriding its row value and operation (headers like LSN are kept). */\nfunction withValue(\n template: ChangeMessage<Row<unknown>>,\n value: Row<unknown>,\n operation: Operation,\n): ChangeMessage<Row<unknown>> {\n return { ...template, value, headers: { ...template.headers, operation } };\n}\n\n/** Shallow-merge the row values of an ordered op segment, last-write-wins per column. */\nfunction mergeValues(segment: ChangeMessage<Row<unknown>>[]): Row<unknown> {\n return Object.assign({}, ...segment.map((message) => message.value)) as Row<unknown>;\n}\n\n/**\n * Fold a drained shape batch (ordered by LSN, one shape) to one net operation per primary key\n * (ADR-0014 decision 1), so the read path can bulk-apply without the `UPDATE … FROM` / `INSERT …\n * SELECT json_to_recordset(…)` same-PK join hazard (those use **one arbitrary** matching row when\n * the source holds duplicate PKs). Each PK's ops are replayed in LSN order down to:\n *\n * - **trailing `delete`** ⇒ a single DELETE;\n * - **`insert` with no preceding delete**, then any updates ⇒ a single INSERT with merged values\n * (a *plain* insert — a genuine PK collision still surfaces, never a silent upsert, commit `de12bb6`);\n * - **only `update`s** ⇒ a single UPDATE with merged values;\n * - **re-created** (`[delete, … , insert, …]`, no trailing delete) ⇒ DELETE **and** INSERT, so the\n * pre-existing row is cleared first (faithful to the per-row `DELETE`-then-`INSERT`; a plain INSERT\n * would collide with the row the dropped delete was meant to remove);\n * - **`update` after a delete** (`[delete, update]` and kin) is malformed for a faithful stream\n * (an update asserts the row exists) ⇒ throw, surfacing stream corruption rather than silently\n * dropping it.\n *\n * Pure and dependency-free by design (ADR-0014 / ISS-06): property-tested against the oracle\n * *fold-then-bulk ≡ ordered per-row apply* over random same-PK sequences and random initial state.\n */\nexport function foldChangeBatch(messages: ChangeMessage<Row<unknown>>[]): FoldedShapeBatch {\n const groups = new Map<string, ChangeMessage<Row<unknown>>[]>();\n for (const message of messages) {\n let group = groups.get(message.key);\n if (!group) {\n group = [];\n groups.set(message.key, group);\n }\n group.push(message);\n }\n\n const folded: FoldedShapeBatch = { deletes: [], inserts: [], updates: [] };\n for (const [key, ops] of groups) {\n foldKey(key, ops, folded);\n }\n return folded;\n}\n\nfunction foldKey(key: string, ops: ChangeMessage<Row<unknown>>[], folded: FoldedShapeBatch): void {\n const lastDeleteIndex = ops.findLastIndex((message) => message.headers.operation === \"delete\");\n\n // A trailing delete is the net effect regardless of anything before it; emit one DELETE.\n if (lastDeleteIndex === ops.length - 1) {\n folded.deletes.push(ops[lastDeleteIndex]!);\n return;\n }\n\n // The net is decided by the segment after the last delete (or the whole sequence if none).\n const segment = ops.slice(lastDeleteIndex + 1);\n const merged = mergeValues(segment);\n const template = segment[segment.length - 1]!;\n const startsWithInsert = segment[0]!.headers.operation === \"insert\";\n const hadDelete = lastDeleteIndex >= 0;\n\n if (startsWithInsert) {\n if (hadDelete) {\n // Re-created: clear the pre-existing row, then insert the new one (DELETE before INSERT).\n folded.deletes.push(ops[lastDeleteIndex]!);\n }\n folded.inserts.push(withValue(template, merged, \"insert\") as InsertChangeMessage);\n return;\n }\n\n if (hadDelete) {\n throw new Error(`foldChangeBatch: malformed batch — update after delete for key ${JSON.stringify(key)}`);\n }\n folded.updates.push(withValue(template, merged, \"update\"));\n}\n",
|
|
31
|
-
"// Started life as a copy of @electric-sql/pglite-sync (Apache-2.0, © ElectricSQL — see NOTICE).\n// Fully internalized (ADR-0009); upstream compatibility is an explicit anti-goal (ADR-0028) — evolve freely.\nimport type { Offset } from \"@electric-sql/client\";\nimport type { PGliteInterface, Transaction } from \"@electric-sql/pglite\";\nimport { eq } from \"drizzle-orm\";\n\nimport { quoteIdentifier } from \"@pgxsinkit/contracts\";\n\nimport { renderCreateTableSql } from \"../schema\";\nimport { drizzleOverPg } from \"./drizzle-executor\";\nimport { getMetadataTables } from \"./metadata-tables\";\nimport { type Lsn, type SubscriptionKey } from \"./types\";\n\nexport interface SubscriptionState {\n key: SubscriptionKey;\n shape_metadata: Record<string, ShapeSubscriptionState>;\n last_lsn: Lsn;\n}\n\nexport interface ShapeSubscriptionState {\n handle: string;\n offset: Offset;\n}\n\nexport interface GetSubscriptionStateOptions {\n readonly pg: PGliteInterface | Transaction;\n readonly metadataSchema: string;\n readonly subscriptionKey: SubscriptionKey;\n}\n\nexport async function getSubscriptionState({\n pg,\n metadataSchema,\n subscriptionKey,\n}: GetSubscriptionStateOptions): Promise<SubscriptionState | null> {\n const { subscriptionsMetadata } =
|
|
32
|
-
"// Started life as a copy of @electric-sql/pglite-sync (Apache-2.0, © ElectricSQL — see NOTICE).\n// Fully internalized (ADR-0009); upstream compatibility is an explicit anti-goal (ADR-0028) — evolve freely.\nimport type { ChangeMessage, FetchError, Row, ShapeStreamInterface, ShapeStreamOptions } from \"@electric-sql/client\";\nimport type { PgliteDatabase } from \"drizzle-orm/pglite\";\n\nimport type { SyncTableRegistry } from \"@pgxsinkit/contracts\";\n\nimport type { GroupBootStamp } from \"../boot-report\";\n\n// Re-exported so in-repo tests (e.g. tests/unit/sync-engine.test.ts) can name these Electric types\n// via this engine module — they resolve here, inside @pgxsinkit/client's dependency scope, without\n// the root workspace needing a direct dependency on the Electric client packages.\nexport type { Row, ShapeStreamOptions } from \"@electric-sql/client\";\nexport type { MultiShapeMessages } from \"@electric-sql/experimental\";\n\nexport type Lsn = bigint;\n\nexport type SubscriptionKey = string;\nexport type InitialInsertMethod = \"insert\" | \"copy\" | \"json\";\n\n/** Default hard cap on commit-transaction attempts before the engine goes degraded (ADR-0009). */\nexport const DEFAULT_MAX_COMMIT_RETRIES = 5;\n\n/**\n * Per-shape options for the group form (ADR-0029 D1). Every table-scoped fact — local table identity,\n * projection, primary keys, apply strategy, column types — is derived by the engine from the\n * group-level `registry` and this shape's `tableKey`; none is passed here. Only the Electric shape\n * stream, an optional per-shape backfill override, and the must-refetch hook remain.\n */\nexport interface ShapeToTableOptions {\n shape: ShapeStreamOptions<Row<unknown>>;\n /** The registry table key this shape applies into — the engine's sole per-table spec (ADR-0029 D1). */\n tableKey: string;\n /**\n * Must-refetch override: replaces the default `TRUNCATE` cache wipe (ADR-0029 D4). Receives a Drizzle\n * handle bound to the commit transaction (`drizzleOverPg(tx)`), so a scoped clear authors tier-①\n * (`db.delete(table).where(…)`).\n */\n onMustRefetch?: ((db: PgliteDatabase) => Promise<void>) | undefined;\n /**\n * Per-shape initial-backfill apply strategy override (ADR-0009 decisions 2 + 3). In a consistency\n * group each shape resolves its own apply path, so one shape's backfill never forces the rest onto\n * plain `INSERT`. When set it wins over the registry-classified strategy; otherwise the strategy is\n * derived from the entry and mapped, else the group-level default applies.\n */\n initialInsertMethod?: InitialInsertMethod | undefined;\n}\n\nexport interface SyncShapesToTablesOptions {\n key: string | null;\n /** The engine's per-table spec source (ADR-0029 D1): every shape's `tableKey` resolves against it. */\n registry: SyncTableRegistry;\n shapes: Record<string, ShapeToTableOptions>;\n initialInsertMethod?: InitialInsertMethod | undefined;\n onInitialSync?: (() => void) | undefined;\n /**\n * Fresh-store prefetch overlap (ADR-0032 S4 / backlog-0003). When present, the group is on a\n * PROVABLY-FRESH store (a claimed schemaless spare — the caller's `freshStore` hint), so the engine\n * starts the shape streams and BUFFERS their catch-up into the memory inbox immediately — WITHOUT the\n * two DB touches the sequential path takes first (`initMetadataTables`, `getSubscriptionState`) — and\n * gates every commit (the first write to PGlite) until this promise resolves. The owner resolves it\n * once the local store is ready (schema exec + journal recovery + store-version reconcile complete), so\n * the network catch-up overlaps those local phases instead of running strictly after them. Absent → the\n * exact sequential path (warm stores, and every non-overlap caller). Because a fresh store has no prior\n * subscription state, the overlap treats the group as a new subscription (`subState === null`), which the\n * `freshStore` gate guarantees.\n */\n dbReady?: Promise<void> | undefined;\n /** Stream-level (network / fetch) error from Electric, forwarded to `MultiShapeStream.subscribe`. */\n onError?: ((error: FetchError | Error) => void) | undefined;\n /**\n * Commit-level error surfacing (ADR-0009 decision 5). Fired when a sync commit transaction\n * still fails after `maxCommitRetries` jittered-backoff attempts. The engine then holds its\n * buffer and committed frontier (never advancing `isUpToDate` on an unapplied commit) so the\n * read cache cannot silently diverge; recovery is a later commit or a restart/refetch.\n */\n onSyncError?: ((error: Error) => void) | undefined;\n /**\n * Fired whenever the stream delivers a batch — i.e. a fetch just succeeded (ADR-0013 Phase 3).\n * The runtime uses this as the read path's \"alive again\" signal to clear an `auth-needed` status\n * once sync resumes after re-authentication.\n */\n onSyncActivity?: (() => void) | undefined;\n /** Hard cap on commit-transaction attempts before going degraded. Defaults to {@link DEFAULT_MAX_COMMIT_RETRIES}. */\n maxCommitRetries?: number | undefined;\n /**\n * Backoff before re-attempting a failed commit, as a function of the attempt number. Defaults to\n * the runtime's jittered backoff (`computeRetryDelayMs`). A test seam — pass `() => 0` for an\n * immediate retry instead of sleeping the real backoff.\n */\n commitRetryDelayMs?: ((attempt: number) => number) | undefined;\n /**\n * Boot observability (ADR-0034): a per-group accumulator, stamped as this group's stream chain delivers\n * batches (`onBatchDelivered`), applies commits into PGlite (`onApply`), and reaches initial sync\n * (`markReady`). Present only for eager + promoted BOOT groups; absent for on-demand lazy starts and any\n * boot without report instrumentation.\n */\n bootStamp?: GroupBootStamp | undefined;\n}\n\nexport interface SyncShapesToTablesResult {\n unsubscribe: () => void;\n readonly isUpToDate: boolean;\n streams: Record<string, ShapeStreamInterface<Row<unknown>>>;\n}\n\n/**\n * Single-shape options (ADR-0029 D6): thin sugar over the group form, taking the same entry-based\n * fields plus a `shapeKey`. Every table-scoped fact is derived from `(registry, tableKey)`.\n */\nexport interface SyncShapeToTableOptions {\n shape: ShapeStreamOptions<Row<unknown>>;\n registry: SyncTableRegistry;\n tableKey: string;\n shapeKey: string | null;\n initialInsertMethod?: InitialInsertMethod | undefined;\n onInitialSync?: (() => void) | undefined;\n onError?: ((error: FetchError | Error) => void) | undefined;\n /** Commit-level error surfacing (ADR-0009 decision 5); see {@link SyncShapesToTablesOptions.onSyncError}. */\n onSyncError?: ((error: Error) => void) | undefined;\n /** Hard cap on commit-transaction attempts before going degraded. Defaults to {@link DEFAULT_MAX_COMMIT_RETRIES}. */\n maxCommitRetries?: number | undefined;\n /** Backoff before re-attempting a failed commit; see {@link SyncShapesToTablesOptions.commitRetryDelayMs}. */\n commitRetryDelayMs?: ((attempt: number) => number) | undefined;\n onMustRefetch?: ((db: PgliteDatabase) => Promise<void>) | undefined;\n}\n\nexport interface SyncShapeToTableResult {\n unsubscribe: () => void;\n readonly isUpToDate: boolean;\n stream: ShapeStreamInterface<Row<unknown>>;\n}\n\nexport interface ElectricSyncOptions {\n debug?: boolean;\n metadataSchema?: string;\n}\n\nexport type InsertChangeMessage = ChangeMessage<Row<unknown>> & {\n headers: { operation: \"insert\" };\n};\n",
|
|
32
|
+
"// Started life as a copy of @electric-sql/pglite-sync (Apache-2.0, © ElectricSQL — see NOTICE).\n// Fully internalized (ADR-0009); upstream compatibility is an explicit anti-goal (ADR-0028) — evolve freely.\nimport type { Offset } from \"@electric-sql/client\";\nimport type { PGliteInterface, Transaction } from \"@electric-sql/pglite\";\nimport { eq } from \"drizzle-orm\";\n\nimport { quoteIdentifier } from \"@pgxsinkit/contracts\";\n\nimport { renderCreateTableSql } from \"../schema\";\nimport { drizzleOverPg } from \"./drizzle-executor\";\nimport { getMetadataTables, getSessionMetadataTables, pickMetadataTables } from \"./metadata-tables\";\nimport { type Lsn, type SubscriptionKey } from \"./types\";\n\nexport interface SubscriptionState {\n key: SubscriptionKey;\n shape_metadata: Record<string, ShapeSubscriptionState>;\n last_lsn: Lsn;\n}\n\nexport interface ShapeSubscriptionState {\n handle: string;\n offset: Offset;\n}\n\nexport interface GetSubscriptionStateOptions {\n readonly pg: PGliteInterface | Transaction;\n readonly metadataSchema: string;\n readonly subscriptionKey: SubscriptionKey;\n /**\n * ADR-0042: read the SESSION (`pg_temp`) cursor instead of the durable one for an ephemeral group. On\n * every engine boot the session table is empty, so a returning ephemeral group correctly reads `null`\n * (a brand-new subscription) and re-streams its whole shape from scratch over the recreated TEMP cluster.\n */\n readonly sessionScoped?: boolean;\n}\n\nexport async function getSubscriptionState({\n pg,\n metadataSchema,\n subscriptionKey,\n sessionScoped = false,\n}: GetSubscriptionStateOptions): Promise<SubscriptionState | null> {\n const { subscriptionsMetadata } = pickMetadataTables(metadataSchema, sessionScoped);\n const rows = await drizzleOverPg(pg)\n .select()\n .from(subscriptionsMetadata)\n .where(eq(subscriptionsMetadata.key, subscriptionKey));\n\n if (rows.length === 0) {\n return null;\n }\n if (rows.length > 1) {\n throw new Error(`Multiple subscriptions found for key: ${subscriptionKey}`);\n }\n\n const row = rows[0];\n if (!row) {\n throw new Error(`Subscription row missing for key: ${subscriptionKey}`);\n }\n if (typeof row.key !== \"string\") {\n throw new Error(`Invalid key type: ${typeof row.key}`);\n }\n if (!row.shape_metadata || typeof row.shape_metadata !== \"object\") {\n throw new Error(\"Invalid shape_metadata payload\");\n }\n if (typeof row.last_lsn !== \"string\") {\n throw new Error(`Invalid last_lsn type: ${typeof row.last_lsn}`);\n }\n\n return {\n key: row.key,\n shape_metadata: row.shape_metadata,\n last_lsn: BigInt(row.last_lsn),\n };\n}\n\nexport interface UpdateSubscriptionStateOptions {\n pg: PGliteInterface | Transaction;\n metadataSchema: string;\n subscriptionKey: SubscriptionKey;\n shapeMetadata: Record<string, ShapeSubscriptionState>;\n lastLsn: Lsn;\n debug?: boolean;\n /** ADR-0042: persist the cursor to the SESSION (`pg_temp`) table for an ephemeral group. */\n sessionScoped?: boolean;\n}\n\nexport async function updateSubscriptionState({\n pg,\n metadataSchema,\n subscriptionKey,\n shapeMetadata,\n lastLsn,\n debug,\n sessionScoped = false,\n}: UpdateSubscriptionStateOptions) {\n if (debug) {\n console.log(\"updating subscription state\", subscriptionKey, shapeMetadata, lastLsn);\n }\n\n const { subscriptionsMetadata } = pickMetadataTables(metadataSchema, sessionScoped);\n const lastLsnText = lastLsn.toString();\n await drizzleOverPg(pg)\n .insert(subscriptionsMetadata)\n .values({ key: subscriptionKey, shape_metadata: shapeMetadata, last_lsn: lastLsnText })\n .onConflictDoUpdate({\n target: subscriptionsMetadata.key,\n set: { shape_metadata: shapeMetadata, last_lsn: lastLsnText },\n });\n}\n\nexport interface DeleteSubscriptionStateOptions {\n pg: PGliteInterface | Transaction;\n metadataSchema: string;\n subscriptionKey: SubscriptionKey;\n}\n\nexport async function deleteSubscriptionState({ pg, metadataSchema, subscriptionKey }: DeleteSubscriptionStateOptions) {\n // ADR-0042: SCOPE-BLIND delete — remove the key from BOTH the durable and the session (`pg_temp`) cursor\n // tables. Idempotent (a `WHERE key = …` no-op on the table that never held it), so every existing caller —\n // `desync`, `discardEphemeral`, the `\"rebuilt\"` all-keys reset — clears both with zero caller changes, and\n // a persistent→ephemeral flip leaves no orphaned durable cursor row behind.\n const db = drizzleOverPg(pg);\n const { subscriptionsMetadata } = getMetadataTables(metadataSchema);\n const session = getSessionMetadataTables();\n await db.delete(subscriptionsMetadata).where(eq(subscriptionsMetadata.key, subscriptionKey));\n await db.delete(session.subscriptionsMetadata).where(eq(session.subscriptionsMetadata.key, subscriptionKey));\n}\n\nexport interface MigrateSubscriptionMetadataTablesOptions {\n pg: PGliteInterface | Transaction;\n metadataSchema: string;\n}\n\nexport async function migrateSubscriptionMetadataTables({\n pg,\n metadataSchema,\n}: MigrateSubscriptionMetadataTablesOptions) {\n // ADR-0029 D3: the metadata relations are RENDERED from the `metadata-tables.ts` pgTables through the\n // in-house schema renderer (`renderCreateTableSql`), so the pgTable is the single source and the old\n // DDL/pgTable drift can no longer exist. The CREATE SCHEMA + `SET` GUC default remain tier-③-by-nature\n // (schema identifier assembled at construction; the GUC has no tier-①/② form). Executed together as\n // one batch, exactly as before — same relations, same IF NOT EXISTS idempotence, same GUC default.\n const { subscriptionsMetadata, shapeRowTags } = getMetadataTables(metadataSchema);\n // ADR-0042: alongside the durable relations, provision the SESSION (`pg_temp`) cursor + tag tables in the\n // SAME migrate step (once per engine, memoized by the caller). Their DDL is the unqualified `CREATE TEMP\n // TABLE` form rendered from the same session pgTables (single-source, ADR-0029 D3) — the TEMP keyword\n // places them in `pg_temp` where the DML (schema-qualified `pg_temp.*`) reads/writes them. They die with\n // the engine, so an ephemeral group's cursor lifetime is mechanically tied to the TEMP cluster it indexes.\n const session = getSessionMetadataTables();\n const statements = [\n `SET ${metadataSchema}.syncing = false;`,\n `CREATE SCHEMA IF NOT EXISTS ${quoteIdentifier(metadataSchema)};`,\n ...renderCreateTableSql(subscriptionsMetadata),\n ...renderCreateTableSql(shapeRowTags),\n ...renderCreateTableSql(session.subscriptionsMetadata, { temp: true }),\n ...renderCreateTableSql(session.shapeRowTags, { temp: true }),\n ];\n await pg.exec(statements.join(\"\\n\"));\n}\n",
|
|
33
|
+
"// Started life as a copy of @electric-sql/pglite-sync (Apache-2.0, © ElectricSQL — see NOTICE).\n// Fully internalized (ADR-0009); upstream compatibility is an explicit anti-goal (ADR-0028) — evolve freely.\nimport type { ChangeMessage, FetchError, Row, ShapeStreamInterface, ShapeStreamOptions } from \"@electric-sql/client\";\nimport type { PgliteDatabase } from \"drizzle-orm/pglite\";\n\nimport type { SyncTableRegistry } from \"@pgxsinkit/contracts\";\n\nimport type { GroupBootStamp } from \"../boot-report\";\n\n// Re-exported so in-repo tests (e.g. tests/unit/sync-engine.test.ts) can name these Electric types\n// via this engine module — they resolve here, inside @pgxsinkit/client's dependency scope, without\n// the root workspace needing a direct dependency on the Electric client packages.\nexport type { Row, ShapeStreamOptions } from \"@electric-sql/client\";\nexport type { MultiShapeMessages } from \"@electric-sql/experimental\";\n\nexport type Lsn = bigint;\n\nexport type SubscriptionKey = string;\nexport type InitialInsertMethod = \"insert\" | \"copy\" | \"json\";\n\n/** Default hard cap on commit-transaction attempts before the engine goes degraded (ADR-0009). */\nexport const DEFAULT_MAX_COMMIT_RETRIES = 5;\n\n/**\n * Per-shape options for the group form (ADR-0029 D1). Every table-scoped fact — local table identity,\n * projection, primary keys, apply strategy, column types — is derived by the engine from the\n * group-level `registry` and this shape's `tableKey`; none is passed here. Only the Electric shape\n * stream, an optional per-shape backfill override, and the must-refetch hook remain.\n */\nexport interface ShapeToTableOptions {\n shape: ShapeStreamOptions<Row<unknown>>;\n /** The registry table key this shape applies into — the engine's sole per-table spec (ADR-0029 D1). */\n tableKey: string;\n /**\n * Must-refetch override: replaces the default `TRUNCATE` cache wipe (ADR-0029 D4). Receives a Drizzle\n * handle bound to the commit transaction (`drizzleOverPg(tx)`), so a scoped clear authors tier-①\n * (`db.delete(table).where(…)`).\n */\n onMustRefetch?: ((db: PgliteDatabase) => Promise<void>) | undefined;\n /**\n * Per-shape initial-backfill apply strategy override (ADR-0009 decisions 2 + 3). In a consistency\n * group each shape resolves its own apply path, so one shape's backfill never forces the rest onto\n * plain `INSERT`. When set it wins over the registry-classified strategy; otherwise the strategy is\n * derived from the entry and mapped, else the group-level default applies.\n */\n initialInsertMethod?: InitialInsertMethod | undefined;\n}\n\nexport interface SyncShapesToTablesOptions {\n key: string | null;\n /** The engine's per-table spec source (ADR-0029 D1): every shape's `tableKey` resolves against it. */\n registry: SyncTableRegistry;\n shapes: Record<string, ShapeToTableOptions>;\n /**\n * ADR-0042: this group's sync bookkeeping (subscription cursor + tagged-subquery reason sets) is\n * SESSION-scoped — stored in the engine's `pg_temp` metadata relations that die with the engine, not the\n * durable ones. Set for an `ephemeral`-retention group, whose whole cluster is already TEMP: the cursor\n * and tags then die with the rows they index, so a returning engine re-streams the shape from scratch\n * instead of resuming a stale durable cursor over a recreated-empty TEMP cluster. Default `false` — every\n * persistent group's storage is byte-identical to before. One storage-scope bit; the engine never learns\n * the retention model.\n */\n sessionScoped?: boolean | undefined;\n initialInsertMethod?: InitialInsertMethod | undefined;\n onInitialSync?: (() => void) | undefined;\n /**\n * Fresh-store prefetch overlap (ADR-0032 S4 / backlog-0003). When present, the group is on a\n * PROVABLY-FRESH store (a claimed schemaless spare — the caller's `freshStore` hint), so the engine\n * starts the shape streams and BUFFERS their catch-up into the memory inbox immediately — WITHOUT the\n * two DB touches the sequential path takes first (`initMetadataTables`, `getSubscriptionState`) — and\n * gates every commit (the first write to PGlite) until this promise resolves. The owner resolves it\n * once the local store is ready (schema exec + journal recovery + store-version reconcile complete), so\n * the network catch-up overlaps those local phases instead of running strictly after them. Absent → the\n * exact sequential path (warm stores, and every non-overlap caller). Because a fresh store has no prior\n * subscription state, the overlap treats the group as a new subscription (`subState === null`), which the\n * `freshStore` gate guarantees.\n */\n dbReady?: Promise<void> | undefined;\n /** Stream-level (network / fetch) error from Electric, forwarded to `MultiShapeStream.subscribe`. */\n onError?: ((error: FetchError | Error) => void) | undefined;\n /**\n * Commit-level error surfacing (ADR-0009 decision 5). Fired when a sync commit transaction\n * still fails after `maxCommitRetries` jittered-backoff attempts. The engine then holds its\n * buffer and committed frontier (never advancing `isUpToDate` on an unapplied commit) so the\n * read cache cannot silently diverge; recovery is a later commit or a restart/refetch.\n */\n onSyncError?: ((error: Error) => void) | undefined;\n /**\n * Fired whenever the stream delivers a batch — i.e. a fetch just succeeded (ADR-0013 Phase 3).\n * The runtime uses this as the read path's \"alive again\" signal to clear an `auth-needed` status\n * once sync resumes after re-authentication.\n */\n onSyncActivity?: (() => void) | undefined;\n /** Hard cap on commit-transaction attempts before going degraded. Defaults to {@link DEFAULT_MAX_COMMIT_RETRIES}. */\n maxCommitRetries?: number | undefined;\n /**\n * Backoff before re-attempting a failed commit, as a function of the attempt number. Defaults to\n * the runtime's jittered backoff (`computeRetryDelayMs`). A test seam — pass `() => 0` for an\n * immediate retry instead of sleeping the real backoff.\n */\n commitRetryDelayMs?: ((attempt: number) => number) | undefined;\n /**\n * Boot observability (ADR-0034): a per-group accumulator, stamped as this group's stream chain delivers\n * batches (`onBatchDelivered`), applies commits into PGlite (`onApply`), and reaches initial sync\n * (`markReady`). Present only for eager + promoted BOOT groups; absent for on-demand lazy starts and any\n * boot without report instrumentation.\n */\n bootStamp?: GroupBootStamp | undefined;\n}\n\nexport interface SyncShapesToTablesResult {\n unsubscribe: () => void;\n readonly isUpToDate: boolean;\n streams: Record<string, ShapeStreamInterface<Row<unknown>>>;\n}\n\n/**\n * Single-shape options (ADR-0029 D6): thin sugar over the group form, taking the same entry-based\n * fields plus a `shapeKey`. Every table-scoped fact is derived from `(registry, tableKey)`.\n */\nexport interface SyncShapeToTableOptions {\n shape: ShapeStreamOptions<Row<unknown>>;\n registry: SyncTableRegistry;\n tableKey: string;\n shapeKey: string | null;\n /** ADR-0042: SESSION-scope this shape's cursor + tags (ephemeral retention); see {@link SyncShapesToTablesOptions.sessionScoped}. */\n sessionScoped?: boolean | undefined;\n initialInsertMethod?: InitialInsertMethod | undefined;\n onInitialSync?: (() => void) | undefined;\n onError?: ((error: FetchError | Error) => void) | undefined;\n /** Commit-level error surfacing (ADR-0009 decision 5); see {@link SyncShapesToTablesOptions.onSyncError}. */\n onSyncError?: ((error: Error) => void) | undefined;\n /** Hard cap on commit-transaction attempts before going degraded. Defaults to {@link DEFAULT_MAX_COMMIT_RETRIES}. */\n maxCommitRetries?: number | undefined;\n /** Backoff before re-attempting a failed commit; see {@link SyncShapesToTablesOptions.commitRetryDelayMs}. */\n commitRetryDelayMs?: ((attempt: number) => number) | undefined;\n onMustRefetch?: ((db: PgliteDatabase) => Promise<void>) | undefined;\n}\n\nexport interface SyncShapeToTableResult {\n unsubscribe: () => void;\n readonly isUpToDate: boolean;\n stream: ShapeStreamInterface<Row<unknown>>;\n}\n\nexport interface ElectricSyncOptions {\n debug?: boolean;\n metadataSchema?: string;\n}\n\nexport type InsertChangeMessage = ChangeMessage<Row<unknown>> & {\n headers: { operation: \"insert\" };\n};\n",
|
|
33
34
|
"// The live-query DIFF machinery (ADR-0032 S2 §4). Two pure pieces sit either side of the bridge:\n// - {@link computeLiveDiff} (worker-side): turn a fresh ordered result-set into a {added, changed, removed}\n// diff against the previously-sent one, keyed by the query's PK — so only deltas cross the wire.\n// - {@link LiveRowsMaterializer} (tab-side): fold each diff back into an ordered array while preserving\n// row-object identity for unchanged rows (React memo bails on `===`).\n// Both are transport-free and worker-free, so they unit-test directly.\n\nimport type { LiveDiffPayload } from \"./protocol\";\n\n// A NUL separator — never a legitimate character inside a PK text value, so composite keys can't collide.\nconst KEY_SEP = String.fromCharCode(0);\n\n/**\n * The stable key for a result row (§4). With `pkColumns`, join their values (composite-safe) — this is the\n * diff-keying identity, so a row whose PK is unchanged is the SAME logical row even if other columns moved.\n * Without `pkColumns` (a keyless query) fall back to the whole-row JSON value: still diff-shaped (never a\n * full resend), but an update surfaces as remove+add rather than a `changed` — the documented keyless\n * fallback. Duplicate identical keyless rows collapse under this scheme (accepted for the fallback).\n */\nexport function rowKey(row: Record<string, unknown>, pkColumns: readonly string[] | undefined): string {\n if (pkColumns && pkColumns.length > 0) {\n return pkColumns.map((col) => String(row[col])).join(KEY_SEP);\n }\n return JSON.stringify(row);\n}\n\n/** A shallow value-equality over a row's own enumerable keys — decides `changed` vs unchanged in a diff. */\nfunction rowsEqual(a: Record<string, unknown>, b: Record<string, unknown>): boolean {\n const aKeys = Object.keys(a);\n const bKeys = Object.keys(b);\n if (aKeys.length !== bKeys.length) return false;\n for (const key of aKeys) {\n if (!Object.is(a[key], b[key])) return false;\n }\n return true;\n}\n\n/** The worker's per-subscription memory: the last delivered rows keyed by {@link rowKey}, in delivered order. */\nexport interface LiveDiffState {\n pkColumns?: readonly string[];\n /** key → the exact row body last sent, so the next diff can detect `changed` and skip unchanged rows. */\n previous: Map<string, Record<string, unknown>>;\n}\n\n/** Seed the diff state from the initial snapshot (which the worker sends verbatim, not as a diff). */\nexport function seedLiveDiffState(\n rows: readonly Record<string, unknown>[],\n pkColumns: readonly string[] | undefined,\n): LiveDiffState {\n const previous = new Map<string, Record<string, unknown>>();\n for (const row of rows) previous.set(rowKey(row, pkColumns), row);\n return { ...(pkColumns ? { pkColumns } : {}), previous };\n}\n\n/**\n * Diff a fresh ordered result set against the state's previous set, MUTATING the state to the new set and\n * returning the wire diff (§4). `order` is every key in the new ORDER BY order (keys only — cheap); `added`/\n * `changed` carry the delta row BODIES; `removed` carries dropped keys. Never emits the full result set: a\n * single-row change yields one `changed` and the (key-only) `order`.\n */\nexport function computeLiveDiff(\n state: LiveDiffState,\n nextRows: readonly Record<string, unknown>[],\n): Omit<LiveDiffPayload, \"queryId\"> {\n const order: string[] = [];\n const added: { key: string; row: Record<string, unknown> }[] = [];\n const changed: { key: string; row: Record<string, unknown> }[] = [];\n const nextKeys = new Set<string>();\n const nextMap = new Map<string, Record<string, unknown>>();\n\n for (const row of nextRows) {\n const key = rowKey(row, state.pkColumns);\n // A duplicate key within one result set (composite PK not actually unique, or a keyless collision):\n // keep the first, so `order`/diff stay a faithful set. Rare; the read projections are PK-unique.\n if (nextKeys.has(key)) continue;\n nextKeys.add(key);\n nextMap.set(key, row);\n order.push(key);\n\n const prior = state.previous.get(key);\n if (prior === undefined) {\n added.push({ key, row });\n } else if (!rowsEqual(prior, row)) {\n changed.push({ key, row });\n }\n }\n\n const removed: string[] = [];\n for (const key of state.previous.keys()) {\n if (!nextKeys.has(key)) removed.push(key);\n }\n\n state.previous = nextMap;\n return { order, added, changed, removed };\n}\n\n/**\n * The tab-side fold of live diffs into an ordered row array with STABLE object identity (§4). The initial\n * snapshot seeds the cache; each diff rebuilds the array from `diff.order`, reusing the cached object for\n * any key not in `added`/`changed` (so an unchanged row keeps `===` and a memoized React row skips its\n * re-render), and installing a fresh object for added/changed keys. Order is exactly `diff.order` — the\n * query's ORDER BY as delivered by the worker.\n */\nexport class LiveRowsMaterializer<TRow extends Record<string, unknown> = Record<string, unknown>> {\n private byKey = new Map<string, TRow>();\n private rows: TRow[] = [];\n private readonly pkColumns: readonly string[] | undefined;\n\n constructor(pkColumns: readonly string[] | undefined) {\n this.pkColumns = pkColumns;\n }\n\n /** Seed from the initial snapshot; returns the initial ordered rows (each a distinct cached object). */\n seed(initialRows: readonly TRow[]): TRow[] {\n this.byKey = new Map();\n this.rows = [];\n for (const row of initialRows) {\n const key = rowKey(row, this.pkColumns);\n this.byKey.set(key, row);\n this.rows.push(row);\n }\n return this.rows;\n }\n\n /** Apply a diff; returns the new ordered array (a fresh array, but unchanged rows keep their object identity). */\n apply(diff: Omit<LiveDiffPayload, \"queryId\">): TRow[] {\n for (const key of diff.removed) this.byKey.delete(key);\n for (const { key, row } of diff.added) this.byKey.set(key, row as TRow);\n for (const { key, row } of diff.changed) this.byKey.set(key, row as TRow);\n // Rebuild strictly from the delivered order, reusing whatever object each key now maps to. Added/changed\n // keys already point at fresh objects (set above); every other key keeps its prior object (=== holds).\n this.rows = diff.order.map((key) => this.byKey.get(key)!).filter((row): row is TRow => row !== undefined);\n return this.rows;\n }\n\n /** The current ordered rows (identity-stable across `apply` calls for unchanged rows). */\n current(): TRow[] {\n return this.rows;\n }\n}\n",
|
|
34
35
|
"// Canonical fingerprint for a live query (ADR-0040 decisions 2 & 3). Two identical live queries — same\n// POST-WRAP SQL, same bound params, same key mode — must map to ONE PGlite registration; anything that\n// changes what PGlite actually runs (or how the diff is keyed) must map to a DISTINCT one. The fingerprint\n// covers EXECUTION-relevant inputs only: the materialized SQL, a TYPED encoding of the params, and the PK\n// columns (which pick `live.incrementalQuery` vs `live.query` and drive the diff key). `use` is deliberately\n// NOT an input — activation/hydration are per-subscriber pre-steps that never influence the registration\n// (ADR-0040 decision 3), so keying on `use` would only split sharing.\n//\n// The param codec runs over the DECODED (structured-clone) values and TAGS every leaf by type, so a value\n// can never collide with a different-typed value that happens to stringify the same — a `Date` never with\n// its ISO string, a `Uint8Array` never with its hex text, a number never with its numeric string.\n\n/** The map key (full canonical string — the dedup identity) plus a short digest for diagnostics (Slice 5). */\nexport interface LiveQueryFingerprint {\n /** The exact dedup key: two subscriptions share a registration iff their `key` is identical. */\n key: string;\n /** A short, opaque hash of `key` — for diagnostics/observability only, NEVER used for dedup. */\n digest: string;\n}\n\n// Per-call unique token for values we cannot canonicalize (unknown prototypes). A random suffix guarantees\n// two opaque values never collide; the counter guarantees uniqueness even within one millisecond.\nlet opaqueCounter = 0;\nfunction opaqueToken(): string {\n return `${(opaqueCounter++).toString(36)}.${Math.random().toString(36).slice(2)}`;\n}\n\n/** Lowercase hex of a byte buffer — portable (no `Buffer`/`btoa`, so it runs in a browser SharedWorker). */\nfunction toHex(bytes: Uint8Array): string {\n let hex = \"\";\n for (const byte of bytes) hex += byte.toString(16).padStart(2, \"0\");\n return hex;\n}\n\nfunction isPlainObject(value: object): boolean {\n const proto = Object.getPrototypeOf(value);\n return proto === Object.prototype || proto === null;\n}\n\n/** A JSON-safe, type-tagged encoding node: a `[tag, …payload]` tuple whose first element is the type tag. */\ntype Encoded = readonly [string, ...unknown[]];\n\n/**\n * Encode one decoded value into a type-TAGGED, JSON-SAFE STRUCTURE (a `[tag, …]` tuple), never a flat string.\n * The tag is the first array element, so two values of different types can never collide, and because the\n * whole tuple is serialized ONCE with `JSON.stringify` (below), JSON does all the escaping/framing — a\n * delimiter-bearing string in an array or object can no longer masquerade as extra members (the flat-string\n * codec's collision class, e.g. `[[\"x,s:y\"]]` vs `[[\"x\",\"y\"]]`). Recurses through arrays (order-significant)\n * and plain objects (keys SORTED, so object key order never changes the fingerprint).\n */\nfunction encodeValue(value: unknown): Encoded {\n if (value === null) return [\"z\"]; // null\n if (value === undefined) return [\"v\"]; // undefined (distinct from null)\n switch (typeof value) {\n case \"boolean\":\n return [\"b\", value];\n case \"number\":\n // `String` already canonicalizes signed zero (`String(-0) === \"0\"`) and renders NaN/±Infinity\n // deterministically; NaN is an ALLOWED value here (two NaN params share a fingerprint), not a bail-out.\n return [\"n\", String(value)];\n case \"bigint\":\n return [\"i\", value.toString()];\n case \"string\":\n return [\"s\", value];\n case \"object\": {\n if (value instanceof Date) return [\"d\", value.getTime()]; // tagged epoch-ms — never equals an ISO string\n if (value instanceof Uint8Array) return [\"x\", toHex(value)];\n if (value instanceof ArrayBuffer) return [\"x\", toHex(new Uint8Array(value))];\n // Honour the view's window: encoding the WHOLE underlying buffer would falsely collide two different\n // views sharing one buffer (a wrong-dedup — the exact hazard this codec exists to prevent).\n if (ArrayBuffer.isView(value)) {\n const view = value as ArrayBufferView;\n return [\"x\", toHex(new Uint8Array(view.buffer, view.byteOffset, view.byteLength))];\n }\n if (Array.isArray(value)) return [\"a\", value.map(encodeValue)];\n if (isPlainObject(value)) {\n const record = value as Record<string, unknown>;\n const members = Object.keys(record)\n .sort()\n .map((k) => [k, encodeValue(record[k])] as const);\n return [\"o\", members];\n }\n // Unknown prototype (a class instance, Map, Set, …): we cannot canonicalize it safely, so tag it\n // `opaque` with a per-call unique token — it will NEVER dedup with anything (including an identical\n // instance) and NEVER falsely collide. Correctness over sharing for the values we don't understand.\n return [\"q\", opaqueToken()];\n }\n default:\n // function / symbol — not producible by structured clone, but stay safe: treat as opaque.\n return [\"q\", opaqueToken()];\n }\n}\n\n/** FNV-1a (32-bit) → 8 hex chars. Diagnostics only; the FULL `key` string is the dedup identity, never this. */\nfunction shortDigest(key: string): string {\n let hash = 0x811c9dc5;\n for (let i = 0; i < key.length; i++) {\n hash ^= key.charCodeAt(i);\n hash = Math.imul(hash, 0x01000193);\n }\n return (hash >>> 0).toString(16).padStart(8, \"0\");\n}\n\n/**\n * Fingerprint a live query. `materialSql` is the POST-WRAP SQL (the manager's registration input); `params`\n * are the decoded bound params; `pkColumns` selects the key mode. Returns the full canonical `key` (the dedup\n * identity) and a short `digest` for diagnostics.\n */\nexport function fingerprintLiveQuery(\n materialSql: string,\n params: readonly unknown[],\n pkColumns?: readonly string[],\n): LiveQueryFingerprint {\n // Single-column PK → PGlite `live.incrementalQuery`; composite/keyless → `live.query` + worker-side diff.\n // The mode AND the exact pk columns both matter: same SQL with a different pk column is a different\n // registration (different diff key), and incremental vs full are different PGlite machines.\n const mode = pkColumns && pkColumns.length === 1 ? \"inc\" : \"full\";\n // ONE `JSON.stringify` over a fixed-shape object of type-tagged encoding STRUCTURES: the SQL is its own JSON\n // string element (cannot bleed into params), and JSON escaping makes the whole key unambiguous — no manual\n // delimiter framing anywhere, so no delimiter-bearing value can forge extra structure.\n const key = JSON.stringify({\n sql: materialSql,\n params: params.map(encodeValue),\n pk: pkColumns ? [...pkColumns] : null,\n mode,\n });\n return { key, digest: shortDigest(key) };\n}\n",
|
|
35
36
|
"// The worker-owned live-query manager (ADR-0040). It owns the PGlite `live` registration lifecycle, the\n// single change listener + shared `LiveDiffState` per query, and the awaited-teardown bookkeeping (decision\n// 1). Slice 3 added DEDUPLICATION: identical live queries (same fingerprint — see live-query-fingerprint.ts)\n// share ONE registration and ONE diff computation, fanned out to every subscriber (decision 2). Slice 4 adds\n// BOUNDED ZERO-SUBSCRIBER KEEP-ALIVE (decision 4): when the last subscriber of an entry leaves, a nonzero\n// effective keep-alive retains the registration for a grace period so a matching resubscribe reuses it\n// verbatim (no ~400 ms re-materialization); retention is bounded by explicit count/row budgets and defaults\n// to OFF (keep-alive 0 → tear down immediately, byte-identical to Slice 3).\n//\n// What stays with the CALLER (`defineSyncWorker`), never this manager (ADR-0040 decision 3): lazy-relation\n// activation (`prepareQuery`), hydration accounting (`hydratingTablesFor` → `groupReady`), the\n// `live-initial`/`live-diff`/`live-hydrated` bridge posting with its per-`queryId` correlation, and\n// `wrapLiveQueryForMaterialization` (the manager receives POST-WRAP SQL — the fingerprint's SQL input). Those\n// are per-subscriber pre-/post-steps that never influence the shared registration or its rows; in particular\n// `use` NEVER reaches here, so differing `use` sets share one registration.\n\nimport type { LiveNamespace, LiveQuery, LiveQueryResults } from \"@electric-sql/pglite/live\";\n\nimport { syncDebug } from \"../debug\";\nimport { computeLiveDiff, type LiveDiffState, seedLiveDiffState } from \"./live-diff\";\nimport { fingerprintLiveQuery } from \"./live-query-fingerprint\";\nimport type { LiveDiffPayload } from \"./protocol\";\n\ntype Row = Record<string, unknown>;\n\n/** The wire diff a subscriber receives — exactly `computeLiveDiff`'s output, minus the caller's `queryId`. */\nexport type LiveDiffWire = Omit<LiveDiffPayload, \"queryId\">;\n\n/** The two delivery callbacks a subscriber supplies; the caller wires these to its bridge posting. */\nexport interface LiveSubscriber {\n /** The verbatim initial snapshot (NOT a diff), delivered ONCE before any diff (rows-before-diff ordering). */\n deliverInitial(rows: readonly Row[]): void;\n /** A subsequent change, already diffed against the last delivered set. */\n deliverDiff(diff: LiveDiffWire): void;\n}\n\n/** Post-wrap SQL + bound params + optional single-column PK (selects `incrementalQuery` vs `query`). */\nexport interface LiveQuerySpec {\n materialSql: string;\n params: unknown[];\n pkColumns?: readonly string[];\n}\n\n/** Per-subscription options (ADR-0040). */\nexport interface LiveSubscribeOptions {\n /**\n * How long (ms) THIS subscriber asks the entry to be retained after IT (and any siblings) leave. The\n * entry's effective keep-alive is `max(policy default, the max hint of the current active generation)`\n * (see the generation rule on `subscribe`); the worker count/row budgets stay authoritative over any hint.\n * Absent / 0 → no retention from this subscriber. Must be a finite number ≥ 0.\n */\n keepAliveMs?: number;\n /**\n * An opaque grouping key for diagnostics only (ADR-0040 decision 5) — never part of the fingerprint, so it\n * NEVER affects dedup or registration. The worker passes one stable scope per bridge port, so a snapshot's\n * `scopeCount` reads as the distinct-tab count; the in-process client passes none.\n */\n scope?: string;\n}\n\n/** A live registration's handle: awaited/tracked teardown and a coalesced refresh. */\nexport interface LiveSubscription {\n /** Non-blocking for the caller; the promise is retained internally so `dispose()` awaits it (decision 1). */\n unsubscribe(): Promise<void>;\n /** Force one recompute; concurrent calls SHARE one underlying `live.refresh()` (never N stacked reruns). */\n refresh(): Promise<void>;\n}\n\n/** The manager's bounded keep-alive policy (ADR-0040 decision 4). All fields default; the block is opt-in. */\nexport interface LiveQueryPolicy {\n /**\n * Default retention (ms) for a zero-subscriber entry, floored by each subscriber's own `keepAliveMs` hint.\n * Default 0 — the current route-scoped behaviour (tear a query down the moment its last consumer leaves).\n * The standing argument for 0: a retained zero-subscriber entry STILL pays a full SQL rerun + diff on every\n * dependent-table write — PGlite live queries cannot be paused, only torn down — so retention trades that\n * standing cost for avoiding re-materialization, and is only worth it for a genuinely hot, re-mounted query.\n */\n defaultKeepAliveMs?: number;\n /** Max simultaneously-retained (zero-subscriber) entries; LRU-evicted past this. Active entries never count. */\n maxRetainedQueries?: number;\n /** Max total rows held across ALL retained entries; LRU-evicted past this. Active entries never count. */\n maxRetainedRows?: number;\n}\n\ntype TimerHandle = unknown;\n\n/**\n * The signed-32-bit `setTimeout` delay ceiling (ADR-0040 decision 4). Browsers and Node clamp a delay above\n * this to ~0, so a \"30-day\" keep-alive would EXPIRE IMMEDIATELY rather than retain — the opposite of intent.\n * A keep-alive above this is rejected at the public boundary (never silently clamped), matching the ADR's\n * deliberate refusal of de-facto permanent retention. The budgets (count/rows) are NOT timers and are uncapped.\n */\nconst MAX_KEEP_ALIVE_MS = 2_147_483_647;\n\nexport interface LiveQueryManagerDeps {\n /** The engine's `live` namespace — only the two registration entry points are used. */\n live: Pick<LiveNamespace, \"query\" | \"incrementalQuery\">;\n /** Bounded keep-alive policy (ADR-0040 decision 4); omitted → all defaults (retention off). */\n policy?: LiveQueryPolicy;\n /** Monotonic clock for keep-alive LRU accounting. Default `performance.now()` (Date.now fallback). */\n now?: () => number;\n /** Injectable eviction timer (tests drive it deterministically). Default `setTimeout`. */\n setTimer?: (callback: () => void, ms: number) => TimerHandle;\n /** Injectable timer cancel. Default `clearTimeout`. */\n clearTimer?: (handle: TimerHandle) => void;\n}\n\n/**\n * A structured-clone-safe, per-entry diagnostics record (ADR-0040 decision 5). It carries ONLY opaque\n * fingerprint digests and counts/timings — NEVER SQL text, bound param values, or result-row values (those\n * live only in the fingerprint's private `key`, which is deliberately absent here). Safe to cross the bridge\n * and surface in support tooling.\n */\nexport interface LiveQueryDiagnostics {\n /** The opaque fingerprint digest (a short hash — see live-query-fingerprint.ts). NEVER the full key. */\n digest: string;\n /** Current subscriber count (0 while retained). */\n subscriberCount: number;\n /**\n * Distinct subscription scopes on this entry. The worker passes one scope per bridge port, so in WORKER\n * mode this is the number of distinct tabs on the query; the in-process client passes none, so it stays 1\n * while any subscriber is attached (0 while retained).\n */\n scopeCount: number;\n /** Rows currently held in the shared diff state. */\n rowCount: number;\n /** Whether this is a zero-subscriber entry currently kept alive (ADR-0040 decision 4). */\n retained: boolean;\n /** How many subscribes JOINED this entry rather than creating it (active-joins + retained rejoins). */\n dedupHits: number;\n /** Monotonic stamp (ms) when the entry was created. */\n createdAt: number;\n /** Time (ms) the registration setup took, or `null` until setup completes. */\n setupMs: number | null;\n /** Refresh timings for the shared registration (the hydration-chain / force refreshes). */\n refresh: { count: number; lastMs: number | null; totalMs: number; maxMs: number };\n /** Monotonic stamp (ms) of the last transition to zero subscribers, or `null` if never retained. */\n lastUsedAt: number | null;\n /** How long (ms) the entry has been retained (now − lastUsedAt), or `null` when not retained. */\n retainedSinceMs: number | null;\n /** A teardown is in flight (the entry is unsubscribing from PGlite). */\n teardownPending: boolean;\n}\n\nexport interface LiveQueryManager {\n subscribe(spec: LiveQuerySpec, subscriber: LiveSubscriber, opts?: LiveSubscribeOptions): Promise<LiveSubscription>;\n /** Tear down every live registration and await ALL teardowns (the Slice-1 close-vs-unsubscribe guard). */\n dispose(): Promise<void>;\n /**\n * A point-in-time diagnostics snapshot (ADR-0040 decision 5): one plain-object record per live entry,\n * carrying digests + counts/timings only — NO SQL, params, or rows. For the `liveQueryDiagnostics` RPC and\n * support tooling.\n */\n snapshot(): LiveQueryDiagnostics[];\n}\n\n/**\n * Validate a keep-alive policy at the public boundary (ADR-0040 decision 4 — bounded, no permanent retention).\n * Every provided field must be a finite number ≥ 0; the two budgets must additionally be integers. Throws a\n * `TypeError` naming the offending field so a misconfiguration fails at construction, not at first subscribe.\n */\nexport function validateLiveQueryPolicy(policy: LiveQueryPolicy | undefined): void {\n if (policy == null) return;\n const ms = (name: keyof LiveQueryPolicy, value: number | undefined) => {\n if (value !== undefined && (!Number.isFinite(value) || value < 0)) {\n throw new TypeError(`[pgxsinkit] liveQueries.${String(name)} must be a finite number >= 0 (got ${value})`);\n }\n // A keep-alive above the signed-32-bit timer ceiling would clamp to ~0 and expire immediately (see\n // MAX_KEEP_ALIVE_MS) — reject it rather than let a huge value become a no-retention footgun.\n if (value !== undefined && value > MAX_KEEP_ALIVE_MS) {\n throw new TypeError(\n `[pgxsinkit] liveQueries.${String(name)} must be <= ${MAX_KEEP_ALIVE_MS} ms (the platform setTimeout ceiling; got ${value})`,\n );\n }\n };\n const int = (name: keyof LiveQueryPolicy, value: number | undefined) => {\n if (value !== undefined && (!Number.isInteger(value) || value < 0)) {\n throw new TypeError(`[pgxsinkit] liveQueries.${String(name)} must be a non-negative integer (got ${value})`);\n }\n };\n ms(\"defaultKeepAliveMs\", policy.defaultKeepAliveMs);\n int(\"maxRetainedQueries\", policy.maxRetainedQueries);\n int(\"maxRetainedRows\", policy.maxRetainedRows);\n}\n\n/** One deduplicated registration: a shared listener + diff state, fanned out to many subscribers. */\ninterface LiveEntry {\n readonly key: string;\n readonly digest: string;\n /** Resolves once `registered`/`state`/`listener` are wired; rejects (and removes the entry) on setup failure. */\n readonly setup: Promise<void>;\n /**\n * Fan-out map keyed by an opaque per-subscription token (so `(port, queryId)` callers stay independent),\n * carrying each subscriber's keep-alive hint and diagnostics scope.\n */\n readonly subscribers: Map<symbol, { subscriber: LiveSubscriber; keepAliveMs: number; scope: string | undefined }>;\n registered?: LiveQuery<Row>;\n listener?: (results: LiveQueryResults<Row>) => void;\n state?: LiveDiffState;\n torn: boolean;\n teardown?: Promise<void>;\n refreshInFlight?: Promise<void>;\n /** Monotonic stamp of the last transition to zero subscribers — the LRU key while retained. */\n lastUsedAt?: number;\n /** The live eviction timer while retained; cleared on rejoin, expiry, eviction, or dispose. */\n evictionTimer?: TimerHandle;\n /**\n * The max keep-alive hint observed during the CURRENT active generation (reset to the joiner's hint on any\n * 0→1 join, `max`'d on every later join). The last-out effective keep-alive is `max(default, this)` — so it\n * is independent of the ORDER subscribers depart in (a hint no longer vanishes the instant its subscriber\n * leaves), making equivalent subscriber sets behave identically.\n */\n generationKeepAliveMs: number;\n // ── Diagnostics counters (ADR-0040 decision 5) — digests/counts/timings only, never SQL/params/rows ──\n readonly createdAt: number;\n dedupHits: number;\n setupMs?: number;\n refreshCount: number;\n refreshLastMs?: number;\n refreshTotalMs: number;\n refreshMaxMs: number;\n teardownPending: boolean;\n}\n\nexport function createLiveQueryManager(deps: LiveQueryManagerDeps): LiveQueryManager {\n validateLiveQueryPolicy(deps.policy);\n const { live } = deps;\n const policy = {\n defaultKeepAliveMs: deps.policy?.defaultKeepAliveMs ?? 0,\n maxRetainedQueries: deps.policy?.maxRetainedQueries ?? 16,\n maxRetainedRows: deps.policy?.maxRetainedRows ?? 50_000,\n };\n const now = deps.now ?? (() => (typeof performance !== \"undefined\" ? performance.now() : Date.now()));\n const setTimer = deps.setTimer ?? ((callback: () => void, ms: number) => setTimeout(callback, ms));\n const clearTimer =\n deps.clearTimer ?? ((handle: TimerHandle) => clearTimeout(handle as ReturnType<typeof setTimeout>));\n\n // ADR-0040 decision 1 (originally define-sync-worker's Slice 1): a fire-and-forget live `unsubscribe()`\n // still in flight when PGlite closes wedges the process forever. Every teardown promise is retained here so\n // `dispose()` settles them ALL before the caller closes the engine; rejections are swallowed so an\n // interrupted teardown never becomes an unhandled rejection.\n const pendingTeardowns = new Set<Promise<void>>();\n // The deduplication table: one entry per fingerprint (identical live queries share it).\n const entries = new Map<string, LiveEntry>();\n // Zero-subscriber entries currently being kept alive (ADR-0040 decision 4). ONLY these are counted against\n // the budgets and eligible for LRU eviction; active (subscriber-holding) entries are never in this set.\n const retained = new Set<LiveEntry>();\n // In-flight `subscribe()` calls (each resolves only once its join/self-teardown has fully run). `dispose()`\n // drains these so a subscribe completing mid-dispose is torn down instead of leaking a live query.\n const setups = new Set<Promise<void>>();\n // Manager-level count of dedup HITS — subscribes that joined an EXISTING entry (active-join or retained\n // rejoin) rather than creating a registration. Surfaced on the debug rail (`live-query dedup-hit`).\n let dedupHits = 0;\n let disposed = false;\n\n const createEntry = (key: string, digest: string, spec: LiveQuerySpec): LiveEntry => {\n const entry: LiveEntry = {\n key,\n digest,\n subscribers: new Map(),\n torn: false,\n generationKeepAliveMs: 0,\n createdAt: now(),\n dedupHits: 0,\n refreshCount: 0,\n refreshTotalMs: 0,\n refreshMaxMs: 0,\n teardownPending: false,\n // Assigned synchronously just below — the IIFE reads `entry`, which is fully initialized by then.\n setup: undefined as unknown as Promise<void>,\n };\n (entry as { setup: Promise<void> }).setup = (async () => {\n const setupStartedAt = now();\n const { materialSql, params, pkColumns } = spec;\n // Single-column PK → PGlite's incremental machinery (`live.incrementalQuery`); composite/keyless →\n // `live.query` (full ordered result each fire) + worker-side diff. Identical selection to the pre-dedup\n // path; the fingerprint already encoded this choice as its `mode`.\n const registered =\n pkColumns && pkColumns.length === 1\n ? await live.incrementalQuery<Row>(materialSql, params, pkColumns[0]!)\n : await live.query<Row>(materialSql, params);\n const state = seedLiveDiffState(registered.initialResults.rows, pkColumns);\n const listener = (results: LiveQueryResults<Row>) => {\n // `subscribe` fires only on a real change (never the initial), so every fire yields a genuine delta.\n // ONE diff, computed once against the shared state, fanned to EVERY current subscriber (decision 2).\n const diff = computeLiveDiff(state, results.rows);\n // Isolate per subscriber: a throwing consumer (the in-process `onRows` reaches app code) must NOT\n // starve its siblings — the shared state already advanced, so a skipped delivery is unrecoverable.\n for (const record of entry.subscribers.values()) {\n try {\n record.subscriber.deliverDiff(diff);\n } catch {\n syncDebug(\"live-query subscriber-error\", { digest: entry.digest });\n }\n }\n // A retained (zero-subscriber) entry stays live and its rows can GROW past the row budget on a write.\n // Re-enforce OUTSIDE this callback (a queued microtask) — eviction's PGlite `unsubscribe()` must not\n // run inside PGlite's own notification call (ADR-0040 decision 4 — the budget stays authoritative).\n if (retained.has(entry)) queueMicrotask(() => enforceBudgets());\n };\n registered.subscribe(listener);\n entry.registered = registered;\n entry.state = state;\n entry.listener = listener;\n entry.setupMs = now() - setupStartedAt;\n syncDebug(\"live-query register\", { digest, setupMs: Math.round(entry.setupMs) });\n })();\n // Failed setup: drop the entry so every joined waiter rejects and a LATER subscribe builds a fresh one.\n entry.setup.catch(() => {\n if (entries.get(key) === entry) entries.delete(key);\n });\n return entry;\n };\n\n const tearDownEntry = (entry: LiveEntry): Promise<void> => {\n if (entry.torn) return entry.teardown ?? Promise.resolve();\n entry.torn = true;\n entry.teardownPending = true;\n // Deliberately keep the torn entry in the map until its teardown COMPLETES: a resubscribe to the same\n // fingerprint arriving mid-teardown must find it, await the teardown, and only THEN build a fresh entry\n // (ADR-0040 decision 2 — never overlap a new registration with the old one's in-flight unsubscribe).\n const teardown = (async () => {\n // Wait out setup so there is a registration to unsubscribe (setup may still be in flight under dispose,\n // or a resubscribe-during-teardown awaiting this promise). A failed setup leaves nothing to unwind.\n await entry.setup.catch(() => {});\n if (entry.registered && entry.listener) await entry.registered.unsubscribe(entry.listener);\n })()\n .catch(() => {\n // A completed teardown failure is a one-shot event surfaced ONLY on the debug rail (ADR-0040\n // decision 5): the entry is removed from the map in the finally below, so no ordinary snapshot could\n // ever observe a per-entry flag — the rail line (buffered + replayable) is the sole failure signal.\n syncDebug(\"live-query teardown-failed\", { digest: entry.digest });\n })\n .finally(() => {\n entry.teardownPending = false;\n // Drop the slot only if still ours — a fresh entry never replaces it while we hold the map key, but\n // stay defensive against a future keep-alive path swapping entries under the same fingerprint.\n if (entries.get(entry.key) === entry) entries.delete(entry.key);\n syncDebug(\"live-query teardown-complete\", { digest: entry.digest });\n });\n entry.teardown = teardown;\n pendingTeardowns.add(teardown);\n void teardown.finally(() => pendingTeardowns.delete(teardown));\n return teardown;\n };\n\n /** Stop retaining an entry (rejoin / eviction / dispose): clear its timer and drop it from the retained set. */\n const cancelEviction = (entry: LiveEntry): void => {\n if (entry.evictionTimer !== undefined) {\n clearTimer(entry.evictionTimer);\n entry.evictionTimer = undefined;\n }\n retained.delete(entry);\n };\n\n /** Total rows held across all retained (zero-subscriber) entries — the row-budget accumulator. */\n const retainedRowTotal = (): number => {\n let total = 0;\n for (const entry of retained) total += entry.state?.previous.size ?? 0;\n return total;\n };\n\n // Enforce the retention budgets (ADR-0040 decision 4): while either the count OR the total-row budget is\n // exceeded, evict the LRU retained entry (smallest `lastUsedAt`). Budgets are AUTHORITATIVE over any hint,\n // and ONLY zero-subscriber entries are ever counted or evicted — active entries are untouchable. Run on\n // every transition INTO retained AND after a retained entry's rows grow (queued from the listener).\n const enforceBudgets = (): void => {\n if (disposed) return; // dispose owns teardown; a queued re-check after dispose is a no-op\n while (retained.size > policy.maxRetainedQueries || retainedRowTotal() > policy.maxRetainedRows) {\n // The count budget is checked first, so it is the reason whenever it is the one exceeded (a single\n // over-budget entry that trips both is attributed to the count budget).\n const reason = retained.size > policy.maxRetainedQueries ? \"count-budget\" : \"row-budget\";\n let victim: LiveEntry | undefined;\n for (const entry of retained) {\n if (victim === undefined || (entry.lastUsedAt ?? 0) < (victim.lastUsedAt ?? 0)) victim = entry;\n }\n if (victim === undefined) break;\n cancelEviction(victim);\n syncDebug(\"live-query evicted\", { digest: victim.digest, reason });\n void tearDownEntry(victim);\n }\n };\n\n const onEvictionTimer = (entry: LiveEntry): void => {\n entry.evictionTimer = undefined;\n // Guard the rejoin race: only tear down if the entry is STILL retained and zero-subscriber. A rejoin\n // cancelled the timer and removed it from `retained`; a stale/cancelled timer is a no-op.\n if (entry.torn || !retained.has(entry) || entry.subscribers.size > 0) return;\n retained.delete(entry);\n syncDebug(\"live-query evicted\", { digest: entry.digest, reason: \"expiry\" });\n void tearDownEntry(entry);\n };\n\n const removeSubscriber = (entry: LiveEntry, token: symbol): Promise<void> => {\n // Idempotent per subscriber: a second unsubscribe for the same token is a no-op (returns any teardown).\n if (!entry.subscribers.has(token)) return entry.teardown ?? Promise.resolve();\n entry.subscribers.delete(token);\n if (entry.subscribers.size > 0) return Promise.resolve(); // another subscriber still holds the registration\n // ── Last subscriber out (ADR-0040 decision 4) ──: the effective keep-alive is the max of the policy\n // default and the CURRENT generation's max hint — order-independent (see `generationKeepAliveMs`).\n const effective = Math.max(policy.defaultKeepAliveMs, entry.generationKeepAliveMs);\n // Never retain under dispose or on a torn entry: the drain in `dispose()` cancelled all timers and cleared\n // `retained`, so retaining here would re-arm a timer the engine close can no longer cancel (a post-close\n // stale timeout, the hang class decision 1 removed).\n if (effective <= 0 || disposed || entry.torn) return tearDownEntry(entry);\n // Retain: keep the registration + diff state live for the grace period (the listener keeps the state\n // current with zero fan-out), start an eviction timer, and enforce the budgets on this new retention.\n entry.lastUsedAt = now();\n retained.add(entry);\n entry.evictionTimer = setTimer(() => onEvictionTimer(entry), effective);\n syncDebug(\"live-query retained\", { digest: entry.digest, keepAliveMs: effective });\n enforceBudgets();\n return Promise.resolve();\n };\n\n const refreshEntry = (entry: LiveEntry): Promise<void> => {\n if (entry.torn || !entry.registered) return Promise.resolve();\n // Coalesce PER ENTRY, shared across all subscribers (ADR-0040 plan risk note): concurrent refreshes —\n // e.g. several subscribers finishing hydration together — collapse to ONE underlying `live.refresh()`,\n // whose single diff fans out to everyone. N hydrating subscribers never stack N full reruns. Time the\n // underlying refresh into the entry's diagnostics stats (decision 5).\n if (entry.refreshInFlight === undefined) {\n const startedAt = now();\n entry.refreshInFlight = entry.registered.refresh().finally(() => {\n const ms = now() - startedAt;\n entry.refreshCount++;\n entry.refreshLastMs = ms;\n entry.refreshTotalMs += ms;\n if (ms > entry.refreshMaxMs) entry.refreshMaxMs = ms;\n delete entry.refreshInFlight;\n });\n }\n return entry.refreshInFlight;\n };\n\n const subscribe = async (\n spec: LiveQuerySpec,\n subscriber: LiveSubscriber,\n opts?: LiveSubscribeOptions,\n ): Promise<LiveSubscription> => {\n // Reject synchronously once disposal has begun (ADR-0040 decision 1): a subscribe that started after\n // dispose would create a registration whose self-teardown nothing awaits — the exact close race.\n if (disposed) throw new Error(\"[pgxsinkit] live-query subscribe after dispose — the engine is closing\");\n const hint = opts?.keepAliveMs;\n if (hint !== undefined && (!Number.isFinite(hint) || hint < 0)) {\n throw new TypeError(`[pgxsinkit] keepAliveMs must be a finite number >= 0 (got ${hint})`);\n }\n // A hint above the signed-32-bit timer ceiling (see MAX_KEEP_ALIVE_MS) would clamp to ~0 and expire\n // immediately — reject it at the boundary, same as the policy default (ADR-0040 decision 4).\n if (hint !== undefined && hint > MAX_KEEP_ALIVE_MS) {\n throw new TypeError(\n `[pgxsinkit] keepAliveMs must be <= ${MAX_KEEP_ALIVE_MS} ms (the platform setTimeout ceiling; got ${hint})`,\n );\n }\n const keepAliveMs = hint ?? 0;\n const scope = opts?.scope;\n // Track this whole call so `dispose()` can drain the post-await join before it settles the teardown set —\n // otherwise a join completing mid-dispose would leak.\n let markSetupDone!: () => void;\n const setupDone = new Promise<void>((resolve) => {\n markSetupDone = resolve;\n });\n setups.add(setupDone);\n\n try {\n const { key, digest } = fingerprintLiveQuery(spec.materialSql, spec.params, spec.pkColumns);\n\n // Resolve a joinable, non-tearing entry (single-flight over BOTH setup and teardown):\n // - existing & healthy → join it (shared registration);\n // - existing & tearing down → await the teardown, then build a fresh entry (resubscribe-during-teardown);\n // - absent → create it (its `setup` is the shared single-flight registration for concurrent joiners).\n let entry = entries.get(key);\n while (entry && entry.torn) {\n await entry.teardown;\n entry = entries.get(key);\n }\n // Rejoin within grace (ADR-0040 decision 4): a retained zero-subscriber entry is reused verbatim — cancel\n // its eviction NOW (synchronously, before any await) so the timer cannot fire while we join; the snapshot\n // below comes from the still-current diff state, exactly as for an active entry.\n if (entry && retained.has(entry)) cancelEviction(entry);\n // A dedup HIT (ADR-0040 decision 5): we are joining an EXISTING entry (active-join OR retained-rejoin)\n // rather than creating a registration. The first subscriber of a fresh fingerprint is NOT a hit.\n const isDedupHit = entry != null;\n if (!entry) {\n entry = createEntry(key, digest, spec);\n entries.set(key, entry);\n }\n const joined = entry;\n if (isDedupHit) {\n dedupHits++;\n joined.dedupHits++;\n syncDebug(\"live-query dedup-hit\", { digest: joined.digest, dedupHits });\n }\n\n // Await the SHARED setup: concurrent subscribers to one fingerprint all await the SAME promise, so there\n // is exactly one registration. A failed setup rejects here for every joined waiter (the entry was already\n // removed by `createEntry`'s catch), so a later subscribe starts clean.\n await joined.setup;\n\n // ── JOIN ATOMICALLY (ADR-0040 decision 2) ─────────────────────────────────────────────────────────\n // Snapshot the entry's CURRENT rows from the shared diff state AND register this subscriber in the\n // fan-out map in ONE synchronous section — there MUST be no `await` between the snapshot and the\n // membership write. A listener fire (computeLiveDiff → deliverDiff) is synchronous, so with no yield here\n // no diff can land between the two: the joiner can neither miss a diff (it would be added to the map\n // first) nor be handed one its snapshot already reflects (the snapshot is taken first). The initial rows\n // come from the diff state, NOT a fresh PGlite read — the registration is already current.\n //\n // Keep-alive GENERATION rule (ADR-0040 decision 4): a 0→1 join opens a new generation and RESETS the\n // entry's generation hint to this joiner's; any later join `max`'s it. The last-out effective keep-alive\n // is `max(default, generationKeepAliveMs)`, so it depends only on the SET of hints in a generation, not\n // the order subscribers leave — equivalent subscriber sets behave identically.\n const firstOfGeneration = joined.subscribers.size === 0;\n joined.generationKeepAliveMs = firstOfGeneration\n ? keepAliveMs\n : Math.max(joined.generationKeepAliveMs, keepAliveMs);\n const token = Symbol(\"live-subscriber\");\n const snapshot = [...joined.state!.previous.values()];\n joined.subscribers.set(token, { subscriber, keepAliveMs, scope });\n try {\n subscriber.deliverInitial(snapshot);\n } catch (error) {\n // A failed initial delivery must not leak membership (the caller gets no handle to unsubscribe with).\n // Roll the token back; if that emptied the entry, tear it down NOW — a failed join never retains.\n joined.subscribers.delete(token);\n if (joined.subscribers.size === 0) void tearDownEntry(joined);\n throw error;\n }\n // ────────────────────────────────────────────────────────────────────────────────────────────────────\n\n return {\n unsubscribe: () => removeSubscriber(joined, token),\n refresh: () => refreshEntry(joined),\n };\n } finally {\n setups.delete(setupDone);\n markSetupDone();\n }\n };\n\n const dispose = async (): Promise<void> => {\n disposed = true;\n // Cancel every retention timer up front so none can fire mid-dispose.\n for (const entry of entries.values()) {\n if (entry.evictionTimer !== undefined) {\n clearTimer(entry.evictionTimer);\n entry.evictionTimer = undefined;\n }\n }\n retained.clear();\n // DRAIN to a stable empty state rather than a single snapshot: an in-flight subscribe (in `setups`) can\n // complete its join AFTER a one-shot teardown pass and leave a registration whose teardown nothing awaits\n // — the close race. `disposed` blocks NEW subscribes (they throw), and every teardown deletes its entry,\n // so this loop terminates once no setup, entry, or teardown remains.\n while (setups.size > 0 || entries.size > 0 || pendingTeardowns.size > 0) {\n await Promise.allSettled([...setups]);\n for (const entry of entries.values()) void tearDownEntry(entry);\n await Promise.allSettled([...pendingTeardowns]);\n }\n };\n\n const snapshot = (): LiveQueryDiagnostics[] => {\n const records: LiveQueryDiagnostics[] = [];\n for (const entry of entries.values()) {\n const isRetained = retained.has(entry);\n const scopes = new Set<string | undefined>();\n for (const { scope } of entry.subscribers.values()) scopes.add(scope);\n records.push({\n digest: entry.digest,\n subscriberCount: entry.subscribers.size,\n scopeCount: scopes.size,\n rowCount: entry.state?.previous.size ?? 0,\n retained: isRetained,\n dedupHits: entry.dedupHits,\n createdAt: entry.createdAt,\n setupMs: entry.setupMs ?? null,\n refresh: {\n count: entry.refreshCount,\n lastMs: entry.refreshLastMs ?? null,\n totalMs: entry.refreshTotalMs,\n maxMs: entry.refreshMaxMs,\n },\n lastUsedAt: entry.lastUsedAt ?? null,\n retainedSinceMs: isRetained && entry.lastUsedAt != null ? Math.max(0, now() - entry.lastUsedAt) : null,\n teardownPending: entry.teardownPending,\n });\n }\n return records;\n };\n\n return { subscribe, dispose, snapshot };\n}\n",
|
|
36
|
-
"// The bridge protocol (ADR-0032 S2). Everything that crosses between a tab and the shared sync engine\n// travels as a typed {@link BridgeEnvelope} over a minimal {@link BridgePort} (a MessagePort-shaped\n// transport). The router only ever inspects the envelope's `type`/`id`; its `payload` is OPAQUE to the\n// router and always passes through a {@link BridgeCodec}, so a later columnar/transferable codec can be\n// swapped in WITHOUT any protocol change (see BridgeCodec's doc).\n//\n// Deliberately transport-agnostic: `defineSyncWorker` and `attachSyncClient` both talk to a `BridgePort`,\n// never a real `Worker`/`SharedWorker` directly — which is exactly why the whole bridge is unit-testable\n// over bun's `MessageChannel` with no worker at all.\n\nimport type { SyncRuntimeStatus } from \"@pgxsinkit/contracts\";\n\nimport type { BootReport } from \"../boot-report\";\nimport type { ExportReport } from \"../export-store\";\n\nexport const BRIDGE_CHANNEL = \"pgxsinkit-bridge\" as const;\nexport const BRIDGE_PROTOCOL_VERSION = 1 as const;\n\n/**\n * A structured-clone transferable (an `ArrayBuffer`, a `MessagePort`, …). The library carries no DOM lib\n * dependency (like the convergence triggers), so this is the toolkit's own name for the type a future\n * columnar codec would hand to `postMessage`'s transfer list. v1's identity codec never produces one.\n */\nexport type BridgeTransferable = unknown;\n\n/**\n * The minimal MessagePort-shaped transport the bridge needs — the intersection of a real `MessagePort`,\n * a `SharedWorker` port, and a dedicated `Worker`/`self`. Injected everywhere so the protocol layer is\n * exercised with a plain `MessageChannel` (no Worker) in tests. `start()` is optional (MessagePort needs\n * it, `Worker`/`self` do not); `close()` is optional (a dedicated `self` cannot be closed by the tab).\n */\nexport interface BridgePort {\n postMessage: (message: unknown, transfer?: BridgeTransferable[]) => void;\n addEventListener: (type: \"message\", listener: (event: { data: unknown }) => void) => void;\n removeEventListener: (type: \"message\", listener: (event: { data: unknown }) => void) => void;\n start?: () => void;\n close?: () => void;\n}\n\n/**\n * The wire envelope. `payload` is the codec-encoded body — opaque to the router, which only routes on\n * `type` and correlates on `id`. Keeping the body opaque is what lets a future codec return a columnar\n * buffer (a transferable) in `payload` without any change to routing.\n */\nexport interface BridgeEnvelope {\n ch: typeof BRIDGE_CHANNEL;\n v: typeof BRIDGE_PROTOCOL_VERSION;\n type: BridgeMessageType;\n /** Correlation id for request/response pairs (rpc, subscribe, token pull). Absent for fire-and-forget fanout. */\n id?: string;\n /** Codec-encoded body — opaque to the router; decode with the same {@link BridgeCodec}. */\n payload: unknown;\n}\n\nexport type BridgeMessageType =\n // tab → worker\n | \"provision\"\n | \"attach\"\n | \"detach\"\n | \"token-push\"\n | \"token-response\"\n | \"rpc\"\n | \"subscribe\"\n | \"unsubscribe\"\n | \"wake\"\n | \"set-online\"\n // worker → tab\n | \"provision-ack\"\n | \"attach-ack\"\n | \"token-request\"\n | \"rpc-result\"\n | \"live-initial\"\n | \"live-diff\"\n | \"live-hydrated\"\n | \"event\";\n\n// ─── Payload shapes ───────────────────────────────────────────────────────────\n\n/** A single auth token snapshot the tab owns and pushes to the worker (ADR-0032 decision 3). */\nexport interface AuthTokenSnapshot {\n accessToken: string;\n /** Absolute expiry in epoch milliseconds (`Date.now()`-comparable), so the worker can apply an expiry margin. */\n expiresAt: number;\n}\n\n/**\n * tab → worker: pre-spawn the store WITHOUT booting the engine (ADR-0032 decision 5). Sent at the\n * login screen against the freshly-named spare worker: the worker only runs PGlite `create`/initdb\n * (off every thread that matters) and holds the raw store idle — no schema, no shape streams, no token\n * — until the real {@link AttachPayload} arrives (with config + token) and adopts the provisioned store.\n * Role-agnostic on purpose: the spare is minted before the user (and role) is known, so provisioning\n * carries no registry — the schema is applied at attach with the role-resolved registry.\n */\nexport interface ProvisionPayload {\n /** The bound store id (informational; naming is done tab-side via the SharedWorker name). */\n storeId?: string;\n /**\n * The plain store PATH (ADR-0036) to `create` ahead of attach — a name, not a storage URL; the worker\n * derives the backend (IndexedDB in a browser worker). When omitted, `storeId`/the worker default is used.\n */\n storePath?: string;\n /**\n * @internal INTERNAL WIRE FIELD (not consumer config, ADR-0036). Carries the testing memory-backend\n * override across the bridge, because a symbol-keyed marker does NOT survive `postMessage` structured\n * clone — so the worker's memory-store selection travels as this explicit field. Set only by the test\n * lane (via the attaching helper); a browser worker never sends it.\n */\n testStoreBackend?: \"memory\";\n}\n\n/** worker → tab: the provision completed (or failed). Lets the login screen confirm the spare is warm. */\nexport interface ProvisionAckPayload {\n ok: boolean;\n storeId?: string;\n /** Present when `!ok` — the initdb/create failed; the worker falls back to a fresh create at attach. */\n error?: { message: string };\n}\n\n/**\n * tab → worker: a store-backup tarball to restore from, carried on the boot {@link AttachPayload}\n * (ADR-0035 decision 6). The mirror image of {@link ExportArtefactWire}: a `File`/`Blob` cannot cross the\n * bridge as a transferable, so it is decomposed into its zero-copy `ArrayBuffer` (listed on `postMessage`'s\n * transfer list) plus the metadata to rebuild it, and the worker reassembles a `Blob` from\n * `buffer`/`mimeType` to hand `createSyncClient` as `restoreFrom`.\n */\nexport interface RestoreArtefactWire {\n /** The backup tarball bytes — transferred, not copied. */\n buffer: ArrayBuffer;\n /** The backup file name (informational; PGlite's `loadDataDir` reads the bytes, not the name). */\n fileName: string;\n /** The backup MIME type (`application/x-gzip` / `application/x-tar`), used to rebuild the `Blob`. */\n mimeType: string;\n}\n\n/** tab → worker: the attach handshake. The first attach boots the engine; later attaches join it. */\nexport interface AttachPayload {\n /** The bound store id (SharedWorker naming resolves it tab-side before attach — ADR-0032 decision 5). */\n storeId?: string;\n /**\n * Explicit plain store PATH (ADR-0036) if the worker should create its own store — a name, not a storage\n * URL; the worker derives the backend. When omitted, `storeId`/the worker default is used.\n */\n storePath?: string;\n /**\n * @internal INTERNAL WIRE FIELD (not consumer config, ADR-0036). Carries the testing memory-backend\n * override across the bridge — a symbol-keyed marker does not survive structured clone, so the worker's\n * memory-store selection travels as this explicit field. Set only by the test lane; never by a browser tab.\n */\n testStoreBackend?: \"memory\";\n /**\n * Restore the store from a backup on THIS attach (ADR-0035 decision 6) — the worker-mode carrier of\n * `createSyncClient`'s `restoreFrom`. Restore rides the FIRST attach (the boot attach): a `File`/`Blob`\n * cannot cross `postMessage` as a transferable, so the tab decomposes it into a transferred `ArrayBuffer`\n * plus its name/mime — the {@link ExportArtefactWire} pattern in reverse — and the worker recomposes it\n * into a `Blob` and hands it to `createSyncClient`. Absent on every ordinary attach. An attach that carries\n * this AFTER the engine has already booted is REFUSED (you cannot restore into a running store).\n */\n restore?: RestoreArtefactWire;\n /** The tab's current auth token at attach time, or null when unauthenticated. */\n token: AuthTokenSnapshot | null;\n /**\n * Serializable per-attach config overrides (kept minimal; the urls are baked into the worker). `role`\n * selects which baked registry the worker boots (ADR-0032 S3): the spare is minted role-agnostic, so\n * the role is only known at claim/attach — a single worker file bakes BOTH registries and picks here.\n * `freshStore` is the fresh-store prefetch-overlap hint (ADR-0032 S4): the tab's claim path knows a\n * claimed spare is schemaless (fresh) while a mapped/returning store never is, and forwards that here so\n * the worker's `createSyncClient` can overlap the shape catch-up with the local boot phases.\n */\n config?: { syncEnabled?: boolean; role?: string; freshStore?: boolean };\n}\n\n/**\n * tab → worker: gate the worker's outbound convergence (the board's Offline toggle, ADR-0032 S3). In\n * in-process mode the toggle gates the local `autoSync` trigger; the worker owns convergence instead, so\n * the tab forwards the flag and the worker suppresses/resumes its flush passes. Going back online fires\n * one immediate pass so queued writes flush without waiting for the next interval tick.\n */\nexport interface SetOnlinePayload {\n online: boolean;\n}\n\n/** worker → tab: attach acknowledged. `alreadyBooted` is false for the attach that booted the engine. */\nexport interface AttachAckPayload {\n alreadyBooted: boolean;\n /**\n * True when the engine's initial sync had ALREADY fired by the time this attach was acked (a late\n * attach, ADR-0032 FIX 3). `ready` is monotonic in-process — once it resolves it stays resolved even if\n * the phase later degrades — so a tab attaching after that moment must resolve `ready` immediately from\n * the ack, rather than wait for a phase-\"ready\" status that may never come again.\n */\n engineReady?: boolean;\n /**\n * Present when the engine boot REJECTED for this attach: the tab rejects `attachSyncClient` with this\n * message instead of hanging forever on the ack (ADR-0032 FIX 1). A later attach retries the boot.\n */\n error?: { message: string; detail?: unknown };\n}\n\n/** worker → tab: a broadcast pull-request — any attached tab may answer, first response wins (ADR-0032 decision 3). */\nexport interface TokenRequestPayload {\n requestId: string;\n}\n\n/** tab → worker: the answer to a {@link TokenRequestPayload}. `token: null` = the tab has none. */\nexport interface TokenResponsePayload {\n requestId: string;\n token: AuthTokenSnapshot | null;\n}\n\n/**\n * The RPC ops the attach facade proxies to the worker's booted client — the write API (mirrors\n * `client.mutate`/flush), mutation-state reads, and the one-shot raw inspection reads (`rawQuery`/`rawExec`).\n */\nexport type RpcOp =\n | \"create\"\n | \"update\"\n | \"delete\"\n | \"batch\"\n | \"transaction\"\n | \"flush\"\n | \"reconcile\"\n | \"retryFailed\"\n | \"recoverSending\"\n | \"discardConflict\"\n | \"discardQuarantined\"\n | \"desync\"\n | \"discardEphemeral\"\n | \"readMutationDetails\"\n | \"diagnostics\"\n | \"rawQuery\"\n | \"rawExec\"\n // Boot observability (ADR-0034): pull the worker engine's most recent completed boot report. Returns the\n // stored report (or null) regardless of when this tab attached, so a late tab reads a boot predating it.\n | \"bootReport\"\n // Live-query diagnostics (ADR-0040 decision 5): pull the worker manager's per-entry snapshot (digests +\n // counts/timings, NEVER SQL/params/rows). Returns [] before any subscription / when the manager is absent.\n | \"liveQueryDiagnostics\"\n // Store backup (ADR-0035): the worker runs the live `exportStore` on its owned client; the dump crosses\n // back as a transferred `ArrayBuffer` ({@link ExportArtefactWire}), rebuilt into a `File` tab-side.\n | \"exportStore\"\n // Diagnostic dump (ADR-0035): the worker runs `exportDiagnostics` on its owned client (live datadir dump\n // → memory throwaway clone → `pg_dump`); the SQL crosses back as the same transferred `ArrayBuffer` wire.\n | \"exportDiagnostics\"\n // Data export (ADR-0035): the worker runs `exportData` on its owned client (drain the journal → throwaway\n // clone → `pg_dump -t` per synced table); the portable SQL crosses back as the same transferred wire.\n | \"exportData\";\n\n/** tab → worker: a write/read-of-mutation-state RPC. `id` correlates the matching {@link RpcResultPayload}. */\nexport interface RpcPayload {\n op: RpcOp;\n args: unknown[];\n}\n\n/**\n * worker → tab: the wire form of ANY local-store export (ADR-0035) — the store backup's tarball OR the\n * diagnostic dump's SQL — carried as the `value` of an {@link RpcResultPayload}. The artefact crosses as a\n * transferred `ArrayBuffer` (zero-copy — the sender lists `buffer` in `postMessage`'s transfer list) plus\n * the metadata to rebuild it; the tab reconstructs a `File` from `buffer`/`fileName`/`mimeType`. A `File`\n * cannot itself be transferred, so it is decomposed here and reassembled tab-side, exactly the pattern the\n * codec's transferable seam anticipates for a zero-copy live-diff payload. `report` is the discriminated\n * {@link ExportReport} union, so the tab knows which export it round-tripped.\n */\nexport interface ExportArtefactWire {\n /** The artefact bytes (tarball or SQL) — transferred, not copied. */\n buffer: ArrayBuffer;\n /** The generated (or caller-supplied) artefact file name. */\n fileName: string;\n /** The artefact MIME type (`application/x-gzip` / `application/x-tar` for a backup, `application/sql` for a dump). */\n mimeType: string;\n /** The export report (ADR-0035), structured-cloned as a plain object — the `kind`-discriminated union. */\n report: ExportReport;\n}\n\n/** worker → tab: an RPC outcome, mirroring today's in-process resolve/reject semantics. */\nexport interface RpcResultPayload {\n ok: boolean;\n /** The resolved value (present when `ok`). */\n value?: unknown;\n /** The rejection message + optional structured detail (present when `!ok`). */\n error?: { message: string; detail?: unknown };\n}\n\n/** tab → worker: register a live query. `id` correlates the initial snapshot; `queryId` keys subsequent diffs. */\nexport interface SubscribePayload {\n queryId: string;\n sql: string;\n params: unknown[];\n /**\n * The unique output aliases the worker wraps the query's columns under so it is safe to MATERIALISE\n * (one per output column, in the compiled SQL's column order). ADDITIVE and backward-compatible: an\n * older tab omits it and the worker leaves the SQL untouched (name-keyed rows, as before); a newer tab\n * supplies it for a JOIN with same-named columns, which `live.query`/`live.incrementalQuery` otherwise\n * refuse to materialise (`column \"title\" specified more than once`). When present, result columns are\n * the aliases, so {@link pkColumns} must name a PK by its alias.\n */\n fields?: string[];\n /**\n * The result's primary-key columns, driving diff keying (§4). One column → the incremental path\n * (`live.incrementalQuery`); many → worker-side diff by composite PK; empty/absent → value-identity\n * fallback for a keyless query. When {@link fields} is supplied these name the ALIASED result columns.\n */\n pkColumns?: string[];\n /** Lazy relations to activate before the query runs (ADR-0021), forwarded to the worker's `prepareQuery`. */\n use?: string[];\n /**\n * Per-subscription keep-alive hint (ms) for the worker's live-query manager (ADR-0040 decision 4): how long\n * the shared registration should be retained after this subscription's last consumer leaves, so a matching\n * resubscribe reuses it verbatim. ADDITIVE and backward-compatible both directions — an older tab omits it\n * (the worker falls back to its `liveQueries.defaultKeepAliveMs`), and an older worker ignores it. Absent\n * means \"no hint\".\n */\n keepAliveMs?: number;\n}\n\n/** worker → tab: the initial ordered snapshot for a subscription. `id` correlates the `subscribe` request. */\nexport interface LiveInitialPayload {\n queryId: string;\n rows: Record<string, unknown>[];\n /**\n * The `lazy` relations the worker's guard activated for this query (ADR-0021) — the relations held out\n * of the eager boot set. Observability only: {@link hydratingTables}, not this, drives the tab's\n * `hydrated` promise.\n */\n lazyTables?: string[];\n /**\n * The referenced consistency groups' member tables (eager OR lazy) that were NOT YET caught up when this\n * snapshot was taken (ADR-0021 / ADR-0032). Non-empty → the tab builds a `hydrated` promise the worker\n * settles via `live-hydrated` (posted after the catch-up rows on this same port). Absent → every\n * referenced group was already ready (steady state) or sync is disabled: nothing to hydrate.\n */\n hydratingTables?: string[];\n}\n\n/**\n * worker → tab: the subscription's lazy relations have completed their initial catch-up AND the live\n * query has been refreshed against the caught-up store (ADR-0021). Posted on the SAME port as the\n * live-diff stream, strictly after the refresh-triggered diff — so when the tab sees this, the rows\n * reflecting the catch-up have already been delivered. Resolves the tab subscription's `hydrated`\n * promise (the React hooks' `hydrating` gate); never sent for a query with no pending groups (steady\n * state / sync disabled), i.e. an empty `live-initial` {@link LiveInitialPayload.hydratingTables}.\n */\nexport interface LiveHydratedPayload {\n queryId: string;\n}\n\n/**\n * worker → tab: a DIFF update for a subscription (§4). Never a full result-set resend after the initial\n * snapshot. `order` is the full ordered list of row keys (cheap — keys only, no row bodies); `added`/\n * `changed` carry only the delta row bodies; `removed` carries only the dropped keys. The tab materializer\n * rebuilds the ordered array from `order`, reusing cached row objects for keys not in `added`/`changed` so\n * an unchanged row keeps its object identity (React memo bails on `===`).\n */\nexport interface LiveDiffPayload {\n queryId: string;\n /** Every result key in ORDER BY order (the query's delivered order). */\n order: string[];\n added: { key: string; row: Record<string, unknown> }[];\n changed: { key: string; row: Record<string, unknown> }[];\n removed: string[];\n}\n\n/** worker → tab: the single broadcast event stream (ADR-0032 decision 7), re-exposed as today's callbacks. */\nexport type BridgeEvent =\n | { kind: \"status\"; status: SyncRuntimeStatus }\n | { kind: \"groupReady\"; groupKey: string }\n | { kind: \"conflict\"; details: unknown }\n | { kind: \"quarantine\"; details: unknown }\n | { kind: \"reject\"; details: unknown }\n | { kind: \"schema-change\"; event: unknown }\n | { kind: \"sync-error\"; message: string }\n | { kind: \"timing\"; label: string; ms: number; data?: Record<string, unknown> }\n // Boot observability (ADR-0034): the one-shot boot report, broadcast to currently-attached ports when the\n // engine's boot finalizes (the push counterpart of the `bootReport` pull). Later tabs read it via the pull.\n | { kind: \"boot-report\"; report: BootReport }\n // The debug rail (ADR-0032 decision 7): stamped with the WORKER's monotonic clock and origin-tagged so a\n // tab can re-print it as `[pgxsinkit·w <stamp>ms] <line>` — a SharedWorker's own console is invisible.\n | { kind: \"debug\"; stamp: number; line: string; data?: Record<string, unknown> };\n\n/** tab → worker: an app-driven wake (online/visibilitychange), treated as a convergence pass request. */\nexport interface WakePayload {\n reason: \"online\" | \"visibility\" | \"manual\";\n}\n\n// ─── Codec seam ─────────────────────────────────────────────────────────────\n\n/**\n * The codec every bridge payload crosses through (owner-mandated seam, ADR-0032 S2 §1). v1 ships exactly\n * ONE codec — {@link identityCodec}, which relies on the transport's own structured clone. The seam exists\n * so a columnar/transferable codec (e.g. one that packs live-diff rows into a shared `ArrayBuffer` and\n * returns it as a transferable) can be swapped in later WITHOUT any protocol change: the router already\n * treats `BridgeEnvelope.payload` as opaque, and `encode` may return `{ payload, transfer }` so the sender\n * hands transferables to `postMessage`. Keep encode/decode inverse and side-effect free.\n */\nexport interface BridgeCodec {\n /** Encode a raw payload into the envelope body. May declare transferables for a future zero-copy codec. */\n encode: (payload: unknown) => { payload: unknown; transfer?: BridgeTransferable[] };\n /** Decode an envelope body back into the raw payload. Inverse of {@link encode}. */\n decode: (payload: unknown) => unknown;\n}\n\n/**\n * The v1 identity codec: the body IS the payload, and the transport's structured clone does the real\n * copying. No transferables. The only codec shipped in S2 — swapping in a columnar codec later touches\n * only this object, never the message types or the router.\n */\nexport const identityCodec: BridgeCodec = {\n encode: (payload) => ({ payload }),\n decode: (payload) => payload,\n};\n\n// ─── Envelope helpers ─────────────────────────────────────────────────────────\n\n/** Build a wire envelope, running the payload through the codec. Returns the envelope + any transferables. */\nexport function encodeEnvelope(\n codec: BridgeCodec,\n type: BridgeMessageType,\n payload: unknown,\n id?: string,\n): { envelope: BridgeEnvelope; transfer?: BridgeTransferable[] } {\n const encoded = codec.encode(payload);\n const envelope: BridgeEnvelope = {\n ch: BRIDGE_CHANNEL,\n v: BRIDGE_PROTOCOL_VERSION,\n type,\n payload: encoded.payload,\n ...(id !== undefined ? { id } : {}),\n };\n return { envelope, ...(encoded.transfer ? { transfer: encoded.transfer } : {}) };\n}\n\n/** Type-guard a received message as a bridge envelope of the current protocol version (ignore foreign traffic). */\nexport function isBridgeEnvelope(data: unknown): data is BridgeEnvelope {\n return (\n typeof data === \"object\" &&\n data !== null &&\n (data as { ch?: unknown }).ch === BRIDGE_CHANNEL &&\n (data as { v?: unknown }).v === BRIDGE_PROTOCOL_VERSION\n );\n}\n\n/**\n * Send a typed message over a port: encode → post (with any transferables). The one write choke point.\n * `transfer` lets a caller declare payload-specific transferables (e.g. a store-backup's `ArrayBuffer`,\n * ADR-0035) WITHOUT teaching the shared codec about that op — they are merged after any the codec itself\n * produces, so both the codec's future zero-copy path and per-message transfers coexist.\n */\nexport function postBridgeMessage(\n port: BridgePort,\n codec: BridgeCodec,\n type: BridgeMessageType,\n payload: unknown,\n id?: string,\n transfer?: BridgeTransferable[],\n): void {\n const { envelope, transfer: codecTransfer } = encodeEnvelope(codec, type, payload, id);\n const allTransfer = [...(codecTransfer ?? []), ...(transfer ?? [])];\n if (allTransfer.length > 0) {\n port.postMessage(envelope, allTransfer);\n } else {\n port.postMessage(envelope);\n }\n}\n",
|
|
37
|
-
"// The tab facade (ADR-0032 S2, decisions 3/4/6/7). `attachSyncClient` returns the SAME client shape as\n// `createSyncClient` wherever semantics allow — the write API (RPC-backed), per-group readiness, the\n// live-rows seam, `ready`/`status`/`stop` — transparently proxied to the one shared worker engine. The tab\n// stays the single auth owner: it pushes its token at attach and on `notifyAuthChanged`, and answers the\n// worker's expiry pull-requests via `getToken`.\n//\n// One-shot Drizzle reads (`query`/`queryRaw`/…), local `pglite`/`ensureSynced`/`destroy` are NOT proxied in\n// S2 (the mandated attach surface is the write API + live rows + readiness) — they throw a clear\n// not-supported error. Query BUILDING still works on the tab: `drizzle`/`views` are the same build-only\n// handles `createSyncClient` exposes, compiled to SQL here and executed in the worker.\n\nimport type { Results } from \"@electric-sql/pglite\";\n\nimport type {\n MutationDiagnostics,\n SyncRuntimeStatus,\n SyncTableName,\n SyncTableRegistry,\n WriteMode,\n} from \"@pgxsinkit/contracts\";\n\nimport type { BootReport } from \"../boot-report\";\nimport type { DataExportOptions, DataExportResult } from \"../export-data\";\nimport type { DiagnosticExportOptions, DiagnosticExportResult } from \"../export-dump\";\nimport type { StoreExportOptions, StoreExportResult } from \"../export-store\";\nimport {\n buildRegistryReadHandles,\n type LiveQueryDiagnostics,\n type LiveRowsSubscription,\n type MutationBatchItem,\n type MutationDetail,\n type SubscribeLiveRowsInput,\n type SyncClient,\n type SyncTransaction,\n type SyncTransactionResult,\n} from \"../index\";\nimport type { LocalStoreVersionEvent } from \"../local-store\";\nimport { readTestStoreMarker } from \"../store-path\";\nimport { LiveRowsMaterializer } from \"./live-diff\";\nimport {\n type AttachAckPayload,\n type AttachPayload,\n type AuthTokenSnapshot,\n type BridgeCodec,\n type BridgeEvent,\n type BridgePort,\n type BridgeTransferable,\n type ExportArtefactWire,\n identityCodec,\n isBridgeEnvelope,\n type LiveDiffPayload,\n type LiveHydratedPayload,\n type LiveInitialPayload,\n postBridgeMessage,\n type ProvisionAckPayload,\n type RestoreArtefactWire,\n type RpcOp,\n type RpcResultPayload,\n type TokenRequestPayload,\n} from \"./protocol\";\n\n/** A `Worker`/`SharedWorker`-shaped handle: a dedicated `Worker` IS the port; a `SharedWorker` carries `.port`. */\ninterface WorkerLike {\n port?: BridgePort;\n postMessage?: (message: unknown, transfer?: BridgeTransferable[]) => void;\n addEventListener?: (type: \"message\", listener: (event: { data: unknown }) => void) => void;\n removeEventListener?: (type: \"message\", listener: (event: { data: unknown }) => void) => void;\n}\n\nexport interface AttachSyncClientOptions<TRegistry extends SyncTableRegistry> {\n registry: TRegistry;\n /** A native `Worker` or `SharedWorker` (or anything port-shaped). Provide this OR {@link port}. */\n worker?: WorkerLike;\n /** A raw transport port (a `MessageChannel` port in tests, a `SharedWorker.port` in a browser). */\n port?: BridgePort;\n /**\n * The tab's token provider (ADR-0032 decision 3). Richer than `createSyncClient`'s string form: the\n * worker needs the EXPIRY to apply its pull margin, so this yields `{accessToken, expiresAt}` (or null\n * when unauthenticated). Pushed at attach and answered on every worker pull-request.\n */\n getToken?: () => Promise<AuthTokenSnapshot | null>;\n /** The bound store id (resolved tab-side before attach — SharedWorker naming, ADR-0032 decision 5). */\n storeId?: string;\n /**\n * The plain store PATH (ADR-0036) the worker opens if it must create its own store — a name, not a\n * storage URL. Spread `memoryStoreForTests(...)` from `@pgxsinkit/client/testing` here for a memory store\n * in tests (it also carries the internal marker forwarded to the worker as the memory-backend override).\n */\n storePath?: string;\n syncEnabled?: boolean;\n /**\n * Which baked registry the worker boots (ADR-0032 S3) — forwarded in the attach `config.role`. A worker\n * file that bakes multiple role variants (the board's admin/member) picks by this; single-registry\n * workers ignore it.\n */\n role?: string;\n /**\n * Fresh-store prefetch-overlap hint (ADR-0032 S4), forwarded in the attach `config.freshStore`. Set true\n * ONLY when the tab knows the store is a claimed schemaless spare (never for a mapped/returning store);\n * the worker's `createSyncClient` then overlaps the shape catch-up with its local boot phases.\n */\n freshStore?: boolean;\n /**\n * Restore the worker's store from a backup on attach (ADR-0035 decision 6) — the worker-mode `restoreFrom`.\n * A `File`/`Blob` as produced by {@link SyncClient.exportStore}; the facade decomposes it into a transferred\n * `ArrayBuffer` + name/mime ({@link RestoreArtefactWire}) and the worker recomposes it for `createSyncClient`.\n * Restore rides the FIRST (boot) attach: passing it when the worker's engine has ALREADY booted rejects the\n * attach with a typed error (you cannot restore into a running store). The restored engine boots offline and\n * its recovered journal is quarantined, exactly as in-process — see `restoreFrom` on `createSyncClient`.\n */\n restoreFrom?: File | Blob;\n codec?: BridgeCodec;\n onStatusChange?: (status: SyncRuntimeStatus) => void;\n onConflict?: (details: MutationDetail[]) => void;\n onQuarantine?: (details: MutationDetail[]) => void;\n onReject?: (details: MutationDetail[]) => void;\n onSchemaChange?: (event: LocalStoreVersionEvent) => void;\n onSyncError?: (error: Error) => void;\n /**\n * Boot observability (ADR-0034): invoked once with the worker engine's finalized {@link BootReport} if the\n * engine's boot finalizes WHILE this tab is attached (the one-shot `boot-report` broadcast). A tab that\n * attaches AFTER the boot never receives the push — it reads the report via {@link SyncClient.bootReport}.\n */\n onBootReport?: (report: BootReport) => void;\n}\n\n/**\n * The worker-attached client: `SyncClient`'s shape, worker-proxied, plus `notifyAuthChanged` (re-push the\n * token after an app auth-state change, ADR-0032 decision 3). The unsupported one-shot-read members throw.\n */\nexport type AttachedSyncClient<TRegistry extends SyncTableRegistry> = SyncClient<TRegistry> & {\n notifyAuthChanged: () => void;\n /**\n * Forward the app's Offline toggle to the worker (ADR-0032 S3). The worker owns convergence, so the\n * tab cannot gate a local trigger; this sends `set-online`, which suppresses/resumes the worker's flush\n * passes (resuming fires one immediate pass). The in-process client gates its own `autoSync` instead.\n */\n setOnline: (online: boolean) => void;\n};\n\nexport async function attachSyncClient<const TRegistry extends SyncTableRegistry>(\n options: AttachSyncClientOptions<TRegistry>,\n): Promise<AttachedSyncClient<TRegistry>> {\n const codec = options.codec ?? identityCodec;\n const port = resolvePort(options);\n\n // ─── Correlation + subscription bookkeeping ──────────────────────────────────────────────────────\n let nextId = 0;\n const newId = (prefix: string) => `${prefix}-${++nextId}`;\n const rpcPending = new Map<string, { resolve: (value: unknown) => void; reject: (error: Error) => void }>();\n const initialPending = new Map<\n string,\n { resolve: (payload: LiveInitialPayload) => void; reject: (error: Error) => void }\n >();\n const diffHandlers = new Map<string, (diff: Omit<LiveDiffPayload, \"queryId\">) => void>();\n // Resolvers for per-subscription `hydrated` promises, keyed by queryId. The worker posts\n // `live-hydrated` on the same port as the diff stream, strictly after the catch-up rows — so\n // resolution here guarantees the rows have already been applied by the materializer.\n const hydratedPending = new Map<string, () => void>();\n // Set once this tab detaches (explicit `stop()` OR a terminal `pagehide`). Guards NEW operations (they\n // reject at once) and lets `detachFromWorker` settle every outstanding promise — the port listener is torn\n // down on detach, so an unsettled `rpc`/`live-initial` waiter would otherwise hang forever (ADR-0040 P2).\n let detached = false;\n const detachError = () => new Error(\"[pgxsinkit] client detached — the tab released its worker attachment\");\n\n // ─── Status + readiness ──────────────────────────────────────────────────────────────────────────\n const status: SyncRuntimeStatus = { phase: \"booting\", isRunning: false };\n let resolveReady!: () => void;\n const ready = new Promise<void>((resolve) => {\n resolveReady = resolve;\n });\n let readyResolved = false;\n const readyGroups = new Set<string>();\n const groupWaiters = new Map<string, Array<() => void>>();\n\n // ─── Auth: push at attach + on notifyAuthChanged, answer pull-requests ────────────────────────────\n const pushToken = async () => {\n const token = options.getToken ? await options.getToken() : null;\n postBridgeMessage(port, codec, \"token-push\", token);\n };\n const answerPull = async (requestId: string) => {\n const token = options.getToken ? await options.getToken() : null;\n postBridgeMessage(port, codec, \"token-response\", { requestId, token });\n };\n\n // ─── Inbound message routing ─────────────────────────────────────────────────────────────────────\n const markReady = () => {\n if (readyResolved) return;\n readyResolved = true;\n resolveReady();\n };\n // Record a group as ready and settle any waiters — shared by the discrete `groupReady` edge and the\n // status snapshot's `status.groups` merge (ADR-0032 FIX 4), so a tab attaching after the edge fired\n // still resolves `client.groupReady(table)` off the snapshot it gets at attach.\n const markGroupReady = (groupKey: string) => {\n readyGroups.add(groupKey);\n const waiters = groupWaiters.get(groupKey);\n if (waiters) {\n groupWaiters.delete(groupKey);\n for (const resolve of waiters) resolve();\n }\n };\n const onEvent = (event: BridgeEvent) => {\n switch (event.kind) {\n case \"status\": {\n Object.assign(status, event.status);\n options.onStatusChange?.(event.status);\n // Match the in-process contract EXACTLY (ADR-0032 FIX 3): `ready` resolves ONLY from phase\n // \"ready\" (all eager groups caught up, or the syncEnabled:false path). `auth-needed`/`degraded`\n // do NOT resolve it — an engine stuck retrying auth keeps `ready` pending, as in-process.\n if (event.status.phase === \"ready\") markReady();\n // Late-attach group merge (ADR-0032 FIX 4): fold every already-ready group from the snapshot.\n for (const [groupKey, ready] of Object.entries(event.status.groups ?? {})) {\n if (ready) markGroupReady(groupKey);\n }\n break;\n }\n case \"groupReady\": {\n markGroupReady(event.groupKey);\n break;\n }\n case \"conflict\":\n options.onConflict?.(event.details as MutationDetail[]);\n break;\n case \"quarantine\":\n options.onQuarantine?.(event.details as MutationDetail[]);\n break;\n case \"reject\":\n options.onReject?.(event.details as MutationDetail[]);\n break;\n case \"schema-change\":\n options.onSchemaChange?.(event.event as LocalStoreVersionEvent);\n break;\n case \"sync-error\":\n options.onSyncError?.(new Error(event.message));\n break;\n case \"boot-report\":\n // Boot observability (ADR-0034): the one-shot push for a tab attached at finalize. A late tab never\n // gets this event and pulls the report via `client.bootReport()` instead.\n options.onBootReport?.(event.report);\n break;\n case \"debug\": {\n // Re-print the worker's rail line gated on THIS tab's own flag, origin-tagged with the worker's\n // monotonic stamp (ADR-0032 decision 7) — a SharedWorker's own console is otherwise invisible.\n if ((globalThis as { __pgxsinkitDebug?: boolean }).__pgxsinkitDebug === true) {\n const line = `[pgxsinkit·w ${event.stamp.toFixed(0)}ms] ${event.line}`;\n if (event.data) console.debug(line, event.data);\n else console.debug(line);\n }\n break;\n }\n case \"timing\":\n break;\n default:\n break;\n }\n };\n\n const listener = (message: { data: unknown }) => {\n if (!isBridgeEnvelope(message.data)) return;\n const envelope = message.data;\n const payload = codec.decode(envelope.payload);\n switch (envelope.type) {\n case \"attach-ack\": {\n const ack = payload as AttachAckPayload;\n // A boot failure crosses in the ack's `error` (ADR-0032 FIX 1): reject the handshake so\n // `attachSyncClient` rejects instead of hanging forever. On success, the engine exists and the\n // status event that follows drives `ready`; `engineReady` covers a LATE attach whose engine already\n // fired its monotonic `ready` before this ack (FIX 3), so resolve `ready` straight away.\n if (ack.error) {\n attachAckReject?.(rebuildError(ack.error));\n } else {\n if (ack.engineReady) markReady();\n attachAckResolve?.(ack);\n }\n break;\n }\n case \"token-request\":\n void answerPull((payload as TokenRequestPayload).requestId);\n break;\n case \"rpc-result\": {\n const id = envelope.id;\n if (id == null) break;\n const result = payload as RpcResultPayload;\n const pending = rpcPending.get(id);\n if (pending) {\n rpcPending.delete(id);\n if (result.ok) pending.resolve(result.value);\n else pending.reject(rebuildError(result.error));\n break;\n }\n // A failed `subscribe` is reported as an `rpc-result` correlated by the subscribe's envelope id\n // (the worker has no client to hand an initial snapshot), so route the miss to the initial waiter\n // (ADR-0032 FIX 2). A successful subscribe never lands here — it resolves via `live-initial`.\n const initial = initialPending.get(id);\n if (initial && !result.ok) {\n initialPending.delete(id);\n initial.reject(rebuildError(result.error));\n }\n break;\n }\n case \"live-initial\": {\n const id = envelope.id;\n const initial = payload as LiveInitialPayload;\n if (id != null) {\n const pending = initialPending.get(id);\n if (pending) {\n initialPending.delete(id);\n pending.resolve(initial);\n }\n }\n break;\n }\n case \"live-diff\": {\n const diff = payload as LiveDiffPayload;\n diffHandlers.get(diff.queryId)?.(diff);\n break;\n }\n case \"live-hydrated\": {\n const { queryId } = payload as LiveHydratedPayload;\n hydratedPending.get(queryId)?.();\n hydratedPending.delete(queryId);\n break;\n }\n case \"event\":\n onEvent(payload as BridgeEvent);\n break;\n default:\n break;\n }\n };\n port.addEventListener(\"message\", listener);\n port.start?.();\n\n // ─── RPC helper ──────────────────────────────────────────────────────────────────────────────────\n const rpc = <T>(op: RpcOp, args: unknown[]): Promise<T> => {\n // A detached client has no live port listener, so a worker reply could never resolve this — reject at\n // once rather than register a forever-pending waiter (ADR-0040 P2).\n if (detached) return Promise.reject(detachError());\n const id = newId(\"rpc\");\n return new Promise<T>((resolve, reject) => {\n rpcPending.set(id, { resolve: resolve as (value: unknown) => void, reject });\n postBridgeMessage(port, codec, \"rpc\", { op, args }, id);\n });\n };\n\n // ─── Attach handshake ────────────────────────────────────────────────────────────────────────────\n let attachAckResolve: ((ack: AttachAckPayload) => void) | null = null;\n let attachAckReject: ((error: Error) => void) | null = null;\n const attachAck = new Promise<AttachAckPayload>((resolve, reject) => {\n attachAckResolve = resolve;\n attachAckReject = reject;\n });\n\n // ─── Detach (explicit stop AND page teardown) ──────────────────────────────────────────────────────\n // The platform fires NO close event on a SharedWorker port — a tab that simply closes would leave its\n // subscriptions (and their per-write rerun cost) alive in the worker for the worker's whole lifetime\n // (ADR-0040 decision 1; surfaced by the two-tab board e2e). So the same detach runs from `stop()` AND from\n // `pagehide` with `persisted === false` — the terminal signal of a real close/navigate-away. A\n // bfcache-parked page (`persisted === true`) keeps its attachment: its port survives parking and resumes\n // on restore, so detaching there would strand the restored page. Idempotent — pagehide then stop is safe.\n //\n // Installed BEFORE the attach handshake is posted/awaited (ADR-0040 P2): a tab that closes DURING a slow\n // worker boot must still send `detach` and reject the pending attach-ack, rather than leaving the worker\n // holding stale port/token bookkeeping for a page that is already gone. Pre-ack every pending map below is\n // empty, so the settlement loops are no-ops except for the attach-ack rejection.\n const detachFromWorker = (): void => {\n if (detached) return;\n detached = true;\n status.isRunning = false;\n // Detach THIS tab; the worker engine keeps running for other tabs (ADR-0032 decision 2).\n for (const queryId of diffHandlers.keys()) postBridgeMessage(port, codec, \"unsubscribe\", { queryId });\n diffHandlers.clear();\n postBridgeMessage(port, codec, \"detach\", null);\n // Settle every tab-side promise now the port listener is about to go (ADR-0040 P2) — otherwise an\n // operation still awaiting a worker reply hangs forever. RPCs and initial subscribes promise DATA, so\n // REJECT them (fabricating a value is worse than a clear failure); hydration and group-ready waiters are\n // DONENESS signals, so RESOLVE them (their awaiters are void-chained hook code that should settle, not\n // throw). The attach-ack is rejected too so a detach DURING boot rejects `attachSyncClient` (a no-op once\n // it has already settled).\n attachAckReject?.(detachError());\n for (const pending of rpcPending.values()) pending.reject(detachError());\n rpcPending.clear();\n for (const pending of initialPending.values()) pending.reject(detachError());\n initialPending.clear();\n for (const resolve of hydratedPending.values()) resolve();\n hydratedPending.clear();\n for (const waiters of groupWaiters.values()) for (const resolve of waiters) resolve();\n groupWaiters.clear();\n if (pagehideListener) pageWindow?.removeEventListener(\"pagehide\", pagehideListener);\n port.removeEventListener(\"message\", listener);\n port.close?.();\n };\n // Structural window guard — this file compiles without the DOM lib (it also runs under tests/workers).\n interface PageLifecycleWindowLike {\n addEventListener(type: \"pagehide\", handler: (event: { persisted: boolean }) => void): void;\n removeEventListener(type: \"pagehide\", handler: (event: { persisted: boolean }) => void): void;\n }\n const pageWindow = (globalThis as { window?: PageLifecycleWindowLike }).window;\n const pagehideListener = pageWindow\n ? (event: { persisted: boolean }) => {\n if (!event.persisted) detachFromWorker();\n }\n : undefined;\n if (pagehideListener) pageWindow?.addEventListener(\"pagehide\", pagehideListener);\n\n const initialToken = options.getToken ? await options.getToken() : null;\n // The testing memory-backend override travels as an explicit wire field, not the symbol marker — a symbol\n // does not survive `postMessage` structured clone (ADR-0036). Read it off the spread helper's options here.\n const memoryOverride = readTestStoreMarker(options) === \"memory\";\n // Restore (ADR-0035 decision 6): a `File`/`Blob` cannot cross as a transferable, so decompose it into a\n // zero-copy `ArrayBuffer` + name/mime (the `ExportArtefactWire` pattern in reverse) and list the buffer on\n // the attach `postMessage`'s transfer list. Read the bytes BEFORE building the payload (async).\n const restoreWire: RestoreArtefactWire | undefined = options.restoreFrom\n ? {\n buffer: await options.restoreFrom.arrayBuffer(),\n fileName: options.restoreFrom instanceof File ? options.restoreFrom.name : \"restore.pgdata.tar\",\n mimeType: options.restoreFrom.type || \"application/octet-stream\",\n }\n : undefined;\n const attachPayload: AttachPayload = {\n token: initialToken,\n ...(options.storeId ? { storeId: options.storeId } : {}),\n ...(options.storePath ? { storePath: options.storePath } : {}),\n ...(memoryOverride ? { testStoreBackend: \"memory\" as const } : {}),\n ...(restoreWire ? { restore: restoreWire } : {}),\n ...(options.syncEnabled != null || options.role != null || options.freshStore != null\n ? {\n config: {\n ...(options.syncEnabled != null ? { syncEnabled: options.syncEnabled } : {}),\n ...(options.role != null ? { role: options.role } : {}),\n ...(options.freshStore != null ? { freshStore: options.freshStore } : {}),\n },\n }\n : {}),\n };\n postBridgeMessage(port, codec, \"attach\", attachPayload, undefined, restoreWire ? [restoreWire.buffer] : undefined);\n try {\n await attachAck;\n } catch (error) {\n // The worker's engine boot failed (ADR-0032 FIX 1) OR a terminal pagehide rejected the ack mid-boot\n // (ADR-0040 P2): run the full detach so BOTH the message listener AND the pagehide listener are removed\n // (no port/window handler leaks), then let the error propagate out of `attachSyncClient`. Idempotent, so\n // a pagehide that already detached makes this a cheap no-op.\n detachFromWorker();\n throw error;\n }\n status.isRunning = true;\n\n // ─── Live-rows seam (ADR-0032 S2 §4) ─────────────────────────────────────────────────────────────\n const subscribeLiveRows = async <TRow extends Record<string, unknown>>(\n input: SubscribeLiveRowsInput,\n onRows: (rows: TRow[]) => void,\n ): Promise<LiveRowsSubscription<TRow>> => {\n // A detached client has no port listener, so `live-initial` could never arrive — reject at once rather\n // than register a forever-pending initial waiter (ADR-0040 P2).\n if (detached) throw detachError();\n const queryId = newId(\"live\");\n const id = newId(\"sub\");\n const materializer = new LiveRowsMaterializer<TRow>(input.pkColumns);\n diffHandlers.set(queryId, (diff) => {\n onRows(materializer.apply(diff));\n });\n let initial: LiveInitialPayload;\n try {\n initial = await new Promise<LiveInitialPayload>((resolve, reject) => {\n initialPending.set(id, { resolve, reject });\n postBridgeMessage(\n port,\n codec,\n \"subscribe\",\n {\n queryId,\n sql: input.sql,\n params: [...input.params],\n ...(input.fields ? { fields: [...input.fields] } : {}),\n ...(input.pkColumns ? { pkColumns: [...input.pkColumns] } : {}),\n ...(input.use ? { use: [...input.use] } : {}),\n // Per-subscription keep-alive hint (ADR-0040 decision 4) forwarded to the worker's manager.\n ...(input.keepAliveMs != null ? { keepAliveMs: input.keepAliveMs } : {}),\n },\n id,\n );\n });\n } catch (error) {\n // The worker rejected the subscribe (invalid SQL, etc.); the initial-payload waiter rejected via the\n // `rpc-result` route (ADR-0032 FIX 2). Drop the pre-registered diff handler so no orphan survives.\n diffHandlers.delete(queryId);\n throw error;\n }\n const initialRows = materializer.seed(initial.rows as TRow[]);\n // Pending groups present → build the `hydrated` promise the worker settles via `live-hydrated` (posted\n // after the catch-up rows on the same port — rows-before-signal). A missing/empty `hydratingTables`\n // means every referenced group (eager OR lazy) was already ready (steady state) or sync is disabled:\n // no hydration is pending, so no promise. Resolved on unsubscribe too, so an abandoned subscription\n // never leaves a forever-pending promise behind.\n let hydrated: Promise<void> | undefined;\n if (initial.hydratingTables && initial.hydratingTables.length > 0) {\n hydrated = new Promise<void>((resolve) => {\n hydratedPending.set(queryId, resolve);\n });\n }\n return {\n initialRows,\n unsubscribe: () => {\n diffHandlers.delete(queryId);\n hydratedPending.get(queryId)?.();\n hydratedPending.delete(queryId);\n postBridgeMessage(port, codec, \"unsubscribe\", { queryId });\n },\n // The lazy relations the worker's guard activated for this query (observability). `hydrated` — driven\n // by `hydratingTables`, not this — resolves once every pending group's caught-up rows are delivered.\n ...(initial.lazyTables ? { lazyTables: initial.lazyTables } : {}),\n ...(hydrated ? { hydrated } : {}),\n };\n };\n\n // ─── Assembled client ────────────────────────────────────────────────────────────────────────────\n const { drizzle, views } = buildRegistryReadHandles(options.registry);\n const notSupported = (name: string) => (): never => {\n throw new Error(\n `[pgxsinkit] ${name} is not available on a worker-attached client (ADR-0032 S2). Use the live-rows hooks / subscribeLiveRows for reads, the write API for mutations.`,\n );\n };\n\n const groupKeyForTable = (table: SyncTableName<TRegistry>): string | undefined => {\n const entry = options.registry[table];\n return entry?.consistencyGroup ?? entry?.shape?.shapeKey;\n };\n\n const client: AttachedSyncClient<TRegistry> = {\n drizzle,\n views,\n // The tab has no local PGlite; reads go through the live-rows bridge. Touching `.pglite` is a misuse.\n pglite: new Proxy(\n {},\n {\n get: notSupported(\"client.pglite\"),\n },\n ) as never,\n tables: Object.fromEntries(\n Object.keys(options.registry).map((tableKey) => [\n tableKey,\n {\n key: tableKey,\n mode: options.registry[tableKey as SyncTableName<TRegistry>]!.mode,\n create: (input: unknown) => rpc<void>(\"create\", [tableKey, input]),\n update: (entityKey: Record<string, string>, patch: unknown) =>\n rpc<void>(\"update\", [tableKey, entityKey, patch]),\n delete: (entityKey: Record<string, string>) => rpc<void>(\"delete\", [tableKey, entityKey]),\n },\n ]),\n ) as SyncClient<TRegistry>[\"tables\"],\n ready,\n status,\n start: async () => {\n await ready;\n },\n stop: async () => {\n detachFromWorker();\n },\n destroy: notSupported(\"client.destroy\"),\n dropReadCache: notSupported(\"client.dropReadCache\"),\n flush: (table) => rpc<void>(\"flush\", [table]),\n reconcile: (table) => rpc<void>(\"reconcile\", [table]),\n retryFailed: (table) => rpc<void>(\"retryFailed\", [table]),\n recoverSending: (table) => rpc<void>(\"recoverSending\", [table]),\n readMutationDetails: (table) => rpc<MutationDetail[]>(\"readMutationDetails\", [table]),\n // Inspection reads run in the worker (ADR-0032 S2) — the same surface as the in-process client. `pglite`\n // itself stays blocked (below); these route the raw statement over the RPC round-trip instead.\n rawQuery: (sql, params, options) => rpc<Results>(\"rawQuery\", [sql, params, options]),\n rawExec: (sql, options) => rpc<Results[]>(\"rawExec\", [sql, options]),\n mutate: {\n create: (table, input) => rpc<void>(\"create\", [table, input]),\n update: (table, entityKey, patch) => rpc<void>(\"update\", [table, entityKey, patch]),\n delete: (table, entityKey) => rpc<void>(\"delete\", [table, entityKey]),\n batch: (items) => rpc<void>(\"batch\", [items]),\n },\n discardConflict: (table, entityKey) => rpc<void>(\"discardConflict\", [table, entityKey]),\n discardQuarantined: (table, entityKey) => rpc<void>(\"discardQuarantined\", [table, entityKey]),\n diagnostics: (table) => rpc<{ mutation: MutationDiagnostics }>(\"diagnostics\", [table]),\n query: notSupported(\"client.query\"),\n queryRow: notSupported(\"client.queryRow\"),\n queryRaw: notSupported(\"client.queryRaw\"),\n queryRawRow: notSupported(\"client.queryRawRow\"),\n ensureSynced: notSupported(\"client.ensureSynced\"),\n isSynced: notSupported(\"client.isSynced\"),\n // In SharedWorker mode the engine is SHARED, so a desync from one tab reverts the consistency group for\n // EVERY attached tab — inherent to desync's group-wide semantics (that footgun is why the narrower\n // `discardEphemeral` exists). The RPC runs the worker's real `desync` (same refusals as in-process).\n desync: (key) => rpc<void>(\"desync\", [key]),\n // Scoped, multi-tab-safe finalize (ADR-0021): drops an ephemeral relation's local rows and reverts it to\n // dormant. Safe under a shared engine because an ephemeral window is per-delivery-session and inherently\n // single-consumer; the RPC runs the worker's real `discardEphemeral` (refuses persistent members).\n discardEphemeral: (key) => rpc<void>(\"discardEphemeral\", [key]),\n // The worker activates lazy relations inside its `subscribe` handler (via the `use` hint), so the tab's\n // `prepareQuery` is a no-op — the live-rows subscription is already guarded worker-side (ADR-0021).\n // Empty `lazyTables`: the real scan's keys travel back on the subscription itself (`live-initial`).\n prepareQuery: async () => ({ lazyTables: [] }),\n // The worker computes the pending hydrating tables inside its `subscribe` handler (on its owned client)\n // and reports them back on `live-initial` (`hydratingTables`), so the tab-side seam is a no-op here.\n hydratingTablesFor: () => [],\n transaction: async ({ mode }: { mode: WriteMode }, run) => {\n // Collect the unit's mutations tab-side (the run callback cannot cross the wire), then RPC the\n // serialized items + mode; the worker replays them into a real `client.transaction` (matching acks).\n const collected: MutationBatchItem<TRegistry>[] = [];\n const txTables = Object.fromEntries(\n Object.keys(options.registry).map((tableKey) => [\n tableKey,\n {\n create: (input: unknown) => {\n collected.push({ table: tableKey, kind: \"create\", input } as MutationBatchItem<TRegistry>);\n },\n update: (entityKey: Record<string, string>, patch: unknown) => {\n collected.push({ table: tableKey, kind: \"update\", entityKey, patch } as MutationBatchItem<TRegistry>);\n },\n updateBlind: (entityKey: Record<string, string>, patch: unknown) => {\n // ADR-0022 addendum: the `blind` flag rides the serialized item across the wire; the worker\n // replays it through `client.transaction`'s `updateBlind`, identical to the in-process client.\n collected.push({\n table: tableKey,\n kind: \"update\",\n entityKey,\n patch,\n blind: true,\n } as MutationBatchItem<TRegistry>);\n },\n delete: (entityKey: Record<string, string>) => {\n collected.push({ table: tableKey, kind: \"delete\", entityKey } as MutationBatchItem<TRegistry>);\n },\n },\n ]),\n ) as SyncTransaction<TRegistry>[\"tables\"];\n await run({ tables: txTables });\n if (collected.length === 0) return { acks: [] };\n return rpc<SyncTransactionResult>(\"transaction\", [{ mode, items: collected }]);\n },\n groupReady: async (table) => {\n // A detached client will never receive further `groupReady`/status edges — reject at once rather than\n // register a waiter that detach already drained (ADR-0040 P2).\n if (detached) throw detachError();\n const groupKey = groupKeyForTable(table);\n if (groupKey == null || readyGroups.has(groupKey)) return;\n await new Promise<void>((resolve) => {\n const waiters = groupWaiters.get(groupKey) ?? [];\n waiters.push(resolve);\n groupWaiters.set(groupKey, waiters);\n });\n },\n subscribeLiveRows,\n // Boot observability (ADR-0034): pull the worker engine's stored boot report over the bridge — returns\n // the same report regardless of when this tab attached (a late tab reads a boot that predates it).\n bootReport: () => rpc<BootReport | null>(\"bootReport\", []),\n // Live-query diagnostics (ADR-0040 decision 5): pull the worker manager's per-entry snapshot over the\n // bridge (digests + counts only — plain objects that structured-clone across the wire).\n liveQueryDiagnostics: () => rpc<LiveQueryDiagnostics[]>(\"liveQueryDiagnostics\", []),\n // Store backup (ADR-0035): the worker runs the live export on its owned client (its lifecycle slot\n // serialises it against every tab). The dump crosses back as a transferred `ArrayBuffer`; rebuild the\n // `File` tab-side from the wire form — NOT in the notSupported set (unlike the local `pglite` reads).\n exportStore: async (exportOptions?: StoreExportOptions): Promise<StoreExportResult> => {\n const wire = await rpc<ExportArtefactWire>(\"exportStore\", [exportOptions]);\n return {\n file: new File([wire.buffer], wire.fileName, { type: wire.mimeType }),\n // The wire carries the discriminated union; `exportStore` always round-trips a store-backup report.\n report: wire.report as StoreExportResult[\"report\"],\n };\n },\n // Diagnostic dump (ADR-0035): the worker runs the throwaway-clone dump on its owned client (same\n // lifecycle slot as every tab). The SQL crosses back as the same transferred `ArrayBuffer`; rebuild the\n // `File` tab-side. NOT in the notSupported set (unlike the local `pglite` reads).\n exportDiagnostics: async (exportOptions?: DiagnosticExportOptions): Promise<DiagnosticExportResult> => {\n const wire = await rpc<ExportArtefactWire>(\"exportDiagnostics\", [exportOptions]);\n return {\n file: new File([wire.buffer], wire.fileName, { type: wire.mimeType }),\n // The wire carries the discriminated union; `exportDiagnostics` always round-trips a diagnostic-dump report.\n report: wire.report as DiagnosticExportResult[\"report\"],\n };\n },\n // Data export (ADR-0035): the worker runs the drain-guarded `pg_dump -t` export on its owned client (same\n // lifecycle slot as every tab). The portable SQL crosses back as the same transferred `ArrayBuffer`;\n // rebuild the `File` tab-side. A `DataExportDrainError` surfaces as the rejected RPC (deserialised tab-side).\n exportData: async (exportOptions?: DataExportOptions): Promise<DataExportResult> => {\n const wire = await rpc<ExportArtefactWire>(\"exportData\", [exportOptions]);\n return {\n file: new File([wire.buffer], wire.fileName, { type: wire.mimeType }),\n // The wire carries the discriminated union; `exportData` always round-trips a data-export report.\n report: wire.report as DataExportResult[\"report\"],\n };\n },\n notifyAuthChanged: () => {\n void pushToken();\n },\n setOnline: (online: boolean) => {\n postBridgeMessage(port, codec, \"set-online\", { online });\n },\n };\n\n return client;\n}\n\n/**\n * Pre-spawn a worker's store WITHOUT attaching (ADR-0032 decision 5). Sent at the board's login screen\n * against a freshly-named spare `SharedWorker`: the worker runs PGlite `create`/initdb only and holds the\n * raw store idle until the real {@link attachSyncClient} claim adopts it. Resolves when the worker acks the\n * provision (its initdb settled); rejects only if the worker reports the create failed — the caller treats\n * either outcome as best-effort, since attach falls back to a fresh create regardless.\n */\nexport function provisionSyncWorker<TRegistry extends SyncTableRegistry>(\n options: Pick<AttachSyncClientOptions<TRegistry>, \"worker\" | \"port\" | \"storeId\" | \"storePath\" | \"codec\">,\n): Promise<void> {\n const codec = options.codec ?? identityCodec;\n const port = resolvePort(options);\n // The testing memory-backend override travels as an explicit wire field (a symbol does not survive\n // structured clone, ADR-0036) — read it off the spread helper's options and forward it to the worker.\n const memoryOverride = readTestStoreMarker(options) === \"memory\";\n return new Promise<void>((resolve, reject) => {\n const listener = (message: { data: unknown }) => {\n if (!isBridgeEnvelope(message.data)) return;\n if (message.data.type !== \"provision-ack\") return;\n port.removeEventListener(\"message\", listener);\n const ack = codec.decode(message.data.payload) as ProvisionAckPayload;\n if (ack.ok) resolve();\n else reject(new Error(ack.error?.message ?? \"worker provision failed\"));\n };\n port.addEventListener(\"message\", listener);\n port.start?.();\n postBridgeMessage(port, codec, \"provision\", {\n ...(options.storeId ? { storeId: options.storeId } : {}),\n ...(options.storePath ? { storePath: options.storePath } : {}),\n ...(memoryOverride ? { testStoreBackend: \"memory\" as const } : {}),\n });\n });\n}\n\n/** Resolve the transport port from the options: an explicit port, a SharedWorker's `.port`, or a Worker itself. */\nfunction resolvePort(options: { port?: BridgePort; worker?: WorkerLike }): BridgePort {\n if (options.port) return options.port;\n const worker = options.worker;\n if (!worker) throw new Error(\"attachSyncClient: provide a `worker` or a `port`.\");\n if (worker.port) return worker.port;\n if (worker.postMessage && worker.addEventListener && worker.removeEventListener) {\n return worker as BridgePort;\n }\n throw new Error(\"attachSyncClient: the provided `worker` is neither a Worker nor a SharedWorker port.\");\n}\n\n/** Rebuild an Error from the bridge's serialized `{message, detail}` shape, carrying `detail` through. */\nfunction rebuildError(error: RpcResultPayload[\"error\"]): Error {\n const rebuilt = new Error(error?.message ?? \"worker rpc failed\");\n if (error && \"detail\" in error && error.detail !== undefined) {\n (rebuilt as Error & { detail?: unknown }).detail = error.detail;\n }\n return rebuilt;\n}\n",
|
|
37
|
+
"// The bridge protocol (ADR-0032 S2). Everything that crosses between a tab and the shared sync engine\n// travels as a typed {@link BridgeEnvelope} over a minimal {@link BridgePort} (a MessagePort-shaped\n// transport). The router only ever inspects the envelope's `type`/`id`; its `payload` is OPAQUE to the\n// router and always passes through a {@link BridgeCodec}, so a later columnar/transferable codec can be\n// swapped in WITHOUT any protocol change (see BridgeCodec's doc).\n//\n// Deliberately transport-agnostic: `defineSyncWorker` and `attachSyncClient` both talk to a `BridgePort`,\n// never a real `Worker`/`SharedWorker` directly — which is exactly why the whole bridge is unit-testable\n// over bun's `MessageChannel` with no worker at all.\n\nimport type { SyncRuntimeStatus } from \"@pgxsinkit/contracts\";\n\nimport type { BootReport } from \"../boot-report\";\nimport type { ExportReport } from \"../export-store\";\n\nexport const BRIDGE_CHANNEL = \"pgxsinkit-bridge\" as const;\nexport const BRIDGE_PROTOCOL_VERSION = 1 as const;\n\n/**\n * A structured-clone transferable (an `ArrayBuffer`, a `MessagePort`, …). The library carries no DOM lib\n * dependency (like the convergence triggers), so this is the toolkit's own name for the type a future\n * columnar codec would hand to `postMessage`'s transfer list. v1's identity codec never produces one.\n */\nexport type BridgeTransferable = unknown;\n\n/**\n * The minimal MessagePort-shaped transport the bridge needs — the intersection of a real `MessagePort`,\n * a `SharedWorker` port, and a dedicated `Worker`/`self`. Injected everywhere so the protocol layer is\n * exercised with a plain `MessageChannel` (no Worker) in tests. `start()` is optional (MessagePort needs\n * it, `Worker`/`self` do not); `close()` is optional (a dedicated `self` cannot be closed by the tab).\n */\nexport interface BridgePort {\n postMessage: (message: unknown, transfer?: BridgeTransferable[]) => void;\n addEventListener: (type: \"message\", listener: (event: { data: unknown }) => void) => void;\n removeEventListener: (type: \"message\", listener: (event: { data: unknown }) => void) => void;\n start?: () => void;\n close?: () => void;\n}\n\n/**\n * The wire envelope. `payload` is the codec-encoded body — opaque to the router, which only routes on\n * `type` and correlates on `id`. Keeping the body opaque is what lets a future codec return a columnar\n * buffer (a transferable) in `payload` without any change to routing.\n */\nexport interface BridgeEnvelope {\n ch: typeof BRIDGE_CHANNEL;\n v: typeof BRIDGE_PROTOCOL_VERSION;\n type: BridgeMessageType;\n /** Correlation id for request/response pairs (rpc, subscribe, token pull). Absent for fire-and-forget fanout. */\n id?: string;\n /** Codec-encoded body — opaque to the router; decode with the same {@link BridgeCodec}. */\n payload: unknown;\n}\n\nexport type BridgeMessageType =\n // tab → worker\n | \"provision\"\n | \"attach\"\n | \"detach\"\n | \"token-push\"\n | \"token-response\"\n | \"rpc\"\n | \"subscribe\"\n | \"unsubscribe\"\n | \"wake\"\n | \"set-online\"\n // worker → tab\n | \"provision-ack\"\n | \"attach-ack\"\n | \"token-request\"\n | \"rpc-result\"\n | \"live-initial\"\n | \"live-diff\"\n | \"live-hydrated\"\n | \"event\";\n\n// ─── Payload shapes ───────────────────────────────────────────────────────────\n\n/** A single auth token snapshot the tab owns and pushes to the worker (ADR-0032 decision 3). */\nexport interface AuthTokenSnapshot {\n accessToken: string;\n /** Absolute expiry in epoch milliseconds (`Date.now()`-comparable), so the worker can apply an expiry margin. */\n expiresAt: number;\n}\n\n/**\n * tab → worker: pre-spawn the store WITHOUT booting the engine (ADR-0032 decision 5). Sent at the\n * login screen against the freshly-named spare worker: the worker only runs PGlite `create`/initdb\n * (off every thread that matters) and holds the raw store idle — no schema, no shape streams, no token\n * — until the real {@link AttachPayload} arrives (with config + token) and adopts the provisioned store.\n * Role-agnostic on purpose: the spare is minted before the user (and role) is known, so provisioning\n * carries no registry — the schema is applied at attach with the role-resolved registry.\n */\nexport interface ProvisionPayload {\n /** The bound store id (informational; naming is done tab-side via the SharedWorker name). */\n storeId?: string;\n /**\n * The plain store PATH (ADR-0036) to `create` ahead of attach — a name, not a storage URL; the worker\n * derives the backend (IndexedDB in a browser worker). When omitted, `storeId`/the worker default is used.\n */\n storePath?: string;\n /**\n * @internal INTERNAL WIRE FIELD (not consumer config, ADR-0036). Carries the testing memory-backend\n * override across the bridge, because a symbol-keyed marker does NOT survive `postMessage` structured\n * clone — so the worker's memory-store selection travels as this explicit field. Set only by the test\n * lane (via the attaching helper); a browser worker never sends it.\n */\n testStoreBackend?: \"memory\";\n}\n\n/** worker → tab: the provision completed (or failed). Lets the login screen confirm the spare is warm. */\nexport interface ProvisionAckPayload {\n ok: boolean;\n storeId?: string;\n /** Present when `!ok` — the initdb/create failed; the worker falls back to a fresh create at attach. */\n error?: { message: string };\n}\n\n/**\n * tab → worker: a store-backup tarball to restore from, carried on the boot {@link AttachPayload}\n * (ADR-0035 decision 6). The mirror image of {@link ExportArtefactWire}: a `File`/`Blob` cannot cross the\n * bridge as a transferable, so it is decomposed into its zero-copy `ArrayBuffer` (listed on `postMessage`'s\n * transfer list) plus the metadata to rebuild it, and the worker reassembles a `Blob` from\n * `buffer`/`mimeType` to hand `createSyncClient` as `restoreFrom`.\n */\nexport interface RestoreArtefactWire {\n /** The backup tarball bytes — transferred, not copied. */\n buffer: ArrayBuffer;\n /** The backup file name (informational; PGlite's `loadDataDir` reads the bytes, not the name). */\n fileName: string;\n /** The backup MIME type (`application/x-gzip` / `application/x-tar`), used to rebuild the `Blob`. */\n mimeType: string;\n}\n\n/** tab → worker: the attach handshake. The first attach boots the engine; later attaches join it. */\nexport interface AttachPayload {\n /** The bound store id (SharedWorker naming resolves it tab-side before attach — ADR-0032 decision 5). */\n storeId?: string;\n /**\n * Explicit plain store PATH (ADR-0036) if the worker should create its own store — a name, not a storage\n * URL; the worker derives the backend. When omitted, `storeId`/the worker default is used.\n */\n storePath?: string;\n /**\n * @internal INTERNAL WIRE FIELD (not consumer config, ADR-0036). Carries the testing memory-backend\n * override across the bridge — a symbol-keyed marker does not survive structured clone, so the worker's\n * memory-store selection travels as this explicit field. Set only by the test lane; never by a browser tab.\n */\n testStoreBackend?: \"memory\";\n /**\n * Restore the store from a backup on THIS attach (ADR-0035 decision 6) — the worker-mode carrier of\n * `createSyncClient`'s `restoreFrom`. Restore rides the FIRST attach (the boot attach): a `File`/`Blob`\n * cannot cross `postMessage` as a transferable, so the tab decomposes it into a transferred `ArrayBuffer`\n * plus its name/mime — the {@link ExportArtefactWire} pattern in reverse — and the worker recomposes it\n * into a `Blob` and hands it to `createSyncClient`. Absent on every ordinary attach. An attach that carries\n * this AFTER the engine has already booted is REFUSED (you cannot restore into a running store).\n */\n restore?: RestoreArtefactWire;\n /** The tab's current auth token at attach time, or null when unauthenticated. */\n token: AuthTokenSnapshot | null;\n /**\n * Serializable per-attach config overrides (kept minimal; the urls are baked into the worker). `role`\n * selects which baked registry the worker boots (ADR-0032 S3): the spare is minted role-agnostic, so\n * the role is only known at claim/attach — a single worker file bakes BOTH registries and picks here.\n * `freshStore` is the fresh-store prefetch-overlap hint (ADR-0032 S4): the tab's claim path knows a\n * claimed spare is schemaless (fresh) while a mapped/returning store never is, and forwards that here so\n * the worker's `createSyncClient` can overlap the shape catch-up with the local boot phases.\n */\n config?: { syncEnabled?: boolean; role?: string; freshStore?: boolean };\n}\n\n/**\n * tab → worker: gate the worker's outbound convergence (the board's Offline toggle, ADR-0032 S3). In\n * in-process mode the toggle gates the local `autoSync` trigger; the worker owns convergence instead, so\n * the tab forwards the flag and the worker suppresses/resumes its flush passes. Going back online fires\n * one immediate pass so queued writes flush without waiting for the next interval tick.\n */\nexport interface SetOnlinePayload {\n online: boolean;\n}\n\n/**\n * The two background boot stages the worker announces over the bridge as one-shot milestones (ADR-0041\n * stage 2). `localReadReady` is NOT in this set: under the Option B contract the `attach-ack` fires AT the\n * engine's `localReadReady`, so a tab resolves that stage from the ack itself (early OR late attach) — it\n * needs no separate milestone. `writeReady` and `bootSettled` cross in the background write/sync tail, after\n * the ack, so they DO ride milestone messages (and the late-attach ack fold).\n */\nexport type BootMilestone = \"writeReady\" | \"bootSettled\";\n\n/** worker → tab: attach acknowledged. `alreadyBooted` is false for the attach that booted the engine. */\nexport interface AttachAckPayload {\n alreadyBooted: boolean;\n /**\n * True when the engine's initial sync had ALREADY fired by the time this attach was acked (a late\n * attach, ADR-0032 FIX 3). `ready` is monotonic in-process — once it resolves it stays resolved even if\n * the phase later degrades — so a tab attaching after that moment must resolve `ready` immediately from\n * the ack, rather than wait for a phase-\"ready\" status that may never come again.\n */\n engineReady?: boolean;\n /**\n * Late-attach milestone fold (ADR-0041 stage 2): true when the engine had ALREADY crossed `writeReady` /\n * `bootSettled` by the time this attach was acked, so a tab attaching after the stage fired resolves it\n * straight from the ack rather than waiting for a `milestone` broadcast it missed. The ack fires AT\n * `localReadReady`, so that stage is always implied by a non-error ack and carries no boolean.\n */\n writeReady?: boolean;\n bootSettled?: boolean;\n /**\n * Late-attach failure fold (ADR-0041 stage 2): present when the engine's background write/sync tail had\n * already REJECTED a downstream stage before this attach was acked. The tab rejects the matching stage\n * promise (so a gated write / `bootSettled` awaiter fails loudly rather than hangs) — but the attach\n * itself still RESOLVES (the engine reached `localReadReady`; only the tail failed). A live milestone\n * failure after attach rides the `milestone-error` broadcast instead.\n */\n writeReadyError?: { message: string; detail?: unknown };\n bootSettledError?: { message: string; detail?: unknown };\n /**\n * Present when the engine boot REJECTED for this attach: the tab rejects `attachSyncClient` with this\n * message instead of hanging forever on the ack (ADR-0032 FIX 1). A later attach retries the boot. This\n * is a LOCAL-READ-CORE failure (the engine never reached `localReadReady`); a tail failure after\n * `localReadReady` uses the stage-error fields above and does NOT reject the attach.\n */\n error?: { message: string; detail?: unknown };\n}\n\n/** worker → tab: a broadcast pull-request — any attached tab may answer, first response wins (ADR-0032 decision 3). */\nexport interface TokenRequestPayload {\n requestId: string;\n}\n\n/** tab → worker: the answer to a {@link TokenRequestPayload}. `token: null` = the tab has none. */\nexport interface TokenResponsePayload {\n requestId: string;\n token: AuthTokenSnapshot | null;\n}\n\n/**\n * The RPC ops the attach facade proxies to the worker's booted client — the write API (mirrors\n * `client.mutate`/flush), mutation-state reads, and the one-shot raw inspection reads (`rawQuery`/`rawExec`).\n */\nexport type RpcOp =\n | \"create\"\n | \"update\"\n | \"delete\"\n | \"batch\"\n | \"transaction\"\n | \"flush\"\n | \"reconcile\"\n | \"retryFailed\"\n | \"recoverSending\"\n | \"discardConflict\"\n | \"discardQuarantined\"\n | \"desync\"\n | \"discardEphemeral\"\n | \"readMutationDetails\"\n | \"diagnostics\"\n | \"rawQuery\"\n | \"rawExec\"\n // Boot observability (ADR-0034): pull the worker engine's most recent completed boot report. Returns the\n // stored report (or null) regardless of when this tab attached, so a late tab reads a boot predating it.\n | \"bootReport\"\n // Live-query diagnostics (ADR-0040 decision 5): pull the worker manager's per-entry snapshot (digests +\n // counts/timings, NEVER SQL/params/rows). Returns [] before any subscription / when the manager is absent.\n | \"liveQueryDiagnostics\"\n // Store backup (ADR-0035): the worker runs the live `exportStore` on its owned client; the dump crosses\n // back as a transferred `ArrayBuffer` ({@link ExportArtefactWire}), rebuilt into a `File` tab-side.\n | \"exportStore\"\n // Diagnostic dump (ADR-0035): the worker runs `exportDiagnostics` on its owned client (live datadir dump\n // → memory throwaway clone → `pg_dump`); the SQL crosses back as the same transferred `ArrayBuffer` wire.\n | \"exportDiagnostics\"\n // Data export (ADR-0035): the worker runs `exportData` on its owned client (drain the journal → throwaway\n // clone → `pg_dump -t` per synced table); the portable SQL crosses back as the same transferred wire.\n | \"exportData\";\n\n/** tab → worker: a write/read-of-mutation-state RPC. `id` correlates the matching {@link RpcResultPayload}. */\nexport interface RpcPayload {\n op: RpcOp;\n args: unknown[];\n}\n\n/**\n * worker → tab: the wire form of ANY local-store export (ADR-0035) — the store backup's tarball OR the\n * diagnostic dump's SQL — carried as the `value` of an {@link RpcResultPayload}. The artefact crosses as a\n * transferred `ArrayBuffer` (zero-copy — the sender lists `buffer` in `postMessage`'s transfer list) plus\n * the metadata to rebuild it; the tab reconstructs a `File` from `buffer`/`fileName`/`mimeType`. A `File`\n * cannot itself be transferred, so it is decomposed here and reassembled tab-side, exactly the pattern the\n * codec's transferable seam anticipates for a zero-copy live-diff payload. `report` is the discriminated\n * {@link ExportReport} union, so the tab knows which export it round-tripped.\n */\nexport interface ExportArtefactWire {\n /** The artefact bytes (tarball or SQL) — transferred, not copied. */\n buffer: ArrayBuffer;\n /** The generated (or caller-supplied) artefact file name. */\n fileName: string;\n /** The artefact MIME type (`application/x-gzip` / `application/x-tar` for a backup, `application/sql` for a dump). */\n mimeType: string;\n /** The export report (ADR-0035), structured-cloned as a plain object — the `kind`-discriminated union. */\n report: ExportReport;\n}\n\n/** worker → tab: an RPC outcome, mirroring today's in-process resolve/reject semantics. */\nexport interface RpcResultPayload {\n ok: boolean;\n /** The resolved value (present when `ok`). */\n value?: unknown;\n /** The rejection message + optional structured detail (present when `!ok`). */\n error?: { message: string; detail?: unknown };\n}\n\n/** tab → worker: register a live query. `id` correlates the initial snapshot; `queryId` keys subsequent diffs. */\nexport interface SubscribePayload {\n queryId: string;\n sql: string;\n params: unknown[];\n /**\n * The unique output aliases the worker wraps the query's columns under so it is safe to MATERIALISE\n * (one per output column, in the compiled SQL's column order). ADDITIVE and backward-compatible: an\n * older tab omits it and the worker leaves the SQL untouched (name-keyed rows, as before); a newer tab\n * supplies it for a JOIN with same-named columns, which `live.query`/`live.incrementalQuery` otherwise\n * refuse to materialise (`column \"title\" specified more than once`). When present, result columns are\n * the aliases, so {@link pkColumns} must name a PK by its alias.\n */\n fields?: string[];\n /**\n * The result's primary-key columns, driving diff keying (§4). One column → the incremental path\n * (`live.incrementalQuery`); many → worker-side diff by composite PK; empty/absent → value-identity\n * fallback for a keyless query. When {@link fields} is supplied these name the ALIASED result columns.\n */\n pkColumns?: string[];\n /** Lazy relations to activate before the query runs (ADR-0021), forwarded to the worker's `prepareQuery`. */\n use?: string[];\n /**\n * Per-subscription keep-alive hint (ms) for the worker's live-query manager (ADR-0040 decision 4): how long\n * the shared registration should be retained after this subscription's last consumer leaves, so a matching\n * resubscribe reuses it verbatim. ADDITIVE and backward-compatible both directions — an older tab omits it\n * (the worker falls back to its `liveQueries.defaultKeepAliveMs`), and an older worker ignores it. Absent\n * means \"no hint\".\n */\n keepAliveMs?: number;\n}\n\n/** worker → tab: the initial ordered snapshot for a subscription. `id` correlates the `subscribe` request. */\nexport interface LiveInitialPayload {\n queryId: string;\n rows: Record<string, unknown>[];\n /**\n * The `lazy` relations the worker's guard activated for this query (ADR-0021) — the relations held out\n * of the eager boot set. Observability only: {@link hydratingTables}, not this, drives the tab's\n * `hydrated` promise.\n */\n lazyTables?: string[];\n /**\n * The referenced consistency groups' member tables (eager OR lazy) that were NOT YET caught up when this\n * snapshot was taken (ADR-0021 / ADR-0032). Non-empty → the tab builds a `hydrated` promise the worker\n * settles via `live-hydrated` (posted after the catch-up rows on this same port). Absent → every\n * referenced group was already ready (steady state) or sync is disabled: nothing to hydrate.\n */\n hydratingTables?: string[];\n}\n\n/**\n * worker → tab: the subscription's lazy relations have completed their initial catch-up AND the live\n * query has been refreshed against the caught-up store (ADR-0021). Posted on the SAME port as the\n * live-diff stream, strictly after the refresh-triggered diff — so when the tab sees this, the rows\n * reflecting the catch-up have already been delivered. Resolves the tab subscription's `hydrated`\n * promise (the React hooks' `hydrating` gate); never sent for a query with no pending groups (steady\n * state / sync disabled), i.e. an empty `live-initial` {@link LiveInitialPayload.hydratingTables}.\n */\nexport interface LiveHydratedPayload {\n queryId: string;\n}\n\n/**\n * worker → tab: a DIFF update for a subscription (§4). Never a full result-set resend after the initial\n * snapshot. `order` is the full ordered list of row keys (cheap — keys only, no row bodies); `added`/\n * `changed` carry only the delta row bodies; `removed` carries only the dropped keys. The tab materializer\n * rebuilds the ordered array from `order`, reusing cached row objects for keys not in `added`/`changed` so\n * an unchanged row keeps its object identity (React memo bails on `===`).\n */\nexport interface LiveDiffPayload {\n queryId: string;\n /** Every result key in ORDER BY order (the query's delivered order). */\n order: string[];\n added: { key: string; row: Record<string, unknown> }[];\n changed: { key: string; row: Record<string, unknown> }[];\n removed: string[];\n}\n\n/** worker → tab: the single broadcast event stream (ADR-0032 decision 7), re-exposed as today's callbacks. */\nexport type BridgeEvent =\n | { kind: \"status\"; status: SyncRuntimeStatus }\n | { kind: \"groupReady\"; groupKey: string }\n // Staged boot readiness (ADR-0041 stage 2): a one-shot milestone as the engine crosses a background boot\n // stage (`writeReady` / `bootSettled`), broadcast to currently-attached ports. A tab attaching AFTER a\n // stage fired never sees the broadcast — it folds the current milestone set off its `attach-ack` instead.\n // One engine crosses each stage once; every port observes the same monotonic sequence (ack fold + event).\n | { kind: \"milestone\"; stage: BootMilestone }\n // The mirror failure edge: the background write/sync tail REJECTED a downstream stage (ADR-0041). Rejects\n // the tab's matching `writeReady` / `bootSettled` promise so an awaiter fails loudly rather than hanging;\n // `localReadReady` (and the resolved attach) are unaffected — the engine reached local-read readiness.\n | { kind: \"milestone-error\"; stage: BootMilestone; error: { message: string; detail?: unknown } }\n | { kind: \"conflict\"; details: unknown }\n | { kind: \"quarantine\"; details: unknown }\n | { kind: \"reject\"; details: unknown }\n | { kind: \"schema-change\"; event: unknown }\n | { kind: \"sync-error\"; message: string }\n | { kind: \"timing\"; label: string; ms: number; data?: Record<string, unknown> }\n // Boot observability (ADR-0034): the one-shot boot report, broadcast to currently-attached ports when the\n // engine's boot finalizes (the push counterpart of the `bootReport` pull). Later tabs read it via the pull.\n | { kind: \"boot-report\"; report: BootReport }\n // The debug rail (ADR-0032 decision 7): stamped with the WORKER's monotonic clock and origin-tagged so a\n // tab can re-print it as `[pgxsinkit·w <stamp>ms] <line>` — a SharedWorker's own console is invisible.\n | { kind: \"debug\"; stamp: number; line: string; data?: Record<string, unknown> };\n\n/** tab → worker: an app-driven wake (online/visibilitychange), treated as a convergence pass request. */\nexport interface WakePayload {\n reason: \"online\" | \"visibility\" | \"manual\";\n}\n\n// ─── Codec seam ─────────────────────────────────────────────────────────────\n\n/**\n * The codec every bridge payload crosses through (owner-mandated seam, ADR-0032 S2 §1). v1 ships exactly\n * ONE codec — {@link identityCodec}, which relies on the transport's own structured clone. The seam exists\n * so a columnar/transferable codec (e.g. one that packs live-diff rows into a shared `ArrayBuffer` and\n * returns it as a transferable) can be swapped in later WITHOUT any protocol change: the router already\n * treats `BridgeEnvelope.payload` as opaque, and `encode` may return `{ payload, transfer }` so the sender\n * hands transferables to `postMessage`. Keep encode/decode inverse and side-effect free.\n */\nexport interface BridgeCodec {\n /** Encode a raw payload into the envelope body. May declare transferables for a future zero-copy codec. */\n encode: (payload: unknown) => { payload: unknown; transfer?: BridgeTransferable[] };\n /** Decode an envelope body back into the raw payload. Inverse of {@link encode}. */\n decode: (payload: unknown) => unknown;\n}\n\n/**\n * The v1 identity codec: the body IS the payload, and the transport's structured clone does the real\n * copying. No transferables. The only codec shipped in S2 — swapping in a columnar codec later touches\n * only this object, never the message types or the router.\n */\nexport const identityCodec: BridgeCodec = {\n encode: (payload) => ({ payload }),\n decode: (payload) => payload,\n};\n\n// ─── Envelope helpers ─────────────────────────────────────────────────────────\n\n/** Build a wire envelope, running the payload through the codec. Returns the envelope + any transferables. */\nexport function encodeEnvelope(\n codec: BridgeCodec,\n type: BridgeMessageType,\n payload: unknown,\n id?: string,\n): { envelope: BridgeEnvelope; transfer?: BridgeTransferable[] } {\n const encoded = codec.encode(payload);\n const envelope: BridgeEnvelope = {\n ch: BRIDGE_CHANNEL,\n v: BRIDGE_PROTOCOL_VERSION,\n type,\n payload: encoded.payload,\n ...(id !== undefined ? { id } : {}),\n };\n return { envelope, ...(encoded.transfer ? { transfer: encoded.transfer } : {}) };\n}\n\n/** Type-guard a received message as a bridge envelope of the current protocol version (ignore foreign traffic). */\nexport function isBridgeEnvelope(data: unknown): data is BridgeEnvelope {\n return (\n typeof data === \"object\" &&\n data !== null &&\n (data as { ch?: unknown }).ch === BRIDGE_CHANNEL &&\n (data as { v?: unknown }).v === BRIDGE_PROTOCOL_VERSION\n );\n}\n\n/**\n * Send a typed message over a port: encode → post (with any transferables). The one write choke point.\n * `transfer` lets a caller declare payload-specific transferables (e.g. a store-backup's `ArrayBuffer`,\n * ADR-0035) WITHOUT teaching the shared codec about that op — they are merged after any the codec itself\n * produces, so both the codec's future zero-copy path and per-message transfers coexist.\n */\nexport function postBridgeMessage(\n port: BridgePort,\n codec: BridgeCodec,\n type: BridgeMessageType,\n payload: unknown,\n id?: string,\n transfer?: BridgeTransferable[],\n): void {\n const { envelope, transfer: codecTransfer } = encodeEnvelope(codec, type, payload, id);\n const allTransfer = [...(codecTransfer ?? []), ...(transfer ?? [])];\n if (allTransfer.length > 0) {\n port.postMessage(envelope, allTransfer);\n } else {\n port.postMessage(envelope);\n }\n}\n",
|
|
38
|
+
"// The tab facade (ADR-0032 S2, decisions 3/4/6/7). `attachSyncClient` returns the SAME client shape as\n// `createSyncClient` wherever semantics allow — the write API (RPC-backed), per-group readiness, the\n// live-rows seam, `ready`/`status`/`stop` — transparently proxied to the one shared worker engine. The tab\n// stays the single auth owner: it pushes its token at attach and on `notifyAuthChanged`, and answers the\n// worker's expiry pull-requests via `getToken`.\n//\n// One-shot Drizzle reads (`query`/`queryRaw`/…), local `pglite`/`ensureSynced`/`destroy` are NOT proxied in\n// S2 (the mandated attach surface is the write API + live rows + readiness) — they throw a clear\n// not-supported error. Query BUILDING still works on the tab: `drizzle`/`views` are the same build-only\n// handles `createSyncClient` exposes, compiled to SQL here and executed in the worker.\n\nimport type { Results } from \"@electric-sql/pglite\";\n\nimport type {\n MutationDiagnostics,\n SyncRuntimeStatus,\n SyncTableName,\n SyncTableRegistry,\n WriteMode,\n} from \"@pgxsinkit/contracts\";\n\nimport type { BootReport } from \"../boot-report\";\nimport type { DataExportOptions, DataExportResult } from \"../export-data\";\nimport type { DiagnosticExportOptions, DiagnosticExportResult } from \"../export-dump\";\nimport type { StoreExportOptions, StoreExportResult } from \"../export-store\";\nimport {\n buildRegistryReadHandles,\n ClientDisposedError,\n createMutationsApi,\n type LiveQueryDiagnostics,\n type LiveRowsSubscription,\n type MutationBatchItem,\n type MutationDetail,\n type SubscribeLiveRowsInput,\n type SyncClient,\n type SyncTransaction,\n type SyncTransactionResult,\n} from \"../index\";\nimport type { LocalStoreVersionEvent } from \"../local-store\";\nimport { readTestStoreMarker } from \"../store-path\";\nimport { LiveRowsMaterializer } from \"./live-diff\";\nimport {\n type AttachAckPayload,\n type AttachPayload,\n type AuthTokenSnapshot,\n type BridgeCodec,\n type BridgeEvent,\n type BridgePort,\n type BridgeTransferable,\n type ExportArtefactWire,\n identityCodec,\n isBridgeEnvelope,\n type LiveDiffPayload,\n type LiveHydratedPayload,\n type LiveInitialPayload,\n postBridgeMessage,\n type ProvisionAckPayload,\n type RestoreArtefactWire,\n type RpcOp,\n type RpcResultPayload,\n type TokenRequestPayload,\n} from \"./protocol\";\n\n/** A `Worker`/`SharedWorker`-shaped handle: a dedicated `Worker` IS the port; a `SharedWorker` carries `.port`. */\ninterface WorkerLike {\n port?: BridgePort;\n postMessage?: (message: unknown, transfer?: BridgeTransferable[]) => void;\n addEventListener?: (type: \"message\", listener: (event: { data: unknown }) => void) => void;\n removeEventListener?: (type: \"message\", listener: (event: { data: unknown }) => void) => void;\n}\n\nexport interface AttachSyncClientOptions<TRegistry extends SyncTableRegistry> {\n registry: TRegistry;\n /** A native `Worker` or `SharedWorker` (or anything port-shaped). Provide this OR {@link port}. */\n worker?: WorkerLike;\n /** A raw transport port (a `MessageChannel` port in tests, a `SharedWorker.port` in a browser). */\n port?: BridgePort;\n /**\n * The tab's token provider (ADR-0032 decision 3). Richer than `createSyncClient`'s string form: the\n * worker needs the EXPIRY to apply its pull margin, so this yields `{accessToken, expiresAt}` (or null\n * when unauthenticated). Pushed at attach and answered on every worker pull-request.\n */\n getToken?: () => Promise<AuthTokenSnapshot | null>;\n /** The bound store id (resolved tab-side before attach — SharedWorker naming, ADR-0032 decision 5). */\n storeId?: string;\n /**\n * The plain store PATH (ADR-0036) the worker opens if it must create its own store — a name, not a\n * storage URL. Spread `memoryStoreForTests(...)` from `@pgxsinkit/client/testing` here for a memory store\n * in tests (it also carries the internal marker forwarded to the worker as the memory-backend override).\n */\n storePath?: string;\n syncEnabled?: boolean;\n /**\n * Which baked registry the worker boots (ADR-0032 S3) — forwarded in the attach `config.role`. A worker\n * file that bakes multiple role variants (the board's admin/member) picks by this; single-registry\n * workers ignore it.\n */\n role?: string;\n /**\n * Fresh-store prefetch-overlap hint (ADR-0032 S4), forwarded in the attach `config.freshStore`. Set true\n * ONLY when the tab knows the store is a claimed schemaless spare (never for a mapped/returning store);\n * the worker's `createSyncClient` then overlaps the shape catch-up with its local boot phases.\n */\n freshStore?: boolean;\n /**\n * Restore the worker's store from a backup on attach (ADR-0035 decision 6) — the worker-mode `restoreFrom`.\n * A `File`/`Blob` as produced by {@link SyncClient.exportStore}; the facade decomposes it into a transferred\n * `ArrayBuffer` + name/mime ({@link RestoreArtefactWire}) and the worker recomposes it for `createSyncClient`.\n * Restore rides the FIRST (boot) attach: passing it when the worker's engine has ALREADY booted rejects the\n * attach with a typed error (you cannot restore into a running store). The restored engine boots offline and\n * its recovered journal is quarantined, exactly as in-process — see `restoreFrom` on `createSyncClient`.\n */\n restoreFrom?: File | Blob;\n codec?: BridgeCodec;\n onStatusChange?: (status: SyncRuntimeStatus) => void;\n onConflict?: (details: MutationDetail[]) => void;\n onQuarantine?: (details: MutationDetail[]) => void;\n onReject?: (details: MutationDetail[]) => void;\n onSchemaChange?: (event: LocalStoreVersionEvent) => void;\n onSyncError?: (error: Error) => void;\n /**\n * Boot observability (ADR-0034): invoked once with the worker engine's finalized {@link BootReport} if the\n * engine's boot finalizes WHILE this tab is attached (the one-shot `boot-report` broadcast). A tab that\n * attaches AFTER the boot never receives the push — it reads the report via {@link SyncClient.bootReport}.\n */\n onBootReport?: (report: BootReport) => void;\n}\n\n/**\n * The worker-attached client: `SyncClient`'s shape, worker-proxied, plus `notifyAuthChanged` (re-push the\n * token after an app auth-state change, ADR-0032 decision 3). The unsupported one-shot-read members throw.\n */\nexport type AttachedSyncClient<TRegistry extends SyncTableRegistry> = SyncClient<TRegistry> & {\n notifyAuthChanged: () => void;\n /**\n * Forward the app's Offline toggle to the worker (ADR-0032 S3). The worker owns convergence, so the\n * tab cannot gate a local trigger; this sends `set-online`, which suppresses/resumes the worker's flush\n * passes (resuming fires one immediate pass). The in-process client gates its own `autoSync` instead.\n */\n setOnline: (online: boolean) => void;\n};\n\nexport async function attachSyncClient<const TRegistry extends SyncTableRegistry>(\n options: AttachSyncClientOptions<TRegistry>,\n): Promise<AttachedSyncClient<TRegistry>> {\n const codec = options.codec ?? identityCodec;\n const port = resolvePort(options);\n\n // ─── Correlation + subscription bookkeeping ──────────────────────────────────────────────────────\n let nextId = 0;\n const newId = (prefix: string) => `${prefix}-${++nextId}`;\n const rpcPending = new Map<string, { resolve: (value: unknown) => void; reject: (error: Error) => void }>();\n const initialPending = new Map<\n string,\n { resolve: (payload: LiveInitialPayload) => void; reject: (error: Error) => void }\n >();\n const diffHandlers = new Map<string, (diff: Omit<LiveDiffPayload, \"queryId\">) => void>();\n // Resolvers for per-subscription `hydrated` promises, keyed by queryId. The worker posts\n // `live-hydrated` on the same port as the diff stream, strictly after the catch-up rows — so\n // resolution here guarantees the rows have already been applied by the materializer.\n const hydratedPending = new Map<string, () => void>();\n // Set once this tab detaches (explicit `stop()` OR a terminal `pagehide`). Guards NEW operations (they\n // reject at once) and lets `detachFromWorker` settle every outstanding promise — the port listener is torn\n // down on detach, so an unsettled `rpc`/`live-initial` waiter would otherwise hang forever (ADR-0040 P2).\n let detached = false;\n const detachError = () => new Error(\"[pgxsinkit] client detached — the tab released its worker attachment\");\n\n // ─── Status + readiness ──────────────────────────────────────────────────────────────────────────\n const status: SyncRuntimeStatus = { phase: \"booting\", isRunning: false };\n let resolveReady!: () => void;\n // FIX 2: `ready` gains a reject path so a detach BEFORE initial sync settles it (an attached client stopped\n // pre-ready would otherwise leave `client.ready` / `client.start()` pending forever). Guarded below.\n let rejectReady!: (error: unknown) => void;\n const ready = new Promise<void>((resolve, reject) => {\n resolveReady = resolve;\n rejectReady = reject;\n });\n void ready.catch(() => undefined);\n let readyResolved = false;\n const readyGroups = new Set<string>();\n const groupWaiters = new Map<string, Array<() => void>>();\n\n // ─── Auth: push at attach + on notifyAuthChanged, answer pull-requests ────────────────────────────\n const pushToken = async () => {\n const token = options.getToken ? await options.getToken() : null;\n postBridgeMessage(port, codec, \"token-push\", token);\n };\n const answerPull = async (requestId: string) => {\n const token = options.getToken ? await options.getToken() : null;\n postBridgeMessage(port, codec, \"token-response\", { requestId, token });\n };\n\n // ─── Inbound message routing ─────────────────────────────────────────────────────────────────────\n const markReady = () => {\n if (readyResolved) return;\n readyResolved = true;\n resolveReady();\n };\n // Record a group as ready and settle any waiters — shared by the discrete `groupReady` edge and the\n // status snapshot's `status.groups` merge (ADR-0032 FIX 4), so a tab attaching after the edge fired\n // still resolves `client.groupReady(table)` off the snapshot it gets at attach.\n const markGroupReady = (groupKey: string) => {\n readyGroups.add(groupKey);\n const waiters = groupWaiters.get(groupKey);\n if (waiters) {\n groupWaiters.delete(groupKey);\n for (const resolve of waiters) resolve();\n }\n };\n const onEvent = (event: BridgeEvent) => {\n switch (event.kind) {\n case \"status\": {\n Object.assign(status, event.status);\n options.onStatusChange?.(event.status);\n // Match the in-process contract EXACTLY (ADR-0032 FIX 3): `ready` resolves ONLY from phase\n // \"ready\" (all eager groups caught up, or the syncEnabled:false path). `auth-needed`/`degraded`\n // do NOT resolve it — an engine stuck retrying auth keeps `ready` pending, as in-process.\n if (event.status.phase === \"ready\") markReady();\n // Late-attach group merge (ADR-0032 FIX 4): fold every already-ready group from the snapshot.\n for (const [groupKey, ready] of Object.entries(event.status.groups ?? {})) {\n if (ready) markGroupReady(groupKey);\n }\n break;\n }\n case \"groupReady\": {\n markGroupReady(event.groupKey);\n break;\n }\n case \"milestone\": {\n // Staged boot readiness (ADR-0041 stage 2): the engine crossed a background stage while this tab was\n // attached. Idempotent with the ack's late-attach fold — whichever observes it first wins.\n if (event.stage === \"writeReady\") settleWriteReady();\n else if (event.stage === \"bootSettled\") settleBootSettled();\n break;\n }\n case \"milestone-error\": {\n // The background write/sync tail rejected a downstream stage (ADR-0041): fail the matching stage so a\n // gated write / `bootSettled` awaiter fails loudly. `localReadReady` and the resolved attach are\n // unaffected — the engine reached local-read readiness before the tail failed.\n if (event.stage === \"writeReady\") failWriteReady(rebuildError(event.error));\n else if (event.stage === \"bootSettled\") failBootSettled(rebuildError(event.error));\n break;\n }\n case \"conflict\":\n options.onConflict?.(event.details as MutationDetail[]);\n break;\n case \"quarantine\":\n options.onQuarantine?.(event.details as MutationDetail[]);\n break;\n case \"reject\":\n options.onReject?.(event.details as MutationDetail[]);\n break;\n case \"schema-change\":\n options.onSchemaChange?.(event.event as LocalStoreVersionEvent);\n break;\n case \"sync-error\":\n options.onSyncError?.(new Error(event.message));\n break;\n case \"boot-report\":\n // Boot observability (ADR-0034): the one-shot push for a tab attached at finalize. A late tab never\n // gets this event and pulls the report via `client.bootReport()` instead.\n options.onBootReport?.(event.report);\n break;\n case \"debug\": {\n // Re-print the worker's rail line gated on THIS tab's own flag, origin-tagged with the worker's\n // monotonic stamp (ADR-0032 decision 7) — a SharedWorker's own console is otherwise invisible.\n if ((globalThis as { __pgxsinkitDebug?: boolean }).__pgxsinkitDebug === true) {\n const line = `[pgxsinkit·w ${event.stamp.toFixed(0)}ms] ${event.line}`;\n if (event.data) console.debug(line, event.data);\n else console.debug(line);\n }\n break;\n }\n case \"timing\":\n break;\n default:\n break;\n }\n };\n\n const listener = (message: { data: unknown }) => {\n if (!isBridgeEnvelope(message.data)) return;\n const envelope = message.data;\n const payload = codec.decode(envelope.payload);\n switch (envelope.type) {\n case \"attach-ack\": {\n const ack = payload as AttachAckPayload;\n // A LOCAL-READ-CORE boot failure crosses in the ack's `error` (ADR-0032 FIX 1): reject the handshake\n // so `attachSyncClient` rejects instead of hanging forever. On success, the engine reached\n // `localReadReady` — resolve that stage now (the ack fires AT localReadReady, ADR-0041 Option B) and\n // fold any downstream milestones/failures the tail already crossed (a late attach). `engineReady`\n // covers a LATE attach whose engine already fired its monotonic `ready` before this ack (FIX 3).\n if (ack.error) {\n attachAckReject?.(rebuildError(ack.error));\n } else {\n if (ack.engineReady) markReady();\n resolveLocalReadReady();\n // Late-attach milestone fold: the stage may have already crossed (or failed) before this tab\n // attached, in which case there is no broadcast to catch — settle it straight from the ack.\n if (ack.writeReady) settleWriteReady();\n if (ack.writeReadyError) failWriteReady(rebuildError(ack.writeReadyError));\n if (ack.bootSettled) settleBootSettled();\n if (ack.bootSettledError) failBootSettled(rebuildError(ack.bootSettledError));\n attachAckResolve?.(ack);\n }\n break;\n }\n case \"token-request\":\n void answerPull((payload as TokenRequestPayload).requestId);\n break;\n case \"rpc-result\": {\n const id = envelope.id;\n if (id == null) break;\n const result = payload as RpcResultPayload;\n const pending = rpcPending.get(id);\n if (pending) {\n rpcPending.delete(id);\n if (result.ok) pending.resolve(result.value);\n else pending.reject(rebuildError(result.error));\n break;\n }\n // A failed `subscribe` is reported as an `rpc-result` correlated by the subscribe's envelope id\n // (the worker has no client to hand an initial snapshot), so route the miss to the initial waiter\n // (ADR-0032 FIX 2). A successful subscribe never lands here — it resolves via `live-initial`.\n const initial = initialPending.get(id);\n if (initial && !result.ok) {\n initialPending.delete(id);\n initial.reject(rebuildError(result.error));\n }\n break;\n }\n case \"live-initial\": {\n const id = envelope.id;\n const initial = payload as LiveInitialPayload;\n if (id != null) {\n const pending = initialPending.get(id);\n if (pending) {\n initialPending.delete(id);\n pending.resolve(initial);\n }\n }\n break;\n }\n case \"live-diff\": {\n const diff = payload as LiveDiffPayload;\n diffHandlers.get(diff.queryId)?.(diff);\n break;\n }\n case \"live-hydrated\": {\n const { queryId } = payload as LiveHydratedPayload;\n hydratedPending.get(queryId)?.();\n hydratedPending.delete(queryId);\n break;\n }\n case \"event\":\n onEvent(payload as BridgeEvent);\n break;\n default:\n break;\n }\n };\n port.addEventListener(\"message\", listener);\n port.start?.();\n\n // ─── RPC helper ──────────────────────────────────────────────────────────────────────────────────\n const rpc = <T>(op: RpcOp, args: unknown[]): Promise<T> => {\n // A detached client has no live port listener, so a worker reply could never resolve this — reject at\n // once rather than register a forever-pending waiter (ADR-0040 P2).\n if (detached) return Promise.reject(detachError());\n const id = newId(\"rpc\");\n return new Promise<T>((resolve, reject) => {\n rpcPending.set(id, { resolve: resolve as (value: unknown) => void, reject });\n postBridgeMessage(port, codec, \"rpc\", { op, args }, id);\n });\n };\n\n // ─── Attach handshake ────────────────────────────────────────────────────────────────────────────\n let attachAckResolve: ((ack: AttachAckPayload) => void) | null = null;\n let attachAckReject: ((error: Error) => void) | null = null;\n const attachAck = new Promise<AttachAckPayload>((resolve, reject) => {\n attachAckResolve = resolve;\n attachAckReject = reject;\n });\n\n // ADR-0041 stage 2 — staged boot readiness on the worker-attached client. The `attach-ack` fires AT the\n // engine's `localReadReady` (the Option B contract), so this client resolves `attachSyncClient` there and\n // `localReadReady` is settled off the ack. `writeReady`/`bootSettled` cross in the engine's background tail:\n // they resolve off the `milestone` broadcast when this tab is attached as the stage fires, OR off the ack's\n // late-attach fold when the stage had already fired before this tab attached — one engine crosses each stage\n // once, so both routes observe the same monotonic sequence. A tail failure rejects the matching stage via\n // the `milestone-error` broadcast / the ack's stage-error fold, so a gated write or a `bootSettled` awaiter\n // fails loudly rather than hanging. All guarded so a rejection on an unconsumed stage is never unhandled.\n let resolveLocalReadReady!: () => void;\n const localReadReady = new Promise<void>((resolve) => {\n resolveLocalReadReady = resolve;\n });\n let resolveWriteReady!: () => void;\n let rejectWriteReady!: (error: unknown) => void;\n const writeReady = new Promise<void>((resolve, reject) => {\n resolveWriteReady = resolve;\n rejectWriteReady = reject;\n });\n let resolveBootSettled!: () => void;\n let rejectBootSettled!: (error: unknown) => void;\n const bootSettled = new Promise<void>((resolve, reject) => {\n resolveBootSettled = resolve;\n rejectBootSettled = reject;\n });\n void localReadReady.catch(() => undefined);\n void writeReady.catch(() => undefined);\n void bootSettled.catch(() => undefined);\n // Idempotent settlers — a stage may be signalled by BOTH the ack fold and a milestone event (or by a\n // detach), and must settle exactly once. `localReadReady` never rejects (a local-read-core failure rejects\n // the attach handshake instead, so this client is never handed out).\n let writeReadySettled = false;\n let bootSettledSettled = false;\n const settleWriteReady = () => {\n if (writeReadySettled) return;\n writeReadySettled = true;\n resolveWriteReady();\n };\n const failWriteReady = (error: unknown) => {\n if (writeReadySettled) return;\n writeReadySettled = true;\n rejectWriteReady(error);\n };\n const settleBootSettled = () => {\n if (bootSettledSettled) return;\n bootSettledSettled = true;\n resolveBootSettled();\n };\n const failBootSettled = (error: unknown) => {\n if (bootSettledSettled) return;\n bootSettledSettled = true;\n rejectBootSettled(error);\n };\n\n // ─── Detach (explicit stop AND page teardown) ──────────────────────────────────────────────────────\n // The platform fires NO close event on a SharedWorker port — a tab that simply closes would leave its\n // subscriptions (and their per-write rerun cost) alive in the worker for the worker's whole lifetime\n // (ADR-0040 decision 1; surfaced by the two-tab board e2e). So the same detach runs from `stop()` AND from\n // `pagehide` with `persisted === false` — the terminal signal of a real close/navigate-away. A\n // bfcache-parked page (`persisted === true`) keeps its attachment: its port survives parking and resumes\n // on restore, so detaching there would strand the restored page. Idempotent — pagehide then stop is safe.\n //\n // Installed BEFORE the attach handshake is posted/awaited (ADR-0040 P2): a tab that closes DURING a slow\n // worker boot must still send `detach` and reject the pending attach-ack, rather than leaving the worker\n // holding stale port/token bookkeeping for a page that is already gone. Pre-ack every pending map below is\n // empty, so the settlement loops are no-ops except for the attach-ack rejection.\n const detachFromWorker = (): void => {\n if (detached) return;\n detached = true;\n status.isRunning = false;\n // Detach THIS tab; the worker engine keeps running for other tabs (ADR-0032 decision 2).\n for (const queryId of diffHandlers.keys()) postBridgeMessage(port, codec, \"unsubscribe\", { queryId });\n diffHandlers.clear();\n postBridgeMessage(port, codec, \"detach\", null);\n // Settle every tab-side promise now the port listener is about to go (ADR-0040 P2) — otherwise an\n // operation still awaiting a worker reply hangs forever. RPCs and initial subscribes promise DATA, so\n // REJECT them (fabricating a value is worse than a clear failure); hydration and group-ready waiters are\n // DONENESS signals, so RESOLVE them (their awaiters are void-chained hook code that should settle, not\n // throw). The attach-ack is rejected too so a detach DURING boot rejects `attachSyncClient` (a no-op once\n // it has already settled).\n attachAckReject?.(detachError());\n // ADR-0041 (FIX A): reject EVERY still-pending readiness STAGE with ONE typed `ClientDisposedError`, so\n // `instanceof ClientDisposedError` behaves identically in worker and in-process mode (the class doc + the\n // in-process client already promise the typed error on disposal). `detachError()` stays for RPC/subscription\n // rejections below, where the more specific \"client detached\" message is useful for a data operation.\n // `localReadReady` is left as-is: pre-ack it never resolved (the attach itself rejected); post-ack it already\n // resolved. The `milestone-error` path is untouched — that is a genuine engine failure, not disposal.\n const disposedError = new ClientDisposedError();\n failWriteReady(disposedError);\n failBootSettled(disposedError);\n // The attached `ready` had NO reject path — a detach BEFORE initial sync would otherwise leave\n // `client.ready` / `client.start()` pending forever. Settle it once with the same disposed error.\n if (!readyResolved) {\n readyResolved = true;\n rejectReady(disposedError);\n }\n for (const pending of rpcPending.values()) pending.reject(detachError());\n rpcPending.clear();\n for (const pending of initialPending.values()) pending.reject(detachError());\n initialPending.clear();\n for (const resolve of hydratedPending.values()) resolve();\n hydratedPending.clear();\n for (const waiters of groupWaiters.values()) for (const resolve of waiters) resolve();\n groupWaiters.clear();\n if (pagehideListener) pageWindow?.removeEventListener(\"pagehide\", pagehideListener);\n port.removeEventListener(\"message\", listener);\n port.close?.();\n };\n // Structural window guard — this file compiles without the DOM lib (it also runs under tests/workers).\n interface PageLifecycleWindowLike {\n addEventListener(type: \"pagehide\", handler: (event: { persisted: boolean }) => void): void;\n removeEventListener(type: \"pagehide\", handler: (event: { persisted: boolean }) => void): void;\n }\n const pageWindow = (globalThis as { window?: PageLifecycleWindowLike }).window;\n const pagehideListener = pageWindow\n ? (event: { persisted: boolean }) => {\n if (!event.persisted) detachFromWorker();\n }\n : undefined;\n if (pagehideListener) pageWindow?.addEventListener(\"pagehide\", pagehideListener);\n\n const initialToken = options.getToken ? await options.getToken() : null;\n // The testing memory-backend override travels as an explicit wire field, not the symbol marker — a symbol\n // does not survive `postMessage` structured clone (ADR-0036). Read it off the spread helper's options here.\n const memoryOverride = readTestStoreMarker(options) === \"memory\";\n // Restore (ADR-0035 decision 6): a `File`/`Blob` cannot cross as a transferable, so decompose it into a\n // zero-copy `ArrayBuffer` + name/mime (the `ExportArtefactWire` pattern in reverse) and list the buffer on\n // the attach `postMessage`'s transfer list. Read the bytes BEFORE building the payload (async).\n const restoreWire: RestoreArtefactWire | undefined = options.restoreFrom\n ? {\n buffer: await options.restoreFrom.arrayBuffer(),\n fileName: options.restoreFrom instanceof File ? options.restoreFrom.name : \"restore.pgdata.tar\",\n mimeType: options.restoreFrom.type || \"application/octet-stream\",\n }\n : undefined;\n const attachPayload: AttachPayload = {\n token: initialToken,\n ...(options.storeId ? { storeId: options.storeId } : {}),\n ...(options.storePath ? { storePath: options.storePath } : {}),\n ...(memoryOverride ? { testStoreBackend: \"memory\" as const } : {}),\n ...(restoreWire ? { restore: restoreWire } : {}),\n ...(options.syncEnabled != null || options.role != null || options.freshStore != null\n ? {\n config: {\n ...(options.syncEnabled != null ? { syncEnabled: options.syncEnabled } : {}),\n ...(options.role != null ? { role: options.role } : {}),\n ...(options.freshStore != null ? { freshStore: options.freshStore } : {}),\n },\n }\n : {}),\n };\n postBridgeMessage(port, codec, \"attach\", attachPayload, undefined, restoreWire ? [restoreWire.buffer] : undefined);\n try {\n await attachAck;\n } catch (error) {\n // The worker's engine boot failed (ADR-0032 FIX 1) OR a terminal pagehide rejected the ack mid-boot\n // (ADR-0040 P2): run the full detach so BOTH the message listener AND the pagehide listener are removed\n // (no port/window handler leaks), then let the error propagate out of `attachSyncClient`. Idempotent, so\n // a pagehide that already detached makes this a cheap no-op.\n detachFromWorker();\n throw error;\n }\n status.isRunning = true;\n\n // ─── Live-rows seam (ADR-0032 S2 §4) ─────────────────────────────────────────────────────────────\n const subscribeLiveRows = async <TRow extends Record<string, unknown>>(\n input: SubscribeLiveRowsInput,\n onRows: (rows: TRow[]) => void,\n ): Promise<LiveRowsSubscription<TRow>> => {\n // A detached client has no port listener, so `live-initial` could never arrive — reject at once rather\n // than register a forever-pending initial waiter (ADR-0040 P2).\n if (detached) throw detachError();\n const queryId = newId(\"live\");\n const id = newId(\"sub\");\n const materializer = new LiveRowsMaterializer<TRow>(input.pkColumns);\n diffHandlers.set(queryId, (diff) => {\n onRows(materializer.apply(diff));\n });\n let initial: LiveInitialPayload;\n try {\n initial = await new Promise<LiveInitialPayload>((resolve, reject) => {\n initialPending.set(id, { resolve, reject });\n postBridgeMessage(\n port,\n codec,\n \"subscribe\",\n {\n queryId,\n sql: input.sql,\n params: [...input.params],\n ...(input.fields ? { fields: [...input.fields] } : {}),\n ...(input.pkColumns ? { pkColumns: [...input.pkColumns] } : {}),\n ...(input.use ? { use: [...input.use] } : {}),\n // Per-subscription keep-alive hint (ADR-0040 decision 4) forwarded to the worker's manager.\n ...(input.keepAliveMs != null ? { keepAliveMs: input.keepAliveMs } : {}),\n },\n id,\n );\n });\n } catch (error) {\n // The worker rejected the subscribe (invalid SQL, etc.); the initial-payload waiter rejected via the\n // `rpc-result` route (ADR-0032 FIX 2). Drop the pre-registered diff handler so no orphan survives.\n diffHandlers.delete(queryId);\n throw error;\n }\n const initialRows = materializer.seed(initial.rows as TRow[]);\n // Pending groups present → build the `hydrated` promise the worker settles via `live-hydrated` (posted\n // after the catch-up rows on the same port — rows-before-signal). A missing/empty `hydratingTables`\n // means every referenced group (eager OR lazy) was already ready (steady state) or sync is disabled:\n // no hydration is pending, so no promise. Resolved on unsubscribe too, so an abandoned subscription\n // never leaves a forever-pending promise behind.\n let hydrated: Promise<void> | undefined;\n if (initial.hydratingTables && initial.hydratingTables.length > 0) {\n hydrated = new Promise<void>((resolve) => {\n hydratedPending.set(queryId, resolve);\n });\n }\n return {\n initialRows,\n unsubscribe: () => {\n diffHandlers.delete(queryId);\n hydratedPending.get(queryId)?.();\n hydratedPending.delete(queryId);\n postBridgeMessage(port, codec, \"unsubscribe\", { queryId });\n },\n // The lazy relations the worker's guard activated for this query (observability). `hydrated` — driven\n // by `hydratingTables`, not this — resolves once every pending group's caught-up rows are delivered.\n ...(initial.lazyTables ? { lazyTables: initial.lazyTables } : {}),\n ...(hydrated ? { hydrated } : {}),\n };\n };\n\n // ─── Assembled client ────────────────────────────────────────────────────────────────────────────\n const { drizzle, views } = buildRegistryReadHandles(options.registry);\n const notSupported = (name: string) => (): never => {\n throw new Error(\n `[pgxsinkit] ${name} is not available on a worker-attached client (ADR-0032 S2). Use the live-rows hooks / subscribeLiveRows for reads, the write API for mutations.`,\n );\n };\n\n const groupKeyForTable = (table: SyncTableName<TRegistry>): string | undefined => {\n const entry = options.registry[table];\n return entry?.consistencyGroup ?? entry?.shape?.shapeKey;\n };\n\n const client: AttachedSyncClient<TRegistry> = {\n drizzle,\n views,\n // The tab has no local PGlite; reads go through the live-rows bridge. Touching `.pglite` is a misuse.\n pglite: new Proxy(\n {},\n {\n get: notSupported(\"client.pglite\"),\n },\n ) as never,\n tables: Object.fromEntries(\n Object.keys(options.registry).map((tableKey) => [\n tableKey,\n {\n key: tableKey,\n mode: options.registry[tableKey as SyncTableName<TRegistry>]!.mode,\n create: (input: unknown) => rpc<void>(\"create\", [tableKey, input]),\n update: (entityKey: Record<string, string>, patch: unknown) =>\n rpc<void>(\"update\", [tableKey, entityKey, patch]),\n delete: (entityKey: Record<string, string>) => rpc<void>(\"delete\", [tableKey, entityKey]),\n },\n ]),\n ) as SyncClient<TRegistry>[\"tables\"],\n localReadReady,\n writeReady,\n bootSettled,\n ready,\n status,\n start: async () => {\n await ready;\n },\n stop: async () => {\n detachFromWorker();\n },\n destroy: notSupported(\"client.destroy\"),\n dropReadCache: notSupported(\"client.dropReadCache\"),\n flush: (table) => rpc<void>(\"flush\", [table]),\n reconcile: (table) => rpc<void>(\"reconcile\", [table]),\n retryFailed: (table) => rpc<void>(\"retryFailed\", [table]),\n recoverSending: (table) => rpc<void>(\"recoverSending\", [table]),\n readMutationDetails: (table) => rpc<MutationDetail[]>(\"readMutationDetails\", [table]),\n // Inspection reads run in the worker (ADR-0032 S2) — the same surface as the in-process client. `pglite`\n // itself stays blocked (below); these route the raw statement over the RPC round-trip instead.\n rawQuery: (sql, params, options) => rpc<Results>(\"rawQuery\", [sql, params, options]),\n rawExec: (sql, options) => rpc<Results[]>(\"rawExec\", [sql, options]),\n mutate: {\n create: (table, input) => rpc<void>(\"create\", [table, input]),\n update: (table, entityKey, patch) => rpc<void>(\"update\", [table, entityKey, patch]),\n delete: (table, entityKey) => rpc<void>(\"delete\", [table, entityKey]),\n batch: (items) => rpc<void>(\"batch\", [items]),\n },\n discardConflict: (table, entityKey) => rpc<void>(\"discardConflict\", [table, entityKey]),\n discardQuarantined: (table, entityKey) => rpc<void>(\"discardQuarantined\", [table, entityKey]),\n diagnostics: (table) => rpc<{ mutation: MutationDiagnostics }>(\"diagnostics\", [table]),\n // The registry-wide mutation-status API (slice 4) over the SAME factory the in-process client uses,\n // wired to this facade's shared seams: the live-rows bridge (`subscribeLiveRows`) and the one-shot\n // `rawQuery` RPC. No new bridge message — `client.mutations` behaves identically to the in-process client.\n mutations: createMutationsApi({\n registry: options.registry,\n subscribeLiveRows,\n query: (sql, params) => rpc<Results>(\"rawQuery\", [sql, params]),\n }),\n query: notSupported(\"client.query\"),\n queryRow: notSupported(\"client.queryRow\"),\n queryRaw: notSupported(\"client.queryRaw\"),\n queryRawRow: notSupported(\"client.queryRawRow\"),\n ensureSynced: notSupported(\"client.ensureSynced\"),\n isSynced: notSupported(\"client.isSynced\"),\n // In SharedWorker mode the engine is SHARED, so a desync from one tab reverts the consistency group for\n // EVERY attached tab — inherent to desync's group-wide semantics (that footgun is why the narrower\n // `discardEphemeral` exists). The RPC runs the worker's real `desync` (same refusals as in-process).\n desync: (key) => rpc<void>(\"desync\", [key]),\n // Scoped, multi-tab-safe finalize (ADR-0021): drops an ephemeral relation's local rows and reverts it to\n // dormant. Safe under a shared engine because an ephemeral window is per-delivery-session and inherently\n // single-consumer; the RPC runs the worker's real `discardEphemeral` (refuses persistent members).\n discardEphemeral: (key) => rpc<void>(\"discardEphemeral\", [key]),\n // The worker activates lazy relations inside its `subscribe` handler (via the `use` hint), so the tab's\n // `prepareQuery` is a no-op — the live-rows subscription is already guarded worker-side (ADR-0021).\n // Empty `lazyTables`: the real scan's keys travel back on the subscription itself (`live-initial`).\n prepareQuery: async () => ({ lazyTables: [] }),\n // The worker computes the pending hydrating tables inside its `subscribe` handler (on its owned client)\n // and reports them back on `live-initial` (`hydratingTables`), so the tab-side seam is a no-op here.\n hydratingTablesFor: () => [],\n transaction: async ({ mode }: { mode: WriteMode }, run) => {\n // Collect the unit's mutations tab-side (the run callback cannot cross the wire), then RPC the\n // serialized items + mode; the worker replays them into a real `client.transaction` (matching acks).\n const collected: MutationBatchItem<TRegistry>[] = [];\n const txTables = Object.fromEntries(\n Object.keys(options.registry).map((tableKey) => [\n tableKey,\n {\n create: (input: unknown) => {\n collected.push({ table: tableKey, kind: \"create\", input } as MutationBatchItem<TRegistry>);\n },\n update: (entityKey: Record<string, string>, patch: unknown) => {\n collected.push({ table: tableKey, kind: \"update\", entityKey, patch } as MutationBatchItem<TRegistry>);\n },\n updateBlind: (entityKey: Record<string, string>, patch: unknown) => {\n // ADR-0022 addendum: the `blind` flag rides the serialized item across the wire; the worker\n // replays it through `client.transaction`'s `updateBlind`, identical to the in-process client.\n collected.push({\n table: tableKey,\n kind: \"update\",\n entityKey,\n patch,\n blind: true,\n } as MutationBatchItem<TRegistry>);\n },\n delete: (entityKey: Record<string, string>) => {\n collected.push({ table: tableKey, kind: \"delete\", entityKey } as MutationBatchItem<TRegistry>);\n },\n },\n ]),\n ) as SyncTransaction<TRegistry>[\"tables\"];\n await run({ tables: txTables });\n if (collected.length === 0) return { acks: [] };\n return rpc<SyncTransactionResult>(\"transaction\", [{ mode, items: collected }]);\n },\n groupReady: async (table) => {\n // A detached client will never receive further `groupReady`/status edges — reject at once rather than\n // register a waiter that detach already drained (ADR-0040 P2).\n if (detached) throw detachError();\n const groupKey = groupKeyForTable(table);\n if (groupKey == null || readyGroups.has(groupKey)) return;\n await new Promise<void>((resolve) => {\n const waiters = groupWaiters.get(groupKey) ?? [];\n waiters.push(resolve);\n groupWaiters.set(groupKey, waiters);\n });\n },\n subscribeLiveRows,\n // Boot observability (ADR-0034): pull the worker engine's stored boot report over the bridge — returns\n // the same report regardless of when this tab attached (a late tab reads a boot that predates it).\n bootReport: () => rpc<BootReport | null>(\"bootReport\", []),\n // Live-query diagnostics (ADR-0040 decision 5): pull the worker manager's per-entry snapshot over the\n // bridge (digests + counts only — plain objects that structured-clone across the wire).\n liveQueryDiagnostics: () => rpc<LiveQueryDiagnostics[]>(\"liveQueryDiagnostics\", []),\n // Store backup (ADR-0035): the worker runs the live export on its owned client (its lifecycle slot\n // serialises it against every tab). The dump crosses back as a transferred `ArrayBuffer`; rebuild the\n // `File` tab-side from the wire form — NOT in the notSupported set (unlike the local `pglite` reads).\n exportStore: async (exportOptions?: StoreExportOptions): Promise<StoreExportResult> => {\n const wire = await rpc<ExportArtefactWire>(\"exportStore\", [exportOptions]);\n return {\n file: new File([wire.buffer], wire.fileName, { type: wire.mimeType }),\n // The wire carries the discriminated union; `exportStore` always round-trips a store-backup report.\n report: wire.report as StoreExportResult[\"report\"],\n };\n },\n // Diagnostic dump (ADR-0035): the worker runs the throwaway-clone dump on its owned client (same\n // lifecycle slot as every tab). The SQL crosses back as the same transferred `ArrayBuffer`; rebuild the\n // `File` tab-side. NOT in the notSupported set (unlike the local `pglite` reads).\n exportDiagnostics: async (exportOptions?: DiagnosticExportOptions): Promise<DiagnosticExportResult> => {\n const wire = await rpc<ExportArtefactWire>(\"exportDiagnostics\", [exportOptions]);\n return {\n file: new File([wire.buffer], wire.fileName, { type: wire.mimeType }),\n // The wire carries the discriminated union; `exportDiagnostics` always round-trips a diagnostic-dump report.\n report: wire.report as DiagnosticExportResult[\"report\"],\n };\n },\n // Data export (ADR-0035): the worker runs the drain-guarded `pg_dump -t` export on its owned client (same\n // lifecycle slot as every tab). The portable SQL crosses back as the same transferred `ArrayBuffer`;\n // rebuild the `File` tab-side. A `DataExportDrainError` surfaces as the rejected RPC (deserialised tab-side).\n exportData: async (exportOptions?: DataExportOptions): Promise<DataExportResult> => {\n const wire = await rpc<ExportArtefactWire>(\"exportData\", [exportOptions]);\n return {\n file: new File([wire.buffer], wire.fileName, { type: wire.mimeType }),\n // The wire carries the discriminated union; `exportData` always round-trips a data-export report.\n report: wire.report as DataExportResult[\"report\"],\n };\n },\n notifyAuthChanged: () => {\n void pushToken();\n },\n setOnline: (online: boolean) => {\n postBridgeMessage(port, codec, \"set-online\", { online });\n },\n };\n\n return client;\n}\n\n/**\n * Pre-spawn a worker's store WITHOUT attaching (ADR-0032 decision 5). Sent at the board's login screen\n * against a freshly-named spare `SharedWorker`: the worker runs PGlite `create`/initdb only and holds the\n * raw store idle until the real {@link attachSyncClient} claim adopts it. Resolves when the worker acks the\n * provision (its initdb settled); rejects only if the worker reports the create failed — the caller treats\n * either outcome as best-effort, since attach falls back to a fresh create regardless.\n */\nexport function provisionSyncWorker<TRegistry extends SyncTableRegistry>(\n options: Pick<AttachSyncClientOptions<TRegistry>, \"worker\" | \"port\" | \"storeId\" | \"storePath\" | \"codec\">,\n): Promise<void> {\n const codec = options.codec ?? identityCodec;\n const port = resolvePort(options);\n // The testing memory-backend override travels as an explicit wire field (a symbol does not survive\n // structured clone, ADR-0036) — read it off the spread helper's options and forward it to the worker.\n const memoryOverride = readTestStoreMarker(options) === \"memory\";\n return new Promise<void>((resolve, reject) => {\n const listener = (message: { data: unknown }) => {\n if (!isBridgeEnvelope(message.data)) return;\n if (message.data.type !== \"provision-ack\") return;\n port.removeEventListener(\"message\", listener);\n const ack = codec.decode(message.data.payload) as ProvisionAckPayload;\n if (ack.ok) resolve();\n else reject(new Error(ack.error?.message ?? \"worker provision failed\"));\n };\n port.addEventListener(\"message\", listener);\n port.start?.();\n postBridgeMessage(port, codec, \"provision\", {\n ...(options.storeId ? { storeId: options.storeId } : {}),\n ...(options.storePath ? { storePath: options.storePath } : {}),\n ...(memoryOverride ? { testStoreBackend: \"memory\" as const } : {}),\n });\n });\n}\n\n/** Resolve the transport port from the options: an explicit port, a SharedWorker's `.port`, or a Worker itself. */\nfunction resolvePort(options: { port?: BridgePort; worker?: WorkerLike }): BridgePort {\n if (options.port) return options.port;\n const worker = options.worker;\n if (!worker) throw new Error(\"attachSyncClient: provide a `worker` or a `port`.\");\n if (worker.port) return worker.port;\n if (worker.postMessage && worker.addEventListener && worker.removeEventListener) {\n return worker as BridgePort;\n }\n throw new Error(\"attachSyncClient: the provided `worker` is neither a Worker nor a SharedWorker port.\");\n}\n\n/** Rebuild an Error from the bridge's serialized `{message, detail}` shape, carrying `detail` through. */\nfunction rebuildError(error: RpcResultPayload[\"error\"]): Error {\n const rebuilt = new Error(error?.message ?? \"worker rpc failed\");\n if (error && \"detail\" in error && error.detail !== undefined) {\n (rebuilt as Error & { detail?: unknown }).detail = error.detail;\n }\n return rebuilt;\n}\n",
|
|
38
39
|
"// The worker's single auth token cache + pull mechanism (ADR-0032 decision 3). The worker holds exactly\n// ONE token and NEVER refreshes it — the tab layer is the sole auth owner (exactly one refresher exists, so\n// GoTrue refresh-token reuse detection can never trip). A read/write that finds the cache within the expiry\n// margin triggers ONE pull broadcast; concurrent needs dedupe onto that single in-flight pull; the first\n// tab answer wins. Factored out of `defineSyncWorker` so this mechanism is unit-tested in isolation.\n\nimport type { AuthTokenSnapshot } from \"./protocol\";\n\nexport interface WorkerTokenCache {\n /**\n * Resolve the access token for a shape/flush request. Returns the cached token when it is comfortably\n * ahead of expiry; otherwise broadcasts ONE pull (deduped across concurrent callers) and resolves when a\n * tab answers. Falls back to the (stale) cached token if a pull yields nothing.\n */\n getToken: () => Promise<string | undefined>;\n /** The tab pushed a fresh token (auth state change or the initial attach) — cache it and satisfy any pull. */\n push: (token: AuthTokenSnapshot | null) => void;\n /**\n * Seed the cache from a LATER attach's token, but only if it is strictly fresher than what is cached\n * (ADR-0032 FIX 5). Attach seeding must never CLOBBER a fresher cached token with an older/null one —\n * only the explicit `push` path (the tab as auth owner saying \"this is current\") may overwrite\n * unconditionally, including null on logout.\n */\n pushIfFresher: (token: AuthTokenSnapshot | null) => void;\n /** A tab answered a pull-request. First matching answer wins; later duplicates are ignored. */\n respond: (requestId: string, token: AuthTokenSnapshot | null) => void;\n}\n\nexport function createWorkerTokenCache(options: {\n marginMs: number;\n broadcastRequest: (requestId: string) => void;\n now?: () => number;\n}): WorkerTokenCache {\n const now = options.now ?? (() => Date.now());\n let cached: AuthTokenSnapshot | null = null;\n let inFlight: Promise<AuthTokenSnapshot | null> | null = null;\n let resolveInFlight: ((token: AuthTokenSnapshot | null) => void) | null = null;\n let currentRequestId: string | null = null;\n let requestCounter = 0;\n\n const settle = (token: AuthTokenSnapshot | null) => {\n if (token) cached = token;\n const resolve = resolveInFlight;\n inFlight = null;\n resolveInFlight = null;\n currentRequestId = null;\n resolve?.(token);\n };\n\n return {\n getToken: async () => {\n if (cached && cached.expiresAt - now() > options.marginMs) {\n return cached.accessToken;\n }\n if (!inFlight) {\n currentRequestId = `pull-${++requestCounter}`;\n inFlight = new Promise<AuthTokenSnapshot | null>((resolve) => {\n resolveInFlight = resolve;\n });\n // Exactly one broadcast per pull; concurrent getToken calls below await the same `inFlight`.\n options.broadcastRequest(currentRequestId);\n }\n const answered = await inFlight;\n return answered?.accessToken ?? cached?.accessToken;\n },\n push: (token) => {\n cached = token;\n // A push satisfies an outstanding pull too (the tab volunteered before answering the request).\n if (inFlight) settle(token);\n },\n pushIfFresher: (token) => {\n if (!token) return;\n if (cached && cached.expiresAt >= token.expiresAt) return;\n // Strictly fresher than the cache (or the cache is empty) → adopt it via `push`, which also settles\n // any in-flight pull.\n cached = token;\n if (inFlight) settle(token);\n },\n respond: (requestId, token) => {\n // First response for the CURRENT pull wins; a stale/duplicate requestId (or no pull) is ignored.\n if (inFlight && requestId === currentRequestId) settle(token);\n },\n };\n}\n",
|
|
39
|
-
"// The worker entry factory (ADR-0032 S2, decisions 3/4/6/7). `defineSyncWorker` boots ONE sync engine and\n// fans it out to N attached tabs over the bridge. The first attach boots the engine by calling the\n// unchanged `createSyncClient` (the strongest form of \"reuse createSyncClient internals\" — the in-process\n// boot pipeline runs verbatim, so the unit suite stays its equivalence proof); later attaches join it.\n//\n// It serves BOTH a native `SharedWorker` (`onconnect`, many ports) and a dedicated `Worker` (one implicit\n// port) behind {@link SyncWorkerHost.connect} — the same entry a test drives with a plain `MessageChannel`\n// port, so no real Worker is needed to exercise the whole protocol.\n\nimport type { SyncRuntimeStatus, SyncTableName, SyncTableRegistry, WriteMode } from \"@pgxsinkit/contracts\";\n\nimport { type ConvergenceTrigger, createIntervalConvergenceTrigger } from \"../convergence\";\nimport { setSyncDebugSink, syncDebug } from \"../debug\";\nimport {\n type ClientPGlite,\n createClientPGlite,\n type CreateSyncClientOptions,\n createSyncClient,\n type DataExportOptions,\n type DiagnosticExportOptions,\n type MutationBatchItem,\n type RawQueryOptions,\n type StoreExportOptions,\n type SyncClient,\n} from \"../index\";\nimport { wrapLiveQueryForMaterialization } from \"../live-rows-sql\";\nimport type { LocalStoreVersionEvent } from \"../local-store\";\nimport { readTestStoreMarker, TEST_STORE_BACKEND, type TestStoreMarker } from \"../store-path\";\nimport {\n createLiveQueryManager,\n type LiveQueryManager,\n type LiveSubscription,\n validateLiveQueryPolicy,\n} from \"./live-query-manager\";\nimport {\n type AttachPayload,\n type BridgeCodec,\n type BridgeEnvelope,\n type BridgeEvent,\n type BridgePort,\n type ExportArtefactWire,\n identityCodec,\n isBridgeEnvelope,\n postBridgeMessage,\n type ProvisionPayload,\n type RpcOp,\n type RpcPayload,\n type SetOnlinePayload,\n type SubscribePayload,\n type TokenResponsePayload,\n} from \"./protocol\";\nimport { createWorkerTokenCache } from \"./token-cache\";\n\nexport interface DefineSyncWorkerOptions<TRegistry extends SyncTableRegistry> {\n /**\n * The sync registry — imported as CODE by the worker file, never cloned into it (ADR-0032 decision 4).\n * When {@link resolveRegistry} is also given this is the DEFAULT (used when the attach carries no role\n * or an unknown one).\n */\n registry: TRegistry;\n /**\n * Resolve the registry to boot from the attach's `config.role` (ADR-0032 S3). A single worker file can\n * bake BOTH role variants (e.g. the board's admin/member registries — same TS shape, different write\n * capability) and pick per-attach, which the spare flow needs: the spare is provisioned role-agnostic\n * (before the user is known) and the role is only settled at claim/attach. Returns `undefined` to fall\n * back to {@link registry}.\n */\n resolveRegistry?: (role: string | undefined) => TRegistry | undefined;\n /**\n * How the worker creates its raw PGlite store (provision + fresh-attach paths). Defaults to\n * {@link createClientPGlite}, which loads PGlite's own boot assets — in a browser worker those hit the\n * same-origin HTTP cache the tab's login-screen warm already primed (ADR-0032 S3). Injected in tests.\n * Takes a plain store PATH (ADR-0036); the internal `backendOverride` is the test lane's memory selection.\n */\n createPglite?: (storePath: string, backendOverride?: \"memory\") => Promise<ClientPGlite>;\n electricUrl: string;\n writeUrl: string;\n /** Static headers on every read + write request (e.g. a gateway `apikey`). See `createSyncClient`. */\n requestHeaders?: Record<string, string>;\n /** Write-only headers merged over {@link requestHeaders} (e.g. region/DB-affinity). See `createSyncClient`. */\n writeRequestHeaders?: Record<string, string>;\n /** Default plain store PATH (ADR-0036) if the first attach carries none — a name, not a storage URL. */\n storePath?: string;\n maxMutationAttempts?: number;\n syncEnabled?: boolean;\n /**\n * How close to expiry (ms) a cached token may be before a read/write that needs it triggers a pull\n * broadcast (ADR-0032 decision 3). Default 30s — comfortably ahead of a long-poll cycle.\n */\n tokenExpiryMarginMs?: number;\n /**\n * The worker's own convergence cadence (ms) — the interval trigger FALLBACK only. Local writes\n * flush immediately via the event-driven `requestPass` seam and tab `wake` signals, so this\n * interval exists purely for retry/recovery sweeps; each idle pass still costs real worker CPU\n * (`flush` + `reconcile` queries). Default 15000.\n */\n convergenceIntervalMs?: number;\n /** Injected transport binder. Defaults to auto-detecting the SharedWorker/dedicated-worker global scope. */\n installGlobal?: boolean;\n /** Injected codec (ADR-0032 S2 §1). Defaults to the v1 identity codec. */\n codec?: BridgeCodec;\n /**\n * A raw PGlite the worker uses instead of creating its own (forwarded to `createSyncClient`'s\n * {@link CreateSyncClientOptions.precreatedPglite}) — the client still applies schema/reconcile. In a\n * browser worker the store is minted internally (`storePath`); this is the seam for a prepopulated store in\n * tests, and the future spare-worker claim (ADR-0032 decision 5).\n */\n precreatedPglite?: CreateSyncClientOptions<TRegistry>[\"precreatedPglite\"];\n /** A fully-provisioned PGlite (forwarded to {@link CreateSyncClientOptions.pgliteInstance}; caller owns schema). */\n pgliteInstance?: CreateSyncClientOptions<TRegistry>[\"pgliteInstance\"];\n /**\n * Bounded zero-subscriber keep-alive for the live-query manager (ADR-0040 decision 4). When an entry's last\n * subscriber leaves, a nonzero effective keep-alive retains its PGlite registration + diff state for a grace\n * period so a matching resubscribe (e.g. a re-mounted route across tabs) reuses it verbatim — no ~400 ms\n * re-materialization. Bounded by explicit budgets; DEFAULTS OFF (`defaultKeepAliveMs: 0` → tear a query\n * down the instant its last consumer leaves, byte-identical to the pre-keep-alive behaviour). Standing\n * argument for the 0 default: a retained entry STILL pays a full SQL rerun + diff on every dependent write —\n * PGlite live queries cannot be paused — so retention only pays off for a genuinely hot, re-mounted query.\n */\n liveQueries?: {\n /** Baseline retention (ms) for a zero-subscriber entry; floored by each subscriber's own hint. Default 0. */\n defaultKeepAliveMs?: number;\n /** Max simultaneously-retained (zero-subscriber) entries — LRU-evicted past this. Default 16. */\n maxRetainedQueries?: number;\n /** Max total rows across all retained entries — LRU-evicted past this. Default 50_000. */\n maxRetainedRows?: number;\n };\n}\n\n/** The worker-side host: attach ports, await the boot, and (for tests) tear down. */\nexport interface SyncWorkerHost<TRegistry extends SyncTableRegistry> {\n /** Bind a transport port (a SharedWorker connection, the dedicated-worker `self`, or a test channel port). */\n connect: (port: BridgePort) => void;\n /** Resolves with the booted in-process engine once the first attach's `createSyncClient` completes. */\n whenBooted: () => Promise<SyncClient<TRegistry>>;\n /** Detach every port and stop the underlying client — for tests and dedicated-worker teardown. */\n close: () => Promise<void>;\n}\n\ninterface LiveSub {\n // The manager-owned handle: `unsubscribe()` (awaited teardown, tracked inside the manager — ADR-0040\n // decision 1) and a coalesced `refresh()` the hydration chain drives.\n subscription: LiveSubscription;\n port: BridgePort;\n}\n\n/**\n * Build a worker host over the given engine config. In a real worker file the consumer calls this at module\n * top level and it auto-binds the global scope; a test constructs it and drives {@link SyncWorkerHost.connect}.\n */\nexport function defineSyncWorker<const TRegistry extends SyncTableRegistry>(\n options: DefineSyncWorkerOptions<TRegistry>,\n): SyncWorkerHost<TRegistry> {\n // Fail at construction, not first subscribe, on a bad keep-alive policy (ADR-0040 decision 4 — bounded).\n validateLiveQueryPolicy(options.liveQueries);\n const codec = options.codec ?? identityCodec;\n const tokenExpiryMarginMs = options.tokenExpiryMarginMs ?? 30_000;\n const convergenceIntervalMs = options.convergenceIntervalMs ?? 15_000;\n const createPglite =\n options.createPglite ??\n ((storePath: string, backendOverride?: \"memory\") =>\n createClientPGlite(storePath, backendOverride ? { backendOverride } : undefined));\n // A testing acknowledgment (ADR-0036) spread into THIS worker's options — needed when a test injects a\n // non-persistent BYO store (`precreatedPglite` / `pgliteInstance` / a memory-returning `createPglite`),\n // which `createSyncClient` would otherwise refuse. Forwarded to the boot below. A browser worker never\n // sets it; a memory selection carried on the attach wire wins over it.\n const workerTestMarker = readTestStoreMarker(options);\n\n const ports = new Set<BridgePort>();\n const liveSubs = new Map<string, LiveSub>();\n // The live-query lifecycle (PGlite registration, diff listener, and the ADR-0040 decision-1 awaited-teardown\n // set) lives in a single manager owned per engine. Created lazily on first subscribe because it needs the\n // booted client's `live` namespace (`active.pglite.live`); the worker never restarts its engine in place\n // (ADR-0040 decision 7), so one manager serves the host's whole lifetime. `close()` disposes it.\n let liveManager: LiveQueryManager | null = null;\n const ensureLiveManager = (active: SyncClient<TRegistry>): LiveQueryManager =>\n (liveManager ??= createLiveQueryManager({\n live: active.pglite.live,\n ...(options.liveQueries ? { policy: options.liveQueries } : {}),\n }));\n // Subscribes that have entered `handleSubscribe` but not yet reached `liveSubs.set` (they are mid-await on\n // prepareQuery / hydration / manager setup). Registered SYNCHRONOUSLY at entry, keyed by `queryId`, so an\n // `unsubscribe`/`detach` arriving during those awaits can mark the pending subscribe CANCELLED — otherwise\n // it would finish and store a subscription for an already-gone port, escaping the awaited-teardown boundary\n // (ADR-0040 decision 1). Removed in `handleSubscribe`'s finally.\n const pendingSubscribes = new Map<string, { port: BridgePort; cancelled: boolean }>();\n // Host shutdown state (ADR-0040 decision 1 — the pending-before-manager close race). `close()` flips\n // `closing` and awaits every in-flight `handleSubscribe` task BEFORE disposing the manager, so a subscribe\n // still mid-await when close begins can neither create a registration afterwards (it early-bails on\n // `closing`) nor escape the awaited-teardown boundary. `inFlightSubscribes` holds each whole-call task.\n let closing = false;\n const inFlightSubscribes = new Set<Promise<void>>();\n // One stable, opaque diagnostics scope per bridge port (ADR-0040 decision 5) — so a snapshot's `scopeCount`\n // reads as the distinct-tab count. Never part of the fingerprint; a lazy per-port counter.\n const portScopes = new WeakMap<BridgePort, string>();\n let nextScopeId = 0;\n const scopeForPort = (port: BridgePort): string => {\n let scope = portScopes.get(port);\n if (scope === undefined) {\n scope = `port-${nextScopeId++}`;\n portScopes.set(port, scope);\n }\n return scope;\n };\n\n // ─── Pre-spawned (schemaless) store — the spare flow (ADR-0032 decision 5) ────────────────────────\n // A `provision` mints the raw PGlite (initdb only) and holds it idle here; the first real `attach`\n // adopts it as `precreatedPglite` (the client still runs schema/journal recovery/reconcile). Provision\n // is role-agnostic — the registry is chosen at attach — so the same warmed store serves either role.\n // `stamp` carries the spare's create timing (ADR-0034): a boot adopting this store reports the initdb cost\n // as `BootReport.provision` (with `phases.pgliteCreateMs = null`) instead of timing a create it never ran.\n let provisioned: {\n storePath: string;\n pglite: Promise<ClientPGlite>;\n stamp: Promise<{ initdbMs: number; provisionReadyAt: number }>;\n } | null = null;\n\n // ─── Outbound-convergence gate — the tab's Offline toggle over the bridge (ADR-0032 S3) ───────────\n // The worker owns convergence; the tab forwards its Offline flag as `set-online`. When suppressed the\n // interval trigger's `shouldConverge` returns false (writes stage in the journal, unsent) and a `wake`\n // is ignored; resuming fires one immediate pass so the queue flushes at once.\n let convergenceSuppressed = false;\n let fireConvergence: (() => void) | null = null;\n const baseTrigger = createIntervalConvergenceTrigger(convergenceIntervalMs);\n const gatedTrigger: ConvergenceTrigger = {\n subscribe: (onSignal) => {\n fireConvergence = onSignal;\n const unsubscribe = baseTrigger.subscribe(onSignal);\n return () => {\n fireConvergence = null;\n unsubscribe();\n };\n },\n shouldConverge: () => !convergenceSuppressed && baseTrigger.shouldConverge(),\n };\n\n // ─── The single auth token cache + pull mechanism (ADR-0032 decision 3) ──────────────────────────\n const tokenCache = createWorkerTokenCache({\n marginMs: tokenExpiryMarginMs,\n broadcastRequest: (requestId) => {\n syncDebug(\"worker token pull broadcast\", { requestId, tabs: ports.size });\n broadcast(\"token-request\", { requestId });\n },\n });\n const getWorkerAuthToken = () => tokenCache.getToken();\n\n // ─── The broadcast event channel (ADR-0032 decision 7) ───────────────────────────────────────────\n const seenReadyGroups = new Set<string>();\n const broadcast = (type: BridgeEnvelope[\"type\"], payload: unknown) => {\n for (const port of ports) postBridgeMessage(port, codec, type, payload);\n };\n const broadcastEvent = (event: BridgeEvent) => broadcast(\"event\", event);\n\n // ─── Debug-rail buffer + replay (ADR-0034) ───────────────────────────────────────────────────────\n // The engine boots on the first ATTACH, but the front half of boot (provision, and the boot rail's\n // schema/journal/reconcile lines) can be emitted before any debug-enabled tab is listening — so they\n // vanished. Install the sink at construction (not at boot) into a bounded ring buffer, so the whole boot\n // is captured from worker start; the buffer is REPLAYED (marked `[replay]`) to the first attach, while the\n // back half streams live over the bridge. Bounded so a long-lived worker never grows the buffer unbounded.\n const RAIL_BUFFER_MAX = 500;\n const railBuffer: Array<{ stamp: number; line: string; data?: Record<string, unknown> }> = [];\n let railReplayed = false;\n setSyncDebugSink((line, stamp, data) => {\n if (railBuffer.length >= RAIL_BUFFER_MAX) railBuffer.shift();\n railBuffer.push({ stamp, line, ...(data ? { data } : {}) });\n broadcastEvent({ kind: \"debug\", stamp, line, ...(data ? { data } : {}) });\n });\n const nowStamp = () => (typeof performance !== \"undefined\" ? performance.now() : Date.now());\n // Replay the pre-attach rail buffer to the first attaching port. Taken as a snapshot BEFORE this attach's\n // boot runs, so the boot's own lines (which stream live to this now-connected port) are never doubled.\n const replayRailBufferTo = (port: BridgePort) => {\n if (railReplayed) return;\n railReplayed = true;\n const buffered = [...railBuffer];\n postBridgeMessage(port, codec, \"event\", {\n kind: \"debug\",\n stamp: nowStamp(),\n line: `[replay] replaying ${buffered.length} buffered rail line(s)`,\n } satisfies BridgeEvent);\n for (const entry of buffered) {\n postBridgeMessage(port, codec, \"event\", {\n kind: \"debug\",\n stamp: entry.stamp,\n line: `[replay] ${entry.line}`,\n ...(entry.data ? { data: entry.data } : {}),\n } satisfies BridgeEvent);\n }\n };\n\n const emitStatus = (status: SyncRuntimeStatus) => {\n broadcastEvent({ kind: \"status\", status });\n // Derive a per-group `groupReady` event for each group that newly reached ready, so a tab gets both the\n // status snapshot (`status.groups`) and a discrete edge to await (ADR-0032 decision 6/7).\n for (const [groupKey, ready] of Object.entries(status.groups ?? {})) {\n if (ready && !seenReadyGroups.has(groupKey)) {\n seenReadyGroups.add(groupKey);\n broadcastEvent({ kind: \"groupReady\", groupKey });\n }\n }\n };\n\n // ─── Engine boot — reuse createSyncClient verbatim (ADR-0032 decision 1/4) ────────────────────────\n let client: SyncClient<TRegistry> | null = null;\n let bootPromise: Promise<SyncClient<TRegistry>> | null = null;\n // The role the engine actually booted with (from the FIRST attach's config). Later attaches compare\n // their requested role against this and get a warning on mismatch (ADR-0032 FIX 5) — never a reject.\n let bootedRole: string | undefined;\n // The engine's `ready` is monotonic: once its initial sync lands it stays resolved even if the phase\n // later degrades. A tab attaching AFTER that moment must still get a resolved `ready`, so track whether\n // it has fired and tell the ack (ADR-0032 FIX 3).\n let engineReadyFired = false;\n let resolveBooted!: (client: SyncClient<TRegistry>) => void;\n const bootedPromise = new Promise<SyncClient<TRegistry>>((resolve) => {\n resolveBooted = resolve;\n });\n\n const boot = (attach: AttachPayload): Promise<SyncClient<TRegistry>> => {\n if (bootPromise) return bootPromise;\n // The tab is the auth owner: seed the cache with the token it presented at attach (decision 3).\n tokenCache.push(attach.token);\n bootedRole = attach.config?.role;\n // The debug-rail sink is installed at construction (ADR-0034) so it buffers from worker start and\n // forwards live to tabs, stamped with the WORKER's monotonic clock (decision 7) — see above.\n // Resolve the registry from the attach's role (ADR-0032 S3): a single worker file bakes both variants\n // and the claim/attach settles which one boots — the spare was provisioned before the role was known.\n const registry = options.resolveRegistry?.(attach.config?.role) ?? options.registry;\n // storePath-first, matching the `provision` handler's resolution (below): the board sends BOTH a bare\n // `storeId` (SharedWorker naming, tab-side) AND the real `storePath` (`pgxsinkit-board-<id>`), and the\n // PGlite store lives at `storePath` — so the provisioned store's path must be what we adopt on.\n // `storeId` is only a last-ditch fallback for a caller that passes it as the store path.\n const storePath = attach.storePath ?? attach.storeId ?? options.storePath ?? \"pgxsinkit-overlay-v1\";\n // The testing memory-backend override rides as an explicit wire field (a symbol does not survive\n // structured clone, ADR-0036); re-stamp it as the internal marker on the createSyncClient options below.\n // A memory selection on the attach wins over the worker's own acknowledgment (memory implies acknowledged).\n const backendOverride = attach.testStoreBackend;\n const testMarker: TestStoreMarker | undefined = backendOverride === \"memory\" ? \"memory\" : workerTestMarker;\n // Restore (ADR-0035 decision 6): the tab decomposed the backup into a transferred `ArrayBuffer` + mime\n // (`RestoreArtefactWire`); recompose a `Blob` to hand `createSyncClient` as `restoreFrom`. Restore OWNS the\n // store's creation (a `loadDataDir` seed), so it is mutually exclusive with adopting a pre-provisioned or\n // caller-supplied instance — when restoring, we suppress the adopt paths below rather than let\n // createSyncClient throw the exclusion error.\n const restoreFrom = attach.restore\n ? new Blob([attach.restore.buffer], { type: attach.restore.mimeType })\n : undefined;\n // Adopt a matching pre-provisioned store (its initdb already ran off-thread) as `precreatedPglite`;\n // createSyncClient falls back to a fresh `storePath` create if that promise rejects — a pure accelerator.\n // Never adopt when restoring (restore boots a brand-new store from the backup, not the provisioned one).\n const adoptingProvisioned = restoreFrom == null && provisioned != null && provisioned.storePath === storePath;\n const precreatedPglite = adoptingProvisioned\n ? provisioned!.pglite\n : restoreFrom\n ? undefined\n : options.precreatedPglite;\n // The adopted spare's create timing feeds `BootReport.provision` (ADR-0034); absent otherwise.\n const provisionStamp = adoptingProvisioned ? provisioned!.stamp : undefined;\n if (adoptingProvisioned) {\n syncDebug(\"worker adopting provisioned store\", { storePath });\n }\n if (restoreFrom) {\n syncDebug(\"worker restoring store from backup\", { storePath, byteLength: attach.restore!.buffer.byteLength });\n }\n bootPromise = createSyncClient<TRegistry>({\n registry,\n electricUrl: options.electricUrl,\n writeUrl: options.writeUrl,\n storePath,\n // Re-stamp the internal testing marker (ADR-0036) so `createSyncClient`'s option handling selects the\n // memory backend on its fallback create and/or bypasses the BYO refusal for an injected test store —\n // the wire field / worker acknowledgment are the cross-clone carriers for it.\n ...(testMarker ? { [TEST_STORE_BACKEND]: testMarker } : {}),\n // Restore rides the boot attach (ADR-0035 decision 6): createSyncClient seeds the fresh store via\n // `loadDataDir`, boots offline, and quarantines the recovered journal.\n ...(restoreFrom ? { restoreFrom } : {}),\n // Boot observability (ADR-0034): label the report `worker`, and forward the provision stamp so an\n // adopted spare's initdb cost is reported rather than a create this boot never ran.\n bootMode: \"worker\",\n ...(provisionStamp ? { provisionStamp } : {}),\n ...(precreatedPglite ? { precreatedPglite } : {}),\n ...(options.pgliteInstance && restoreFrom == null ? { pgliteInstance: options.pgliteInstance } : {}),\n // Fresh-store prefetch overlap (ADR-0032 S4): the tab's claim path proved this store a schemaless\n // spare and forwarded the hint in the attach config, so the shape catch-up overlaps schema exec +\n // journal recovery + reconcile. Never inferred from \"adopting a provisioned store\": the board\n // provisions a worker even for a MAPPED (returning) user, whose idb is NOT fresh — only the claim\n // path's explicit hint distinguishes them.\n ...(attach.config?.freshStore === true ? { freshStore: true } : {}),\n getAuthToken: getWorkerAuthToken,\n // The worker owns convergence via the interval trigger, GATED by the tab's Offline toggle\n // (`set-online`); tabs additionally forward online/visibility as `wake` pass requests (below).\n autoSync: gatedTrigger,\n syncEnabled: attach.config?.syncEnabled ?? options.syncEnabled ?? true,\n ...(options.requestHeaders ? { requestHeaders: options.requestHeaders } : {}),\n ...(options.writeRequestHeaders ? { writeRequestHeaders: options.writeRequestHeaders } : {}),\n ...(options.maxMutationAttempts != null ? { maxMutationAttempts: options.maxMutationAttempts } : {}),\n onStatusChange: (status) => emitStatus(status),\n onConflict: (details) => broadcastEvent({ kind: \"conflict\", details }),\n onQuarantine: (details) => broadcastEvent({ kind: \"quarantine\", details }),\n onReject: (details) => broadcastEvent({ kind: \"reject\", details }),\n onSchemaChange: (event: LocalStoreVersionEvent) => broadcastEvent({ kind: \"schema-change\", event }),\n onSyncError: (error) => broadcastEvent({ kind: \"sync-error\", message: error.message }),\n // Boot observability (ADR-0034): broadcast the finalized report to currently-attached ports (one-shot\n // push). Later tabs read the same report via the `bootReport` pull RPC — there is no replay event.\n onBootReport: (report) => broadcastEvent({ kind: \"boot-report\", report }),\n });\n return bootPromise;\n };\n\n const whenBooted = () => bootedPromise;\n\n // ─── Write / mutation-state RPC dispatch ─────────────────────────────────────────────────────────\n const dispatchRpc = async (active: SyncClient<TRegistry>, op: RpcOp, args: unknown[]): Promise<unknown> => {\n type TableKey = SyncTableName<TRegistry>;\n switch (op) {\n case \"create\":\n return active.mutate.create(args[0] as TableKey, args[1] as never);\n case \"update\":\n return active.mutate.update(args[0] as TableKey, args[1] as Record<string, string>, args[2] as never);\n case \"delete\":\n return active.mutate.delete(args[0] as TableKey, args[1] as Record<string, string>);\n case \"batch\":\n return active.mutate.batch(args[0] as ReadonlyArray<MutationBatchItem<TRegistry>>);\n case \"transaction\": {\n // The tab collected the unit's mutations (the run callback can't cross the wire); the worker replays\n // the serialized items into a real `client.transaction` so pessimistic acks / optimistic flush match\n // the in-process semantics exactly.\n const { mode, items } = args[0] as { mode: WriteMode; items: MutationBatchItem<TRegistry>[] };\n return active.transaction({ mode }, (tx) => {\n for (const item of items) {\n const handle = tx.tables[item.table];\n if (item.kind === \"create\") {\n handle.create(item.input as never);\n } else if (item.kind === \"update\") {\n // ADR-0022 addendum: a `blind` update replays through `updateBlind` (journal-only, no overlay).\n if (item.blind) handle.updateBlind(item.entityKey, item.patch as never);\n else handle.update(item.entityKey, item.patch as never);\n } else {\n handle.delete(item.entityKey);\n }\n }\n });\n }\n case \"flush\":\n return active.flush(args[0] as TableKey | undefined);\n case \"reconcile\":\n return active.reconcile(args[0] as TableKey | undefined);\n case \"retryFailed\":\n return active.retryFailed(args[0] as TableKey | undefined);\n case \"recoverSending\":\n return active.recoverSending(args[0] as TableKey | undefined);\n case \"discardConflict\":\n return active.discardConflict(args[0] as TableKey, args[1] as Record<string, string>);\n case \"discardQuarantined\":\n return active.discardQuarantined(args[0] as TableKey, args[1] as Record<string, string>);\n case \"desync\":\n return active.desync(args[0] as TableKey);\n case \"discardEphemeral\":\n return active.discardEphemeral(args[0] as TableKey);\n case \"readMutationDetails\":\n return active.readMutationDetails(args[0] as TableKey | undefined);\n case \"diagnostics\":\n return active.diagnostics(args[0] as TableKey | undefined);\n case \"rawQuery\":\n // Inspection read (ADR-0032 S2): run straight against the worker's own store — `active.pglite`\n // exists worker-side (it's the in-process client). `Results` rows/fields structured-clone across\n // the wire (Dates survive postMessage), so the tab receives the same shape it would in-process.\n // The options arg is the clonable RawQueryOptions subset (rowMode) — the REPL's array mode.\n return active.rawQuery(args[0] as string, args[1] as unknown[] | undefined, args[2] as RawQueryOptions);\n case \"rawExec\":\n return active.rawExec(args[0] as string, args[1] as RawQueryOptions);\n case \"bootReport\":\n // Boot observability (ADR-0034): the worker engine's stored report (or null). Pull, so a late tab\n // reads a boot predating it; the report structured-clones across the bridge as a plain object.\n return active.bootReport();\n case \"liveQueryDiagnostics\":\n // Live-query diagnostics (ADR-0040 decision 5): the manager lives in THIS host closure (not on\n // `active`), so read it directly. Plain-object records (digests + counts only) structured-clone\n // across the bridge; `[]` when nothing has subscribed yet (the manager is created lazily).\n return liveManager?.snapshot() ?? [];\n case \"exportStore\": {\n // Store backup (ADR-0035): run the live export on the worker's OWN client (its lifecycle slot\n // serialises it against every tab's export). A `File` cannot cross the bridge as a transferable, so\n // decompose it into an `ExportArtefactWire` — the `ArrayBuffer` is listed on `postMessage`'s transfer\n // list in the `rpc` handler and rebuilt into a `File` tab-side.\n const { file, report } = await active.exportStore(args[0] as StoreExportOptions | undefined);\n const buffer = await file.arrayBuffer();\n return { buffer, fileName: file.name, mimeType: file.type, report } satisfies ExportArtefactWire;\n }\n case \"exportDiagnostics\": {\n // Diagnostic dump (ADR-0035): identical bridge shape to the store backup — the worker runs the live\n // datadir dump → memory throwaway clone → `pg_dump` on its OWN client (same lifecycle slot), and the\n // SQL crosses back as the same transferred-`ArrayBuffer` `ExportArtefactWire`.\n const { file, report } = await active.exportDiagnostics(args[0] as DiagnosticExportOptions | undefined);\n const buffer = await file.arrayBuffer();\n return { buffer, fileName: file.name, mimeType: file.type, report } satisfies ExportArtefactWire;\n }\n case \"exportData\": {\n // Data export (ADR-0035): identical bridge shape — the worker runs the drain-guarded `pg_dump -t`\n // per-synced-table export on its OWN client (same lifecycle slot), and the portable SQL crosses back\n // as the same transferred-`ArrayBuffer` `ExportArtefactWire`. A DataExportDrainError rejects the RPC\n // like any other failure (serialised back to the tab).\n const { file, report } = await active.exportData(args[0] as DataExportOptions | undefined);\n const buffer = await file.arrayBuffer();\n return { buffer, fileName: file.name, mimeType: file.type, report } satisfies ExportArtefactWire;\n }\n default: {\n const exhaustive: never = op;\n throw new Error(`unknown rpc op ${String(exhaustive)}`);\n }\n }\n };\n\n // ─── Live-query bridge (ADR-0032 S2 §4) ──────────────────────────────────────────────────────────\n // `queryId`s are minted by a PER-TAB counter (`live-1`, `live-2`, …), so two tabs collide on the bare id —\n // every worker-side bookkeeping key MUST be port-scoped or one tab's unsubscribe/close tears down another\n // tab's identically-numbered subscription (latent since ADR-0032; exposed the moment tab close started\n // sending unsubscribes — the two-tab board e2e's scenario (c)). The wire keeps the bare `queryId` (the\n // port disambiguates); only the worker's maps compose it with the port's scope.\n const subKeyFor = (port: BridgePort, queryId: string): string => `${scopeForPort(port)}:${queryId}`;\n\n const handleSubscribe = (port: BridgePort, id: string | undefined, payload: SubscribePayload): Promise<void> => {\n // Register the in-flight subscribe SYNCHRONOUSLY (before the first await) so an `unsubscribe`/`detach`/\n // `close` arriving mid-await can mark it cancelled (ADR-0040 decision 1 — no subscription escapes teardown).\n const pending = { port, cancelled: false };\n const subKey = subKeyFor(port, payload.queryId);\n pendingSubscribes.set(subKey, pending);\n // Track the WHOLE call so `close()` awaits it before disposing the manager: the task is added to\n // `inFlightSubscribes` synchronously here and removed in its own finally, so close can never observe an\n // empty set while a subscribe is still awaiting prepareQuery / hydration / manager setup.\n // `let task!` (not `const`): the finally references `task` to remove itself, and it only runs after the\n // first await — by then the assignment below has completed, so the definite-assignment assertion is safe.\n let task!: Promise<void>;\n task = (async () => {\n try {\n await handleSubscribeInner(port, id, payload, pending, subKey);\n } finally {\n pendingSubscribes.delete(subKey);\n inFlightSubscribes.delete(task);\n }\n })();\n inFlightSubscribes.add(task);\n return task;\n };\n\n const handleSubscribeInner = async (\n port: BridgePort,\n id: string | undefined,\n payload: SubscribePayload,\n pending: { port: BridgePort; cancelled: boolean },\n subKey: string,\n ) => {\n const active = client ?? (await bootPromise);\n if (!active) throw new Error(\"subscribe before attach\");\n const { queryId, sql, params, pkColumns, use, fields, keepAliveMs } = payload;\n // Activate any lazy relations the query reads BEFORE registering the live query (ADR-0021) — the worker\n // owns the real client, so its `prepareQuery` does the real work; the tab's `prepareQuery` is a no-op.\n // Scan the ORIGINAL sql (the wrap only adds an outer `SELECT * FROM (...)`; table refs are inside).\n // The activated keys travel back on the initial snapshot: activation is stream-start, not catch-up,\n // so the tab needs them to await `groupReady` (its `hydrating` signal) without blocking this register.\n const prepared = await active.prepareQuery({ sql, ...(use ? { use: use as SyncTableName<TRegistry>[] } : {}) });\n // Hydration spans EVERY referenced consistency group (eager AND lazy), computed on the real client the\n // worker owns: the referenced tables whose group is not yet caught up at subscribe time. Empty (steady\n // state / sync disabled) → no `hydrated` gating at all; otherwise it drives both the `live-initial`\n // `hydratingTables` field (the tab's `hydrating` source) and the `live-hydrated` block below.\n const hydratingTables = active.hydratingTablesFor({ sql, ...(use ? { use: use as string[] } : {}) });\n\n // Render the query safe to materialise: a JOIN with same-named columns fails BOTH live APIs' temp-view\n // creation (`column \"title\" specified more than once`) unless every output column has a unique alias.\n // No `fields` → SQL unchanged (backward-compatible name-keyed rows; the aliased path keys by alias). The\n // wrap stays caller-side (ADR-0040 decision 3): the manager receives POST-WRAP SQL as its query input.\n const materialSql = wrapLiveQueryForMaterialization(sql, fields);\n // Early bail BEFORE the manager is created (ADR-0040 decision 1 — the pending-before-manager close race):\n // if the host is closing, this subscribe was cancelled, or its port detached WHILE we awaited prepareQuery\n // / hydration, do NOT call `ensureLiveManager` — creating a registration now would race the engine close\n // with a fire-and-forget teardown nothing awaits (a manager born after `close()` disposed is never\n // disposed). Post the rpc error for this subscribe id so a still-live tab's `subscribeLiveRows` rejects\n // instead of hanging, and return without touching the manager. The post-setup check below still catches a\n // cancellation that lands DURING manager setup (after the manager already exists).\n if (closing || pending.cancelled || !ports.has(port)) {\n postBridgeMessage(\n port,\n codec,\n \"rpc-result\",\n {\n ok: false,\n error: { message: \"[pgxsinkit] subscribe cancelled — the worker is closing or the port detached\" },\n },\n id,\n );\n return;\n }\n // The manager owns registration + diff + teardown; the bridge posting (per-`queryId`, with the caller-owned\n // `lazyTables`/`hydratingTables` observability fields) stays here — those are per-subscriber pre-steps.\n const subscription = await ensureLiveManager(active).subscribe(\n { materialSql, params: params as unknown[], ...(pkColumns ? { pkColumns } : {}) },\n {\n deliverInitial: (rows) => {\n // Initial snapshot verbatim (not a diff), correlated to the subscribe request so the tab resolves.\n postBridgeMessage(\n port,\n codec,\n \"live-initial\",\n {\n queryId,\n rows,\n // `lazyTables` = the activated lazy relations (observability); `hydratingTables` = the referenced\n // groups (eager OR lazy) still catching up, which the tab turns into its `hydrated` promise.\n ...(prepared.lazyTables.length > 0 ? { lazyTables: prepared.lazyTables.map(String) } : {}),\n ...(hydratingTables.length > 0 ? { hydratingTables: [...hydratingTables] } : {}),\n },\n id,\n );\n },\n deliverDiff: (diff) => {\n postBridgeMessage(port, codec, \"live-diff\", { queryId, ...diff });\n },\n },\n // The per-subscriber keep-alive hint (ADR-0040 decision 4) — kept OUT of the spec so it never touches\n // the fingerprint (decision 3). Absent → no hint (the manager falls back to its policy default). The\n // `scope` is one stable id per port (decision 5 diagnostics), also fingerprint-excluded.\n { ...(keepAliveMs != null ? { keepAliveMs } : {}), scope: scopeForPort(port) },\n );\n // The port was detached, or this query was unsubscribed, WHILE we awaited (prepareQuery / hydration /\n // manager setup all yield). Neither cleanup path found a `liveSubs` entry — so undo the just-created\n // subscription here and DO NOT record it, else it would outlive its port (ADR-0040 decision 1). A\n // `live-initial` may already have been posted to a dead port; that is harmless (a closed port's\n // postMessage is a no-op) and not worth preventing. `closing` is included so a `close()` that began DURING\n // manager setup still unwinds this just-created subscription rather than recording it.\n if (closing || pending.cancelled || !ports.has(port)) {\n void subscription.unsubscribe();\n return;\n }\n liveSubs.set(subKey, { port, subscription });\n\n // Hydration completion travels the SAME port as the diff stream, so ordering is guaranteed: await the\n // pending groups' catch-up (eager AND lazy), force one refresh of the live query against the caught-up\n // store (its listener posts the rows as a live-diff, synchronously inside the refresh), THEN post\n // `live-hydrated`. The tab therefore always has the caught-up rows before its `hydrated` resolves — a\n // readiness signal on a side channel (e.g. the `groupReady` broadcast) can beat the rows and flash a\n // false \"empty\" state. Skipped entirely when nothing is pending (steady state / sync disabled).\n if (hydratingTables.length > 0) {\n void Promise.all(hydratingTables.map((key) => active.groupReady(key as SyncTableName<TRegistry>)))\n .then(async () => {\n if (!liveSubs.has(subKey)) return; // unsubscribed while catching up\n await subscription.refresh();\n if (!liveSubs.has(subKey)) return;\n postBridgeMessage(port, codec, \"live-hydrated\", { queryId });\n })\n .catch(() => undefined); // a torn-down engine mid-catch-up must not surface as an unhandled rejection\n }\n };\n\n // ─── Per-port message routing ────────────────────────────────────────────────────────────────────\n const onPortMessage = (port: BridgePort, data: unknown) => {\n if (!isBridgeEnvelope(data)) return;\n const envelope = data;\n const payload = codec.decode(envelope.payload);\n switch (envelope.type) {\n case \"provision\": {\n // Pre-spawn the raw store (initdb only), idle and schemaless, for the first attach to adopt\n // (ADR-0032 decision 5). A no-op once the engine has booted or a store is already provisioned.\n const provision = payload as ProvisionPayload;\n const storePath = provision.storePath ?? provision.storeId ?? options.storePath ?? \"pgxsinkit-overlay-v1\";\n // The testing memory-backend override rides as an explicit wire field (ADR-0036) — a symbol does not\n // survive structured clone, so the store's backend selection travels here and is passed to createPglite.\n const backendOverride = provision.testStoreBackend;\n if (bootPromise != null || provisioned != null) {\n postBridgeMessage(port, codec, \"provision-ack\", {\n ok: true,\n ...(provision.storeId ? { storeId: provision.storeId } : {}),\n });\n break;\n }\n // Stamp the spare's create timing (ADR-0034): initdb cost + the monotonic instant it became ready,\n // so an adopting boot can compute how long it sat idle before adoption.\n const provisionStartedAt = nowStamp();\n const pglite = createPglite(storePath, backendOverride);\n const stamp = pglite.then(() => {\n const readyAt = nowStamp();\n return { initdbMs: readyAt - provisionStartedAt, provisionReadyAt: readyAt };\n });\n provisioned = { storePath, pglite, stamp };\n // Guard an unobserved rejection when no attach ever adopts it (the page navigated away).\n void pglite.catch(() => undefined);\n void stamp.catch(() => undefined);\n syncDebug(\"worker store provisioned\", { storePath });\n void pglite.then(\n () =>\n postBridgeMessage(port, codec, \"provision-ack\", {\n ok: true,\n ...(provision.storeId ? { storeId: provision.storeId } : {}),\n }),\n (error: unknown) =>\n postBridgeMessage(port, codec, \"provision-ack\", {\n ok: false,\n error: serializeError(error),\n ...(provision.storeId ? { storeId: provision.storeId } : {}),\n }),\n );\n break;\n }\n case \"set-online\": {\n // The tab's Offline toggle over the bridge (ADR-0032 S3). Suppress/resume the worker's outbound\n // convergence; resuming fires one immediate pass so queued writes flush at once.\n const { online } = payload as SetOnlinePayload;\n convergenceSuppressed = !online;\n syncDebug(\"worker convergence gate\", { online });\n if (online) fireConvergence?.();\n break;\n }\n case \"attach\": {\n const attach = payload as AttachPayload;\n // Boot observability (ADR-0034): replay the pre-attach rail buffer (provision + any early lines) to\n // the FIRST attaching tab, so the front half of boot is no longer invisible. Snapshotted before this\n // attach's boot runs, so the boot's own lines (streamed live) are not doubled.\n replayRailBufferTo(port);\n const alreadyBooted = bootPromise !== null;\n // Restore rides the FIRST (boot) attach only (ADR-0035 decision 6): a restore attach that arrives once\n // the engine has already booted CANNOT be honoured — `loadDataDir` is a create-time seed and the store\n // is already live. Reject THIS attach with a typed error rather than silently ignoring the backup, so\n // the caller learns their restore did not happen (the engine keeps running its existing store).\n if (alreadyBooted && attach.restore != null) {\n postBridgeMessage(port, codec, \"attach-ack\", {\n alreadyBooted,\n error: {\n message:\n \"[pgxsinkit] cannot restore into a running store: the worker engine has already booted, and a store backup can only seed a brand-new store on the FIRST attach (ADR-0035 decision 6). Restore into a fresh worker instead.\",\n },\n });\n break;\n }\n if (alreadyBooted) {\n // A later attach seeds auth WITHOUT clobbering a fresher cached token (ADR-0032 FIX 5) — the\n // first-boot `push` already ran, and only an explicit `token-push` (auth owner) may overwrite.\n tokenCache.pushIfFresher(attach.token);\n // Role is a property of the (user, store) the engine already booted for: the worker is\n // one-engine-per-(user,store) by ADR-0032 decision 2 and is NOT keyed by role. A mismatch is an\n // app-layer bug to surface, not a supported topology — warn, keep the booted registry.\n const requested = attach.config?.role;\n if (requested !== bootedRole) {\n syncDebug(\"worker attach role mismatch — engine keeps its booted registry\", {\n booted: bootedRole,\n requested,\n });\n }\n }\n void boot(attach).then(\n (booted) => {\n client = booted;\n resolveBooted(booted);\n // Track the engine's monotonic `ready` edge exactly once, so a LATER attach acked after the\n // initial sync landed can resolve its `ready` straight from the ack (ADR-0032 FIX 3).\n if (!engineReadyFired) {\n void booted.ready.then(() => {\n engineReadyFired = true;\n });\n }\n // Ack AFTER the engine exists so the tab's subsequent traffic (rpc/subscribe) has a client to\n // hit; include current status + per-group readiness for a late-joining tab (decisions 4/6).\n postBridgeMessage(port, codec, \"attach-ack\", {\n alreadyBooted,\n ...(engineReadyFired ? { engineReady: true } : {}),\n });\n postBridgeMessage(port, codec, \"event\", { kind: \"status\", status: booted.status });\n },\n (error: unknown) => {\n // The engine boot rejected: tell THIS attaching tab so it rejects `attachSyncClient` instead of\n // hanging on the ack (ADR-0032 FIX 1), and clear `bootPromise` so a later attach retries the\n // boot. Do NOT clear `provisioned`: a resolved provisioned PGlite holds the only open handle on\n // that store, so a retry must adopt it (createSyncClient falls back internally if it rejected).\n bootPromise = null;\n postBridgeMessage(port, codec, \"attach-ack\", {\n alreadyBooted,\n error: serializeError(error),\n });\n },\n );\n break;\n }\n case \"token-push\": {\n // The tab pushed a fresh token (auth state change) — update the cache and satisfy any in-flight pull.\n tokenCache.push(payload as AttachPayload[\"token\"]);\n break;\n }\n case \"token-response\": {\n const response = payload as TokenResponsePayload;\n // First response for the current pull wins; a stale/duplicate requestId is ignored.\n tokenCache.respond(response.requestId, response.token);\n break;\n }\n case \"rpc\": {\n const { op, args } = payload as RpcPayload;\n const id = envelope.id;\n void (async () => {\n try {\n const active = client ?? (await bootPromise);\n if (!active) throw new Error(\"rpc before attach\");\n const value = await dispatchRpc(active, op, args);\n // An export artefact (backup tarball or diagnostic SQL) crosses zero-copy: transfer its\n // `ArrayBuffer` (rebuilt into a `File` tab-side, ADR-0035). Every other op's value\n // structured-clones in place with no transfer list.\n const transfer =\n op === \"exportStore\" || op === \"exportDiagnostics\" || op === \"exportData\"\n ? [(value as ExportArtefactWire).buffer]\n : undefined;\n postBridgeMessage(port, codec, \"rpc-result\", { ok: true, value }, id, transfer);\n } catch (error) {\n postBridgeMessage(port, codec, \"rpc-result\", { ok: false, error: serializeError(error) }, id);\n }\n })();\n break;\n }\n case \"subscribe\": {\n const id = envelope.id;\n void handleSubscribe(port, id, payload as SubscribePayload).catch((error) => {\n postBridgeMessage(port, codec, \"rpc-result\", { ok: false, error: serializeError(error) }, id);\n });\n break;\n }\n case \"unsubscribe\": {\n const { queryId } = payload as { queryId: string };\n // Compose the SAME port-scoped key the subscribe used — a bare queryId lookup would collide with\n // another tab's identically-numbered subscription (see `subKeyFor`).\n const subKey = subKeyFor(port, queryId);\n const sub = liveSubs.get(subKey);\n if (sub) {\n // Non-blocking for the caller: the manager retains the teardown promise so `close()` awaits it.\n void sub.subscription.unsubscribe();\n liveSubs.delete(subKey);\n } else {\n // No live entry yet → the subscribe is still mid-await. Mark it cancelled so `handleSubscribe`\n // tears down the subscription it is about to create instead of recording it (ADR-0040 decision 1).\n const inFlight = pendingSubscribes.get(subKey);\n if (inFlight) inFlight.cancelled = true;\n }\n break;\n }\n case \"wake\": {\n // A tab forwarded online/visibilitychange (or a manual nudge): treat it as a convergence pass request\n // so a write flushes promptly without waiting for the worker's interval tick (decision 5 seam).\n // Suppressed while the Offline toggle is off — a wake must not flush a simulated-offline board.\n if (!convergenceSuppressed) void bootPromise?.then((active) => void active.flush());\n break;\n }\n default:\n break;\n }\n };\n\n const detachPort = (port: BridgePort) => {\n ports.delete(port);\n for (const [subKey, sub] of liveSubs) {\n if (sub.port === port) {\n // Non-blocking: the manager retains the teardown promise so `close()` awaits it (ADR-0040 decision 1).\n void sub.subscription.unsubscribe();\n liveSubs.delete(subKey);\n }\n }\n // Also cancel every subscribe for this port still mid-await — its `handleSubscribe` will tear down the\n // subscription it is about to create rather than record it for a detached port (ADR-0040 decision 1).\n for (const pending of pendingSubscribes.values()) {\n if (pending.port === port) pending.cancelled = true;\n }\n };\n\n const connect = (port: BridgePort) => {\n ports.add(port);\n const listener = (event: { data: unknown }) => {\n if (isBridgeEnvelope(event.data) && event.data.type === \"detach\") {\n detachPort(port);\n port.removeEventListener(\"message\", listener);\n return;\n }\n onPortMessage(port, event.data);\n };\n port.addEventListener(\"message\", listener);\n port.start?.();\n };\n\n // ─── Global-scope auto-binding (real worker only; tests inject ports via connect) ─────────────────\n if (options.installGlobal !== false) bindGlobalScope(connect);\n\n return {\n connect,\n whenBooted,\n close: async () => {\n // Quiesce pending subscribes FIRST (ADR-0040 decision 1 — the pending-before-manager race): flip\n // `closing`, mark every mid-await subscribe cancelled, and await every in-flight `handleSubscribe` task.\n // This guarantees the manager exists (if any subscribe created one) BEFORE `dispose()` runs, and that no\n // subscribe can create a registration afterwards — each resumes into the `closing` early-bail instead.\n closing = true;\n for (const pending of pendingSubscribes.values()) pending.cancelled = true;\n await Promise.allSettled([...inFlightSubscribes]);\n // Dispose the manager BEFORE `active.stop()` (ADR-0040 decision 1): it tears down every remaining live\n // registration and awaits ALL teardowns, so no fire-and-forget unsubscribe is still in flight when the\n // engine closes (the close-vs-unsubscribe hang). No-op when nothing ever subscribed.\n liveSubs.clear();\n await liveManager?.dispose();\n ports.clear();\n setSyncDebugSink(undefined);\n const active = client ?? (bootPromise ? await bootPromise.catch(() => null) : null);\n await active?.stop();\n },\n };\n}\n\n/** Serialize a thrown value into the bridge's `{message, detail}` error shape (detail only when structured). */\nfunction serializeError(error: unknown): { message: string; detail?: unknown } {\n if (error instanceof Error) {\n const detail = (error as Error & { detail?: unknown }).detail;\n return { message: error.message, ...(detail !== undefined ? { detail } : {}) };\n }\n return { message: String(error) };\n}\n\ninterface SharedWorkerConnectEvent {\n ports: BridgePort[];\n}\ninterface WorkerGlobalScopeLike {\n onconnect?: (event: SharedWorkerConnectEvent) => void;\n postMessage?: (message: unknown) => void;\n addEventListener?: (type: \"message\", listener: (event: { data: unknown }) => void) => void;\n removeEventListener?: (type: \"message\", listener: (event: { data: unknown }) => void) => void;\n}\n\n/**\n * Bind the running global scope to `connect`. A `SharedWorkerGlobalScope` exposes `onconnect` (one event per\n * tab, each carrying a port); a dedicated `DedicatedWorkerGlobalScope` has no `onconnect` but IS itself the\n * single implicit port (`self.postMessage`/`addEventListener`). Neither exists in a plain test/Node context,\n * where the host is driven via {@link SyncWorkerHost.connect} directly — so this is a no-op there.\n */\nfunction bindGlobalScope(connect: (port: BridgePort) => void): void {\n const scope = globalThis as unknown as WorkerGlobalScopeLike;\n const hasSharedWorkerScope =\n typeof (globalThis as { SharedWorkerGlobalScope?: unknown }).SharedWorkerGlobalScope !== \"undefined\";\n const hasDedicatedWorkerScope =\n typeof (globalThis as { DedicatedWorkerGlobalScope?: unknown }).DedicatedWorkerGlobalScope !== \"undefined\";\n\n if (hasSharedWorkerScope) {\n scope.onconnect = (event: SharedWorkerConnectEvent) => {\n const port = event.ports[0];\n if (port) connect(port);\n };\n return;\n }\n if (hasDedicatedWorkerScope && scope.postMessage && scope.addEventListener && scope.removeEventListener) {\n // The dedicated worker's own global scope IS the single port.\n connect({\n postMessage: (message: unknown) => scope.postMessage!(message),\n addEventListener: (type, listener) => scope.addEventListener!(type, listener),\n removeEventListener: (type, listener) => scope.removeEventListener!(type, listener),\n });\n }\n}\n"
|
|
40
|
+
"// The worker entry factory (ADR-0032 S2, decisions 3/4/6/7). `defineSyncWorker` boots ONE sync engine and\n// fans it out to N attached tabs over the bridge. The first attach boots the engine by calling the\n// unchanged `createSyncClient` (the strongest form of \"reuse createSyncClient internals\" — the in-process\n// boot pipeline runs verbatim, so the unit suite stays its equivalence proof); later attaches join it.\n//\n// It serves BOTH a native `SharedWorker` (`onconnect`, many ports) and a dedicated `Worker` (one implicit\n// port) behind {@link SyncWorkerHost.connect} — the same entry a test drives with a plain `MessageChannel`\n// port, so no real Worker is needed to exercise the whole protocol.\n\nimport type { SyncRuntimeStatus, SyncTableName, SyncTableRegistry, WriteMode } from \"@pgxsinkit/contracts\";\n\nimport { type ConvergenceTrigger, createIntervalConvergenceTrigger } from \"../convergence\";\nimport { setSyncDebugSink, syncDebug } from \"../debug\";\nimport {\n type ClientPGlite,\n createClientPGlite,\n type CreateSyncClientOptions,\n createSyncClient,\n type DataExportOptions,\n type DiagnosticExportOptions,\n type MutationBatchItem,\n type RawQueryOptions,\n type StoreExportOptions,\n type SyncClient,\n} from \"../index\";\nimport { wrapLiveQueryForMaterialization } from \"../live-rows-sql\";\nimport type { LocalStoreVersionEvent } from \"../local-store\";\nimport { readTestStoreMarker, TEST_STORE_BACKEND, type TestStoreMarker } from \"../store-path\";\nimport {\n createLiveQueryManager,\n type LiveQueryManager,\n type LiveSubscription,\n validateLiveQueryPolicy,\n} from \"./live-query-manager\";\nimport {\n type AttachPayload,\n type BootMilestone,\n type BridgeCodec,\n type BridgeEnvelope,\n type BridgeEvent,\n type BridgePort,\n type ExportArtefactWire,\n identityCodec,\n isBridgeEnvelope,\n postBridgeMessage,\n type ProvisionPayload,\n type RpcOp,\n type RpcPayload,\n type SetOnlinePayload,\n type SubscribePayload,\n type TokenResponsePayload,\n} from \"./protocol\";\nimport { createWorkerTokenCache } from \"./token-cache\";\n\nexport interface DefineSyncWorkerOptions<TRegistry extends SyncTableRegistry> {\n /**\n * The sync registry — imported as CODE by the worker file, never cloned into it (ADR-0032 decision 4).\n * When {@link resolveRegistry} is also given this is the DEFAULT (used when the attach carries no role\n * or an unknown one).\n */\n registry: TRegistry;\n /**\n * Resolve the registry to boot from the attach's `config.role` (ADR-0032 S3). A single worker file can\n * bake BOTH role variants (e.g. the board's admin/member registries — same TS shape, different write\n * capability) and pick per-attach, which the spare flow needs: the spare is provisioned role-agnostic\n * (before the user is known) and the role is only settled at claim/attach. Returns `undefined` to fall\n * back to {@link registry}.\n */\n resolveRegistry?: (role: string | undefined) => TRegistry | undefined;\n /**\n * How the worker creates its raw PGlite store (provision + fresh-attach paths). Defaults to\n * {@link createClientPGlite}, which loads PGlite's own boot assets — in a browser worker those hit the\n * same-origin HTTP cache the tab's login-screen warm already primed (ADR-0032 S3). Injected in tests.\n * Takes a plain store PATH (ADR-0036); the internal `backendOverride` is the test lane's memory selection.\n */\n createPglite?: (storePath: string, backendOverride?: \"memory\") => Promise<ClientPGlite>;\n electricUrl: string;\n writeUrl: string;\n /** Static headers on every read + write request (e.g. a gateway `apikey`). See `createSyncClient`. */\n requestHeaders?: Record<string, string>;\n /** Write-only headers merged over {@link requestHeaders} (e.g. region/DB-affinity). See `createSyncClient`. */\n writeRequestHeaders?: Record<string, string>;\n /** Default plain store PATH (ADR-0036) if the first attach carries none — a name, not a storage URL. */\n storePath?: string;\n maxMutationAttempts?: number;\n syncEnabled?: boolean;\n /**\n * How close to expiry (ms) a cached token may be before a read/write that needs it triggers a pull\n * broadcast (ADR-0032 decision 3). Default 30s — comfortably ahead of a long-poll cycle.\n */\n tokenExpiryMarginMs?: number;\n /**\n * The worker's own convergence cadence (ms) — the interval trigger FALLBACK only. Local writes\n * flush immediately via the event-driven `requestPass` seam and tab `wake` signals, so this\n * interval exists purely for retry/recovery sweeps; each idle pass still costs real worker CPU\n * (`flush` + `reconcile` queries). Default 15000.\n */\n convergenceIntervalMs?: number;\n /** Injected transport binder. Defaults to auto-detecting the SharedWorker/dedicated-worker global scope. */\n installGlobal?: boolean;\n /** Injected codec (ADR-0032 S2 §1). Defaults to the v1 identity codec. */\n codec?: BridgeCodec;\n /**\n * A raw PGlite the worker uses instead of creating its own (forwarded to `createSyncClient`'s\n * {@link CreateSyncClientOptions.precreatedPglite}) — the client still applies schema/reconcile. In a\n * browser worker the store is minted internally (`storePath`); this is the seam for a prepopulated store in\n * tests, and the future spare-worker claim (ADR-0032 decision 5).\n */\n precreatedPglite?: CreateSyncClientOptions<TRegistry>[\"precreatedPglite\"];\n /** A fully-provisioned PGlite (forwarded to {@link CreateSyncClientOptions.pgliteInstance}; caller owns schema). */\n pgliteInstance?: CreateSyncClientOptions<TRegistry>[\"pgliteInstance\"];\n /**\n * Bounded zero-subscriber keep-alive for the live-query manager (ADR-0040 decision 4). When an entry's last\n * subscriber leaves, a nonzero effective keep-alive retains its PGlite registration + diff state for a grace\n * period so a matching resubscribe (e.g. a re-mounted route across tabs) reuses it verbatim — no ~400 ms\n * re-materialization. Bounded by explicit budgets; DEFAULTS OFF (`defaultKeepAliveMs: 0` → tear a query\n * down the instant its last consumer leaves, byte-identical to the pre-keep-alive behaviour). Standing\n * argument for the 0 default: a retained entry STILL pays a full SQL rerun + diff on every dependent write —\n * PGlite live queries cannot be paused — so retention only pays off for a genuinely hot, re-mounted query.\n */\n liveQueries?: {\n /** Baseline retention (ms) for a zero-subscriber entry; floored by each subscriber's own hint. Default 0. */\n defaultKeepAliveMs?: number;\n /** Max simultaneously-retained (zero-subscriber) entries — LRU-evicted past this. Default 16. */\n maxRetainedQueries?: number;\n /** Max total rows across all retained entries — LRU-evicted past this. Default 50_000. */\n maxRetainedRows?: number;\n };\n}\n\n/** The worker-side host: attach ports, await the boot, and (for tests) tear down. */\nexport interface SyncWorkerHost<TRegistry extends SyncTableRegistry> {\n /** Bind a transport port (a SharedWorker connection, the dedicated-worker `self`, or a test channel port). */\n connect: (port: BridgePort) => void;\n /** Resolves with the booted in-process engine once the first attach's `createSyncClient` completes. */\n whenBooted: () => Promise<SyncClient<TRegistry>>;\n /** Detach every port and stop the underlying client — for tests and dedicated-worker teardown. */\n close: () => Promise<void>;\n}\n\ninterface LiveSub {\n // The manager-owned handle: `unsubscribe()` (awaited teardown, tracked inside the manager — ADR-0040\n // decision 1) and a coalesced `refresh()` the hydration chain drives.\n subscription: LiveSubscription;\n port: BridgePort;\n}\n\n/**\n * Build a worker host over the given engine config. In a real worker file the consumer calls this at module\n * top level and it auto-binds the global scope; a test constructs it and drives {@link SyncWorkerHost.connect}.\n */\nexport function defineSyncWorker<const TRegistry extends SyncTableRegistry>(\n options: DefineSyncWorkerOptions<TRegistry>,\n): SyncWorkerHost<TRegistry> {\n // Fail at construction, not first subscribe, on a bad keep-alive policy (ADR-0040 decision 4 — bounded).\n validateLiveQueryPolicy(options.liveQueries);\n const codec = options.codec ?? identityCodec;\n const tokenExpiryMarginMs = options.tokenExpiryMarginMs ?? 30_000;\n const convergenceIntervalMs = options.convergenceIntervalMs ?? 15_000;\n const createPglite =\n options.createPglite ??\n ((storePath: string, backendOverride?: \"memory\") =>\n createClientPGlite(storePath, backendOverride ? { backendOverride } : undefined));\n // A testing acknowledgment (ADR-0036) spread into THIS worker's options — needed when a test injects a\n // non-persistent BYO store (`precreatedPglite` / `pgliteInstance` / a memory-returning `createPglite`),\n // which `createSyncClient` would otherwise refuse. Forwarded to the boot below. A browser worker never\n // sets it; a memory selection carried on the attach wire wins over it.\n const workerTestMarker = readTestStoreMarker(options);\n\n const ports = new Set<BridgePort>();\n const liveSubs = new Map<string, LiveSub>();\n // The live-query lifecycle (PGlite registration, diff listener, and the ADR-0040 decision-1 awaited-teardown\n // set) lives in a single manager owned per engine. Created lazily on first subscribe because it needs the\n // booted client's `live` namespace (`active.pglite.live`); the worker never restarts its engine in place\n // (ADR-0040 decision 7), so one manager serves the host's whole lifetime. `close()` disposes it.\n let liveManager: LiveQueryManager | null = null;\n const ensureLiveManager = (active: SyncClient<TRegistry>): LiveQueryManager =>\n (liveManager ??= createLiveQueryManager({\n live: active.pglite.live,\n ...(options.liveQueries ? { policy: options.liveQueries } : {}),\n }));\n // Subscribes that have entered `handleSubscribe` but not yet reached `liveSubs.set` (they are mid-await on\n // prepareQuery / hydration / manager setup). Registered SYNCHRONOUSLY at entry, keyed by `queryId`, so an\n // `unsubscribe`/`detach` arriving during those awaits can mark the pending subscribe CANCELLED — otherwise\n // it would finish and store a subscription for an already-gone port, escaping the awaited-teardown boundary\n // (ADR-0040 decision 1). Removed in `handleSubscribe`'s finally.\n const pendingSubscribes = new Map<string, { port: BridgePort; cancelled: boolean }>();\n // Host shutdown state (ADR-0040 decision 1 — the pending-before-manager close race). `close()` flips\n // `closing` and awaits every in-flight `handleSubscribe` task BEFORE disposing the manager, so a subscribe\n // still mid-await when close begins can neither create a registration afterwards (it early-bails on\n // `closing`) nor escape the awaited-teardown boundary. `inFlightSubscribes` holds each whole-call task.\n let closing = false;\n const inFlightSubscribes = new Set<Promise<void>>();\n // One stable, opaque diagnostics scope per bridge port (ADR-0040 decision 5) — so a snapshot's `scopeCount`\n // reads as the distinct-tab count. Never part of the fingerprint; a lazy per-port counter.\n const portScopes = new WeakMap<BridgePort, string>();\n let nextScopeId = 0;\n const scopeForPort = (port: BridgePort): string => {\n let scope = portScopes.get(port);\n if (scope === undefined) {\n scope = `port-${nextScopeId++}`;\n portScopes.set(port, scope);\n }\n return scope;\n };\n\n // ─── Pre-spawned (schemaless) store — the spare flow (ADR-0032 decision 5) ────────────────────────\n // A `provision` mints the raw PGlite (initdb only) and holds it idle here; the first real `attach`\n // adopts it as `precreatedPglite` (the client still runs schema/journal recovery/reconcile). Provision\n // is role-agnostic — the registry is chosen at attach — so the same warmed store serves either role.\n // `stamp` carries the spare's create timing (ADR-0034): a boot adopting this store reports the initdb cost\n // as `BootReport.provision` (with `phases.pgliteCreateMs = null`) instead of timing a create it never ran.\n let provisioned: {\n storePath: string;\n pglite: Promise<ClientPGlite>;\n stamp: Promise<{ initdbMs: number; provisionReadyAt: number }>;\n } | null = null;\n\n // ─── Outbound-convergence gate — the tab's Offline toggle over the bridge (ADR-0032 S3) ───────────\n // The worker owns convergence; the tab forwards its Offline flag as `set-online`. When suppressed the\n // interval trigger's `shouldConverge` returns false (writes stage in the journal, unsent) and a `wake`\n // is ignored; resuming fires one immediate pass so the queue flushes at once.\n let convergenceSuppressed = false;\n let fireConvergence: (() => void) | null = null;\n const baseTrigger = createIntervalConvergenceTrigger(convergenceIntervalMs);\n const gatedTrigger: ConvergenceTrigger = {\n subscribe: (onSignal) => {\n fireConvergence = onSignal;\n const unsubscribe = baseTrigger.subscribe(onSignal);\n return () => {\n fireConvergence = null;\n unsubscribe();\n };\n },\n shouldConverge: () => !convergenceSuppressed && baseTrigger.shouldConverge(),\n };\n\n // ─── The single auth token cache + pull mechanism (ADR-0032 decision 3) ──────────────────────────\n const tokenCache = createWorkerTokenCache({\n marginMs: tokenExpiryMarginMs,\n broadcastRequest: (requestId) => {\n syncDebug(\"worker token pull broadcast\", { requestId, tabs: ports.size });\n broadcast(\"token-request\", { requestId });\n },\n });\n const getWorkerAuthToken = () => tokenCache.getToken();\n\n // ─── The broadcast event channel (ADR-0032 decision 7) ───────────────────────────────────────────\n const seenReadyGroups = new Set<string>();\n const broadcast = (type: BridgeEnvelope[\"type\"], payload: unknown) => {\n for (const port of ports) postBridgeMessage(port, codec, type, payload);\n };\n const broadcastEvent = (event: BridgeEvent) => broadcast(\"event\", event);\n\n // ─── Debug-rail buffer + replay (ADR-0034) ───────────────────────────────────────────────────────\n // The engine boots on the first ATTACH, but the front half of boot (provision, and the boot rail's\n // schema/journal/reconcile lines) can be emitted before any debug-enabled tab is listening — so they\n // vanished. Install the sink at construction (not at boot) into a bounded ring buffer, so the whole boot\n // is captured from worker start; the buffer is REPLAYED (marked `[replay]`) to the first attach, while the\n // back half streams live over the bridge. Bounded so a long-lived worker never grows the buffer unbounded.\n const RAIL_BUFFER_MAX = 500;\n const railBuffer: Array<{ stamp: number; line: string; data?: Record<string, unknown> }> = [];\n let railReplayed = false;\n setSyncDebugSink((line, stamp, data) => {\n if (railBuffer.length >= RAIL_BUFFER_MAX) railBuffer.shift();\n railBuffer.push({ stamp, line, ...(data ? { data } : {}) });\n broadcastEvent({ kind: \"debug\", stamp, line, ...(data ? { data } : {}) });\n });\n const nowStamp = () => (typeof performance !== \"undefined\" ? performance.now() : Date.now());\n // Replay the pre-attach rail buffer to the first attaching port. Taken as a snapshot BEFORE this attach's\n // boot runs, so the boot's own lines (which stream live to this now-connected port) are never doubled.\n const replayRailBufferTo = (port: BridgePort) => {\n if (railReplayed) return;\n railReplayed = true;\n const buffered = [...railBuffer];\n postBridgeMessage(port, codec, \"event\", {\n kind: \"debug\",\n stamp: nowStamp(),\n line: `[replay] replaying ${buffered.length} buffered rail line(s)`,\n } satisfies BridgeEvent);\n for (const entry of buffered) {\n postBridgeMessage(port, codec, \"event\", {\n kind: \"debug\",\n stamp: entry.stamp,\n line: `[replay] ${entry.line}`,\n ...(entry.data ? { data: entry.data } : {}),\n } satisfies BridgeEvent);\n }\n };\n\n const emitStatus = (status: SyncRuntimeStatus) => {\n broadcastEvent({ kind: \"status\", status });\n // Derive a per-group `groupReady` event for each group that newly reached ready, so a tab gets both the\n // status snapshot (`status.groups`) and a discrete edge to await (ADR-0032 decision 6/7).\n for (const [groupKey, ready] of Object.entries(status.groups ?? {})) {\n if (ready && !seenReadyGroups.has(groupKey)) {\n seenReadyGroups.add(groupKey);\n broadcastEvent({ kind: \"groupReady\", groupKey });\n }\n }\n };\n\n // ─── Engine boot — reuse createSyncClient verbatim (ADR-0032 decision 1/4) ────────────────────────\n let client: SyncClient<TRegistry> | null = null;\n let bootPromise: Promise<SyncClient<TRegistry>> | null = null;\n // The role the engine actually booted with (from the FIRST attach's config). Later attaches compare\n // their requested role against this and get a warning on mismatch (ADR-0032 FIX 5) — never a reject.\n let bootedRole: string | undefined;\n // The engine's `ready` is monotonic: once its initial sync lands it stays resolved even if the phase\n // later degrades. A tab attaching AFTER that moment must still get a resolved `ready`, so track whether\n // it has fired and tell the ack (ADR-0032 FIX 3).\n let engineReadyFired = false;\n let resolveBooted!: (client: SyncClient<TRegistry>) => void;\n const bootedPromise = new Promise<SyncClient<TRegistry>>((resolve) => {\n resolveBooted = resolve;\n });\n\n // ─── Boot milestone bridge (ADR-0041 stage 2) ────────────────────────────────────────────────────\n // One engine crosses each background boot stage once. Broadcast a one-shot `milestone` as it crosses\n // `writeReady`/`bootSettled` (or a `milestone-error` if the tail rejects the stage), and FOLD the current\n // set into every `attach-ack` so a tab that attached after a stage fired resolves it from the ack. The\n // ack itself fires AT `localReadReady` (the Option B contract), so that stage needs no milestone. Wired\n // exactly once off the booted client's stage promises (`milestonesWired`), then driven purely by them.\n const milestones = { writeReady: false, bootSettled: false };\n const stageErrors: {\n writeReady?: { message: string; detail?: unknown };\n bootSettled?: { message: string; detail?: unknown };\n } = {};\n let milestonesWired = false;\n const markMilestone = (stage: BootMilestone) => {\n if (milestones[stage]) return;\n milestones[stage] = true;\n broadcastEvent({ kind: \"milestone\", stage });\n };\n const failMilestone = (stage: BootMilestone, error: unknown) => {\n if (stageErrors[stage]) return;\n const serialized = serializeError(error);\n stageErrors[stage] = serialized;\n broadcastEvent({ kind: \"milestone-error\", stage, error: serialized });\n };\n // Attach-ack fold fields for a LATE attach — the milestones/failures already crossed at ack time.\n const milestoneAckFields = () => ({\n ...(milestones.writeReady ? { writeReady: true as const } : {}),\n ...(milestones.bootSettled ? { bootSettled: true as const } : {}),\n ...(stageErrors.writeReady ? { writeReadyError: stageErrors.writeReady } : {}),\n ...(stageErrors.bootSettled ? { bootSettledError: stageErrors.bootSettled } : {}),\n });\n\n const boot = (attach: AttachPayload): Promise<SyncClient<TRegistry>> => {\n if (bootPromise) return bootPromise;\n // The tab is the auth owner: seed the cache with the token it presented at attach (decision 3).\n tokenCache.push(attach.token);\n bootedRole = attach.config?.role;\n // The debug-rail sink is installed at construction (ADR-0034) so it buffers from worker start and\n // forwards live to tabs, stamped with the WORKER's monotonic clock (decision 7) — see above.\n // Resolve the registry from the attach's role (ADR-0032 S3): a single worker file bakes both variants\n // and the claim/attach settles which one boots — the spare was provisioned before the role was known.\n const registry = options.resolveRegistry?.(attach.config?.role) ?? options.registry;\n // storePath-first, matching the `provision` handler's resolution (below): the board sends BOTH a bare\n // `storeId` (SharedWorker naming, tab-side) AND the real `storePath` (`pgxsinkit-board-<id>`), and the\n // PGlite store lives at `storePath` — so the provisioned store's path must be what we adopt on.\n // `storeId` is only a last-ditch fallback for a caller that passes it as the store path.\n const storePath = attach.storePath ?? attach.storeId ?? options.storePath ?? \"pgxsinkit-overlay-v1\";\n // The testing memory-backend override rides as an explicit wire field (a symbol does not survive\n // structured clone, ADR-0036); re-stamp it as the internal marker on the createSyncClient options below.\n // A memory selection on the attach wins over the worker's own acknowledgment (memory implies acknowledged).\n const backendOverride = attach.testStoreBackend;\n const testMarker: TestStoreMarker | undefined = backendOverride === \"memory\" ? \"memory\" : workerTestMarker;\n // Restore (ADR-0035 decision 6): the tab decomposed the backup into a transferred `ArrayBuffer` + mime\n // (`RestoreArtefactWire`); recompose a `Blob` to hand `createSyncClient` as `restoreFrom`. Restore OWNS the\n // store's creation (a `loadDataDir` seed), so it is mutually exclusive with adopting a pre-provisioned or\n // caller-supplied instance — when restoring, we suppress the adopt paths below rather than let\n // createSyncClient throw the exclusion error.\n const restoreFrom = attach.restore\n ? new Blob([attach.restore.buffer], { type: attach.restore.mimeType })\n : undefined;\n // Adopt a matching pre-provisioned store (its initdb already ran off-thread) as `precreatedPglite`;\n // createSyncClient falls back to a fresh `storePath` create if that promise rejects — a pure accelerator.\n // Never adopt when restoring (restore boots a brand-new store from the backup, not the provisioned one).\n const adoptingProvisioned = restoreFrom == null && provisioned != null && provisioned.storePath === storePath;\n const precreatedPglite = adoptingProvisioned\n ? provisioned!.pglite\n : restoreFrom\n ? undefined\n : options.precreatedPglite;\n // The adopted spare's create timing feeds `BootReport.provision` (ADR-0034); absent otherwise.\n const provisionStamp = adoptingProvisioned ? provisioned!.stamp : undefined;\n if (adoptingProvisioned) {\n syncDebug(\"worker adopting provisioned store\", { storePath });\n }\n if (restoreFrom) {\n syncDebug(\"worker restoring store from backup\", { storePath, byteLength: attach.restore!.buffer.byteLength });\n }\n bootPromise = createSyncClient<TRegistry>({\n registry,\n electricUrl: options.electricUrl,\n writeUrl: options.writeUrl,\n storePath,\n // Re-stamp the internal testing marker (ADR-0036) so `createSyncClient`'s option handling selects the\n // memory backend on its fallback create and/or bypasses the BYO refusal for an injected test store —\n // the wire field / worker acknowledgment are the cross-clone carriers for it.\n ...(testMarker ? { [TEST_STORE_BACKEND]: testMarker } : {}),\n // Restore rides the boot attach (ADR-0035 decision 6): createSyncClient seeds the fresh store via\n // `loadDataDir`, boots offline, and quarantines the recovered journal.\n ...(restoreFrom ? { restoreFrom } : {}),\n // Boot observability (ADR-0034): label the report `worker`, and forward the provision stamp so an\n // adopted spare's initdb cost is reported rather than a create this boot never ran.\n bootMode: \"worker\",\n ...(provisionStamp ? { provisionStamp } : {}),\n ...(precreatedPglite ? { precreatedPglite } : {}),\n ...(options.pgliteInstance && restoreFrom == null ? { pgliteInstance: options.pgliteInstance } : {}),\n // Fresh-store prefetch overlap (ADR-0032 S4): the tab's claim path proved this store a schemaless\n // spare and forwarded the hint in the attach config, so the shape catch-up overlaps schema exec +\n // journal recovery + reconcile. Never inferred from \"adopting a provisioned store\": the board\n // provisions a worker even for a MAPPED (returning) user, whose idb is NOT fresh — only the claim\n // path's explicit hint distinguishes them.\n ...(attach.config?.freshStore === true ? { freshStore: true } : {}),\n getAuthToken: getWorkerAuthToken,\n // The worker owns convergence via the interval trigger, GATED by the tab's Offline toggle\n // (`set-online`); tabs additionally forward online/visibility as `wake` pass requests (below).\n autoSync: gatedTrigger,\n syncEnabled: attach.config?.syncEnabled ?? options.syncEnabled ?? true,\n ...(options.requestHeaders ? { requestHeaders: options.requestHeaders } : {}),\n ...(options.writeRequestHeaders ? { writeRequestHeaders: options.writeRequestHeaders } : {}),\n ...(options.maxMutationAttempts != null ? { maxMutationAttempts: options.maxMutationAttempts } : {}),\n onStatusChange: (status) => emitStatus(status),\n onConflict: (details) => broadcastEvent({ kind: \"conflict\", details }),\n onQuarantine: (details) => broadcastEvent({ kind: \"quarantine\", details }),\n onReject: (details) => broadcastEvent({ kind: \"reject\", details }),\n onSchemaChange: (event: LocalStoreVersionEvent) => broadcastEvent({ kind: \"schema-change\", event }),\n onSyncError: (error) => broadcastEvent({ kind: \"sync-error\", message: error.message }),\n // Boot observability (ADR-0034): broadcast the finalized report to currently-attached ports (one-shot\n // push). Later tabs read the same report via the `bootReport` pull RPC — there is no replay event.\n onBootReport: (report) => broadcastEvent({ kind: \"boot-report\", report }),\n // ADR-0041 stage 2 (Option B contract): `createSyncClient` resolves AT `localReadReady`, so the boot\n // promise now resolves there too — the attach handler acks at local-read readiness and the write/sync\n // tail runs in the background, announced to tabs via the `writeReady`/`bootSettled` milestone messages\n // wired in the attach handler below. The stage-1 `await booted.bootSettled` shim is deleted: attach no\n // longer waits for the whole boot, which is exactly the behavioural change this stage delivers.\n });\n return bootPromise;\n };\n\n const whenBooted = () => bootedPromise;\n\n // ─── Write / mutation-state RPC dispatch ─────────────────────────────────────────────────────────\n const dispatchRpc = async (active: SyncClient<TRegistry>, op: RpcOp, args: unknown[]): Promise<unknown> => {\n type TableKey = SyncTableName<TRegistry>;\n switch (op) {\n case \"create\":\n return active.mutate.create(args[0] as TableKey, args[1] as never);\n case \"update\":\n return active.mutate.update(args[0] as TableKey, args[1] as Record<string, string>, args[2] as never);\n case \"delete\":\n return active.mutate.delete(args[0] as TableKey, args[1] as Record<string, string>);\n case \"batch\":\n return active.mutate.batch(args[0] as ReadonlyArray<MutationBatchItem<TRegistry>>);\n case \"transaction\": {\n // The tab collected the unit's mutations (the run callback can't cross the wire); the worker replays\n // the serialized items into a real `client.transaction` so pessimistic acks / optimistic flush match\n // the in-process semantics exactly.\n const { mode, items } = args[0] as { mode: WriteMode; items: MutationBatchItem<TRegistry>[] };\n return active.transaction({ mode }, (tx) => {\n for (const item of items) {\n const handle = tx.tables[item.table];\n if (item.kind === \"create\") {\n handle.create(item.input as never);\n } else if (item.kind === \"update\") {\n // ADR-0022 addendum: a `blind` update replays through `updateBlind` (journal-only, no overlay).\n if (item.blind) handle.updateBlind(item.entityKey, item.patch as never);\n else handle.update(item.entityKey, item.patch as never);\n } else {\n handle.delete(item.entityKey);\n }\n }\n });\n }\n case \"flush\":\n return active.flush(args[0] as TableKey | undefined);\n case \"reconcile\":\n return active.reconcile(args[0] as TableKey | undefined);\n case \"retryFailed\":\n return active.retryFailed(args[0] as TableKey | undefined);\n case \"recoverSending\":\n return active.recoverSending(args[0] as TableKey | undefined);\n case \"discardConflict\":\n return active.discardConflict(args[0] as TableKey, args[1] as Record<string, string>);\n case \"discardQuarantined\":\n return active.discardQuarantined(args[0] as TableKey, args[1] as Record<string, string>);\n case \"desync\":\n return active.desync(args[0] as TableKey);\n case \"discardEphemeral\":\n return active.discardEphemeral(args[0] as TableKey);\n case \"readMutationDetails\":\n return active.readMutationDetails(args[0] as TableKey | undefined);\n case \"diagnostics\":\n return active.diagnostics(args[0] as TableKey | undefined);\n case \"rawQuery\":\n // Inspection read (ADR-0032 S2): run straight against the worker's own store — `active.pglite`\n // exists worker-side (it's the in-process client). `Results` rows/fields structured-clone across\n // the wire (Dates survive postMessage), so the tab receives the same shape it would in-process.\n // The options arg is the clonable RawQueryOptions subset (rowMode) — the REPL's array mode.\n return active.rawQuery(args[0] as string, args[1] as unknown[] | undefined, args[2] as RawQueryOptions);\n case \"rawExec\":\n return active.rawExec(args[0] as string, args[1] as RawQueryOptions);\n case \"bootReport\":\n // Boot observability (ADR-0034): the worker engine's stored report (or null). Pull, so a late tab\n // reads a boot predating it; the report structured-clones across the bridge as a plain object.\n return active.bootReport();\n case \"liveQueryDiagnostics\":\n // Live-query diagnostics (ADR-0040 decision 5): the manager lives in THIS host closure (not on\n // `active`), so read it directly. Plain-object records (digests + counts only) structured-clone\n // across the bridge; `[]` when nothing has subscribed yet (the manager is created lazily).\n return liveManager?.snapshot() ?? [];\n case \"exportStore\": {\n // Store backup (ADR-0035): run the live export on the worker's OWN client (its lifecycle slot\n // serialises it against every tab's export). A `File` cannot cross the bridge as a transferable, so\n // decompose it into an `ExportArtefactWire` — the `ArrayBuffer` is listed on `postMessage`'s transfer\n // list in the `rpc` handler and rebuilt into a `File` tab-side.\n const { file, report } = await active.exportStore(args[0] as StoreExportOptions | undefined);\n const buffer = await file.arrayBuffer();\n return { buffer, fileName: file.name, mimeType: file.type, report } satisfies ExportArtefactWire;\n }\n case \"exportDiagnostics\": {\n // Diagnostic dump (ADR-0035): identical bridge shape to the store backup — the worker runs the live\n // datadir dump → memory throwaway clone → `pg_dump` on its OWN client (same lifecycle slot), and the\n // SQL crosses back as the same transferred-`ArrayBuffer` `ExportArtefactWire`.\n const { file, report } = await active.exportDiagnostics(args[0] as DiagnosticExportOptions | undefined);\n const buffer = await file.arrayBuffer();\n return { buffer, fileName: file.name, mimeType: file.type, report } satisfies ExportArtefactWire;\n }\n case \"exportData\": {\n // Data export (ADR-0035): identical bridge shape — the worker runs the drain-guarded `pg_dump -t`\n // per-synced-table export on its OWN client (same lifecycle slot), and the portable SQL crosses back\n // as the same transferred-`ArrayBuffer` `ExportArtefactWire`. A DataExportDrainError rejects the RPC\n // like any other failure (serialised back to the tab).\n const { file, report } = await active.exportData(args[0] as DataExportOptions | undefined);\n const buffer = await file.arrayBuffer();\n return { buffer, fileName: file.name, mimeType: file.type, report } satisfies ExportArtefactWire;\n }\n default: {\n const exhaustive: never = op;\n throw new Error(`unknown rpc op ${String(exhaustive)}`);\n }\n }\n };\n\n // ─── Live-query bridge (ADR-0032 S2 §4) ──────────────────────────────────────────────────────────\n // `queryId`s are minted by a PER-TAB counter (`live-1`, `live-2`, …), so two tabs collide on the bare id —\n // every worker-side bookkeeping key MUST be port-scoped or one tab's unsubscribe/close tears down another\n // tab's identically-numbered subscription (latent since ADR-0032; exposed the moment tab close started\n // sending unsubscribes — the two-tab board e2e's scenario (c)). The wire keeps the bare `queryId` (the\n // port disambiguates); only the worker's maps compose it with the port's scope.\n const subKeyFor = (port: BridgePort, queryId: string): string => `${scopeForPort(port)}:${queryId}`;\n\n const handleSubscribe = (port: BridgePort, id: string | undefined, payload: SubscribePayload): Promise<void> => {\n // Register the in-flight subscribe SYNCHRONOUSLY (before the first await) so an `unsubscribe`/`detach`/\n // `close` arriving mid-await can mark it cancelled (ADR-0040 decision 1 — no subscription escapes teardown).\n const pending = { port, cancelled: false };\n const subKey = subKeyFor(port, payload.queryId);\n pendingSubscribes.set(subKey, pending);\n // Track the WHOLE call so `close()` awaits it before disposing the manager: the task is added to\n // `inFlightSubscribes` synchronously here and removed in its own finally, so close can never observe an\n // empty set while a subscribe is still awaiting prepareQuery / hydration / manager setup.\n // `let task!` (not `const`): the finally references `task` to remove itself, and it only runs after the\n // first await — by then the assignment below has completed, so the definite-assignment assertion is safe.\n let task!: Promise<void>;\n task = (async () => {\n try {\n await handleSubscribeInner(port, id, payload, pending, subKey);\n } finally {\n pendingSubscribes.delete(subKey);\n inFlightSubscribes.delete(task);\n }\n })();\n inFlightSubscribes.add(task);\n return task;\n };\n\n const handleSubscribeInner = async (\n port: BridgePort,\n id: string | undefined,\n payload: SubscribePayload,\n pending: { port: BridgePort; cancelled: boolean },\n subKey: string,\n ) => {\n const active = client ?? (await bootPromise);\n if (!active) throw new Error(\"subscribe before attach\");\n const { queryId, sql, params, pkColumns, use, fields, keepAliveMs } = payload;\n // Activate any lazy relations the query reads BEFORE registering the live query (ADR-0021) — the worker\n // owns the real client, so its `prepareQuery` does the real work; the tab's `prepareQuery` is a no-op.\n // Scan the ORIGINAL sql (the wrap only adds an outer `SELECT * FROM (...)`; table refs are inside).\n // The activated keys travel back on the initial snapshot: activation is stream-start, not catch-up,\n // so the tab needs them to await `groupReady` (its `hydrating` signal) without blocking this register.\n const prepared = await active.prepareQuery({ sql, ...(use ? { use: use as SyncTableName<TRegistry>[] } : {}) });\n // Hydration spans EVERY referenced consistency group (eager AND lazy), computed on the real client the\n // worker owns: the referenced tables whose group is not yet caught up at subscribe time. Empty (steady\n // state / sync disabled) → no `hydrated` gating at all; otherwise it drives both the `live-initial`\n // `hydratingTables` field (the tab's `hydrating` source) and the `live-hydrated` block below.\n const hydratingTables = active.hydratingTablesFor({ sql, ...(use ? { use: use as string[] } : {}) });\n\n // Render the query safe to materialise: a JOIN with same-named columns fails BOTH live APIs' temp-view\n // creation (`column \"title\" specified more than once`) unless every output column has a unique alias.\n // No `fields` → SQL unchanged (backward-compatible name-keyed rows; the aliased path keys by alias). The\n // wrap stays caller-side (ADR-0040 decision 3): the manager receives POST-WRAP SQL as its query input.\n const materialSql = wrapLiveQueryForMaterialization(sql, fields);\n // Early bail BEFORE the manager is created (ADR-0040 decision 1 — the pending-before-manager close race):\n // if the host is closing, this subscribe was cancelled, or its port detached WHILE we awaited prepareQuery\n // / hydration, do NOT call `ensureLiveManager` — creating a registration now would race the engine close\n // with a fire-and-forget teardown nothing awaits (a manager born after `close()` disposed is never\n // disposed). Post the rpc error for this subscribe id so a still-live tab's `subscribeLiveRows` rejects\n // instead of hanging, and return without touching the manager. The post-setup check below still catches a\n // cancellation that lands DURING manager setup (after the manager already exists).\n if (closing || pending.cancelled || !ports.has(port)) {\n postBridgeMessage(\n port,\n codec,\n \"rpc-result\",\n {\n ok: false,\n error: { message: \"[pgxsinkit] subscribe cancelled — the worker is closing or the port detached\" },\n },\n id,\n );\n return;\n }\n // The manager owns registration + diff + teardown; the bridge posting (per-`queryId`, with the caller-owned\n // `lazyTables`/`hydratingTables` observability fields) stays here — those are per-subscriber pre-steps.\n const subscription = await ensureLiveManager(active).subscribe(\n { materialSql, params: params as unknown[], ...(pkColumns ? { pkColumns } : {}) },\n {\n deliverInitial: (rows) => {\n // Initial snapshot verbatim (not a diff), correlated to the subscribe request so the tab resolves.\n postBridgeMessage(\n port,\n codec,\n \"live-initial\",\n {\n queryId,\n rows,\n // `lazyTables` = the activated lazy relations (observability); `hydratingTables` = the referenced\n // groups (eager OR lazy) still catching up, which the tab turns into its `hydrated` promise.\n ...(prepared.lazyTables.length > 0 ? { lazyTables: prepared.lazyTables.map(String) } : {}),\n ...(hydratingTables.length > 0 ? { hydratingTables: [...hydratingTables] } : {}),\n },\n id,\n );\n },\n deliverDiff: (diff) => {\n postBridgeMessage(port, codec, \"live-diff\", { queryId, ...diff });\n },\n },\n // The per-subscriber keep-alive hint (ADR-0040 decision 4) — kept OUT of the spec so it never touches\n // the fingerprint (decision 3). Absent → no hint (the manager falls back to its policy default). The\n // `scope` is one stable id per port (decision 5 diagnostics), also fingerprint-excluded.\n { ...(keepAliveMs != null ? { keepAliveMs } : {}), scope: scopeForPort(port) },\n );\n // The port was detached, or this query was unsubscribed, WHILE we awaited (prepareQuery / hydration /\n // manager setup all yield). Neither cleanup path found a `liveSubs` entry — so undo the just-created\n // subscription here and DO NOT record it, else it would outlive its port (ADR-0040 decision 1). A\n // `live-initial` may already have been posted to a dead port; that is harmless (a closed port's\n // postMessage is a no-op) and not worth preventing. `closing` is included so a `close()` that began DURING\n // manager setup still unwinds this just-created subscription rather than recording it.\n if (closing || pending.cancelled || !ports.has(port)) {\n void subscription.unsubscribe();\n return;\n }\n liveSubs.set(subKey, { port, subscription });\n\n // Hydration completion travels the SAME port as the diff stream, so ordering is guaranteed: await the\n // pending groups' catch-up (eager AND lazy), force one refresh of the live query against the caught-up\n // store (its listener posts the rows as a live-diff, synchronously inside the refresh), THEN post\n // `live-hydrated`. The tab therefore always has the caught-up rows before its `hydrated` resolves — a\n // readiness signal on a side channel (e.g. the `groupReady` broadcast) can beat the rows and flash a\n // false \"empty\" state. Skipped entirely when nothing is pending (steady state / sync disabled).\n if (hydratingTables.length > 0) {\n void Promise.all(hydratingTables.map((key) => active.groupReady(key as SyncTableName<TRegistry>)))\n .then(async () => {\n if (!liveSubs.has(subKey)) return; // unsubscribed while catching up\n await subscription.refresh();\n if (!liveSubs.has(subKey)) return;\n postBridgeMessage(port, codec, \"live-hydrated\", { queryId });\n })\n .catch(() => undefined); // a torn-down engine mid-catch-up must not surface as an unhandled rejection\n }\n };\n\n // ─── Per-port message routing ────────────────────────────────────────────────────────────────────\n const onPortMessage = (port: BridgePort, data: unknown) => {\n if (!isBridgeEnvelope(data)) return;\n const envelope = data;\n const payload = codec.decode(envelope.payload);\n switch (envelope.type) {\n case \"provision\": {\n // Pre-spawn the raw store (initdb only), idle and schemaless, for the first attach to adopt\n // (ADR-0032 decision 5). A no-op once the engine has booted or a store is already provisioned.\n const provision = payload as ProvisionPayload;\n const storePath = provision.storePath ?? provision.storeId ?? options.storePath ?? \"pgxsinkit-overlay-v1\";\n // The testing memory-backend override rides as an explicit wire field (ADR-0036) — a symbol does not\n // survive structured clone, so the store's backend selection travels here and is passed to createPglite.\n const backendOverride = provision.testStoreBackend;\n if (bootPromise != null || provisioned != null) {\n postBridgeMessage(port, codec, \"provision-ack\", {\n ok: true,\n ...(provision.storeId ? { storeId: provision.storeId } : {}),\n });\n break;\n }\n // Stamp the spare's create timing (ADR-0034): initdb cost + the monotonic instant it became ready,\n // so an adopting boot can compute how long it sat idle before adoption.\n const provisionStartedAt = nowStamp();\n const pglite = createPglite(storePath, backendOverride);\n const stamp = pglite.then(() => {\n const readyAt = nowStamp();\n return { initdbMs: readyAt - provisionStartedAt, provisionReadyAt: readyAt };\n });\n provisioned = { storePath, pglite, stamp };\n // Guard an unobserved rejection when no attach ever adopts it (the page navigated away).\n void pglite.catch(() => undefined);\n void stamp.catch(() => undefined);\n syncDebug(\"worker store provisioned\", { storePath });\n void pglite.then(\n () =>\n postBridgeMessage(port, codec, \"provision-ack\", {\n ok: true,\n ...(provision.storeId ? { storeId: provision.storeId } : {}),\n }),\n (error: unknown) =>\n postBridgeMessage(port, codec, \"provision-ack\", {\n ok: false,\n error: serializeError(error),\n ...(provision.storeId ? { storeId: provision.storeId } : {}),\n }),\n );\n break;\n }\n case \"set-online\": {\n // The tab's Offline toggle over the bridge (ADR-0032 S3). Suppress/resume the worker's outbound\n // convergence; resuming fires one immediate pass so queued writes flush at once.\n const { online } = payload as SetOnlinePayload;\n convergenceSuppressed = !online;\n syncDebug(\"worker convergence gate\", { online });\n if (online) fireConvergence?.();\n break;\n }\n case \"attach\": {\n const attach = payload as AttachPayload;\n // Boot observability (ADR-0034): replay the pre-attach rail buffer (provision + any early lines) to\n // the FIRST attaching tab, so the front half of boot is no longer invisible. Snapshotted before this\n // attach's boot runs, so the boot's own lines (streamed live) are not doubled.\n replayRailBufferTo(port);\n const alreadyBooted = bootPromise !== null;\n // Restore rides the FIRST (boot) attach only (ADR-0035 decision 6): a restore attach that arrives once\n // the engine has already booted CANNOT be honoured — `loadDataDir` is a create-time seed and the store\n // is already live. Reject THIS attach with a typed error rather than silently ignoring the backup, so\n // the caller learns their restore did not happen (the engine keeps running its existing store).\n if (alreadyBooted && attach.restore != null) {\n postBridgeMessage(port, codec, \"attach-ack\", {\n alreadyBooted,\n error: {\n message:\n \"[pgxsinkit] cannot restore into a running store: the worker engine has already booted, and a store backup can only seed a brand-new store on the FIRST attach (ADR-0035 decision 6). Restore into a fresh worker instead.\",\n },\n });\n break;\n }\n if (alreadyBooted) {\n // A later attach seeds auth WITHOUT clobbering a fresher cached token (ADR-0032 FIX 5) — the\n // first-boot `push` already ran, and only an explicit `token-push` (auth owner) may overwrite.\n tokenCache.pushIfFresher(attach.token);\n // Role is a property of the (user, store) the engine already booted for: the worker is\n // one-engine-per-(user,store) by ADR-0032 decision 2 and is NOT keyed by role. A mismatch is an\n // app-layer bug to surface, not a supported topology — warn, keep the booted registry.\n const requested = attach.config?.role;\n if (requested !== bootedRole) {\n syncDebug(\"worker attach role mismatch — engine keeps its booted registry\", {\n booted: bootedRole,\n requested,\n });\n }\n }\n void boot(attach).then(\n (booted) => {\n client = booted;\n resolveBooted(booted);\n // Wire the engine's background stage promises to the milestone bridge exactly ONCE (ADR-0041\n // stage 2). `createSyncClient` resolved at `localReadReady`, so by here the engine has crossed\n // that stage — the ack below carries it implicitly. `writeReady`/`bootSettled` cross later (or\n // fail): broadcast each as a one-shot `milestone`/`milestone-error` for currently-attached ports\n // and fold the current set into every subsequent ack for late attachers.\n if (!milestonesWired) {\n milestonesWired = true;\n void booted.writeReady.then(\n () => markMilestone(\"writeReady\"),\n (error: unknown) => failMilestone(\"writeReady\", error),\n );\n void booted.bootSettled.then(\n () => markMilestone(\"bootSettled\"),\n (error: unknown) => failMilestone(\"bootSettled\", error),\n );\n }\n // Track the engine's monotonic `ready` edge exactly once, so a LATER attach acked after the\n // initial sync landed can resolve its `ready` straight from the ack (ADR-0032 FIX 3).\n if (!engineReadyFired) {\n // ADR-0041: `ready` can now reject if the background write/sync tail fails after the client was\n // handed out; swallow that here so it is not an unhandled rejection (the failure surfaces to\n // tabs via the `milestone-error` broadcast / the stage-error ack fold instead).\n void booted.ready.then(\n () => {\n engineReadyFired = true;\n },\n () => undefined,\n );\n }\n // Ack AFTER the engine exists so the tab's subsequent traffic (rpc/subscribe) has a client to\n // hit; the ack fires AT `localReadReady` (Option B) and folds the current milestone set +\n // engine-ready edge for a late-joining tab (ADR-0041 / ADR-0032 FIX 3).\n postBridgeMessage(port, codec, \"attach-ack\", {\n alreadyBooted,\n ...(engineReadyFired ? { engineReady: true } : {}),\n ...milestoneAckFields(),\n });\n postBridgeMessage(port, codec, \"event\", { kind: \"status\", status: booted.status });\n },\n (error: unknown) => {\n // The engine boot rejected: tell THIS attaching tab so it rejects `attachSyncClient` instead of\n // hanging on the ack (ADR-0032 FIX 1), and clear `bootPromise` so a later attach retries the\n // boot. Do NOT clear `provisioned`: a resolved provisioned PGlite holds the only open handle on\n // that store, so a retry must adopt it (createSyncClient falls back internally if it rejected).\n bootPromise = null;\n postBridgeMessage(port, codec, \"attach-ack\", {\n alreadyBooted,\n error: serializeError(error),\n });\n },\n );\n break;\n }\n case \"token-push\": {\n // The tab pushed a fresh token (auth state change) — update the cache and satisfy any in-flight pull.\n tokenCache.push(payload as AttachPayload[\"token\"]);\n break;\n }\n case \"token-response\": {\n const response = payload as TokenResponsePayload;\n // First response for the current pull wins; a stale/duplicate requestId is ignored.\n tokenCache.respond(response.requestId, response.token);\n break;\n }\n case \"rpc\": {\n const { op, args } = payload as RpcPayload;\n const id = envelope.id;\n void (async () => {\n try {\n const active = client ?? (await bootPromise);\n if (!active) throw new Error(\"rpc before attach\");\n const value = await dispatchRpc(active, op, args);\n // An export artefact (backup tarball or diagnostic SQL) crosses zero-copy: transfer its\n // `ArrayBuffer` (rebuilt into a `File` tab-side, ADR-0035). Every other op's value\n // structured-clones in place with no transfer list.\n const transfer =\n op === \"exportStore\" || op === \"exportDiagnostics\" || op === \"exportData\"\n ? [(value as ExportArtefactWire).buffer]\n : undefined;\n postBridgeMessage(port, codec, \"rpc-result\", { ok: true, value }, id, transfer);\n } catch (error) {\n postBridgeMessage(port, codec, \"rpc-result\", { ok: false, error: serializeError(error) }, id);\n }\n })();\n break;\n }\n case \"subscribe\": {\n const id = envelope.id;\n void handleSubscribe(port, id, payload as SubscribePayload).catch((error) => {\n postBridgeMessage(port, codec, \"rpc-result\", { ok: false, error: serializeError(error) }, id);\n });\n break;\n }\n case \"unsubscribe\": {\n const { queryId } = payload as { queryId: string };\n // Compose the SAME port-scoped key the subscribe used — a bare queryId lookup would collide with\n // another tab's identically-numbered subscription (see `subKeyFor`).\n const subKey = subKeyFor(port, queryId);\n const sub = liveSubs.get(subKey);\n if (sub) {\n // Non-blocking for the caller: the manager retains the teardown promise so `close()` awaits it.\n void sub.subscription.unsubscribe();\n liveSubs.delete(subKey);\n } else {\n // No live entry yet → the subscribe is still mid-await. Mark it cancelled so `handleSubscribe`\n // tears down the subscription it is about to create instead of recording it (ADR-0040 decision 1).\n const inFlight = pendingSubscribes.get(subKey);\n if (inFlight) inFlight.cancelled = true;\n }\n break;\n }\n case \"wake\": {\n // A tab forwarded online/visibilitychange (or a manual nudge): treat it as a convergence pass request\n // so a write flushes promptly without waiting for the worker's interval tick (decision 5 seam).\n // Suppressed while the Offline toggle is off — a wake must not flush a simulated-offline board.\n if (!convergenceSuppressed) void bootPromise?.then((active) => void active.flush());\n break;\n }\n default:\n break;\n }\n };\n\n const detachPort = (port: BridgePort) => {\n ports.delete(port);\n for (const [subKey, sub] of liveSubs) {\n if (sub.port === port) {\n // Non-blocking: the manager retains the teardown promise so `close()` awaits it (ADR-0040 decision 1).\n void sub.subscription.unsubscribe();\n liveSubs.delete(subKey);\n }\n }\n // Also cancel every subscribe for this port still mid-await — its `handleSubscribe` will tear down the\n // subscription it is about to create rather than record it for a detached port (ADR-0040 decision 1).\n for (const pending of pendingSubscribes.values()) {\n if (pending.port === port) pending.cancelled = true;\n }\n };\n\n const connect = (port: BridgePort) => {\n ports.add(port);\n const listener = (event: { data: unknown }) => {\n if (isBridgeEnvelope(event.data) && event.data.type === \"detach\") {\n detachPort(port);\n port.removeEventListener(\"message\", listener);\n return;\n }\n onPortMessage(port, event.data);\n };\n port.addEventListener(\"message\", listener);\n port.start?.();\n };\n\n // ─── Global-scope auto-binding (real worker only; tests inject ports via connect) ─────────────────\n if (options.installGlobal !== false) bindGlobalScope(connect);\n\n return {\n connect,\n whenBooted,\n close: async () => {\n // Quiesce pending subscribes FIRST (ADR-0040 decision 1 — the pending-before-manager race): flip\n // `closing`, mark every mid-await subscribe cancelled, and await every in-flight `handleSubscribe` task.\n // This guarantees the manager exists (if any subscribe created one) BEFORE `dispose()` runs, and that no\n // subscribe can create a registration afterwards — each resumes into the `closing` early-bail instead.\n closing = true;\n for (const pending of pendingSubscribes.values()) pending.cancelled = true;\n await Promise.allSettled([...inFlightSubscribes]);\n // Dispose the manager BEFORE `active.stop()` (ADR-0040 decision 1): it tears down every remaining live\n // registration and awaits ALL teardowns, so no fire-and-forget unsubscribe is still in flight when the\n // engine closes (the close-vs-unsubscribe hang). No-op when nothing ever subscribed.\n liveSubs.clear();\n await liveManager?.dispose();\n ports.clear();\n setSyncDebugSink(undefined);\n const active = client ?? (bootPromise ? await bootPromise.catch(() => null) : null);\n await active?.stop();\n },\n };\n}\n\n/** Serialize a thrown value into the bridge's `{message, detail}` error shape (detail only when structured). */\nfunction serializeError(error: unknown): { message: string; detail?: unknown } {\n if (error instanceof Error) {\n const detail = (error as Error & { detail?: unknown }).detail;\n return { message: error.message, ...(detail !== undefined ? { detail } : {}) };\n }\n return { message: String(error) };\n}\n\ninterface SharedWorkerConnectEvent {\n ports: BridgePort[];\n}\ninterface WorkerGlobalScopeLike {\n onconnect?: (event: SharedWorkerConnectEvent) => void;\n postMessage?: (message: unknown) => void;\n addEventListener?: (type: \"message\", listener: (event: { data: unknown }) => void) => void;\n removeEventListener?: (type: \"message\", listener: (event: { data: unknown }) => void) => void;\n}\n\n/**\n * Bind the running global scope to `connect`. A `SharedWorkerGlobalScope` exposes `onconnect` (one event per\n * tab, each carrying a port); a dedicated `DedicatedWorkerGlobalScope` has no `onconnect` but IS itself the\n * single implicit port (`self.postMessage`/`addEventListener`). Neither exists in a plain test/Node context,\n * where the host is driven via {@link SyncWorkerHost.connect} directly — so this is a no-op there.\n */\nfunction bindGlobalScope(connect: (port: BridgePort) => void): void {\n const scope = globalThis as unknown as WorkerGlobalScopeLike;\n const hasSharedWorkerScope =\n typeof (globalThis as { SharedWorkerGlobalScope?: unknown }).SharedWorkerGlobalScope !== \"undefined\";\n const hasDedicatedWorkerScope =\n typeof (globalThis as { DedicatedWorkerGlobalScope?: unknown }).DedicatedWorkerGlobalScope !== \"undefined\";\n\n if (hasSharedWorkerScope) {\n scope.onconnect = (event: SharedWorkerConnectEvent) => {\n const port = event.ports[0];\n if (port) connect(port);\n };\n return;\n }\n if (hasDedicatedWorkerScope && scope.postMessage && scope.addEventListener && scope.removeEventListener) {\n // The dedicated worker's own global scope IS the single port.\n connect({\n postMessage: (message: unknown) => scope.postMessage!(message),\n addEventListener: (type, listener) => scope.addEventListener!(type, listener),\n removeEventListener: (type, listener) => scope.removeEventListener!(type, listener),\n });\n }\n}\n"
|
|
40
41
|
],
|
|
41
|
-
"mappings": ";;;;AAAA,mBAAS;AACT;AAEA,oBAAS;AACT;AAiBA,gCAAS,+CAAqB;;;ACR9B,IAAM,YAAY,MAAgB,WAA2B,qBAAqB;AAElF,IAAM,MAAM,MAAe,OAAO,gBAAgB,cAAc,YAAY,IAAI,IAAI,KAAK,IAAI;AAU7F,IAAI;AAGG,SAAS,gBAAgB,CAAC,MAAuC;AAAA,EACtE,gBAAgB;AAAA;AAQX,SAAS,SAAS,CAAC,OAAe,MAAsC;AAAA,EAC7E,MAAM,UAAU,UAAU;AAAA,EAC1B,IAAI,CAAC,WAAW,kBAAkB;AAAA,IAAW;AAAA,EAC7C,MAAM,QAAQ,IAAI;AAAA,EAClB,IAAI,SAAS;AAAA,IACX,MAAM,SAAS,cAAc,MAAM,QAAQ,CAAC;AAAA,IAC5C,IAAI,MAAM;AAAA,MACR,QAAQ,MAAM,GAAG,UAAU,SAAS,IAAI;AAAA,IAC1C,EAAO;AAAA,MACL,QAAQ,MAAM,GAAG,UAAU,OAAO;AAAA;AAAA,EAEtC;AAAA,EACA,gBAAgB,OAAO,OAAO,IAAI;A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