@rocicorp/zero 1.13.0-canary.0 → 1.13.0-canary.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/out/shared/src/valita.d.ts.map +1 -1
  2. package/out/shared/src/valita.js +2 -1
  3. package/out/shared/src/valita.js.map +1 -1
  4. package/out/z2s/src/compiler.d.ts.map +1 -1
  5. package/out/z2s/src/compiler.js +4 -2
  6. package/out/z2s/src/compiler.js.map +1 -1
  7. package/out/zero/package.js +2 -2
  8. package/out/zero/package.js.map +1 -1
  9. package/out/zero-cache/src/auth/write-authorizer.js +1 -1
  10. package/out/zero-cache/src/config/zero-config.d.ts +1 -1
  11. package/out/zero-cache/src/config/zero-config.d.ts.map +1 -1
  12. package/out/zero-cache/src/config/zero-config.js +1 -1
  13. package/out/zero-cache/src/config/zero-config.js.map +1 -1
  14. package/out/zero-cache/src/db/lite-tables.js +1 -1
  15. package/out/zero-cache/src/server/inspector-delegate.js +1 -1
  16. package/out/zero-cache/src/services/change-source/pg/change-source-init.js +1 -1
  17. package/out/zero-cache/src/services/change-source/pg/change-source-init.js.map +1 -1
  18. package/out/zero-cache/src/services/change-source/pg/change-source.js +1 -1
  19. package/out/zero-cache/src/services/change-source/pg/initial-sync.js +1 -1
  20. package/out/zero-cache/src/services/change-source/pg/initial-sync.js.map +1 -1
  21. package/out/zero-cache/src/services/change-source/pg/replication-slots.js.map +1 -1
  22. package/out/zero-cache/src/services/change-source/pg/schema/init.js +0 -54
  23. package/out/zero-cache/src/services/change-source/pg/schema/init.js.map +1 -1
  24. package/out/zero-cache/src/services/change-source/pg/schema/shard.d.ts +4 -4
  25. package/out/zero-cache/src/services/change-source/pg/schema/shard.d.ts.map +1 -1
  26. package/out/zero-cache/src/services/change-source/pg/schema/shard.js +12 -7
  27. package/out/zero-cache/src/services/change-source/pg/schema/shard.js.map +1 -1
  28. package/out/zero-cache/src/services/change-source/protocol/backfill-progress.js +2 -2
  29. package/out/zero-cache/src/services/change-source/protocol/backfill-progress.js.map +1 -1
  30. package/out/zero-cache/src/services/change-streamer/backfill-state.js +2 -2
  31. package/out/zero-cache/src/services/change-streamer/backfill-state.js.map +1 -1
  32. package/out/zero-cache/src/services/mutagen/mutagen.js +1 -1
  33. package/out/zero-cache/src/services/replicator/change-log-cookies.js +1 -1
  34. package/out/zero-cache/src/services/replicator/change-processor.js +2 -30
  35. package/out/zero-cache/src/services/replicator/change-processor.js.map +1 -1
  36. package/out/zero-cache/src/services/replicator/schema/change-log.js +1 -1
  37. package/out/zero-cache/src/services/view-syncer/active-users-gauge.js +1 -1
  38. package/out/zero-cache/src/services/view-syncer/pipeline-driver.js +1 -1
  39. package/out/zero-client/src/client/crud-impl.js +1 -1
  40. package/out/zero-client/src/client/ivm-branch.js +1 -1
  41. package/out/zero-client/src/client/version.js +1 -1
  42. package/out/zero-protocol/src/client-schema.js +1 -1
  43. package/out/zero-protocol/src/down.d.ts +2 -2
  44. package/out/zero-schema/src/builder/schema-builder.js +1 -1
  45. package/out/zql/src/builder/builder.js +1 -1
  46. package/out/zql/src/ivm/aggregate.js +1 -1
  47. package/out/zql/src/ivm/flipped-join.js +1 -1
  48. package/out/zql/src/ivm/group-by.js +1 -1
  49. package/out/zql/src/ivm/join-index.js +1 -1
  50. package/out/zql/src/ivm/memory-source.js +1 -1
  51. package/out/zql/src/ivm/view-apply-change.js +1 -1
  52. package/out/zqlite/src/table-source.d.ts.map +1 -1
  53. package/out/zqlite/src/table-source.js +4 -2
  54. package/out/zqlite/src/table-source.js.map +1 -1
  55. package/package.json +2 -2
@@ -1 +1 @@
1
- {"version":3,"file":"backfill-state.js","names":[],"sources":["../../../../../../zero-cache/src/services/change-streamer/backfill-state.ts"],"sourcesContent":["import {unreachable} from '../../../../shared/src/asserts.ts';\nimport {BigIntJSON} from '../../../../shared/src/bigint-json.ts';\nimport {deepEqual} from '../../../../shared/src/json.ts';\nimport {assignProperty} from '../../../../shared/src/objects.ts';\nimport {\n acceptBackfill,\n covers,\n} from '../change-source/protocol/backfill-progress.ts';\nimport type {\n BackfillRequest,\n ChangeStreamData,\n Identifier,\n SchemaChange,\n TableMetadata,\n} from '../change-source/protocol/current.ts';\nimport {schemaChangeTags} from '../change-source/protocol/current/schema-change-tags.ts';\nimport {cookieOps} from '../replicator/change-log-cookies.ts';\nimport type {ChangeTag, WatermarkedChange} from './change-streamer.ts';\n\nfunction tableKey({schema, name}: Identifier) {\n return JSON.stringify([schema, name]);\n}\n\ntype Column = BackfillRequest['columns'][string];\n\n/** A mutable BackfillRequest. */\ntype Backfill = {\n table: {schema: string; name: string; metadata: TableMetadata | null};\n columns: Record<string, Column>;\n};\n\ntype State = Map<string, Backfill>;\n\nfunction clone(state: State): State {\n return new Map(\n Array.from(state, ([key, {table, columns}]) => [\n key,\n {table: {...table}, columns: {...columns}},\n ]),\n );\n}\n\n/**\n * Tags of messages that affect the backfill state. Other messages need not be\n * parsed.\n */\nconst RELEVANT_TAGS = new Set<ChangeTag>([\n 'backfill',\n ...schemaChangeTags.filter(t => t !== 'create-index' && t !== 'drop-index'),\n]);\n\n// Serialized changes are typically forwarded (as the same string) to every\n// subscriber, so a single entry cache avoids re-parsing the same message for\n// each subscriber.\nlet lastParsed: {json: string; change: ChangeStreamData} | undefined;\n\nfunction parse(json: string): ChangeStreamData {\n if (lastParsed?.json !== json) {\n lastParsed = {json, change: BigIntJSON.parse(json) as ChangeStreamData};\n }\n return lastParsed.change;\n}\n\n/**\n * Tracks the state of the pending backfills (and their progress) of a party\n * in the replication stream (e.g. a subscriber, or the change-log itself), by\n * applying the same policies that a subscriber applies to its replica:\n * schema changes are folded with the {@link cookieOps} shared by the\n * cookie jars, and `backfill` / `backfill-completed` messages are accepted\n * or ignored with the continuity policy of {@link acceptBackfill}.\n *\n * Changes are applied transactionally: the changes of a transaction are\n * discarded if it is rolled back, and {@link requests()} only reflects\n * committed transactions.\n */\nexport class BackfillState {\n #state: State;\n #beforeTx: State | null = null;\n\n constructor(requests: readonly BackfillRequest[] = []) {\n this.#state = new Map(\n requests\n .filter(req => Object.keys(req.columns).length > 0)\n .map(({table, columns}) => [\n tableKey(table),\n {table: {...table}, columns: {...columns}},\n ]),\n );\n }\n\n get #committed(): State {\n return this.#beforeTx ?? this.#state;\n }\n\n /** The (committed) pending backfills. */\n requests(): BackfillRequest[] {\n return [...clone(this.#committed).values()];\n }\n\n /**\n * Returns the `requests` with the (committed) progress of this state\n * applied to the columns that are pending in both, i.e. same table, column,\n * and backfill ID. Other columns have no progress (i.e. from scratch).\n */\n withProgress(requests: readonly BackfillRequest[]): BackfillRequest[] {\n const state = this.#committed;\n return requests.map(({table, columns}) => {\n const tracked = state.get(tableKey(table))?.columns;\n return {\n table,\n columns: Object.fromEntries(\n Object.entries(columns).map(([name, {id}]) => {\n const col = tracked?.[name];\n return [\n name,\n col?.progress && deepEqual(col.id, id)\n ? {id, progress: col.progress}\n : {id},\n ];\n }),\n ),\n };\n });\n }\n\n /** Whether there are no (committed) pending backfills. */\n get empty(): boolean {\n return this.#committed.size === 0;\n }\n\n /**\n * Returns the columns (as `schema.table.column` strings) with (committed)\n * pending backfills that are not covered by the (committed) progress of the\n * `stream`, i.e. columns for which the `stream` will not deliver all of the\n * necessary data.\n */\n uncovered(stream: BackfillState): string[] {\n const uncovered: string[] = [];\n const streamState = stream.#committed;\n for (const [key, {table, columns}] of this.#committed) {\n const streamColumns = streamState.get(key)?.columns;\n for (const [name, {id, progress}] of Object.entries(columns)) {\n const s = streamColumns?.[name];\n if (!s || !deepEqual(s.id, id) || !covers(s.progress, progress)) {\n uncovered.push(`${table.schema}.${table.name}.${name}`);\n }\n }\n }\n return uncovered;\n }\n\n /**\n * Applies a serialized change, parsing it only if it is relevant.\n *\n * @returns The columns (as `schema.table.column` strings) of a backfill\n * message that were ignored due to the continuity policy.\n */\n applySerialized([, tag, json]: WatermarkedChange): string[] {\n switch (tag) {\n case 'begin':\n this.#begin();\n return [];\n case 'commit':\n this.#commit();\n return [];\n case 'rollback':\n this.#rollback();\n return [];\n }\n if (!RELEVANT_TAGS.has(tag)) {\n return [];\n }\n return this.apply(parse(json));\n }\n\n /**\n * Applies a change.\n *\n * @returns The columns (as `schema.table.column` strings) of a backfill\n * message that were ignored due to the continuity policy.\n */\n apply(change: ChangeStreamData): string[] {\n switch (change[0]) {\n case 'begin':\n this.#begin();\n return [];\n case 'commit':\n this.#commit();\n return [];\n case 'rollback':\n this.#rollback();\n return [];\n }\n const msg = change[1];\n switch (msg.tag) {\n case 'backfill': {\n const {relation, columns, progressMarks} = msg;\n return this.#applyBackfill(relation, columns, (progress, col) => {\n const result = acceptBackfill(progress, progressMarks);\n if (result.accept) {\n col.progress = result.progress;\n if (col.progress === undefined) {\n delete col.progress;\n }\n }\n return result.accept;\n });\n }\n case 'backfill-completed': {\n const {relation, columns, progressMarks} = msg;\n const backfill = this.#state.get(tableKey(relation));\n const ignored = this.#applyBackfill(\n relation,\n columns,\n (progress, _, name) => {\n const {accept} = acceptBackfill(\n progress,\n progressMarks && {previous: progressMarks.previous},\n );\n if (accept && backfill) {\n delete backfill.columns[name];\n }\n return accept;\n },\n );\n if (backfill && Object.keys(backfill.columns).length === 0) {\n this.#state.delete(tableKey(relation));\n }\n return ignored;\n }\n case 'create-table':\n case 'rename-table':\n case 'update-table-metadata':\n case 'add-column':\n case 'update-column':\n case 'drop-column':\n case 'drop-table':\n this.#applySchemaChange(msg);\n return [];\n }\n return [];\n }\n\n #applyBackfill(\n relation: {schema: string; name: string; rowKey: {columns: string[]}},\n columns: readonly string[],\n apply: (progress: Column['progress'], col: Column, name: string) => boolean,\n ): string[] {\n const backfill = this.#state.get(tableKey(relation));\n if (!backfill) {\n return [];\n }\n const ignored: string[] = [];\n // rowKey columns are excluded from `columns` but are backfilled with them\n // (e.g. for a new table).\n for (const name of [...relation.rowKey.columns, ...columns]) {\n // Not backfill.columns[name], which is Object.prototype for a column\n // named __proto__ that is not being backfilled.\n const col = Object.hasOwn(backfill.columns, name)\n ? backfill.columns[name]\n : undefined;\n if (!col) {\n continue;\n }\n // Copy-on-write, since the column object may be shared with the\n // pre-transaction state.\n const updated = {...col};\n if (apply(col.progress, updated, name)) {\n if (Object.hasOwn(backfill.columns, name)) {\n assignProperty(backfill.columns, name, updated);\n }\n } else {\n ignored.push(`${relation.schema}.${relation.name}.${name}`);\n }\n }\n return ignored;\n }\n\n #applySchemaChange(change: SchemaChange) {\n // Table metadata specified in the same change (e.g. a `create-table` or\n // `add-column`), for backfills of tables that are not yet tracked.\n const metadata = new Map<string, TableMetadata>();\n\n for (const op of cookieOps(change)) {\n switch (op.op) {\n case 'upsert-metadata': {\n const key = tableKey(op.table);\n metadata.set(key, op.metadata);\n const backfill = this.#state.get(key);\n if (backfill) {\n backfill.table.metadata = op.metadata;\n }\n break;\n }\n case 'upsert-backfill': {\n const key = tableKey(op.table);\n let backfill = this.#state.get(key);\n if (!backfill) {\n backfill = {\n table: {\n schema: op.table.schema,\n name: op.table.name,\n metadata: metadata.get(key) ?? null,\n },\n columns: {},\n };\n this.#state.set(key, backfill);\n }\n // A new backfill always starts from scratch.\n assignProperty(backfill.columns, op.column, {id: op.backfill});\n break;\n }\n case 'rename-table': {\n const backfill = this.#state.get(tableKey(op.old));\n if (backfill) {\n this.#state.delete(tableKey(op.old));\n backfill.table.schema = op.new.schema;\n backfill.table.name = op.new.name;\n this.#state.set(tableKey(op.new), backfill);\n }\n break;\n }\n case 'drop-table':\n this.#state.delete(tableKey(op.table));\n break;\n case 'rename-column': {\n const backfill = this.#state.get(tableKey(op.table));\n if (backfill && Object.hasOwn(backfill.columns, op.old)) {\n const col = backfill.columns[op.old];\n delete backfill.columns[op.old];\n assignProperty(backfill.columns, op.new, col);\n }\n break;\n }\n case 'drop-column': {\n const key = tableKey(op.table);\n const backfill = this.#state.get(key);\n if (backfill) {\n delete backfill.columns[op.column];\n if (Object.keys(backfill.columns).length === 0) {\n this.#state.delete(key);\n }\n }\n break;\n }\n case 'complete-backfill':\n // Only produced for `backfill-completed`, which is handled\n // separately (with the continuity policy).\n throw new Error(`unexpected ${op.op} op`);\n default:\n unreachable(op);\n }\n }\n }\n\n #begin() {\n // Tolerate a missing commit/rollback, e.g. from an interrupted stream.\n this.#beforeTx ??= clone(this.#state);\n }\n\n #commit() {\n this.#beforeTx = null;\n }\n\n #rollback() {\n if (this.#beforeTx) {\n this.#state = this.#beforeTx;\n this.#beforeTx = null;\n }\n }\n}\n"],"mappings":";;;;;;;;AAmBA,SAAS,SAAS,EAAC,QAAQ,QAAmB;CAC5C,OAAO,KAAK,UAAU,CAAC,QAAQ,IAAI,CAAC;AACtC;AAYA,SAAS,MAAM,OAAqB;CAClC,OAAO,IAAI,IACT,MAAM,KAAK,QAAQ,CAAC,KAAK,EAAC,OAAO,eAAc,CAC7C,KACA;EAAC,OAAO,EAAC,GAAG,MAAK;EAAG,SAAS,EAAC,GAAG,QAAO;CAAC,CAC3C,CAAC,CACH;AACF;;;;;AAMA,IAAM,gCAAgB,IAAI,IAAe,CACvC,YACA,GAAG,iBAAiB,QAAO,MAAK,MAAM,kBAAkB,MAAM,YAAY,CAC5E,CAAC;AAKD,IAAI;AAEJ,SAAS,MAAM,MAAgC;CAC7C,IAAI,YAAY,SAAS,MACvB,aAAa;EAAC;EAAM,QAAQ,WAAW,MAAM,IAAI;CAAqB;CAExE,OAAO,WAAW;AACpB;;;;;;;;;;;;;AAcA,IAAa,gBAAb,MAA2B;CACzB;CACA,YAA0B;CAE1B,YAAY,WAAuC,CAAC,GAAG;EACrD,KAAK,SAAS,IAAI,IAChB,SACG,QAAO,QAAO,OAAO,KAAK,IAAI,OAAO,CAAC,CAAC,SAAS,CAAC,CAAC,CAClD,KAAK,EAAC,OAAO,cAAa,CACzB,SAAS,KAAK,GACd;GAAC,OAAO,EAAC,GAAG,MAAK;GAAG,SAAS,EAAC,GAAG,QAAO;EAAC,CAC3C,CAAC,CACL;CACF;CAEA,IAAI,aAAoB;EACtB,OAAO,KAAK,aAAa,KAAK;CAChC;;CAGA,WAA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/change-streamer/backfill-state.ts"],"sourcesContent":["import {unreachable} from '../../../../shared/src/asserts.ts';\nimport {BigIntJSON} from '../../../../shared/src/bigint-json.ts';\nimport {deepEqual} from '../../../../shared/src/json.ts';\nimport {\n assignProperty,\n getOwnProperty,\n} from '../../../../shared/src/objects.ts';\nimport {\n acceptBackfill,\n covers,\n} from '../change-source/protocol/backfill-progress.ts';\nimport type {\n BackfillRequest,\n ChangeStreamData,\n Identifier,\n SchemaChange,\n TableMetadata,\n} from '../change-source/protocol/current.ts';\nimport {schemaChangeTags} from '../change-source/protocol/current/schema-change-tags.ts';\nimport {cookieOps} from '../replicator/change-log-cookies.ts';\nimport type {ChangeTag, WatermarkedChange} from './change-streamer.ts';\n\nfunction tableKey({schema, name}: Identifier) {\n return JSON.stringify([schema, name]);\n}\n\ntype Column = BackfillRequest['columns'][string];\n\n/** A mutable BackfillRequest. */\ntype Backfill = {\n table: {schema: string; name: string; metadata: TableMetadata | null};\n columns: Record<string, Column>;\n};\n\ntype State = Map<string, Backfill>;\n\nfunction clone(state: State): State {\n return new Map(\n Array.from(state, ([key, {table, columns}]) => [\n key,\n {table: {...table}, columns: {...columns}},\n ]),\n );\n}\n\n/**\n * Tags of messages that affect the backfill state. Other messages need not be\n * parsed.\n */\nconst RELEVANT_TAGS = new Set<ChangeTag>([\n 'backfill',\n ...schemaChangeTags.filter(t => t !== 'create-index' && t !== 'drop-index'),\n]);\n\n// Serialized changes are typically forwarded (as the same string) to every\n// subscriber, so a single entry cache avoids re-parsing the same message for\n// each subscriber.\nlet lastParsed: {json: string; change: ChangeStreamData} | undefined;\n\nfunction parse(json: string): ChangeStreamData {\n if (lastParsed?.json !== json) {\n lastParsed = {json, change: BigIntJSON.parse(json) as ChangeStreamData};\n }\n return lastParsed.change;\n}\n\n/**\n * Tracks the state of the pending backfills (and their progress) of a party\n * in the replication stream (e.g. a subscriber, or the change-log itself), by\n * applying the same policies that a subscriber applies to its replica:\n * schema changes are folded with the {@link cookieOps} shared by the\n * cookie jars, and `backfill` / `backfill-completed` messages are accepted\n * or ignored with the continuity policy of {@link acceptBackfill}.\n *\n * Changes are applied transactionally: the changes of a transaction are\n * discarded if it is rolled back, and {@link requests()} only reflects\n * committed transactions.\n */\nexport class BackfillState {\n #state: State;\n #beforeTx: State | null = null;\n\n constructor(requests: readonly BackfillRequest[] = []) {\n this.#state = new Map(\n requests\n .filter(req => Object.keys(req.columns).length > 0)\n .map(({table, columns}) => [\n tableKey(table),\n {table: {...table}, columns: {...columns}},\n ]),\n );\n }\n\n get #committed(): State {\n return this.#beforeTx ?? this.#state;\n }\n\n /** The (committed) pending backfills. */\n requests(): BackfillRequest[] {\n return [...clone(this.#committed).values()];\n }\n\n /**\n * Returns the `requests` with the (committed) progress of this state\n * applied to the columns that are pending in both, i.e. same table, column,\n * and backfill ID. Other columns have no progress (i.e. from scratch).\n */\n withProgress(requests: readonly BackfillRequest[]): BackfillRequest[] {\n const state = this.#committed;\n return requests.map(({table, columns}) => {\n const tracked = state.get(tableKey(table))?.columns;\n return {\n table,\n columns: Object.fromEntries(\n Object.entries(columns).map(([name, {id}]) => {\n const col = tracked?.[name];\n return [\n name,\n col?.progress && deepEqual(col.id, id)\n ? {id, progress: col.progress}\n : {id},\n ];\n }),\n ),\n };\n });\n }\n\n /** Whether there are no (committed) pending backfills. */\n get empty(): boolean {\n return this.#committed.size === 0;\n }\n\n /**\n * Returns the columns (as `schema.table.column` strings) with (committed)\n * pending backfills that are not covered by the (committed) progress of the\n * `stream`, i.e. columns for which the `stream` will not deliver all of the\n * necessary data.\n */\n uncovered(stream: BackfillState): string[] {\n const uncovered: string[] = [];\n const streamState = stream.#committed;\n for (const [key, {table, columns}] of this.#committed) {\n const streamColumns = streamState.get(key)?.columns;\n for (const [name, {id, progress}] of Object.entries(columns)) {\n const s = streamColumns?.[name];\n if (!s || !deepEqual(s.id, id) || !covers(s.progress, progress)) {\n uncovered.push(`${table.schema}.${table.name}.${name}`);\n }\n }\n }\n return uncovered;\n }\n\n /**\n * Applies a serialized change, parsing it only if it is relevant.\n *\n * @returns The columns (as `schema.table.column` strings) of a backfill\n * message that were ignored due to the continuity policy.\n */\n applySerialized([, tag, json]: WatermarkedChange): string[] {\n switch (tag) {\n case 'begin':\n this.#begin();\n return [];\n case 'commit':\n this.#commit();\n return [];\n case 'rollback':\n this.#rollback();\n return [];\n }\n if (!RELEVANT_TAGS.has(tag)) {\n return [];\n }\n return this.apply(parse(json));\n }\n\n /**\n * Applies a change.\n *\n * @returns The columns (as `schema.table.column` strings) of a backfill\n * message that were ignored due to the continuity policy.\n */\n apply(change: ChangeStreamData): string[] {\n switch (change[0]) {\n case 'begin':\n this.#begin();\n return [];\n case 'commit':\n this.#commit();\n return [];\n case 'rollback':\n this.#rollback();\n return [];\n }\n const msg = change[1];\n switch (msg.tag) {\n case 'backfill': {\n const {relation, columns, progressMarks} = msg;\n return this.#applyBackfill(relation, columns, (progress, col) => {\n const result = acceptBackfill(progress, progressMarks);\n if (result.accept) {\n col.progress = result.progress;\n if (col.progress === undefined) {\n delete col.progress;\n }\n }\n return result.accept;\n });\n }\n case 'backfill-completed': {\n const {relation, columns, progressMarks} = msg;\n const backfill = this.#state.get(tableKey(relation));\n const ignored = this.#applyBackfill(\n relation,\n columns,\n (progress, _, name) => {\n const {accept} = acceptBackfill(\n progress,\n progressMarks && {previous: progressMarks.previous},\n );\n if (accept && backfill) {\n delete backfill.columns[name];\n }\n return accept;\n },\n );\n if (backfill && Object.keys(backfill.columns).length === 0) {\n this.#state.delete(tableKey(relation));\n }\n return ignored;\n }\n case 'create-table':\n case 'rename-table':\n case 'update-table-metadata':\n case 'add-column':\n case 'update-column':\n case 'drop-column':\n case 'drop-table':\n this.#applySchemaChange(msg);\n return [];\n }\n return [];\n }\n\n #applyBackfill(\n relation: {schema: string; name: string; rowKey: {columns: string[]}},\n columns: readonly string[],\n apply: (progress: Column['progress'], col: Column, name: string) => boolean,\n ): string[] {\n const backfill = this.#state.get(tableKey(relation));\n if (!backfill) {\n return [];\n }\n const ignored: string[] = [];\n // rowKey columns are excluded from `columns` but are backfilled with them\n // (e.g. for a new table).\n for (const name of [...relation.rowKey.columns, ...columns]) {\n // Not backfill.columns[name], which is Object.prototype for a column\n // named __proto__ that is not being backfilled.\n const col = getOwnProperty(backfill.columns, name);\n if (!col) {\n continue;\n }\n // Copy-on-write, since the column object may be shared with the\n // pre-transaction state.\n const updated = {...col};\n if (apply(col.progress, updated, name)) {\n if (Object.hasOwn(backfill.columns, name)) {\n assignProperty(backfill.columns, name, updated);\n }\n } else {\n ignored.push(`${relation.schema}.${relation.name}.${name}`);\n }\n }\n return ignored;\n }\n\n #applySchemaChange(change: SchemaChange) {\n // Table metadata specified in the same change (e.g. a `create-table` or\n // `add-column`), for backfills of tables that are not yet tracked.\n const metadata = new Map<string, TableMetadata>();\n\n for (const op of cookieOps(change)) {\n switch (op.op) {\n case 'upsert-metadata': {\n const key = tableKey(op.table);\n metadata.set(key, op.metadata);\n const backfill = this.#state.get(key);\n if (backfill) {\n backfill.table.metadata = op.metadata;\n }\n break;\n }\n case 'upsert-backfill': {\n const key = tableKey(op.table);\n let backfill = this.#state.get(key);\n if (!backfill) {\n backfill = {\n table: {\n schema: op.table.schema,\n name: op.table.name,\n metadata: metadata.get(key) ?? null,\n },\n columns: {},\n };\n this.#state.set(key, backfill);\n }\n // A new backfill always starts from scratch.\n assignProperty(backfill.columns, op.column, {id: op.backfill});\n break;\n }\n case 'rename-table': {\n const backfill = this.#state.get(tableKey(op.old));\n if (backfill) {\n this.#state.delete(tableKey(op.old));\n backfill.table.schema = op.new.schema;\n backfill.table.name = op.new.name;\n this.#state.set(tableKey(op.new), backfill);\n }\n break;\n }\n case 'drop-table':\n this.#state.delete(tableKey(op.table));\n break;\n case 'rename-column': {\n const backfill = this.#state.get(tableKey(op.table));\n if (backfill && Object.hasOwn(backfill.columns, op.old)) {\n const col = backfill.columns[op.old];\n delete backfill.columns[op.old];\n assignProperty(backfill.columns, op.new, col);\n }\n break;\n }\n case 'drop-column': {\n const key = tableKey(op.table);\n const backfill = this.#state.get(key);\n if (backfill) {\n delete backfill.columns[op.column];\n if (Object.keys(backfill.columns).length === 0) {\n this.#state.delete(key);\n }\n }\n break;\n }\n case 'complete-backfill':\n // Only produced for `backfill-completed`, which is handled\n // separately (with the continuity policy).\n throw new Error(`unexpected ${op.op} op`);\n default:\n unreachable(op);\n }\n }\n }\n\n #begin() {\n // Tolerate a missing commit/rollback, e.g. from an interrupted stream.\n this.#beforeTx ??= clone(this.#state);\n }\n\n #commit() {\n this.#beforeTx = null;\n }\n\n #rollback() {\n if (this.#beforeTx) {\n this.#state = this.#beforeTx;\n this.#beforeTx = null;\n }\n }\n}\n"],"mappings":";;;;;;;;AAsBA,SAAS,SAAS,EAAC,QAAQ,QAAmB;CAC5C,OAAO,KAAK,UAAU,CAAC,QAAQ,IAAI,CAAC;AACtC;AAYA,SAAS,MAAM,OAAqB;CAClC,OAAO,IAAI,IACT,MAAM,KAAK,QAAQ,CAAC,KAAK,EAAC,OAAO,eAAc,CAC7C,KACA;EAAC,OAAO,EAAC,GAAG,MAAK;EAAG,SAAS,EAAC,GAAG,QAAO;CAAC,CAC3C,CAAC,CACH;AACF;;;;;AAMA,IAAM,gCAAgB,IAAI,IAAe,CACvC,YACA,GAAG,iBAAiB,QAAO,MAAK,MAAM,kBAAkB,MAAM,YAAY,CAC5E,CAAC;AAKD,IAAI;AAEJ,SAAS,MAAM,MAAgC;CAC7C,IAAI,YAAY,SAAS,MACvB,aAAa;EAAC;EAAM,QAAQ,WAAW,MAAM,IAAI;CAAqB;CAExE,OAAO,WAAW;AACpB;;;;;;;;;;;;;AAcA,IAAa,gBAAb,MAA2B;CACzB;CACA,YAA0B;CAE1B,YAAY,WAAuC,CAAC,GAAG;EACrD,KAAK,SAAS,IAAI,IAChB,SACG,QAAO,QAAO,OAAO,KAAK,IAAI,OAAO,CAAC,CAAC,SAAS,CAAC,CAAC,CAClD,KAAK,EAAC,OAAO,cAAa,CACzB,SAAS,K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AAK,WAAW;GAClB,KAAK,SAAS,KAAK;GACnB,KAAK,YAAY;EACnB;CACF;AACF"}
@@ -1,7 +1,7 @@
1
1
  import { assert, unreachable } from "../../../../shared/src/asserts.js";
2
2
  import { resolver } from "../../../../shared/src/resolver.js";
3
- import { parse } from "../../../../shared/src/valita.js";
4
3
  import { assignProperty, getOwnProperty } from "../../../../shared/src/objects.js";
4
+ import { parse } from "../../../../shared/src/valita.js";
5
5
  import { InvalidPush, MutationFailed, MutationRateLimited } from "../../../../zero-protocol/src/error-kind-enum.js";
6
6
  import { ZeroCache } from "../../../../zero-protocol/src/error-origin-enum.js";
7
7
  import { ProtocolError, isProtocolError } from "../../../../zero-protocol/src/error.js";
@@ -1,6 +1,6 @@
1
1
  import { unreachable } from "../../../../shared/src/asserts.js";
2
- import { parse, valita_exports } from "../../../../shared/src/valita.js";
3
2
  import { assignProperty } from "../../../../shared/src/objects.js";
3
+ import { parse, valita_exports } from "../../../../shared/src/valita.js";
4
4
  import { BigIntJSON } from "../../../../shared/src/bigint-json.js";
5
5
  import { backfillRequestSchema } from "../change-source/protocol/current/upstream.js";
6
6
  //#region ../zero-cache/src/services/replicator/change-log-cookies.ts
@@ -1,8 +1,8 @@
1
1
  import { assert, unreachable } from "../../../../shared/src/asserts.js";
2
2
  import { deepEqual } from "../../../../shared/src/json.js";
3
3
  import { AbortError } from "../../../../shared/src/abort-error.js";
4
- import { must } from "../../../../shared/src/must.js";
5
4
  import { assignProperty, mapEntries } from "../../../../shared/src/objects.js";
5
+ import { must } from "../../../../shared/src/must.js";
6
6
  import { stringify } from "../../../../shared/src/bigint-json.js";
7
7
  import { id } from "../../types/sql.js";
8
8
  import { ZERO_VERSION_COLUMN_NAME } from "./schema/constants.js";
@@ -20,7 +20,6 @@ import { acceptBackfill } from "../change-source/protocol/backfill-progress.js";
20
20
  import { SqliteError } from "@rocicorp/zero-sqlite3";
21
21
  import { constants } from "node:buffer";
22
22
  //#region ../zero-cache/src/services/replicator/change-processor.ts
23
- var MAX_COMMIT_ATTEMPTS = 5;
24
23
  var BIND_VALUE_TOO_BIG_ERROR = "The bound string, buffer, or bigint is too big";
25
24
  var MAX_SQLITE_BIND_BYTES = Math.min(constants.MAX_LENGTH, constants.MAX_STRING_LENGTH);
26
25
  /**
@@ -636,7 +635,7 @@ var TransactionProcessor = class {
636
635
  this.#db.db.pragma("optimize");
637
636
  this.#lc.info?.(`PRAGMA optimized after schema change (${Date.now() - start} ms)`);
638
637
  }
639
- if (this.#mode !== "initial-sync") this.#commit();
638
+ if (this.#mode !== "initial-sync") this.#db.commit();
640
639
  const elapsedMs = Date.now() - this.#startMs;
641
640
  this.#lc.debug?.(`Committed tx@${this.#version} (${elapsedMs} ms)`);
642
641
  return {
@@ -647,33 +646,6 @@ var TransactionProcessor = class {
647
646
  upstreamCommitTimeMs: commit.commitTimeMs
648
647
  };
649
648
  }
650
- /**
651
- * A wal2 `COMMIT` can fail with SQLITE_BUSY, without consulting the
652
- * busy_timeout, if it switches wal files just as the `ServingCheckpointer`
653
- * briefly locks the file it is switching to: the writer releases its locks
654
- * on that file before taking the read lock that it needs on it. The
655
- * transaction stays open and the switch has already happened, so the next
656
- * attempt does not contend for that lock.
657
- *
658
- * No backoff is needed between attempts: the retry does not switch files
659
- * again, so it never asks for the contended lock, whether or not the
660
- * checkpointer still holds it. A second failure has some other cause.
661
- *
662
- * This is a workaround for a bug in SQLite's wal2 branch (in
663
- * `walRestartLog()`), reported at
664
- * https://sqlite.org/forum/forumpost/63ba0208a66aa7139119b56edb43a416b160ca1996a23de2b0da24ca48fb9b3a.
665
- * The retry runs without the read lock the failed attempt meant to take.
666
- * Remove it once zero-sqlite3 includes a fix.
667
- */
668
- #commit() {
669
- for (let attempt = 1;; attempt++) try {
670
- this.#db.commit();
671
- return;
672
- } catch (e) {
673
- if (attempt === MAX_COMMIT_ATTEMPTS || !(e instanceof SqliteError && e.code === "SQLITE_BUSY")) throw e;
674
- this.#lc.warn?.(`SQLITE_BUSY on COMMIT (attempt ${attempt})`, e);
675
- }
676
- }
677
649
  abort(lc) {
678
650
  lc.info?.(`aborting transaction ${this.#version}`);
679
651
  this.#db.rollback();
@@ -1 +1 @@
1
- {"version":3,"file":"change-processor.js","names":["bufferConstants"],"sources":["../../../../../../zero-cache/src/services/replicator/change-processor.ts"],"sourcesContent":["import {constants as bufferConstants} from 'node:buffer';\nimport type {LogContext} from '@rocicorp/logger';\nimport {SqliteError} from '@rocicorp/zero-sqlite3';\nimport {AbortError} from '../../../../shared/src/abort-error.ts';\nimport {assert, unreachable} from '../../../../shared/src/asserts.ts';\nimport {stringify} from '../../../../shared/src/bigint-json.ts';\nimport {deepEqual} from '../../../../shared/src/json.ts';\nimport {must} from '../../../../shared/src/must.ts';\nimport {assignProperty} from '../../../../shared/src/objects.ts';\nimport {mapEntries} from '../../../../shared/src/objects.ts';\nimport type {DownloadStatus} from '../../../../zero-events/src/status.ts';\nimport {\n createLiteIndex,\n createLiteTableStatement,\n liteColumnDef,\n} from '../../db/create.ts';\nimport {\n computeZqlSpecs,\n listTables,\n type LiteTableSpecWithReplicationStatus,\n} from '../../db/lite-tables.ts';\nimport {\n isArrayColumn,\n isEnumColumn,\n mapPostgresToLite,\n mapPostgresToLiteColumn,\n mapPostgresToLiteIndex,\n} from '../../db/pg-to-lite.ts';\nimport type {ColumnSpec} from '../../db/specs.ts';\nimport type {StatementRunner} from '../../db/statements.ts';\nimport type {LexiVersion} from '../../types/lexi-version.ts';\nimport {\n isUnusableKeyValue,\n JSON_PARSED,\n liteRow,\n type JSONFormat,\n type LiteRow,\n type LiteRowKey,\n type LiteValueType,\n} from '../../types/lite.ts';\nimport {liteTableName} from '../../types/names.ts';\nimport {id} from '../../types/sql.ts';\nimport {\n acceptBackfill,\n type AcceptResult,\n} from '../change-source/protocol/backfill-progress.ts';\nimport type {\n BackfillCompleted,\n BackfillProgressMark,\n Change,\n ColumnAdd,\n ColumnDrop,\n ColumnUpdate,\n Identifier,\n IndexCreate,\n IndexDrop,\n MessageBackfill,\n MessageCommit,\n MessageDelete,\n MessageInsert,\n MessageRelation,\n MessageTruncate,\n MessageUpdate,\n TableCreate,\n TableDrop,\n TableRename,\n TableUpdateMetadata,\n} from '../change-source/protocol/current/data.ts';\nimport type {ChangeStreamData} from '../change-source/protocol/current/downstream.ts';\nimport type {ReplicatorMode} from './replicator.ts';\nimport {BackfillingTracker} from './schema/backfilling.ts';\nimport {ChangeLog, DEL_OP, SET_OP} from './schema/change-log.ts';\nimport {ColumnMetadataStore} from './schema/column-metadata.ts';\nimport {\n ZERO_VERSION_COLUMN_NAME,\n updateReplicationWatermark,\n} from './schema/replication-state.ts';\nimport {TableMetadataTracker} from './schema/table-metadata.ts';\n\nexport type ChangeProcessorMode = ReplicatorMode | 'initial-sync';\n\nconst MAX_COMMIT_ATTEMPTS = 5;\n\nconst BIND_VALUE_TOO_BIG_ERROR =\n 'The bound string, buffer, or bigint is too big';\nconst MAX_SQLITE_BIND_BYTES = Math.min(\n bufferConstants.MAX_LENGTH,\n bufferConstants.MAX_STRING_LENGTH,\n);\n\nexport type CommitResult = {\n watermark: string;\n completedBackfill: DownloadStatus | undefined;\n schemaUpdated: boolean;\n changeLogUpdated: boolean;\n /**\n * Millisecond epoch at which the transaction committed upstream, if the\n * ChangeSource reported one. Propagated to ViewSyncers as the origin\n * timestamp of the end-to-end serving lag measurement.\n */\n upstreamCommitTimeMs?: number | undefined;\n};\n\n/**\n * The ChangeProcessor partitions the stream of messages into transactions\n * by creating a {@link TransactionProcessor} when a transaction begins, and dispatching\n * messages to it until the commit is received.\n *\n * From https://www.postgresql.org/docs/current/protocol-logical-replication.html#PROTOCOL-LOGICAL-MESSAGES-FLOW :\n *\n * \"The logical replication protocol sends individual transactions one by one.\n * This means that all messages between a pair of Begin and Commit messages\n * belong to the same transaction.\"\n */\nexport class ChangeProcessor {\n readonly #db: StatementRunner;\n readonly #changeLog: ChangeLog;\n readonly #tableMetadata: TableMetadataTracker;\n readonly #backfilling: BackfillingTracker;\n readonly #mode: ChangeProcessorMode;\n readonly #failService: (lc: LogContext, err: unknown) => void;\n\n // The TransactionProcessor lazily loads table specs into this Map,\n // and reloads them after a schema change. It is cached here to avoid\n // reading them from the DB on every transaction.\n readonly #tableSpecs = new Map<string, LiteTableSpecWithReplicationStatus>();\n\n #currentTx: TransactionProcessor | null = null;\n\n #failure: Error | undefined;\n\n constructor(\n db: StatementRunner,\n mode: ChangeProcessorMode,\n failService: (lc: LogContext, err: unknown) => void,\n ) {\n this.#db = db;\n this.#changeLog = new ChangeLog(db.db);\n this.#tableMetadata = new TableMetadataTracker(db.db);\n this.#backfilling = new BackfillingTracker(db.db);\n this.#mode = mode;\n this.#failService = failService;\n }\n\n #fail(lc: LogContext, err: unknown) {\n if (!this.#failure) {\n let failureError = err;\n const rollbackErrors = [attempt(() => this.#currentTx?.abort(lc))].filter(\n e => e !== undefined,\n );\n\n if (rollbackErrors.length) {\n const combinedError = new Error(\n `Message processing failed and rollback also failed: operation error = ${String(err)}; rollback error = ${rollbackErrors.map(String).join('; ')}`,\n );\n combinedError.cause = err;\n failureError = combinedError;\n }\n\n this.#failure = ensureError(failureError);\n\n if (!(this.#failure instanceof AbortError)) {\n // Propagate the failure up to the service.\n lc.error?.('Message Processing failed:', this.#failure);\n this.#failService(lc, this.#failure);\n }\n }\n }\n\n abort(lc: LogContext) {\n this.#fail(lc, new AbortError());\n }\n\n /** @return If a transaction was committed. */\n processMessage(\n lc: LogContext,\n downstream: ChangeStreamData,\n ): CommitResult | null {\n const [type, message] = downstream;\n if (this.#failure) {\n lc.debug?.(`Dropping ${message.tag}`);\n return null;\n }\n try {\n const watermark =\n type === 'begin'\n ? downstream[2].commitWatermark\n : type === 'commit'\n ? downstream[2].watermark\n : undefined;\n return this.#processMessage(lc, message, watermark);\n } catch (e) {\n this.#fail(lc, e);\n }\n return null;\n }\n\n #beginTransaction(\n lc: LogContext,\n commitVersion: string,\n jsonFormat: JSONFormat,\n ): TransactionProcessor {\n const start = Date.now();\n\n // litestream can technically hold the lock for an arbitrary amount of time\n // when checkpointing a large commit. Crashing on the busy-timeout in this\n // scenario will either produce a corrupt backup or otherwise prevent\n // replication from proceeding.\n //\n // Instead, retry the lock acquisition indefinitely. If this masks\n // an unknown deadlock situation, manual intervention will be necessary.\n for (let i = 0; ; i++) {\n try {\n return new TransactionProcessor(\n lc,\n this.#db,\n this.#mode,\n this.#changeLog,\n this.#tableMetadata,\n this.#backfilling,\n this.#tableSpecs,\n commitVersion,\n jsonFormat,\n );\n } catch (e) {\n if (e instanceof SqliteError && e.code === 'SQLITE_BUSY') {\n lc.warn?.(\n `SQLITE_BUSY for ${Date.now() - start} ms (attempt ${i + 1}). ` +\n `This is only expected if litestream is performing a large ` +\n `checkpoint.`,\n e,\n );\n continue;\n }\n throw e;\n }\n }\n }\n\n /** @return If a transaction was committed. */\n #processMessage(\n lc: LogContext,\n msg: Change,\n watermark: string | undefined,\n ): CommitResult | null {\n if (msg.tag === 'begin') {\n if (this.#currentTx) {\n throw new Error(`Already in a transaction ${stringify(msg)}`);\n }\n this.#currentTx = this.#beginTransaction(\n lc,\n must(watermark),\n msg.json ?? JSON_PARSED,\n );\n return null;\n }\n\n // For non-begin messages, there should be a #currentTx set.\n const tx = this.#currentTx;\n if (!tx) {\n throw new Error(\n `Received message outside of transaction: ${stringify(msg)}`,\n );\n }\n\n if (msg.tag === 'commit') {\n assert(watermark, 'watermark is required for commit messages');\n const result = tx.processCommit(msg, watermark);\n // Clear only after a successful commit so #fail can roll back a commit\n // path that throws before SQLite has committed.\n this.#currentTx = null;\n return result;\n }\n\n if (msg.tag === 'rollback') {\n tx.abort(lc);\n this.#currentTx = null;\n return null;\n }\n\n switch (msg.tag) {\n case 'insert':\n tx.processInsert(msg);\n break;\n case 'update':\n tx.processUpdate(msg);\n break;\n case 'delete':\n tx.processDelete(msg);\n break;\n case 'truncate':\n tx.processTruncate(msg);\n break;\n case 'create-table':\n tx.processCreateTable(msg);\n break;\n case 'rename-table':\n tx.processRenameTable(msg);\n break;\n case 'update-table-metadata':\n tx.processTableMetadata(msg);\n break;\n case 'add-column':\n tx.processAddColumn(msg);\n break;\n case 'update-column':\n tx.processUpdateColumn(msg);\n break;\n case 'drop-column':\n tx.processDropColumn(msg);\n break;\n case 'drop-table':\n tx.processDropTable(msg);\n break;\n case 'create-index':\n tx.processCreateIndex(msg);\n break;\n case 'drop-index':\n tx.processDropIndex(msg);\n break;\n case 'backfill':\n tx.processBackfill(msg);\n break;\n case 'backfill-completed':\n tx.processBackfillCompleted(msg);\n break;\n default:\n unreachable(msg);\n }\n\n return null;\n }\n}\n\n/**\n * The {@link TransactionProcessor} handles the sequence of messages from\n * upstream, from `BEGIN` to `COMMIT` and executes the corresponding mutations\n * on the {@link postgres.TransactionSql} on the replica.\n *\n * When applying row contents to the replica, the `_0_version` column is added / updated,\n * and a corresponding entry in the `ChangeLog` is added. The version value is derived\n * from the watermark of the preceding transaction (stored as the `nextStateVersion` in the\n * `ReplicationState` table).\n *\n * Side note: For non-streaming Postgres transactions, the commitEndLsn (and thus\n * commit watermark) is available in the `begin` message, so it could theoretically\n * be used for the row version of changes within the transaction. However, the\n * commitEndLsn is not available in the streaming (in-progress) transaction\n * protocol, and may not be available for CDC streams of other upstream types.\n * Therefore, the zero replication protocol is designed to not require the commit\n * watermark when a transaction begins.\n *\n * Also of interest is the fact that all INSERT Messages are logically applied as\n * UPSERTs. See {@link processInsert} for the underlying motivation.\n */\nclass TransactionProcessor {\n readonly #lc: LogContext;\n readonly #startMs: number;\n readonly #db: StatementRunner;\n readonly #mode: ChangeProcessorMode;\n readonly #version: LexiVersion;\n readonly #changeLog: ChangeLog;\n readonly #tableMetadata: TableMetadataTracker;\n readonly #backfilling: BackfillingTracker;\n readonly #tableSpecs: Map<string, LiteTableSpecWithReplicationStatus>;\n readonly #jsonFormat: JSONFormat;\n readonly #columnMetadata: ColumnMetadataStore;\n\n #pos = 0;\n #schemaChanged = false;\n #numChangeLogEntries = 0;\n\n constructor(\n lc: LogContext,\n db: StatementRunner,\n mode: ChangeProcessorMode,\n changeLog: ChangeLog,\n tableMetadata: TableMetadataTracker,\n backfilling: BackfillingTracker,\n tableSpecs: Map<string, LiteTableSpecWithReplicationStatus>,\n commitVersion: LexiVersion,\n jsonFormat: JSONFormat,\n ) {\n this.#startMs = Date.now();\n this.#mode = mode;\n this.#jsonFormat = jsonFormat;\n\n switch (mode) {\n case 'serving':\n // This is the only transaction that commits to the serving replica.\n // Snapshotters use BEGIN CONCURRENT for private changes that are\n // always rolled back, while BEGIN IMMEDIATE lets this writer spill\n // dirty pages during large transactions.\n db.beginImmediate();\n break;\n case 'backup':\n // For the backup-replicator (i.e. replication-manager), there are no View Syncers\n // and thus BEGIN CONCURRENT is not necessary. In fact, BEGIN CONCURRENT can cause\n // deadlocks with forced wal-checkpoints (which `litestream replicate` performs),\n // so it is important to use vanilla transactions in this configuration.\n db.beginImmediate();\n break;\n case 'initial-sync':\n // When the ChangeProcessor is used for initial-sync, the calling code\n // handles the transaction boundaries.\n break;\n default:\n unreachable();\n }\n this.#db = db;\n this.#version = commitVersion;\n this.#lc = lc.withContext('version', commitVersion);\n this.#changeLog = changeLog;\n this.#tableMetadata = tableMetadata;\n this.#backfilling = backfilling;\n this.#tableSpecs = tableSpecs;\n // The column_metadata table is guaranteed to exist since the\n // replica-schema.ts migration to v8.\n this.#columnMetadata = must(ColumnMetadataStore.getInstance(db.db));\n\n if (this.#tableSpecs.size === 0) {\n this.#reloadTableSpecs();\n }\n }\n\n #reloadTableSpecs() {\n this.#tableSpecs.clear();\n // zqlSpecs include the primary key derived from unique indexes\n const zqlSpecs = computeZqlSpecs(this.#lc, this.#db.db, {\n includeBackfillingColumns: true,\n });\n for (let spec of listTables(this.#db.db)) {\n if (!spec.primaryKey) {\n spec = {\n ...spec,\n primaryKey: [\n ...(zqlSpecs.get(spec.name)?.tableSpec.primaryKey ?? []),\n ],\n };\n }\n this.#tableSpecs.set(spec.name, spec);\n }\n }\n\n #tableSpec(name: string) {\n return must(this.#tableSpecs.get(name), `Unknown table ${name}`);\n }\n\n #keyColumns(relation: MessageRelation) {\n return relation.rowKey.type !== 'full'\n ? relation.rowKey.columns // already a suitable key\n : this.#tableSpec(liteTableName(relation)).primaryKey;\n }\n\n #getKey(\n {row, numCols}: {row: LiteRow; numCols: number},\n {relation}: {relation: MessageRelation},\n ): LiteRowKey {\n const keyColumns = this.#keyColumns(relation);\n if (!keyColumns?.length) {\n throw new Error(\n `Cannot replicate table \"${relation.name}\" without a PRIMARY KEY or UNIQUE INDEX`,\n );\n }\n // For the common case (replica identity default), the row is already the\n // key for deletes and updates, in which case a new object can be avoided.\n if (numCols === keyColumns.length) {\n return row;\n }\n const key: Record<string, LiteValueType> = {};\n for (const col of keyColumns) {\n assignProperty(key, col, row[col]);\n }\n return key;\n }\n\n // A NaN has no value on the replica, where it is stored as a NULL, and an\n // infinite number has none in JSON, which is what row keys are in the\n // change log and beyond. A row with either in its key could not be matched\n // by later changes to it, so it is not replicated. (Initial sync and\n // backfills skip these rows as well.)\n #lacksKey(table: string, key: LiteRowKey): boolean {\n for (const v of Object.values(key)) {\n if (isUnusableKeyValue(v)) {\n this.#lc.warn?.(\n `Skipping a row of ${table} with a NaN or an infinite value in its key`,\n );\n return true;\n }\n }\n return false;\n }\n\n processInsert(insert: MessageInsert) {\n const table = liteTableName(insert.relation);\n const tableSpec = this.#tableSpec(table);\n const newRow = liteRow(insert.new, tableSpec, this.#jsonFormat);\n const keyed = !!this.#keyColumns(insert.relation)?.length;\n if (keyed) {\n const key = this.#getKey(newRow, insert);\n if (this.#lacksKey(table, key)) {\n // An earlier row with this key may have left a row or an entry.\n this.#deleteRowLackingKey(table, key, tableSpec.backfilling);\n return;\n }\n }\n\n this.#upsert(table, {\n ...newRow.row,\n [ZERO_VERSION_COLUMN_NAME]: this.#version,\n });\n\n if (!keyed) {\n // INSERTs can be replicated for rows without a PRIMARY KEY or a\n // UNIQUE INDEX. These are written to the replica but not recorded\n // in the changeLog, because these rows cannot participate in IVM.\n //\n // (Once the table schema has been corrected to include a key, the\n // associated schema change will reset pipelines and data can be\n // loaded via hydration.)\n return;\n }\n const key = this.#getKey(newRow, insert);\n this.#logSetOp(table, key, getBackfilledColumns(newRow.row, tableSpec));\n }\n\n // A table without a key gets UPDATEs and DELETEs only with REPLICA IDENTITY\n // FULL, which identifies a row by all of its values. Any one row with those\n // values will do, as they are interchangeable. As with INSERTs, these\n // changes are not recorded in the changeLog.\n #matchRowWithoutKey(table: string, {row}: {row: LiteRow}) {\n const conds = Object.keys(row).map(col => `${id(col)} IS ?`);\n return {\n where: `_rowid_ = (SELECT _rowid_ FROM ${id(table)} WHERE ${conds.join(' AND ')} LIMIT 1)`,\n params: Object.values(row),\n };\n }\n\n #upsert(table: string, row: LiteRow) {\n const columns = Object.keys(row).map(c => id(c));\n this.#db.run(\n `\n INSERT OR REPLACE INTO ${id(table)} (${columns.join(',')})\n VALUES (${Array.from({length: columns.length}).fill('?').join(',')})\n `,\n Object.values(row),\n );\n }\n\n // Updates by default are applied as UPDATE commands to support partial\n // row specifications from the change source. In particular, this is needed\n // to handle updates for which unchanged TOASTed values are not sent:\n //\n // https://www.postgresql.org/docs/current/protocol-logicalrep-message-formats.html#PROTOCOL-LOGICALREP-MESSAGE-FORMATS-TUPLEDATA\n //\n // However, in certain cases an UPDATE may be received for a row that\n // was not initially synced, such as when, an existing table is added\n // to the app's publication.\n //\n // In order to facilitate \"resumptive\" replication, the logic falls back to\n // an INSERT if the update did not change any rows.\n processUpdate(update: MessageUpdate) {\n const table = liteTableName(update.relation);\n const tableSpec = this.#tableSpec(table);\n const newRow = liteRow(update.new, tableSpec, this.#jsonFormat);\n const row = {...newRow.row, [ZERO_VERSION_COLUMN_NAME]: this.#version};\n\n if (update.key && !this.#keyColumns(update.relation)?.length) {\n const {where, params} = this.#matchRowWithoutKey(\n table,\n liteRow(update.key, tableSpec, this.#jsonFormat),\n );\n const setExprs = Object.keys(row).map(col => `${id(col)}=?`);\n const {changes} = this.#db.run(\n `UPDATE ${id(table)} SET ${setExprs.join(',')} WHERE ${where}`,\n [...Object.values(row), ...params],\n );\n if (changes === 0) {\n this.#upsert(table, row);\n }\n return;\n }\n\n // update.key is set with the old values if the key has changed.\n let oldKey = update.key\n ? this.#getKey(\n liteRow(update.key, this.#tableSpec(table), this.#jsonFormat),\n update,\n )\n : null;\n const newKey = this.#getKey(newRow, update);\n\n if (oldKey && this.#lacksKey(table, oldKey)) {\n // The row was not replicated, so the update is applied to its new key,\n // which adds the row.\n this.#deleteRowLackingKey(table, oldKey, tableSpec.backfilling);\n oldKey = null;\n }\n if (this.#lacksKey(table, newKey)) {\n // The row is no longer replicated.\n this.#deleteRowLackingKey(table, newKey, tableSpec.backfilling);\n if (oldKey) {\n this.#delete(table, oldKey);\n this.#logDeleteOp(table, oldKey, tableSpec.backfilling);\n }\n return;\n }\n\n if (oldKey) {\n this.#logDeleteOp(table, oldKey, tableSpec.backfilling);\n }\n this.#logSetOp(table, newKey, getBackfilledColumns(newRow.row, tableSpec));\n\n const currKey = oldKey ?? newKey;\n const conds = Object.keys(currKey).map(col => `${id(col)}=?`);\n const setExprs = Object.keys(row).map(col => `${id(col)}=?`);\n\n try {\n const {changes} = this.#db.run(\n `\n UPDATE ${id(table)}\n SET ${setExprs.join(',')}\n WHERE ${conds.join(' AND ')}\n `,\n [...Object.values(row), ...Object.values(currKey)],\n );\n\n // If the UPDATE did not affect any rows, perform an UPSERT of the\n // new row for resumptive replication.\n if (changes === 0) {\n this.#upsert(table, row);\n }\n } catch (e) {\n if (\n !(e instanceof RangeError) ||\n e.message !== BIND_VALUE_TOO_BIG_ERROR\n ) {\n throw e;\n }\n\n const binding = [...Object.entries(row), ...Object.entries(currKey)]\n .map(\n ([column, value]) =>\n [column, oversizedValueDescription(value)] as const,\n )\n .find(([, description]) => description);\n const relationOid =\n 'relationOid' in update.relation &&\n typeof update.relation.relationOid === 'number'\n ? ` relationOid=${update.relation.relationOid}`\n : '';\n const error = new Error(\n `Oversized SQLite update binding: tx=${this.#version}${relationOid} table=${update.relation.schema}.${update.relation.name} column=${binding?.[0] ?? 'unknown'}${binding?.[1] ? ` ${binding[1]}` : ''}`,\n {cause: e},\n );\n error.name = 'OversizedUpdateBindingError';\n throw error;\n }\n }\n\n processDelete(del: MessageDelete) {\n const table = liteTableName(del.relation);\n const tableSpec = this.#tableSpec(table);\n if (!this.#keyColumns(del.relation)?.length) {\n const {where, params} = this.#matchRowWithoutKey(\n table,\n liteRow(del.key, tableSpec, this.#jsonFormat),\n );\n this.#db.run(`DELETE FROM ${id(table)} WHERE ${where}`, params);\n return;\n }\n const rowKey = this.#getKey(\n liteRow(del.key, tableSpec, this.#jsonFormat),\n del,\n );\n if (this.#lacksKey(table, rowKey)) {\n this.#deleteRowLackingKey(table, rowKey, tableSpec.backfilling);\n return;\n }\n\n this.#delete(table, rowKey);\n this.#logDeleteOp(table, rowKey, tableSpec.backfilling);\n }\n\n // A replica written before these rows were skipped can still hold one: with\n // a NULL in its key for a NaN, or the infinite number itself. It is removed\n // when its upstream row changes. Upstream has at most one row with a given\n // key, so every match is a copy of it.\n #deleteRowLackingKey(\n table: string,\n rowKey: LiteRowKey,\n backfilling: string[] | undefined,\n ) {\n const conds: string[] = [];\n const params: LiteValueType[] = [];\n for (const [col, v] of Object.entries(rowKey)) {\n if (v === null || Number.isNaN(v)) {\n conds.push(`${id(col)} IS NULL`);\n } else {\n conds.push(`${id(col)}=?`);\n params.push(v);\n }\n }\n this.#db.run(\n `DELETE FROM ${id(table)} WHERE ${conds.join(' AND ')}`,\n params,\n );\n // The change log entry of such a row has a null for these values, so no\n // reader can find the row by it. The entry of a delete is skipped by\n // them, where that of the insert or update it replaces is an error. It is\n // written whether or not the row was still there, as an earlier version\n // may have removed the row and left its entry.\n this.#logDeleteOp(table, rowKey, backfilling);\n }\n\n #delete(table: string, rowKey: LiteRowKey) {\n const conds = Object.keys(rowKey).map(col => `${id(col)}=?`);\n this.#db.run(\n `DELETE FROM ${id(table)} WHERE ${conds.join(' AND ')}`,\n Object.values(rowKey),\n );\n }\n\n processTruncate(truncate: MessageTruncate) {\n for (const relation of truncate.relations) {\n const table = liteTableName(relation);\n // Update replica data.\n this.#db.run(`DELETE FROM ${id(table)}`);\n\n // Update change log.\n this.#logTruncateOp(table);\n }\n }\n\n processCreateTable(create: TableCreate) {\n if (create.metadata) {\n this.#tableMetadata.setUpstreamMetadata(create.spec, create.metadata);\n }\n this.#backfilling.apply(create);\n const table = mapPostgresToLite(create.spec);\n this.#db.db.exec(createLiteTableStatement(table));\n\n // Write to metadata table\n for (const [colName, colSpec] of Object.entries(create.spec.columns)) {\n this.#columnMetadata.insert(\n table.name,\n colName,\n colSpec,\n create.backfill?.[colName],\n );\n }\n\n this.#logResetOp(table.name);\n this.#lc.info?.(create.tag, table.name);\n }\n\n processTableMetadata(msg: TableUpdateMetadata) {\n this.#tableMetadata.setUpstreamMetadata(msg.table, msg.new);\n // Inert today: the fold's only op for this tag is `upsert-metadata`, which\n // the line above is the replica's interpreter of. Called anyway so that\n // every site that hands a schema change to one cookie tracker hands it to\n // both -- an exception here would be a schema change the shared fold has an\n // opinion about and this store never sees, which is the drift the fold\n // exists to make impossible.\n this.#backfilling.apply(msg);\n }\n\n processRenameTable(rename: TableRename) {\n this.#tableMetadata.rename(rename.old, rename.new);\n this.#backfilling.apply(rename);\n\n const oldName = liteTableName(rename.old);\n const newName = liteTableName(rename.new);\n if (oldName.toLowerCase() === newName.toLowerCase()) {\n // SQLite ignores case, and would take this for a table that exists.\n const tmpName = `tmp.${newName}`;\n this.#db.db.exec(`ALTER TABLE ${id(oldName)} RENAME TO ${id(tmpName)}`);\n this.#db.db.exec(`ALTER TABLE ${id(tmpName)} RENAME TO ${id(newName)}`);\n } else {\n this.#db.db.exec(`ALTER TABLE ${id(oldName)} RENAME TO ${id(newName)}`);\n }\n\n // Rename in metadata table\n this.#columnMetadata.renameTable(oldName, newName);\n\n this.#bumpVersions(rename.new);\n this.#logResetOp(oldName);\n this.#lc.info?.(rename.tag, oldName, newName);\n }\n\n processAddColumn(msg: ColumnAdd) {\n if (msg.tableMetadata) {\n this.#tableMetadata.setUpstreamMetadata(msg.table, msg.tableMetadata);\n }\n this.#backfilling.apply(msg);\n const table = liteTableName(msg.table);\n const {name} = msg.column;\n const spec = mapPostgresToLiteColumn(table, msg.column);\n this.#db.db.exec(\n `ALTER TABLE ${id(table)} ADD ${id(name)} ${liteColumnDef(spec)}`,\n );\n\n // Write to metadata table\n this.#columnMetadata.insert(table, name, msg.column.spec, msg.backfill);\n\n if (msg.backfill) {\n this.#reloadTableSpecs();\n } else {\n // Make the new column visible immediately if it's not being backfilled.\n // Otherwise, the version bump will happen with the backfill is complete.\n this.#bumpVersions(msg.table);\n }\n this.#lc.info?.(msg.tag, table, msg.column);\n }\n\n processUpdateColumn(msg: ColumnUpdate) {\n // A no-op unless this is a rename, which is the only part of a column\n // update that moves the backfill cookie.\n this.#backfilling.apply(msg);\n\n const table = liteTableName(msg.table);\n let oldName = msg.old.name;\n const newName = msg.new.name;\n\n const storageTypesDiffer = differentStorageTypes(\n msg.old.spec,\n msg.new.spec,\n );\n\n // If neither the column name nor the SQLite data type changes, only the\n // upstream metadata needs to be updated. This includes changes such as a\n // varchar character limit and nullability, which SQLite does not enforce\n // but a freshly built replica still records.\n if (oldName === newName && !storageTypesDiffer) {\n this.#columnMetadata.update(\n table,\n msg.old.name,\n msg.new.name,\n msg.new.spec,\n );\n if (Boolean(msg.old.spec.notNull) !== Boolean(msg.new.spec.notNull)) {\n this.#bumpVersions(msg.table);\n }\n this.#lc.info?.(msg.tag, 'updated metadata only', msg.old, msg.new);\n return;\n }\n // Storage type changes require a new column so that SQLite uses the new\n // representation for existing and future values.\n if (storageTypesDiffer) {\n // update-column can ignore defaults because it does not change the values\n // in existing rows.\n //\n // https://www.postgresql.org/docs/current/sql-altertable.html#SQL-ALTERTABLE-DESC-SET-DROP-DEFAULT\n //\n // \"The new default value will only apply in subsequent INSERT or UPDATE\n // commands; it does not cause rows already in the table to change.\"\n //\n // This allows support for _changing_ column defaults to any expression,\n // since it does not affect what the replica needs to do.\n const newLiteSpec = mapPostgresToLiteColumn(\n table,\n msg.new,\n 'ignore-default',\n );\n if (oldName !== newName) {\n // Rename the column in place first so that SQLite rewrites every\n // reference to it in the table's index definitions, including the\n // WHERE clauses of partial indexes.\n this.#db.db.exec(\n `ALTER TABLE ${id(table)} RENAME ${id(oldName)} TO ${id(newName)}`,\n );\n oldName = newName;\n }\n const tableSpec = must(\n listTables(this.#db.db, false, false).find(\n tableSpec => tableSpec.name === table,\n ),\n );\n // Recreating the table drops its indexes, so capture their DDL to\n // replay afterwards. Auto-indexes (PRIMARY KEY) have no DDL and are\n // recreated by the CREATE TABLE statement itself.\n const indexDDL = this.#db.db\n .prepare(\n `SELECT sql FROM sqlite_master\n WHERE type = 'index' AND tbl_name = ? AND sql IS NOT NULL\n ORDER BY rowid`,\n )\n .all<{sql: string}>(table)\n .map(({sql}) => sql);\n const tmpTable = `tmp.${table}`;\n const columns = Object.keys(tableSpec.columns);\n const stmts = [\n createLiteTableStatement({\n ...tableSpec,\n name: tmpTable,\n columns: mapEntries(tableSpec.columns, (column, spec) => [\n column,\n column === newName ? {...newLiteSpec, pos: spec.pos} : spec,\n ]),\n }),\n `INSERT INTO ${id(tmpTable)} (${columns.map(id).join(',')})\n SELECT ${columns.map(id).join(',')} FROM ${id(table)};`,\n `DROP TABLE ${id(table)};`,\n `ALTER TABLE ${id(tmpTable)} RENAME TO ${id(table)};`,\n ...indexDDL.map(sql => `${sql};`),\n ];\n this.#db.db.exec(stmts.join(''));\n }\n if (oldName !== newName) {\n this.#db.db.exec(\n `ALTER TABLE ${id(table)} RENAME ${id(oldName)} TO ${id(newName)}`,\n );\n }\n\n // Update metadata table\n this.#columnMetadata.update(\n table,\n msg.old.name,\n msg.new.name,\n msg.new.spec,\n );\n\n this.#bumpVersions(msg.table);\n this.#lc.info?.(msg.tag, table, msg.new);\n }\n\n processDropColumn(msg: ColumnDrop) {\n const table = liteTableName(msg.table);\n const {column} = msg;\n this.#db.db.exec(`ALTER TABLE ${id(table)} DROP ${id(column)}`);\n\n // Delete from metadata table\n this.#columnMetadata.deleteColumn(table, column);\n this.#backfilling.apply(msg);\n\n this.#bumpVersions(msg.table);\n this.#lc.info?.(msg.tag, table, column);\n }\n\n processDropTable(drop: TableDrop) {\n this.#tableMetadata.drop(drop.id);\n this.#backfilling.apply(drop);\n\n const name = liteTableName(drop.id);\n this.#db.db.exec(`DROP TABLE IF EXISTS ${id(name)}`);\n\n // Delete from metadata table\n this.#columnMetadata.deleteTable(name);\n\n this.#logResetOp(name);\n this.#lc.info?.(drop.tag, name);\n }\n\n processCreateIndex(create: IndexCreate) {\n const index = mapPostgresToLiteIndex(create.spec);\n createLiteIndex(this.#lc, this.#db.db, index);\n\n // indexes affect tables visibility (e.g. sync-ability is gated on\n // having a unique index), so reset pipelines to refresh table schemas.\n this.#logResetOp(index.tableName);\n this.#lc.info?.(create.tag, index.name);\n }\n\n processDropIndex(drop: IndexDrop) {\n const name = liteTableName(drop.id);\n const indexExisted = this.#db.db\n .prepare(\n `SELECT tbl_name as tableName FROM sqlite_master WHERE type = 'index' AND name = ?`,\n )\n .get(name) as {tableName: string} | undefined;\n\n this.#db.db.exec(`DROP INDEX IF EXISTS ${id(name)}`);\n\n if (indexExisted) {\n // indexes affect tables visibility (e.g. sync-ability is gated on\n // having a unique index), so reset pipelines to refresh table schemas.\n this.#logResetOp(indexExisted.tableName);\n }\n this.#lc.info?.(drop.tag, name);\n }\n\n #bumpVersions(table: Identifier) {\n this.#tableMetadata.setMinRowVersion(table, this.#version);\n this.#logResetOp(liteTableName(table));\n }\n\n /**\n * @param backfilledColumns `backfilling` columns for which values were set\n */\n #logSetOp(\n table: string,\n key: LiteRowKey,\n backfilledColumns: string[] | undefined,\n ) {\n // The \"serving\" replicator always writes to the change-log (for IVM).\n // The \"backup\" replicator only needs to write to the change log\n // when writing columns that are being backfilled.\n if (this.#mode === 'serving' || backfilledColumns !== undefined) {\n this.#changeLog.logSetOp(\n this.#version,\n this.#pos++,\n table,\n key,\n backfilledColumns,\n );\n this.#numChangeLogEntries++;\n }\n }\n\n #logDeleteOp(table: string, key: LiteRowKey, backfilling?: string[]) {\n // The \"serving\" replicator always writes to the change-log (for IVM).\n // The \"backup\" replicator only needs to write to the change log\n // when writing columns that are being backfilled.\n if (this.#mode === 'serving' || backfilling?.length) {\n this.#changeLog.logDeleteOp(this.#version, this.#pos++, table, key);\n this.#numChangeLogEntries++;\n }\n }\n\n #logTruncateOp(table: string) {\n if (this.#mode === 'serving') {\n this.#changeLog.logTruncateOp(this.#version, table);\n this.#numChangeLogEntries++;\n }\n }\n\n #logResetOp(table: string) {\n this.#schemaChanged = true;\n if (this.#mode === 'serving') {\n this.#changeLog.logResetOp(this.#version, table);\n this.#numChangeLogEntries++;\n }\n this.#reloadTableSpecs();\n }\n\n processBackfill({\n relation,\n watermark,\n columns,\n rowValues,\n progressMarks,\n }: MessageBackfill) {\n const tableName = liteTableName(relation);\n const tableSpec = must(this.#tableSpecs.get(tableName));\n const rowKeyCols = relation.rowKey.columns;\n const cols = [...rowKeyCols, ...columns];\n\n // Only columns that are still being backfilled on _this_ replica are\n // written, and of those, only the columns for which this message is\n // contiguous with the data received so far (whose progress is advanced).\n //\n // * Once a column has been published (backfill completed), its values\n // strictly follow the replication timeline, so a subsequent backfill must\n // never overwrite them. This guards against a redundant backfill, e.g.\n // when the view-syncer (re)connects to a replication-manager that is\n // (re)running a backfill this replica already completed.\n // * Data for non-contiguous (ignored) columns is necessarily re-delivered\n // (by a resumed or from-scratch run) before the column can be published,\n // so writing it would be wasted I/O.\n const {accepted, ignored} = this.#trackBackfillProgress(\n relation,\n cols,\n own => acceptBackfill(own, progressMarks),\n );\n if (accepted.length === 0) {\n this.#lc.debug?.(\n ignored.length\n ? `skipping backfill of ${rowValues.length} rows into ` +\n `${tableName}: not contiguous with the progress of columns ` +\n `[${ignored.join(',')}]`\n : `skipping redundant backfill of ${rowValues.length} rows into ` +\n `${tableName} (all columns already published)`,\n progressMarks,\n );\n return;\n }\n if (ignored.length) {\n this.#lc.debug?.(\n `backfill of ${tableName} is not contiguous with the progress ` +\n `of columns [${ignored.join(',')}]`,\n progressMarks,\n );\n }\n const acceptedSet = new Set(accepted);\n\n // Common parts of the INSERT sql statement.\n const insertColsStr = [...cols, ZERO_VERSION_COLUMN_NAME].map(id).join(',');\n const qMarks = Array.from({length: cols.length + 1})\n .fill('?')\n .join(',');\n const rowKeyColsStr = rowKeyCols.map(id).join(',');\n\n let backfilled = 0;\n let skipped = 0;\n for (const v of rowValues) {\n const row = liteRow(\n Object.fromEntries(cols.map((c, i) => [c, v[i]])),\n tableSpec,\n this.#jsonFormat,\n );\n const rowKey = this.#getKey(row, {relation});\n if (this.#lacksKey(tableName, rowKey)) {\n // An earlier version may have left the row or its entry.\n this.#deleteRowLackingKey(tableName, rowKey, tableSpec.backfilling);\n skipped++;\n continue;\n }\n const rowOp = this.#changeLog.getLatestRowOp(tableName, rowKey);\n if (rowOp?.op === DEL_OP && rowOp.stateVersion > watermark) {\n skipped++;\n continue; // the row was deleted after the backfill snapshot\n }\n // Restrict the DO UPDATE columns to those still being backfilled. Never\n // update an already backfilled (i.e. published) column.\n const updates = (\n rowOp?.op === SET_OP\n ? cols.filter(\n c => (rowOp.backfillingColumnVersions[c] ?? '') <= watermark,\n )\n : cols\n ).filter(c => acceptedSet.has(c));\n if (updates.length === 0) {\n // row already has newer values for all accepted backfilling columns.\n skipped++;\n continue;\n }\n const updateStmts = updates.map(col => `${id(col)}=excluded.${id(col)}`);\n this.#db.run(\n /*sql*/ `\n INSERT INTO ${id(tableName)} (${insertColsStr}) VALUES (${qMarks})\n ON CONFLICT (${rowKeyColsStr})\n DO UPDATE SET ${updateStmts.join(',')};\n `,\n ...Object.values(row.row),\n watermark, // the _0_version for new rows (i.e. table backfill)\n );\n backfilled++;\n }\n\n this.#lc.debug?.(\n `backfilled ${backfilled} rows (skipped ${skipped}) into ${tableName}`,\n );\n }\n\n #completedBackfill: DownloadStatus | undefined;\n\n /**\n * Applies `accept` to the tracked progress of each of the `cols` that are\n * still backfilling on this replica, updating the progress of the accepted\n * ones. Columns that are not backfilling (e.g. already published) are\n * neither accepted nor ignored.\n */\n #trackBackfillProgress(\n relation: Identifier,\n cols: readonly string[],\n accept: (progress: BackfillProgressMark | undefined) => AcceptResult,\n ): {accepted: string[]; ignored: string[]} {\n const tracked = this.#backfilling.getProgress(relation);\n const accepted: string[] = [];\n const ignored: string[] = [];\n for (const col of cols) {\n if (!tracked.has(col)) {\n continue; // not backfilling\n }\n const progress = tracked.get(col);\n const result = accept(progress);\n if (!result.accept) {\n ignored.push(col);\n continue;\n }\n accepted.push(col);\n if (!deepEqual(result.progress, progress)) {\n this.#backfilling.setProgress(relation, col, result.progress);\n }\n }\n return {accepted, ignored};\n }\n\n processBackfillCompleted(msg: BackfillCompleted) {\n const {relation, columns, status, progressMarks} = msg;\n const tableName = liteTableName(relation);\n const rowKeyCols = relation.rowKey.columns;\n\n // Only complete the columns whose backfill progress is contiguous with\n // the completed backfill. The others remain backfilling (and will be\n // re-requested by the change-streamer).\n const {accepted, ignored} = this.#trackBackfillProgress(\n relation,\n [...rowKeyCols, ...columns],\n own =>\n acceptBackfill(\n own,\n progressMarks ? {previous: progressMarks.previous} : undefined,\n ),\n );\n if (ignored.length) {\n this.#lc.info?.(\n `ignoring backfill-completed of ${tableName} for columns ` +\n `[${ignored.join(',')}], which have not received all of the data`,\n progressMarks,\n );\n }\n\n // If none of the columns are still backfilling on this replica, they were\n // already published (e.g. a redundant backfill from a replication-manager\n // re-running a backfill this replica already completed). Bumping versions\n // again would spuriously reset pipelines and re-report completion, so treat\n // the completion as a no-op.\n if (accepted.length === 0) {\n if (ignored.length === 0) {\n this.#lc.debug?.(\n `skipping redundant backfill-completed for ${tableName} ` +\n `(all columns already published)`,\n );\n }\n return;\n }\n const ignoredSet = new Set(ignored);\n const cols = [\n ...rowKeyCols.filter(c => !ignoredSet.has(c)),\n ...columns.filter(c => !ignoredSet.has(c)),\n ];\n\n const columnMetadata = must(ColumnMetadataStore.getInstance(this.#db.db));\n for (const col of cols) {\n columnMetadata.clearBackfilling(tableName, col);\n }\n this.#backfilling.complete(relation, cols);\n // Given that new columns are being exposed for every row in the table, bump the\n // row version for all rows.\n this.#bumpVersions(relation);\n if (status) {\n this.#completedBackfill = {table: tableName, columns: cols, ...status};\n }\n this.#lc.info?.(`finished backfilling ${tableName}`);\n\n // Note that there is no need to clear the backfillingColumnVersions values\n // in the changeLog. It could theoretically be done for clarity but:\n // (1) it could be non-trivial in terms of latency introduced and\n // (2) the data must be preserved if _other_ columns are in the process\n // of being backfilled\n //\n // Thus, for speed and simplicity, the values are left as is. (Note that\n // subsequent replicated changes to those rows will clear the values if\n // no backfills are in progress).\n }\n\n processCommit(commit: MessageCommit, watermark: string): CommitResult {\n if (watermark !== this.#version) {\n throw new Error(\n `'commit' version ${watermark} does not match 'begin' version ${\n this.#version\n }: ${stringify(commit)}`,\n );\n }\n updateReplicationWatermark(this.#db, watermark);\n\n if (this.#schemaChanged) {\n const start = Date.now();\n this.#db.db.pragma('optimize');\n this.#lc.info?.(\n `PRAGMA optimized after schema change (${Date.now() - start} ms)`,\n );\n }\n\n if (this.#mode !== 'initial-sync') {\n this.#commit();\n }\n\n const elapsedMs = Date.now() - this.#startMs;\n this.#lc.debug?.(`Committed tx@${this.#version} (${elapsedMs} ms)`);\n\n return {\n watermark,\n completedBackfill: this.#completedBackfill,\n schemaUpdated: this.#schemaChanged,\n changeLogUpdated: this.#numChangeLogEntries > 0,\n upstreamCommitTimeMs: commit.commitTimeMs,\n };\n }\n\n /**\n * A wal2 `COMMIT` can fail with SQLITE_BUSY, without consulting the\n * busy_timeout, if it switches wal files just as the `ServingCheckpointer`\n * briefly locks the file it is switching to: the writer releases its locks\n * on that file before taking the read lock that it needs on it. The\n * transaction stays open and the switch has already happened, so the next\n * attempt does not contend for that lock.\n *\n * No backoff is needed between attempts: the retry does not switch files\n * again, so it never asks for the contended lock, whether or not the\n * checkpointer still holds it. A second failure has some other cause.\n *\n * This is a workaround for a bug in SQLite's wal2 branch (in\n * `walRestartLog()`), reported at\n * https://sqlite.org/forum/forumpost/63ba0208a66aa7139119b56edb43a416b160ca1996a23de2b0da24ca48fb9b3a.\n * The retry runs without the read lock the failed attempt meant to take.\n * Remove it once zero-sqlite3 includes a fix.\n */\n #commit() {\n for (let attempt = 1; ; attempt++) {\n try {\n this.#db.commit();\n return;\n } catch (e) {\n if (\n attempt === MAX_COMMIT_ATTEMPTS ||\n !(e instanceof SqliteError && e.code === 'SQLITE_BUSY')\n ) {\n throw e;\n }\n this.#lc.warn?.(`SQLITE_BUSY on COMMIT (attempt ${attempt})`, e);\n }\n }\n }\n\n abort(lc: LogContext) {\n lc.info?.(`aborting transaction ${this.#version}`);\n this.#db.rollback();\n // A schema change in the transaction reloaded the table specs, which now\n // describe the schema that the rollback undid. Clearing them makes the\n // next transaction reload them from the database.\n this.#tableSpecs.clear();\n }\n}\n\nfunction differentStorageTypes(\n oldSpec: ColumnSpec,\n newSpec: ColumnSpec,\n): boolean {\n return (\n oldSpec.dataType !== newSpec.dataType ||\n isEnumColumn(oldSpec) !== isEnumColumn(newSpec) ||\n isArrayColumn(oldSpec) !== isArrayColumn(newSpec)\n );\n}\n\nfunction getBackfilledColumns(\n row: LiteRow,\n {backfilling}: LiteTableSpecWithReplicationStatus,\n): string[] | undefined {\n if (!backfilling?.length) {\n return undefined; // common case\n }\n return backfilling.filter(col => col in row);\n}\n\nfunction oversizedValueDescription(value: LiteValueType): string | undefined {\n const sizeBytes =\n typeof value === 'string'\n ? Buffer.byteLength(value)\n : value instanceof Uint8Array\n ? value.byteLength\n : undefined;\n if (sizeBytes !== undefined && sizeBytes > MAX_SQLITE_BIND_BYTES) {\n const valueType = typeof value === 'string' ? 'string' : 'buffer';\n return `valueType=${valueType} sizeBytes=${sizeBytes} limitBytes=${MAX_SQLITE_BIND_BYTES}`;\n }\n\n return undefined;\n}\n\n/** Runs `fn`, returning its error rather than throwing it. */\nfunction attempt(fn: () => void): unknown {\n try {\n fn();\n return undefined;\n } catch (e) {\n return e ?? new Error('rollback failed');\n }\n}\n\nfunction ensureError(err: unknown): Error {\n if (err instanceof Error) {\n return err;\n }\n const error = new Error();\n error.cause = err;\n return error;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAiFA,IAAM,sBAAsB;AAE5B,IAAM,2BACJ;AACF,IAAM,wBAAwB,KAAK,IACjCA,UAAgB,YAChBA,UAAgB,iBAClB;;;;;;;;;;;;AA0BA,IAAa,kBAAb,MAA6B;CAC3B;CACA;CACA;CACA;CACA;CACA;CAKA,8BAAuB,IAAI,IAAgD;CAE3E,aAA0C;CAE1C;CAEA,YACE,IACA,MACA,aACA;EACA,KAAK,MAAM;EACX,KAAK,aAAa,IAAI,UAAU,GAAG,EAAE;EACrC,KAAK,iBAAiB,IAAI,qBAAqB,GAAG,EAAE;EACpD,KAAK,eAAe,IAAI,mBAAmB,GAAG,EAAE;EAChD,KAAK,QAAQ;EACb,KAAK,eAAe;CACtB;CAEA,MAAM,IAAgB,KAAc;EAClC,IAAI,CAAC,KAAK,UAAU;GAClB,IAAI,eAAe;GACnB,MAAM,iBAAiB,CAAC,cAAc,KAAK,YAAY,MAAM,EAAE,CAAC,CAAC,CAAC,CAAC,QACjE,MAAK,MAAM,KAAA,CACb;GAEA,IAAI,eAAe,QAAQ;IACzB,MAAM,gCAAgB,IAAI,MACxB,yEAAyE,OAAO,GAAG,EAAE,qBAAqB,eAAe,IAAI,MAAM,CAAC,CAAC,KAAK,IAAI,GAChJ;IACA,cAAc,QAAQ;IACtB,eAAe;GACjB;GAEA,KAAK,WAAW,YAAY,YAAY;GAExC,IAAI,EAAE,KAAK,oBAAoB,aAAa;IAE1C,GAAG,QAAQ,8BAA8B,KAAK,QAAQ;IACtD,KAAK,aAAa,IAAI,KAAK,QAAQ;GACrC;EACF;CACF;CAEA,MAAM,IAAgB;EACpB,KAAK,MAAM,IAA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AS,qBACP,KACA,EAAC,eACqB;CACtB,IAAI,CAAC,aAAa,QAChB;CAEF,OAAO,YAAY,QAAO,QAAO,OAAO,GAAG;AAC7C;AAEA,SAAS,0BAA0B,OAA0C;CAC3E,MAAM,YACJ,OAAO,UAAU,WACb,OAAO,WAAW,KAAK,IACvB,iBAAiB,aACf,MAAM,aACN,KAAA;CACR,IAAI,cAAc,KAAA,KAAa,YAAY,uBAEzC,OAAO,aADW,OAAO,UAAU,WAAW,WAAW,SAC3B,aAAa,UAAU,cAAc;AAIvE;;AAGA,SAAS,QAAQ,IAAyB;CACxC,IAAI;EACF,GAAG;EACH;CACF,SAAS,GAAG;EACV,OAAO,qBAAK,IAAI,MAAM,iBAAiB;CACzC;AACF;AAEA,SAAS,YAAY,KAAqB;CACxC,IAAI,eAAe,OACjB,OAAO;CAET,MAAM,wBAAQ,IAAI,MAAM;CACxB,MAAM,QAAQ;CACd,OAAO;AACT"}
1
+ {"version":3,"file":"change-processor.js","names":["bufferConstants"],"sources":["../../../../../../zero-cache/src/services/replicator/change-processor.ts"],"sourcesContent":["import {constants as bufferConstants} from 'node:buffer';\nimport type {LogContext} from '@rocicorp/logger';\nimport {SqliteError} from '@rocicorp/zero-sqlite3';\nimport {AbortError} from '../../../../shared/src/abort-error.ts';\nimport {assert, unreachable} from '../../../../shared/src/asserts.ts';\nimport {stringify} from '../../../../shared/src/bigint-json.ts';\nimport {deepEqual} from '../../../../shared/src/json.ts';\nimport {must} from '../../../../shared/src/must.ts';\nimport {assignProperty} from '../../../../shared/src/objects.ts';\nimport {mapEntries} from '../../../../shared/src/objects.ts';\nimport type {DownloadStatus} from '../../../../zero-events/src/status.ts';\nimport {\n createLiteIndex,\n createLiteTableStatement,\n liteColumnDef,\n} from '../../db/create.ts';\nimport {\n computeZqlSpecs,\n listTables,\n type LiteTableSpecWithReplicationStatus,\n} from '../../db/lite-tables.ts';\nimport {\n isArrayColumn,\n isEnumColumn,\n mapPostgresToLite,\n mapPostgresToLiteColumn,\n mapPostgresToLiteIndex,\n} from '../../db/pg-to-lite.ts';\nimport type {ColumnSpec} from '../../db/specs.ts';\nimport type {StatementRunner} from '../../db/statements.ts';\nimport type {LexiVersion} from '../../types/lexi-version.ts';\nimport {\n isUnusableKeyValue,\n JSON_PARSED,\n liteRow,\n type JSONFormat,\n type LiteRow,\n type LiteRowKey,\n type LiteValueType,\n} from '../../types/lite.ts';\nimport {liteTableName} from '../../types/names.ts';\nimport {id} from '../../types/sql.ts';\nimport {\n acceptBackfill,\n type AcceptResult,\n} from '../change-source/protocol/backfill-progress.ts';\nimport type {\n BackfillCompleted,\n BackfillProgressMark,\n Change,\n ColumnAdd,\n ColumnDrop,\n ColumnUpdate,\n Identifier,\n IndexCreate,\n IndexDrop,\n MessageBackfill,\n MessageCommit,\n MessageDelete,\n MessageInsert,\n MessageRelation,\n MessageTruncate,\n MessageUpdate,\n TableCreate,\n TableDrop,\n TableRename,\n TableUpdateMetadata,\n} from '../change-source/protocol/current/data.ts';\nimport type {ChangeStreamData} from '../change-source/protocol/current/downstream.ts';\nimport type {ReplicatorMode} from './replicator.ts';\nimport {BackfillingTracker} from './schema/backfilling.ts';\nimport {ChangeLog, DEL_OP, SET_OP} from './schema/change-log.ts';\nimport {ColumnMetadataStore} from './schema/column-metadata.ts';\nimport {\n ZERO_VERSION_COLUMN_NAME,\n updateReplicationWatermark,\n} from './schema/replication-state.ts';\nimport {TableMetadataTracker} from './schema/table-metadata.ts';\n\nexport type ChangeProcessorMode = ReplicatorMode | 'initial-sync';\n\nconst BIND_VALUE_TOO_BIG_ERROR =\n 'The bound string, buffer, or bigint is too big';\nconst MAX_SQLITE_BIND_BYTES = Math.min(\n bufferConstants.MAX_LENGTH,\n bufferConstants.MAX_STRING_LENGTH,\n);\n\nexport type CommitResult = {\n watermark: string;\n completedBackfill: DownloadStatus | undefined;\n schemaUpdated: boolean;\n changeLogUpdated: boolean;\n /**\n * Millisecond epoch at which the transaction committed upstream, if the\n * ChangeSource reported one. Propagated to ViewSyncers as the origin\n * timestamp of the end-to-end serving lag measurement.\n */\n upstreamCommitTimeMs?: number | undefined;\n};\n\n/**\n * The ChangeProcessor partitions the stream of messages into transactions\n * by creating a {@link TransactionProcessor} when a transaction begins, and dispatching\n * messages to it until the commit is received.\n *\n * From https://www.postgresql.org/docs/current/protocol-logical-replication.html#PROTOCOL-LOGICAL-MESSAGES-FLOW :\n *\n * \"The logical replication protocol sends individual transactions one by one.\n * This means that all messages between a pair of Begin and Commit messages\n * belong to the same transaction.\"\n */\nexport class ChangeProcessor {\n readonly #db: StatementRunner;\n readonly #changeLog: ChangeLog;\n readonly #tableMetadata: TableMetadataTracker;\n readonly #backfilling: BackfillingTracker;\n readonly #mode: ChangeProcessorMode;\n readonly #failService: (lc: LogContext, err: unknown) => void;\n\n // The TransactionProcessor lazily loads table specs into this Map,\n // and reloads them after a schema change. It is cached here to avoid\n // reading them from the DB on every transaction.\n readonly #tableSpecs = new Map<string, LiteTableSpecWithReplicationStatus>();\n\n #currentTx: TransactionProcessor | null = null;\n\n #failure: Error | undefined;\n\n constructor(\n db: StatementRunner,\n mode: ChangeProcessorMode,\n failService: (lc: LogContext, err: unknown) => void,\n ) {\n this.#db = db;\n this.#changeLog = new ChangeLog(db.db);\n this.#tableMetadata = new TableMetadataTracker(db.db);\n this.#backfilling = new BackfillingTracker(db.db);\n this.#mode = mode;\n this.#failService = failService;\n }\n\n #fail(lc: LogContext, err: unknown) {\n if (!this.#failure) {\n let failureError = err;\n const rollbackErrors = [attempt(() => this.#currentTx?.abort(lc))].filter(\n e => e !== undefined,\n );\n\n if (rollbackErrors.length) {\n const combinedError = new Error(\n `Message processing failed and rollback also failed: operation error = ${String(err)}; rollback error = ${rollbackErrors.map(String).join('; ')}`,\n );\n combinedError.cause = err;\n failureError = combinedError;\n }\n\n this.#failure = ensureError(failureError);\n\n if (!(this.#failure instanceof AbortError)) {\n // Propagate the failure up to the service.\n lc.error?.('Message Processing failed:', this.#failure);\n this.#failService(lc, this.#failure);\n }\n }\n }\n\n abort(lc: LogContext) {\n this.#fail(lc, new AbortError());\n }\n\n /** @return If a transaction was committed. */\n processMessage(\n lc: LogContext,\n downstream: ChangeStreamData,\n ): CommitResult | null {\n const [type, message] = downstream;\n if (this.#failure) {\n lc.debug?.(`Dropping ${message.tag}`);\n return null;\n }\n try {\n const watermark =\n type === 'begin'\n ? downstream[2].commitWatermark\n : type === 'commit'\n ? downstream[2].watermark\n : undefined;\n return this.#processMessage(lc, message, watermark);\n } catch (e) {\n this.#fail(lc, e);\n }\n return null;\n }\n\n #beginTransaction(\n lc: LogContext,\n commitVersion: string,\n jsonFormat: JSONFormat,\n ): TransactionProcessor {\n const start = Date.now();\n\n // litestream can technically hold the lock for an arbitrary amount of time\n // when checkpointing a large commit. Crashing on the busy-timeout in this\n // scenario will either produce a corrupt backup or otherwise prevent\n // replication from proceeding.\n //\n // Instead, retry the lock acquisition indefinitely. If this masks\n // an unknown deadlock situation, manual intervention will be necessary.\n for (let i = 0; ; i++) {\n try {\n return new TransactionProcessor(\n lc,\n this.#db,\n this.#mode,\n this.#changeLog,\n this.#tableMetadata,\n this.#backfilling,\n this.#tableSpecs,\n commitVersion,\n jsonFormat,\n );\n } catch (e) {\n if (e instanceof SqliteError && e.code === 'SQLITE_BUSY') {\n lc.warn?.(\n `SQLITE_BUSY for ${Date.now() - start} ms (attempt ${i + 1}). ` +\n `This is only expected if litestream is performing a large ` +\n `checkpoint.`,\n e,\n );\n continue;\n }\n throw e;\n }\n }\n }\n\n /** @return If a transaction was committed. */\n #processMessage(\n lc: LogContext,\n msg: Change,\n watermark: string | undefined,\n ): CommitResult | null {\n if (msg.tag === 'begin') {\n if (this.#currentTx) {\n throw new Error(`Already in a transaction ${stringify(msg)}`);\n }\n this.#currentTx = this.#beginTransaction(\n lc,\n must(watermark),\n msg.json ?? JSON_PARSED,\n );\n return null;\n }\n\n // For non-begin messages, there should be a #currentTx set.\n const tx = this.#currentTx;\n if (!tx) {\n throw new Error(\n `Received message outside of transaction: ${stringify(msg)}`,\n );\n }\n\n if (msg.tag === 'commit') {\n assert(watermark, 'watermark is required for commit messages');\n const result = tx.processCommit(msg, watermark);\n // Clear only after a successful commit so #fail can roll back a commit\n // path that throws before SQLite has committed.\n this.#currentTx = null;\n return result;\n }\n\n if (msg.tag === 'rollback') {\n tx.abort(lc);\n this.#currentTx = null;\n return null;\n }\n\n switch (msg.tag) {\n case 'insert':\n tx.processInsert(msg);\n break;\n case 'update':\n tx.processUpdate(msg);\n break;\n case 'delete':\n tx.processDelete(msg);\n break;\n case 'truncate':\n tx.processTruncate(msg);\n break;\n case 'create-table':\n tx.processCreateTable(msg);\n break;\n case 'rename-table':\n tx.processRenameTable(msg);\n break;\n case 'update-table-metadata':\n tx.processTableMetadata(msg);\n break;\n case 'add-column':\n tx.processAddColumn(msg);\n break;\n case 'update-column':\n tx.processUpdateColumn(msg);\n break;\n case 'drop-column':\n tx.processDropColumn(msg);\n break;\n case 'drop-table':\n tx.processDropTable(msg);\n break;\n case 'create-index':\n tx.processCreateIndex(msg);\n break;\n case 'drop-index':\n tx.processDropIndex(msg);\n break;\n case 'backfill':\n tx.processBackfill(msg);\n break;\n case 'backfill-completed':\n tx.processBackfillCompleted(msg);\n break;\n default:\n unreachable(msg);\n }\n\n return null;\n }\n}\n\n/**\n * The {@link TransactionProcessor} handles the sequence of messages from\n * upstream, from `BEGIN` to `COMMIT` and executes the corresponding mutations\n * on the {@link postgres.TransactionSql} on the replica.\n *\n * When applying row contents to the replica, the `_0_version` column is added / updated,\n * and a corresponding entry in the `ChangeLog` is added. The version value is derived\n * from the watermark of the preceding transaction (stored as the `nextStateVersion` in the\n * `ReplicationState` table).\n *\n * Side note: For non-streaming Postgres transactions, the commitEndLsn (and thus\n * commit watermark) is available in the `begin` message, so it could theoretically\n * be used for the row version of changes within the transaction. However, the\n * commitEndLsn is not available in the streaming (in-progress) transaction\n * protocol, and may not be available for CDC streams of other upstream types.\n * Therefore, the zero replication protocol is designed to not require the commit\n * watermark when a transaction begins.\n *\n * Also of interest is the fact that all INSERT Messages are logically applied as\n * UPSERTs. See {@link processInsert} for the underlying motivation.\n */\nclass TransactionProcessor {\n readonly #lc: LogContext;\n readonly #startMs: number;\n readonly #db: StatementRunner;\n readonly #mode: ChangeProcessorMode;\n readonly #version: LexiVersion;\n readonly #changeLog: ChangeLog;\n readonly #tableMetadata: TableMetadataTracker;\n readonly #backfilling: BackfillingTracker;\n readonly #tableSpecs: Map<string, LiteTableSpecWithReplicationStatus>;\n readonly #jsonFormat: JSONFormat;\n readonly #columnMetadata: ColumnMetadataStore;\n\n #pos = 0;\n #schemaChanged = false;\n #numChangeLogEntries = 0;\n\n constructor(\n lc: LogContext,\n db: StatementRunner,\n mode: ChangeProcessorMode,\n changeLog: ChangeLog,\n tableMetadata: TableMetadataTracker,\n backfilling: BackfillingTracker,\n tableSpecs: Map<string, LiteTableSpecWithReplicationStatus>,\n commitVersion: LexiVersion,\n jsonFormat: JSONFormat,\n ) {\n this.#startMs = Date.now();\n this.#mode = mode;\n this.#jsonFormat = jsonFormat;\n\n switch (mode) {\n case 'serving':\n // This is the only transaction that commits to the serving replica.\n // Snapshotters use BEGIN CONCURRENT for private changes that are\n // always rolled back, while BEGIN IMMEDIATE lets this writer spill\n // dirty pages during large transactions.\n db.beginImmediate();\n break;\n case 'backup':\n // For the backup-replicator (i.e. replication-manager), there are no View Syncers\n // and thus BEGIN CONCURRENT is not necessary. In fact, BEGIN CONCURRENT can cause\n // deadlocks with forced wal-checkpoints (which `litestream replicate` performs),\n // so it is important to use vanilla transactions in this configuration.\n db.beginImmediate();\n break;\n case 'initial-sync':\n // When the ChangeProcessor is used for initial-sync, the calling code\n // handles the transaction boundaries.\n break;\n default:\n unreachable();\n }\n this.#db = db;\n this.#version = commitVersion;\n this.#lc = lc.withContext('version', commitVersion);\n this.#changeLog = changeLog;\n this.#tableMetadata = tableMetadata;\n this.#backfilling = backfilling;\n this.#tableSpecs = tableSpecs;\n // The column_metadata table is guaranteed to exist since the\n // replica-schema.ts migration to v8.\n this.#columnMetadata = must(ColumnMetadataStore.getInstance(db.db));\n\n if (this.#tableSpecs.size === 0) {\n this.#reloadTableSpecs();\n }\n }\n\n #reloadTableSpecs() {\n this.#tableSpecs.clear();\n // zqlSpecs include the primary key derived from unique indexes\n const zqlSpecs = computeZqlSpecs(this.#lc, this.#db.db, {\n includeBackfillingColumns: true,\n });\n for (let spec of listTables(this.#db.db)) {\n if (!spec.primaryKey) {\n spec = {\n ...spec,\n primaryKey: [\n ...(zqlSpecs.get(spec.name)?.tableSpec.primaryKey ?? []),\n ],\n };\n }\n this.#tableSpecs.set(spec.name, spec);\n }\n }\n\n #tableSpec(name: string) {\n return must(this.#tableSpecs.get(name), `Unknown table ${name}`);\n }\n\n #keyColumns(relation: MessageRelation) {\n return relation.rowKey.type !== 'full'\n ? relation.rowKey.columns // already a suitable key\n : this.#tableSpec(liteTableName(relation)).primaryKey;\n }\n\n #getKey(\n {row, numCols}: {row: LiteRow; numCols: number},\n {relation}: {relation: MessageRelation},\n ): LiteRowKey {\n const keyColumns = this.#keyColumns(relation);\n if (!keyColumns?.length) {\n throw new Error(\n `Cannot replicate table \"${relation.name}\" without a PRIMARY KEY or UNIQUE INDEX`,\n );\n }\n // For the common case (replica identity default), the row is already the\n // key for deletes and updates, in which case a new object can be avoided.\n if (numCols === keyColumns.length) {\n return row;\n }\n const key: Record<string, LiteValueType> = {};\n for (const col of keyColumns) {\n assignProperty(key, col, row[col]);\n }\n return key;\n }\n\n // A NaN has no value on the replica, where it is stored as a NULL, and an\n // infinite number has none in JSON, which is what row keys are in the\n // change log and beyond. A row with either in its key could not be matched\n // by later changes to it, so it is not replicated. (Initial sync and\n // backfills skip these rows as well.)\n #lacksKey(table: string, key: LiteRowKey): boolean {\n for (const v of Object.values(key)) {\n if (isUnusableKeyValue(v)) {\n this.#lc.warn?.(\n `Skipping a row of ${table} with a NaN or an infinite value in its key`,\n );\n return true;\n }\n }\n return false;\n }\n\n processInsert(insert: MessageInsert) {\n const table = liteTableName(insert.relation);\n const tableSpec = this.#tableSpec(table);\n const newRow = liteRow(insert.new, tableSpec, this.#jsonFormat);\n const keyed = !!this.#keyColumns(insert.relation)?.length;\n if (keyed) {\n const key = this.#getKey(newRow, insert);\n if (this.#lacksKey(table, key)) {\n // An earlier row with this key may have left a row or an entry.\n this.#deleteRowLackingKey(table, key, tableSpec.backfilling);\n return;\n }\n }\n\n this.#upsert(table, {\n ...newRow.row,\n [ZERO_VERSION_COLUMN_NAME]: this.#version,\n });\n\n if (!keyed) {\n // INSERTs can be replicated for rows without a PRIMARY KEY or a\n // UNIQUE INDEX. These are written to the replica but not recorded\n // in the changeLog, because these rows cannot participate in IVM.\n //\n // (Once the table schema has been corrected to include a key, the\n // associated schema change will reset pipelines and data can be\n // loaded via hydration.)\n return;\n }\n const key = this.#getKey(newRow, insert);\n this.#logSetOp(table, key, getBackfilledColumns(newRow.row, tableSpec));\n }\n\n // A table without a key gets UPDATEs and DELETEs only with REPLICA IDENTITY\n // FULL, which identifies a row by all of its values. Any one row with those\n // values will do, as they are interchangeable. As with INSERTs, these\n // changes are not recorded in the changeLog.\n #matchRowWithoutKey(table: string, {row}: {row: LiteRow}) {\n const conds = Object.keys(row).map(col => `${id(col)} IS ?`);\n return {\n where: `_rowid_ = (SELECT _rowid_ FROM ${id(table)} WHERE ${conds.join(' AND ')} LIMIT 1)`,\n params: Object.values(row),\n };\n }\n\n #upsert(table: string, row: LiteRow) {\n const columns = Object.keys(row).map(c => id(c));\n this.#db.run(\n `\n INSERT OR REPLACE INTO ${id(table)} (${columns.join(',')})\n VALUES (${Array.from({length: columns.length}).fill('?').join(',')})\n `,\n Object.values(row),\n );\n }\n\n // Updates by default are applied as UPDATE commands to support partial\n // row specifications from the change source. In particular, this is needed\n // to handle updates for which unchanged TOASTed values are not sent:\n //\n // https://www.postgresql.org/docs/current/protocol-logicalrep-message-formats.html#PROTOCOL-LOGICALREP-MESSAGE-FORMATS-TUPLEDATA\n //\n // However, in certain cases an UPDATE may be received for a row that\n // was not initially synced, such as when, an existing table is added\n // to the app's publication.\n //\n // In order to facilitate \"resumptive\" replication, the logic falls back to\n // an INSERT if the update did not change any rows.\n processUpdate(update: MessageUpdate) {\n const table = liteTableName(update.relation);\n const tableSpec = this.#tableSpec(table);\n const newRow = liteRow(update.new, tableSpec, this.#jsonFormat);\n const row = {...newRow.row, [ZERO_VERSION_COLUMN_NAME]: this.#version};\n\n if (update.key && !this.#keyColumns(update.relation)?.length) {\n const {where, params} = this.#matchRowWithoutKey(\n table,\n liteRow(update.key, tableSpec, this.#jsonFormat),\n );\n const setExprs = Object.keys(row).map(col => `${id(col)}=?`);\n const {changes} = this.#db.run(\n `UPDATE ${id(table)} SET ${setExprs.join(',')} WHERE ${where}`,\n [...Object.values(row), ...params],\n );\n if (changes === 0) {\n this.#upsert(table, row);\n }\n return;\n }\n\n // update.key is set with the old values if the key has changed.\n let oldKey = update.key\n ? this.#getKey(\n liteRow(update.key, this.#tableSpec(table), this.#jsonFormat),\n update,\n )\n : null;\n const newKey = this.#getKey(newRow, update);\n\n if (oldKey && this.#lacksKey(table, oldKey)) {\n // The row was not replicated, so the update is applied to its new key,\n // which adds the row.\n this.#deleteRowLackingKey(table, oldKey, tableSpec.backfilling);\n oldKey = null;\n }\n if (this.#lacksKey(table, newKey)) {\n // The row is no longer replicated.\n this.#deleteRowLackingKey(table, newKey, tableSpec.backfilling);\n if (oldKey) {\n this.#delete(table, oldKey);\n this.#logDeleteOp(table, oldKey, tableSpec.backfilling);\n }\n return;\n }\n\n if (oldKey) {\n this.#logDeleteOp(table, oldKey, tableSpec.backfilling);\n }\n this.#logSetOp(table, newKey, getBackfilledColumns(newRow.row, tableSpec));\n\n const currKey = oldKey ?? newKey;\n const conds = Object.keys(currKey).map(col => `${id(col)}=?`);\n const setExprs = Object.keys(row).map(col => `${id(col)}=?`);\n\n try {\n const {changes} = this.#db.run(\n `\n UPDATE ${id(table)}\n SET ${setExprs.join(',')}\n WHERE ${conds.join(' AND ')}\n `,\n [...Object.values(row), ...Object.values(currKey)],\n );\n\n // If the UPDATE did not affect any rows, perform an UPSERT of the\n // new row for resumptive replication.\n if (changes === 0) {\n this.#upsert(table, row);\n }\n } catch (e) {\n if (\n !(e instanceof RangeError) ||\n e.message !== BIND_VALUE_TOO_BIG_ERROR\n ) {\n throw e;\n }\n\n const binding = [...Object.entries(row), ...Object.entries(currKey)]\n .map(\n ([column, value]) =>\n [column, oversizedValueDescription(value)] as const,\n )\n .find(([, description]) => description);\n const relationOid =\n 'relationOid' in update.relation &&\n typeof update.relation.relationOid === 'number'\n ? ` relationOid=${update.relation.relationOid}`\n : '';\n const error = new Error(\n `Oversized SQLite update binding: tx=${this.#version}${relationOid} table=${update.relation.schema}.${update.relation.name} column=${binding?.[0] ?? 'unknown'}${binding?.[1] ? ` ${binding[1]}` : ''}`,\n {cause: e},\n );\n error.name = 'OversizedUpdateBindingError';\n throw error;\n }\n }\n\n processDelete(del: MessageDelete) {\n const table = liteTableName(del.relation);\n const tableSpec = this.#tableSpec(table);\n if (!this.#keyColumns(del.relation)?.length) {\n const {where, params} = this.#matchRowWithoutKey(\n table,\n liteRow(del.key, tableSpec, this.#jsonFormat),\n );\n this.#db.run(`DELETE FROM ${id(table)} WHERE ${where}`, params);\n return;\n }\n const rowKey = this.#getKey(\n liteRow(del.key, tableSpec, this.#jsonFormat),\n del,\n );\n if (this.#lacksKey(table, rowKey)) {\n this.#deleteRowLackingKey(table, rowKey, tableSpec.backfilling);\n return;\n }\n\n this.#delete(table, rowKey);\n this.#logDeleteOp(table, rowKey, tableSpec.backfilling);\n }\n\n // A replica written before these rows were skipped can still hold one: with\n // a NULL in its key for a NaN, or the infinite number itself. It is removed\n // when its upstream row changes. Upstream has at most one row with a given\n // key, so every match is a copy of it.\n #deleteRowLackingKey(\n table: string,\n rowKey: LiteRowKey,\n backfilling: string[] | undefined,\n ) {\n const conds: string[] = [];\n const params: LiteValueType[] = [];\n for (const [col, v] of Object.entries(rowKey)) {\n if (v === null || Number.isNaN(v)) {\n conds.push(`${id(col)} IS NULL`);\n } else {\n conds.push(`${id(col)}=?`);\n params.push(v);\n }\n }\n this.#db.run(\n `DELETE FROM ${id(table)} WHERE ${conds.join(' AND ')}`,\n params,\n );\n // The change log entry of such a row has a null for these values, so no\n // reader can find the row by it. The entry of a delete is skipped by\n // them, where that of the insert or update it replaces is an error. It is\n // written whether or not the row was still there, as an earlier version\n // may have removed the row and left its entry.\n this.#logDeleteOp(table, rowKey, backfilling);\n }\n\n #delete(table: string, rowKey: LiteRowKey) {\n const conds = Object.keys(rowKey).map(col => `${id(col)}=?`);\n this.#db.run(\n `DELETE FROM ${id(table)} WHERE ${conds.join(' AND ')}`,\n Object.values(rowKey),\n );\n }\n\n processTruncate(truncate: MessageTruncate) {\n for (const relation of truncate.relations) {\n const table = liteTableName(relation);\n // Update replica data.\n this.#db.run(`DELETE FROM ${id(table)}`);\n\n // Update change log.\n this.#logTruncateOp(table);\n }\n }\n\n processCreateTable(create: TableCreate) {\n if (create.metadata) {\n this.#tableMetadata.setUpstreamMetadata(create.spec, create.metadata);\n }\n this.#backfilling.apply(create);\n const table = mapPostgresToLite(create.spec);\n this.#db.db.exec(createLiteTableStatement(table));\n\n // Write to metadata table\n for (const [colName, colSpec] of Object.entries(create.spec.columns)) {\n this.#columnMetadata.insert(\n table.name,\n colName,\n colSpec,\n create.backfill?.[colName],\n );\n }\n\n this.#logResetOp(table.name);\n this.#lc.info?.(create.tag, table.name);\n }\n\n processTableMetadata(msg: TableUpdateMetadata) {\n this.#tableMetadata.setUpstreamMetadata(msg.table, msg.new);\n // Inert today: the fold's only op for this tag is `upsert-metadata`, which\n // the line above is the replica's interpreter of. Called anyway so that\n // every site that hands a schema change to one cookie tracker hands it to\n // both -- an exception here would be a schema change the shared fold has an\n // opinion about and this store never sees, which is the drift the fold\n // exists to make impossible.\n this.#backfilling.apply(msg);\n }\n\n processRenameTable(rename: TableRename) {\n this.#tableMetadata.rename(rename.old, rename.new);\n this.#backfilling.apply(rename);\n\n const oldName = liteTableName(rename.old);\n const newName = liteTableName(rename.new);\n if (oldName.toLowerCase() === newName.toLowerCase()) {\n // SQLite ignores case, and would take this for a table that exists.\n const tmpName = `tmp.${newName}`;\n this.#db.db.exec(`ALTER TABLE ${id(oldName)} RENAME TO ${id(tmpName)}`);\n this.#db.db.exec(`ALTER TABLE ${id(tmpName)} RENAME TO ${id(newName)}`);\n } else {\n this.#db.db.exec(`ALTER TABLE ${id(oldName)} RENAME TO ${id(newName)}`);\n }\n\n // Rename in metadata table\n this.#columnMetadata.renameTable(oldName, newName);\n\n this.#bumpVersions(rename.new);\n this.#logResetOp(oldName);\n this.#lc.info?.(rename.tag, oldName, newName);\n }\n\n processAddColumn(msg: ColumnAdd) {\n if (msg.tableMetadata) {\n this.#tableMetadata.setUpstreamMetadata(msg.table, msg.tableMetadata);\n }\n this.#backfilling.apply(msg);\n const table = liteTableName(msg.table);\n const {name} = msg.column;\n const spec = mapPostgresToLiteColumn(table, msg.column);\n this.#db.db.exec(\n `ALTER TABLE ${id(table)} ADD ${id(name)} ${liteColumnDef(spec)}`,\n );\n\n // Write to metadata table\n this.#columnMetadata.insert(table, name, msg.column.spec, msg.backfill);\n\n if (msg.backfill) {\n this.#reloadTableSpecs();\n } else {\n // Make the new column visible immediately if it's not being backfilled.\n // Otherwise, the version bump will happen with the backfill is complete.\n this.#bumpVersions(msg.table);\n }\n this.#lc.info?.(msg.tag, table, msg.column);\n }\n\n processUpdateColumn(msg: ColumnUpdate) {\n // A no-op unless this is a rename, which is the only part of a column\n // update that moves the backfill cookie.\n this.#backfilling.apply(msg);\n\n const table = liteTableName(msg.table);\n let oldName = msg.old.name;\n const newName = msg.new.name;\n\n const storageTypesDiffer = differentStorageTypes(\n msg.old.spec,\n msg.new.spec,\n );\n\n // If neither the column name nor the SQLite data type changes, only the\n // upstream metadata needs to be updated. This includes changes such as a\n // varchar character limit and nullability, which SQLite does not enforce\n // but a freshly built replica still records.\n if (oldName === newName && !storageTypesDiffer) {\n this.#columnMetadata.update(\n table,\n msg.old.name,\n msg.new.name,\n msg.new.spec,\n );\n if (Boolean(msg.old.spec.notNull) !== Boolean(msg.new.spec.notNull)) {\n this.#bumpVersions(msg.table);\n }\n this.#lc.info?.(msg.tag, 'updated metadata only', msg.old, msg.new);\n return;\n }\n // Storage type changes require a new column so that SQLite uses the new\n // representation for existing and future values.\n if (storageTypesDiffer) {\n // update-column can ignore defaults because it does not change the values\n // in existing rows.\n //\n // https://www.postgresql.org/docs/current/sql-altertable.html#SQL-ALTERTABLE-DESC-SET-DROP-DEFAULT\n //\n // \"The new default value will only apply in subsequent INSERT or UPDATE\n // commands; it does not cause rows already in the table to change.\"\n //\n // This allows support for _changing_ column defaults to any expression,\n // since it does not affect what the replica needs to do.\n const newLiteSpec = mapPostgresToLiteColumn(\n table,\n msg.new,\n 'ignore-default',\n );\n if (oldName !== newName) {\n // Rename the column in place first so that SQLite rewrites every\n // reference to it in the table's index definitions, including the\n // WHERE clauses of partial indexes.\n this.#db.db.exec(\n `ALTER TABLE ${id(table)} RENAME ${id(oldName)} TO ${id(newName)}`,\n );\n oldName = newName;\n }\n const tableSpec = must(\n listTables(this.#db.db, false, false).find(\n tableSpec => tableSpec.name === table,\n ),\n );\n // Recreating the table drops its indexes, so capture their DDL to\n // replay afterwards. Auto-indexes (PRIMARY KEY) have no DDL and are\n // recreated by the CREATE TABLE statement itself.\n const indexDDL = this.#db.db\n .prepare(\n `SELECT sql FROM sqlite_master\n WHERE type = 'index' AND tbl_name = ? AND sql IS NOT NULL\n ORDER BY rowid`,\n )\n .all<{sql: string}>(table)\n .map(({sql}) => sql);\n const tmpTable = `tmp.${table}`;\n const columns = Object.keys(tableSpec.columns);\n const stmts = [\n createLiteTableStatement({\n ...tableSpec,\n name: tmpTable,\n columns: mapEntries(tableSpec.columns, (column, spec) => [\n column,\n column === newName ? {...newLiteSpec, pos: spec.pos} : spec,\n ]),\n }),\n `INSERT INTO ${id(tmpTable)} (${columns.map(id).join(',')})\n SELECT ${columns.map(id).join(',')} FROM ${id(table)};`,\n `DROP TABLE ${id(table)};`,\n `ALTER TABLE ${id(tmpTable)} RENAME TO ${id(table)};`,\n ...indexDDL.map(sql => `${sql};`),\n ];\n this.#db.db.exec(stmts.join(''));\n }\n if (oldName !== newName) {\n this.#db.db.exec(\n `ALTER TABLE ${id(table)} RENAME ${id(oldName)} TO ${id(newName)}`,\n );\n }\n\n // Update metadata table\n this.#columnMetadata.update(\n table,\n msg.old.name,\n msg.new.name,\n msg.new.spec,\n );\n\n this.#bumpVersions(msg.table);\n this.#lc.info?.(msg.tag, table, msg.new);\n }\n\n processDropColumn(msg: ColumnDrop) {\n const table = liteTableName(msg.table);\n const {column} = msg;\n this.#db.db.exec(`ALTER TABLE ${id(table)} DROP ${id(column)}`);\n\n // Delete from metadata table\n this.#columnMetadata.deleteColumn(table, column);\n this.#backfilling.apply(msg);\n\n this.#bumpVersions(msg.table);\n this.#lc.info?.(msg.tag, table, column);\n }\n\n processDropTable(drop: TableDrop) {\n this.#tableMetadata.drop(drop.id);\n this.#backfilling.apply(drop);\n\n const name = liteTableName(drop.id);\n this.#db.db.exec(`DROP TABLE IF EXISTS ${id(name)}`);\n\n // Delete from metadata table\n this.#columnMetadata.deleteTable(name);\n\n this.#logResetOp(name);\n this.#lc.info?.(drop.tag, name);\n }\n\n processCreateIndex(create: IndexCreate) {\n const index = mapPostgresToLiteIndex(create.spec);\n createLiteIndex(this.#lc, this.#db.db, index);\n\n // indexes affect tables visibility (e.g. sync-ability is gated on\n // having a unique index), so reset pipelines to refresh table schemas.\n this.#logResetOp(index.tableName);\n this.#lc.info?.(create.tag, index.name);\n }\n\n processDropIndex(drop: IndexDrop) {\n const name = liteTableName(drop.id);\n const indexExisted = this.#db.db\n .prepare(\n `SELECT tbl_name as tableName FROM sqlite_master WHERE type = 'index' AND name = ?`,\n )\n .get(name) as {tableName: string} | undefined;\n\n this.#db.db.exec(`DROP INDEX IF EXISTS ${id(name)}`);\n\n if (indexExisted) {\n // indexes affect tables visibility (e.g. sync-ability is gated on\n // having a unique index), so reset pipelines to refresh table schemas.\n this.#logResetOp(indexExisted.tableName);\n }\n this.#lc.info?.(drop.tag, name);\n }\n\n #bumpVersions(table: Identifier) {\n this.#tableMetadata.setMinRowVersion(table, this.#version);\n this.#logResetOp(liteTableName(table));\n }\n\n /**\n * @param backfilledColumns `backfilling` columns for which values were set\n */\n #logSetOp(\n table: string,\n key: LiteRowKey,\n backfilledColumns: string[] | undefined,\n ) {\n // The \"serving\" replicator always writes to the change-log (for IVM).\n // The \"backup\" replicator only needs to write to the change log\n // when writing columns that are being backfilled.\n if (this.#mode === 'serving' || backfilledColumns !== undefined) {\n this.#changeLog.logSetOp(\n this.#version,\n this.#pos++,\n table,\n key,\n backfilledColumns,\n );\n this.#numChangeLogEntries++;\n }\n }\n\n #logDeleteOp(table: string, key: LiteRowKey, backfilling?: string[]) {\n // The \"serving\" replicator always writes to the change-log (for IVM).\n // The \"backup\" replicator only needs to write to the change log\n // when writing columns that are being backfilled.\n if (this.#mode === 'serving' || backfilling?.length) {\n this.#changeLog.logDeleteOp(this.#version, this.#pos++, table, key);\n this.#numChangeLogEntries++;\n }\n }\n\n #logTruncateOp(table: string) {\n if (this.#mode === 'serving') {\n this.#changeLog.logTruncateOp(this.#version, table);\n this.#numChangeLogEntries++;\n }\n }\n\n #logResetOp(table: string) {\n this.#schemaChanged = true;\n if (this.#mode === 'serving') {\n this.#changeLog.logResetOp(this.#version, table);\n this.#numChangeLogEntries++;\n }\n this.#reloadTableSpecs();\n }\n\n processBackfill({\n relation,\n watermark,\n columns,\n rowValues,\n progressMarks,\n }: MessageBackfill) {\n const tableName = liteTableName(relation);\n const tableSpec = must(this.#tableSpecs.get(tableName));\n const rowKeyCols = relation.rowKey.columns;\n const cols = [...rowKeyCols, ...columns];\n\n // Only columns that are still being backfilled on _this_ replica are\n // written, and of those, only the columns for which this message is\n // contiguous with the data received so far (whose progress is advanced).\n //\n // * Once a column has been published (backfill completed), its values\n // strictly follow the replication timeline, so a subsequent backfill must\n // never overwrite them. This guards against a redundant backfill, e.g.\n // when the view-syncer (re)connects to a replication-manager that is\n // (re)running a backfill this replica already completed.\n // * Data for non-contiguous (ignored) columns is necessarily re-delivered\n // (by a resumed or from-scratch run) before the column can be published,\n // so writing it would be wasted I/O.\n const {accepted, ignored} = this.#trackBackfillProgress(\n relation,\n cols,\n own => acceptBackfill(own, progressMarks),\n );\n if (accepted.length === 0) {\n this.#lc.debug?.(\n ignored.length\n ? `skipping backfill of ${rowValues.length} rows into ` +\n `${tableName}: not contiguous with the progress of columns ` +\n `[${ignored.join(',')}]`\n : `skipping redundant backfill of ${rowValues.length} rows into ` +\n `${tableName} (all columns already published)`,\n progressMarks,\n );\n return;\n }\n if (ignored.length) {\n this.#lc.debug?.(\n `backfill of ${tableName} is not contiguous with the progress ` +\n `of columns [${ignored.join(',')}]`,\n progressMarks,\n );\n }\n const acceptedSet = new Set(accepted);\n\n // Common parts of the INSERT sql statement.\n const insertColsStr = [...cols, ZERO_VERSION_COLUMN_NAME].map(id).join(',');\n const qMarks = Array.from({length: cols.length + 1})\n .fill('?')\n .join(',');\n const rowKeyColsStr = rowKeyCols.map(id).join(',');\n\n let backfilled = 0;\n let skipped = 0;\n for (const v of rowValues) {\n const row = liteRow(\n Object.fromEntries(cols.map((c, i) => [c, v[i]])),\n tableSpec,\n this.#jsonFormat,\n );\n const rowKey = this.#getKey(row, {relation});\n if (this.#lacksKey(tableName, rowKey)) {\n // An earlier version may have left the row or its entry.\n this.#deleteRowLackingKey(tableName, rowKey, tableSpec.backfilling);\n skipped++;\n continue;\n }\n const rowOp = this.#changeLog.getLatestRowOp(tableName, rowKey);\n if (rowOp?.op === DEL_OP && rowOp.stateVersion > watermark) {\n skipped++;\n continue; // the row was deleted after the backfill snapshot\n }\n // Restrict the DO UPDATE columns to those still being backfilled. Never\n // update an already backfilled (i.e. published) column.\n const updates = (\n rowOp?.op === SET_OP\n ? cols.filter(\n c => (rowOp.backfillingColumnVersions[c] ?? '') <= watermark,\n )\n : cols\n ).filter(c => acceptedSet.has(c));\n if (updates.length === 0) {\n // row already has newer values for all accepted backfilling columns.\n skipped++;\n continue;\n }\n const updateStmts = updates.map(col => `${id(col)}=excluded.${id(col)}`);\n this.#db.run(\n /*sql*/ `\n INSERT INTO ${id(tableName)} (${insertColsStr}) VALUES (${qMarks})\n ON CONFLICT (${rowKeyColsStr})\n DO UPDATE SET ${updateStmts.join(',')};\n `,\n ...Object.values(row.row),\n watermark, // the _0_version for new rows (i.e. table backfill)\n );\n backfilled++;\n }\n\n this.#lc.debug?.(\n `backfilled ${backfilled} rows (skipped ${skipped}) into ${tableName}`,\n );\n }\n\n #completedBackfill: DownloadStatus | undefined;\n\n /**\n * Applies `accept` to the tracked progress of each of the `cols` that are\n * still backfilling on this replica, updating the progress of the accepted\n * ones. Columns that are not backfilling (e.g. already published) are\n * neither accepted nor ignored.\n */\n #trackBackfillProgress(\n relation: Identifier,\n cols: readonly string[],\n accept: (progress: BackfillProgressMark | undefined) => AcceptResult,\n ): {accepted: string[]; ignored: string[]} {\n const tracked = this.#backfilling.getProgress(relation);\n const accepted: string[] = [];\n const ignored: string[] = [];\n for (const col of cols) {\n if (!tracked.has(col)) {\n continue; // not backfilling\n }\n const progress = tracked.get(col);\n const result = accept(progress);\n if (!result.accept) {\n ignored.push(col);\n continue;\n }\n accepted.push(col);\n if (!deepEqual(result.progress, progress)) {\n this.#backfilling.setProgress(relation, col, result.progress);\n }\n }\n return {accepted, ignored};\n }\n\n processBackfillCompleted(msg: BackfillCompleted) {\n const {relation, columns, status, progressMarks} = msg;\n const tableName = liteTableName(relation);\n const rowKeyCols = relation.rowKey.columns;\n\n // Only complete the columns whose backfill progress is contiguous with\n // the completed backfill. The others remain backfilling (and will be\n // re-requested by the change-streamer).\n const {accepted, ignored} = this.#trackBackfillProgress(\n relation,\n [...rowKeyCols, ...columns],\n own =>\n acceptBackfill(\n own,\n progressMarks ? {previous: progressMarks.previous} : undefined,\n ),\n );\n if (ignored.length) {\n this.#lc.info?.(\n `ignoring backfill-completed of ${tableName} for columns ` +\n `[${ignored.join(',')}], which have not received all of the data`,\n progressMarks,\n );\n }\n\n // If none of the columns are still backfilling on this replica, they were\n // already published (e.g. a redundant backfill from a replication-manager\n // re-running a backfill this replica already completed). Bumping versions\n // again would spuriously reset pipelines and re-report completion, so treat\n // the completion as a no-op.\n if (accepted.length === 0) {\n if (ignored.length === 0) {\n this.#lc.debug?.(\n `skipping redundant backfill-completed for ${tableName} ` +\n `(all columns already published)`,\n );\n }\n return;\n }\n const ignoredSet = new Set(ignored);\n const cols = [\n ...rowKeyCols.filter(c => !ignoredSet.has(c)),\n ...columns.filter(c => !ignoredSet.has(c)),\n ];\n\n const columnMetadata = must(ColumnMetadataStore.getInstance(this.#db.db));\n for (const col of cols) {\n columnMetadata.clearBackfilling(tableName, col);\n }\n this.#backfilling.complete(relation, cols);\n // Given that new columns are being exposed for every row in the table, bump the\n // row version for all rows.\n this.#bumpVersions(relation);\n if (status) {\n this.#completedBackfill = {table: tableName, columns: cols, ...status};\n }\n this.#lc.info?.(`finished backfilling ${tableName}`);\n\n // Note that there is no need to clear the backfillingColumnVersions values\n // in the changeLog. It could theoretically be done for clarity but:\n // (1) it could be non-trivial in terms of latency introduced and\n // (2) the data must be preserved if _other_ columns are in the process\n // of being backfilled\n //\n // Thus, for speed and simplicity, the values are left as is. (Note that\n // subsequent replicated changes to those rows will clear the values if\n // no backfills are in progress).\n }\n\n processCommit(commit: MessageCommit, watermark: string): CommitResult {\n if (watermark !== this.#version) {\n throw new Error(\n `'commit' version ${watermark} does not match 'begin' version ${\n this.#version\n }: ${stringify(commit)}`,\n );\n }\n updateReplicationWatermark(this.#db, watermark);\n\n if (this.#schemaChanged) {\n const start = Date.now();\n this.#db.db.pragma('optimize');\n this.#lc.info?.(\n `PRAGMA optimized after schema change (${Date.now() - start} ms)`,\n );\n }\n\n if (this.#mode !== 'initial-sync') {\n this.#db.commit();\n }\n\n const elapsedMs = Date.now() - this.#startMs;\n this.#lc.debug?.(`Committed tx@${this.#version} (${elapsedMs} ms)`);\n\n return {\n watermark,\n completedBackfill: this.#completedBackfill,\n schemaUpdated: this.#schemaChanged,\n changeLogUpdated: this.#numChangeLogEntries > 0,\n upstreamCommitTimeMs: commit.commitTimeMs,\n };\n }\n\n abort(lc: LogContext) {\n lc.info?.(`aborting transaction ${this.#version}`);\n this.#db.rollback();\n // A schema change in the transaction reloaded the table specs, which now\n // describe the schema that the rollback undid. Clearing them makes the\n // next transaction reload them from the database.\n this.#tableSpecs.clear();\n }\n}\n\nfunction differentStorageTypes(\n oldSpec: ColumnSpec,\n newSpec: ColumnSpec,\n): boolean {\n return (\n oldSpec.dataType !== newSpec.dataType ||\n isEnumColumn(oldSpec) !== isEnumColumn(newSpec) ||\n isArrayColumn(oldSpec) !== isArrayColumn(newSpec)\n );\n}\n\nfunction getBackfilledColumns(\n row: LiteRow,\n {backfilling}: LiteTableSpecWithReplicationStatus,\n): string[] | undefined {\n if (!backfilling?.length) {\n return undefined; // common case\n }\n return backfilling.filter(col => col in row);\n}\n\nfunction oversizedValueDescription(value: LiteValueType): string | undefined {\n const sizeBytes =\n typeof value === 'string'\n ? Buffer.byteLength(value)\n : value instanceof Uint8Array\n ? value.byteLength\n : undefined;\n if (sizeBytes !== undefined && sizeBytes > MAX_SQLITE_BIND_BYTES) {\n const valueType = typeof value === 'string' ? 'string' : 'buffer';\n return `valueType=${valueType} sizeBytes=${sizeBytes} limitBytes=${MAX_SQLITE_BIND_BYTES}`;\n }\n\n return undefined;\n}\n\n/** Runs `fn`, returning its error rather than throwing it. */\nfunction attempt(fn: () => void): unknown {\n try {\n fn();\n return undefined;\n } catch (e) {\n return e ?? new Error('rollback failed');\n }\n}\n\nfunction ensureError(err: unknown): Error {\n if (err instanceof Error) {\n return err;\n }\n const error = new Error();\n error.cause = err;\n return error;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAiFA,IAAM,2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AO;CAET,MAAM,wBAAQ,IAAI,MAAM;CACxB,MAAM,QAAQ;CACd,OAAO;AACT"}
@@ -1,6 +1,6 @@
1
1
  import { assert } from "../../../../../shared/src/asserts.js";
2
- import { literalUnion, parse, valita_exports } from "../../../../../shared/src/valita.js";
3
2
  import { assignProperty } from "../../../../../shared/src/objects.js";
3
+ import { literalUnion, parse, valita_exports } from "../../../../../shared/src/valita.js";
4
4
  import { parse as parse$1, stringify } from "../../../../../shared/src/bigint-json.js";
5
5
  import { normalizedKeyOrder } from "../../../types/row-key.js";
6
6
  var CREATE_CHANGELOG_SCHEMA = `
@@ -1,5 +1,5 @@
1
- import { must } from "../../../../shared/src/must.js";
2
1
  import { mapValues } from "../../../../shared/src/objects.js";
2
+ import { must } from "../../../../shared/src/must.js";
3
3
  import { cvrSchema } from "../../types/shards.js";
4
4
  import { RunningState } from "../running-state.js";
5
5
  import { setActiveUsersGetter } from "../../server/anonymous-otel-start.js";
@@ -1,9 +1,9 @@
1
1
  import { assert, unreachable } from "../../../../shared/src/asserts.js";
2
2
  import { deepEqual } from "../../../../shared/src/json.js";
3
+ import { assignProperty } from "../../../../shared/src/objects.js";
3
4
  import { getOrInsertComputed } from "../../../../shared/src/map.js";
4
5
  import { must } from "../../../../shared/src/must.js";
5
6
  import { h32 } from "../../../../shared/src/hash.js";
6
- import { assignProperty } from "../../../../shared/src/objects.js";
7
7
  import { skipYields } from "../../../../zql/src/ivm/skip-yields.js";
8
8
  import { throwOutput } from "../../../../zql/src/ivm/operator.js";
9
9
  import { MeasurePushOperator } from "../../../../zql/src/query/measure-push-operator.js";
@@ -1,9 +1,9 @@
1
1
  import { __exportAll } from "../../../_virtual/_rolldown/runtime.js";
2
2
  import { unreachable } from "../../../shared/src/asserts.js";
3
3
  import { hasOwn } from "../../../shared/src/has-own.js";
4
+ import { assignProperty } from "../../../shared/src/objects.js";
4
5
  import { must } from "../../../shared/src/must.js";
5
6
  import { aggregateValue } from "../../../zero-protocol/src/ast.js";
6
- import { assignProperty } from "../../../shared/src/objects.js";
7
7
  import { consume } from "../../../zql/src/ivm/stream.js";
8
8
  import { AGGREGATE_COUNT_COLUMN, AGGREGATE_KEY_COLUMN, AGGREGATE_ROWS_COLUMN, AGGREGATE_SUM_COLUMN, AGGREGATE_VALUE_COLUMN } from "../../../zql/src/ivm/aggregate.js";
9
9
  import "../../../zero-protocol/src/mutation.js";
@@ -1,10 +1,10 @@
1
1
  import { assert } from "../../../shared/src/asserts.js";
2
+ import { assignProperty } from "../../../shared/src/objects.js";
2
3
  import { wrapIterable } from "../../../shared/src/iterables.js";
3
4
  import { readFromHash } from "../../../replicache/src/db/read.js";
4
5
  import { diff } from "../../../replicache/src/sync/diff.js";
5
6
  import { using, withRead } from "../../../replicache/src/with-transactions.js";
6
7
  import { must } from "../../../shared/src/must.js";
7
- import { assignProperty } from "../../../shared/src/objects.js";
8
8
  import { consume } from "../../../zql/src/ivm/stream.js";
9
9
  import { AGGREGATE_KEY_COLUMN, AGGREGATE_PAYLOAD_COLUMNS, AGGREGATE_VALUE_COLUMN } from "../../../zql/src/ivm/aggregate.js";
10
10
  import { diffBinarySearch } from "../../../replicache/src/subscriptions.js";
@@ -2,7 +2,7 @@
2
2
  /**
3
3
  * The current version of Zero.
4
4
  */
5
- var version = "1.13.0-canary.0";
5
+ var version = "1.13.0-canary.2";
6
6
  //#endregion
7
7
  export { version };
8
8
 
@@ -1,6 +1,6 @@
1
+ import { mapAllEntries } from "../../shared/src/objects.js";
1
2
  import { literalUnion, valita_exports } from "../../shared/src/valita.js";
2
3
  import { must } from "../../shared/src/must.js";
3
- import { mapAllEntries } from "../../shared/src/objects.js";
4
4
  //#region ../zero-protocol/src/client-schema.ts
5
5
  var valueTypeSchema = literalUnion("string", "number", "boolean", "null", "json");
6
6
  var columnSchemaSchema = valita_exports.object({ type: valueTypeSchema });
@@ -57,14 +57,14 @@ export declare const downstreamSchema: v.UnionType<[v.TupleType<[v.Type<"connect
57
57
  clientID: string;
58
58
  };
59
59
  result: {
60
- data?: import("../../shared/src/json.ts").ReadonlyJSONValue | undefined;
61
- } | {
62
60
  error: "app";
63
61
  message?: string | undefined;
64
62
  details?: import("../../shared/src/json.ts").ReadonlyJSONValue | undefined;
65
63
  } | {
66
64
  error: "alreadyProcessed" | "oooMutation";
67
65
  details?: import("../../shared/src/json.ts").ReadonlyJSONValue | undefined;
66
+ } | {
67
+ data?: import("../../shared/src/json.ts").ReadonlyJSONValue | undefined;
68
68
  };
69
69
  };
70
70
  } | {
@@ -1,5 +1,5 @@
1
- import { h64 } from "../../../shared/src/hash.js";
2
1
  import { assignProperty, mapEntries } from "../../../shared/src/objects.js";
2
+ import { h64 } from "../../../shared/src/hash.js";
3
3
  import { AGGREGATE_TABLE_PREFIX } from "../../../zero-protocol/src/aggregate-table.js";
4
4
  import { normalizeClientSchema } from "../../../zero-protocol/src/client-schema.js";
5
5
  //#region ../zero-schema/src/builder/schema-builder.ts
@@ -1,8 +1,8 @@
1
1
  import { assert, unreachable } from "../../../shared/src/asserts.js";
2
+ import { assignProperty } from "../../../shared/src/objects.js";
2
3
  import { parse } from "../../../shared/src/valita.js";
3
4
  import { must } from "../../../shared/src/must.js";
4
5
  import { formatJsonPathReference, simpleConditionSchema } from "../../../zero-protocol/src/ast.js";
5
- import { assignProperty } from "../../../shared/src/objects.js";
6
6
  import { AGGREGATE_KEY_COLUMN, Aggregate, Reducer, aggregateSourceSchema, assertNotSyntheticColumn, isInvertible } from "../ivm/aggregate.js";
7
7
  import { AGGREGATE_TABLE_PREFIX } from "../../../zero-protocol/src/aggregate-table.js";
8
8
  import { completeOrdering } from "../query/complete-ordering.js";