@rocicorp/zero 1.11.0-canary.4 → 1.11.0-canary.6

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 (123) hide show
  1. package/out/replicache/src/kv/expo-sqlite/store.d.ts.map +1 -1
  2. package/out/replicache/src/kv/expo-sqlite/store.js +27 -4
  3. package/out/replicache/src/kv/expo-sqlite/store.js.map +1 -1
  4. package/out/replicache/src/kv/sqlite-store.d.ts +11 -0
  5. package/out/replicache/src/kv/sqlite-store.d.ts.map +1 -1
  6. package/out/replicache/src/kv/sqlite-store.js +43 -3
  7. package/out/replicache/src/kv/sqlite-store.js.map +1 -1
  8. package/out/shared/src/error.d.ts +11 -0
  9. package/out/shared/src/error.d.ts.map +1 -1
  10. package/out/shared/src/error.js +35 -1
  11. package/out/shared/src/error.js.map +1 -1
  12. package/out/shared/src/map.d.ts +7 -2
  13. package/out/shared/src/map.d.ts.map +1 -1
  14. package/out/shared/src/map.js.map +1 -1
  15. package/out/zero/package.js +2 -2
  16. package/out/zero/package.js.map +1 -1
  17. package/out/zero-cache/src/config/normalize.d.ts.map +1 -1
  18. package/out/zero-cache/src/config/normalize.js +7 -1
  19. package/out/zero-cache/src/config/normalize.js.map +1 -1
  20. package/out/zero-cache/src/config/zero-config.d.ts +9 -0
  21. package/out/zero-cache/src/config/zero-config.d.ts.map +1 -1
  22. package/out/zero-cache/src/config/zero-config.js +21 -0
  23. package/out/zero-cache/src/config/zero-config.js.map +1 -1
  24. package/out/zero-cache/src/server/change-streamer.d.ts.map +1 -1
  25. package/out/zero-cache/src/server/change-streamer.js +15 -6
  26. package/out/zero-cache/src/server/change-streamer.js.map +1 -1
  27. package/out/zero-cache/src/server/main.d.ts.map +1 -1
  28. package/out/zero-cache/src/server/main.js +8 -1
  29. package/out/zero-cache/src/server/main.js.map +1 -1
  30. package/out/zero-cache/src/server/mutator.js +2 -0
  31. package/out/zero-cache/src/server/mutator.js.map +1 -1
  32. package/out/zero-cache/src/server/reaper.d.ts.map +1 -1
  33. package/out/zero-cache/src/server/reaper.js +2 -0
  34. package/out/zero-cache/src/server/reaper.js.map +1 -1
  35. package/out/zero-cache/src/server/replicator.d.ts.map +1 -1
  36. package/out/zero-cache/src/server/replicator.js +2 -0
  37. package/out/zero-cache/src/server/replicator.js.map +1 -1
  38. package/out/zero-cache/src/server/runner/zero-dispatcher.d.ts.map +1 -1
  39. package/out/zero-cache/src/server/runner/zero-dispatcher.js +3 -0
  40. package/out/zero-cache/src/server/runner/zero-dispatcher.js.map +1 -1
  41. package/out/zero-cache/src/server/syncer.d.ts.map +1 -1
  42. package/out/zero-cache/src/server/syncer.js +2 -0
  43. package/out/zero-cache/src/server/syncer.js.map +1 -1
  44. package/out/zero-cache/src/services/change-source/pg/initial-sync.js +1 -1
  45. package/out/zero-cache/src/services/change-source/pg/schema/index-predicate.d.ts.map +1 -1
  46. package/out/zero-cache/src/services/change-source/pg/schema/index-predicate.js +68 -8
  47. package/out/zero-cache/src/services/change-source/pg/schema/index-predicate.js.map +1 -1
  48. package/out/zero-cache/src/services/change-streamer/change-log-codec.d.ts +19 -4
  49. package/out/zero-cache/src/services/change-streamer/change-log-codec.d.ts.map +1 -1
  50. package/out/zero-cache/src/services/change-streamer/change-log-codec.js +28 -8
  51. package/out/zero-cache/src/services/change-streamer/change-log-codec.js.map +1 -1
  52. package/out/zero-cache/src/services/change-streamer/change-streamer-http.d.ts +3 -0
  53. package/out/zero-cache/src/services/change-streamer/change-streamer-http.d.ts.map +1 -1
  54. package/out/zero-cache/src/services/change-streamer/change-streamer-http.js +3 -1
  55. package/out/zero-cache/src/services/change-streamer/change-streamer-http.js.map +1 -1
  56. package/out/zero-cache/src/services/change-streamer/change-streamer-service.d.ts +6 -0
  57. package/out/zero-cache/src/services/change-streamer/change-streamer-service.d.ts.map +1 -1
  58. package/out/zero-cache/src/services/change-streamer/change-streamer-service.js +86 -51
  59. package/out/zero-cache/src/services/change-streamer/change-streamer-service.js.map +1 -1
  60. package/out/zero-cache/src/services/change-streamer/schema/tables.d.ts +1 -1
  61. package/out/zero-cache/src/services/change-streamer/schema/tables.d.ts.map +1 -1
  62. package/out/zero-cache/src/services/change-streamer/schema/tables.js +4 -4
  63. package/out/zero-cache/src/services/change-streamer/schema/tables.js.map +1 -1
  64. package/out/zero-cache/src/services/change-streamer/sqlite-change-log-writer.d.ts +6 -1
  65. package/out/zero-cache/src/services/change-streamer/sqlite-change-log-writer.d.ts.map +1 -1
  66. package/out/zero-cache/src/services/change-streamer/sqlite-change-log-writer.js +27 -9
  67. package/out/zero-cache/src/services/change-streamer/sqlite-change-log-writer.js.map +1 -1
  68. package/out/zero-cache/src/services/change-streamer/storer.d.ts +2 -2
  69. package/out/zero-cache/src/services/change-streamer/storer.d.ts.map +1 -1
  70. package/out/zero-cache/src/services/change-streamer/storer.js +6 -5
  71. package/out/zero-cache/src/services/change-streamer/storer.js.map +1 -1
  72. package/out/zero-cache/src/services/litestream/litestream-checkpointer.js +50 -23
  73. package/out/zero-cache/src/services/litestream/litestream-checkpointer.js.map +1 -1
  74. package/out/zero-cache/src/services/profz.d.ts +7 -0
  75. package/out/zero-cache/src/services/profz.d.ts.map +1 -0
  76. package/out/zero-cache/src/services/profz.js +99 -0
  77. package/out/zero-cache/src/services/profz.js.map +1 -0
  78. package/out/zero-cache/src/services/replicator/change-log-stream-writer.d.ts +5 -4
  79. package/out/zero-cache/src/services/replicator/change-log-stream-writer.d.ts.map +1 -1
  80. package/out/zero-cache/src/services/replicator/change-log-stream-writer.js +20 -22
  81. package/out/zero-cache/src/services/replicator/change-log-stream-writer.js.map +1 -1
  82. package/out/zero-cache/src/services/replicator/sqlite-change-log-observability.d.ts +6 -6
  83. package/out/zero-cache/src/services/replicator/sqlite-change-log-observability.d.ts.map +1 -1
  84. package/out/zero-cache/src/services/replicator/sqlite-change-log-observability.js +19 -14
  85. package/out/zero-cache/src/services/replicator/sqlite-change-log-observability.js.map +1 -1
  86. package/out/zero-cache/src/services/view-syncer/cvr.d.ts +17 -0
  87. package/out/zero-cache/src/services/view-syncer/cvr.d.ts.map +1 -1
  88. package/out/zero-cache/src/services/view-syncer/cvr.js +59 -0
  89. package/out/zero-cache/src/services/view-syncer/cvr.js.map +1 -1
  90. package/out/zero-cache/src/services/view-syncer/hydration-circuit-breaker.d.ts +51 -0
  91. package/out/zero-cache/src/services/view-syncer/hydration-circuit-breaker.d.ts.map +1 -0
  92. package/out/zero-cache/src/services/view-syncer/hydration-circuit-breaker.js +78 -0
  93. package/out/zero-cache/src/services/view-syncer/hydration-circuit-breaker.js.map +1 -0
  94. package/out/zero-cache/src/services/view-syncer/pipeline-driver.d.ts.map +1 -1
  95. package/out/zero-cache/src/services/view-syncer/pipeline-driver.js +18 -6
  96. package/out/zero-cache/src/services/view-syncer/pipeline-driver.js.map +1 -1
  97. package/out/zero-cache/src/services/view-syncer/view-syncer.d.ts.map +1 -1
  98. package/out/zero-cache/src/services/view-syncer/view-syncer.js +154 -6
  99. package/out/zero-cache/src/services/view-syncer/view-syncer.js.map +1 -1
  100. package/out/zero-cache/src/types/processes.d.ts +24 -0
  101. package/out/zero-cache/src/types/processes.d.ts.map +1 -1
  102. package/out/zero-cache/src/types/processes.js +25 -1
  103. package/out/zero-cache/src/types/processes.js.map +1 -1
  104. package/out/zero-cache/src/types/profiler.d.ts +12 -0
  105. package/out/zero-cache/src/types/profiler.d.ts.map +1 -1
  106. package/out/zero-cache/src/types/profiler.js +46 -1
  107. package/out/zero-cache/src/types/profiler.js.map +1 -1
  108. package/out/zero-client/src/client/version.js +1 -1
  109. package/out/zero-client/src/client/zero.d.ts.map +1 -1
  110. package/out/zero-client/src/client/zero.js +12 -8
  111. package/out/zero-client/src/client/zero.js.map +1 -1
  112. package/out/zero-protocol/src/down.d.ts +27 -27
  113. package/out/zero-react/src/use-query.d.ts.map +1 -1
  114. package/out/zero-react/src/use-query.js +50 -3
  115. package/out/zero-react/src/use-query.js.map +1 -1
  116. package/out/zero-solid/src/use-query.js +1 -2
  117. package/out/zero-solid/src/use-query.js.map +1 -1
  118. package/out/zql/src/ivm/data.d.ts.map +1 -1
  119. package/out/zql/src/ivm/data.js +8 -3
  120. package/out/zql/src/ivm/data.js.map +1 -1
  121. package/out/zql/src/ivm/view-apply-change.js +6 -1
  122. package/out/zql/src/ivm/view-apply-change.js.map +1 -1
  123. package/package.json +2 -2
@@ -0,0 +1 @@
1
+ {"version":3,"file":"profz.js","names":[],"sources":["../../../../../zero-cache/src/services/profz.ts"],"sourcesContent":["import {randomUUID} from 'node:crypto';\nimport type {LogContext} from '@rocicorp/logger';\nimport auth from 'basic-auth';\nimport type {FastifyReply, FastifyRequest} from 'fastify';\nimport {sleep} from '../../../shared/src/sleep.ts';\nimport type {NormalizedZeroConfig} from '../config/normalize.ts';\nimport {isAdminPasswordValid} from '../config/zero-config.ts';\nimport {\n singleProcessMode,\n type ProfileResponse,\n type ProfileResponseMessage,\n type Worker,\n} from '../types/processes.ts';\nimport {CpuProfiler} from '../types/profiler.ts';\nimport {URLParams} from '../types/url-params.ts';\n\nexport async function handleProfzRequest(\n lc: LogContext,\n config: Pick<NormalizedZeroConfig, 'adminPassword'>,\n req: FastifyRequest,\n res: FastifyReply,\n getWorker?: (() => Promise<Worker>) | undefined,\n forcedWorker?: string | undefined,\n localProcessName: string = 'dispatcher',\n): Promise<void> {\n const credentials = auth(req);\n if (!isAdminPasswordValid(lc, config, credentials?.pass)) {\n void res\n .code(401)\n .header('WWW-Authenticate', 'Basic realm=\"Profz Protected Area\"')\n .send('Unauthorized');\n return;\n }\n\n const params = new URLParams(new URL(req.url, 'http://localhost'));\n const rawDuration =\n params.getInteger('duration', false) ??\n params.getInteger('seconds', false) ??\n 5;\n const durationSec = Math.max(1, Math.min(60, rawDuration));\n const durationMs = durationSec * 1000;\n const targetWorker = forcedWorker ?? params.get('worker', false) ?? undefined;\n const targetWorkerIndex = params.getInteger('index', false) ?? undefined;\n const id = randomUUID();\n\n const responses = new Map<string, unknown>();\n\n // Profile dispatcher / local process if requested, when profiling all processes,\n // or when no worker dispatcher is available (single process / standalone mode)\n const shouldProfileLocal =\n singleProcessMode() ||\n getWorker === undefined ||\n targetWorker === undefined ||\n targetWorker === localProcessName;\n\n const localProfilePromise = shouldProfileLocal\n ? CpuProfiler.profile(durationMs).catch(err => {\n lc.warn?.('Failed to capture local CPU profile:', err);\n return null;\n })\n : Promise.resolve(null);\n\n if (!singleProcessMode() && getWorker !== undefined) {\n try {\n const worker = await getWorker();\n const onMessage = (msg: ProfileResponse) => {\n if (msg.id === id && msg.profile) {\n responses.set(msg.name, msg.profile);\n } else if (msg.id === id && msg.error) {\n lc.warn?.(`Worker ${msg.name} profile error: ${msg.error}`);\n }\n };\n\n worker.onMessageType<ProfileResponseMessage>(\n 'profileResponse',\n onMessage,\n );\n worker.send([\n 'profile',\n {\n id,\n durationMs,\n worker: targetWorker === localProcessName ? '__none__' : targetWorker,\n workerIndex: targetWorkerIndex,\n },\n ]);\n\n // Wait for duration plus grace period for IPC transfer\n await sleep(durationMs + 500);\n } catch (err) {\n lc.warn?.('Failed to dispatch profile request to child workers:', err);\n }\n }\n\n const localProfile = await localProfilePromise;\n if (localProfile) {\n const localName =\n targetWorker ?? (singleProcessMode() ? 'zero-cache' : localProcessName);\n responses.set(localName, localProfile);\n }\n\n // If a single specific worker was requested, return that profile directly\n if (targetWorker !== undefined && targetWorker !== 'all') {\n let matchedProfile = responses.get(targetWorker);\n if (!matchedProfile) {\n // Try matching by prefix or substring (e.g. 'syncer' matches 'syncer-0')\n for (const [name, prof] of responses.entries()) {\n if (name === targetWorker || name.startsWith(`${targetWorker}-`)) {\n matchedProfile = prof;\n break;\n }\n }\n }\n\n if (matchedProfile) {\n void res\n .header('Content-Type', 'application/json')\n .header(\n 'Content-Disposition',\n `attachment; filename=\"${targetWorker}.cpuprofile\"`,\n )\n .send(matchedProfile);\n return;\n }\n\n void res.code(404).send({\n error: `No profile captured for worker \"${targetWorker}\". Available: ${[...responses.keys()].join(', ')}`,\n });\n return;\n }\n\n // Default (Option A): Return multi-process profile bundle as a JSON map\n const bundle: Record<string, unknown> = {};\n for (const [name, prof] of responses.entries()) {\n bundle[name] = prof;\n }\n\n void res\n .header('Content-Type', 'application/json')\n .header(\n 'Content-Disposition',\n `attachment; filename=\"zero-profile-bundle-${Date.now()}.json\"`,\n )\n .send(bundle);\n}\n\nexport async function handleProfrmzRequest(\n lc: LogContext,\n config: NormalizedZeroConfig,\n req: FastifyRequest,\n res: FastifyReply,\n getWorker?: (() => Promise<Worker>) | undefined,\n): Promise<void> {\n const credentials = auth(req);\n if (!isAdminPasswordValid(lc, config, credentials?.pass)) {\n void res\n .code(401)\n .header('WWW-Authenticate', 'Basic realm=\"Profrmz Protected Area\"')\n .send('Unauthorized');\n return;\n }\n\n // In distributed mode, proxy to the upstream Replication Manager\n if (config.changeStreamer.uri) {\n const upstreamURL = new URL('/profz', config.changeStreamer.uri);\n const incomingURL = new URL(req.url, 'http://localhost');\n for (const [key, value] of incomingURL.searchParams.entries()) {\n upstreamURL.searchParams.set(key, value);\n }\n\n try {\n const headers: Record<string, string> = {};\n if (req.headers.authorization) {\n headers.authorization = req.headers.authorization;\n }\n const response = await fetch(upstreamURL.toString(), {\n method: 'GET',\n headers,\n });\n\n res.code(response.status);\n const contentType = response.headers.get('content-type');\n if (contentType) {\n res.header('content-type', contentType);\n }\n const contentDisposition = response.headers.get('content-disposition');\n if (contentDisposition) {\n res.header('content-disposition', contentDisposition);\n }\n\n const body = await response.text();\n return res.send(body);\n } catch (err) {\n lc.error?.(`Failed to proxy /profrmz to RM at ${upstreamURL}:`, err);\n return res.code(502).send({\n error: `Failed to proxy profiling request to RM at ${upstreamURL}: ${String(err)}`,\n });\n }\n }\n\n // In single-node mode, profile local change-streamer / RM process\n return handleProfzRequest(lc, config, req, res, getWorker, 'change-streamer');\n}\n"],"mappings":";;;;;;;;AAgBA,eAAsB,mBACpB,IACA,QACA,KACA,KACA,WACA,cACA,mBAA2B,cACZ;CAEf,IAAI,CAAC,qB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Aa,IAAI,KAAK,KAAK;EAGzC,IAAI;GACF,MAAM,UAAkC,CAAC;GACzC,IAAI,IAAI,QAAQ,eACd,QAAQ,gBAAgB,IAAI,QAAQ;GAEtC,MAAM,WAAW,MAAM,MAAM,YAAY,SAAS,GAAG;IACnD,QAAQ;IACR;GACF,CAAC;GAED,IAAI,KAAK,SAAS,MAAM;GACxB,MAAM,cAAc,SAAS,QAAQ,IAAI,cAAc;GACvD,IAAI,aACF,IAAI,OAAO,gBAAgB,WAAW;GAExC,MAAM,qBAAqB,SAAS,QAAQ,IAAI,qBAAqB;GACrE,IAAI,oBACF,IAAI,OAAO,uBAAuB,kBAAkB;GAGtD,MAAM,OAAO,MAAM,SAAS,KAAK;GACjC,OAAO,IAAI,KAAK,IAAI;EACtB,SAAS,KAAK;GACZ,GAAG,QAAQ,qCAAqC,YAAY,IAAI,GAAG;GACnE,OAAO,IAAI,KAAK,GAAG,EAAE,KAAK,EACxB,OAAO,8CAA8C,YAAY,IAAI,OAAO,GAAG,IACjF,CAAC;EACH;CACF;CAGA,OAAO,mBAAmB,IAAI,QAAQ,KAAK,KAAK,WAAW,iBAAiB;AAC9E"}
@@ -4,7 +4,8 @@ import { type CookieOpTag } from './change-log-cookies.ts';
4
4
  export type ChangeLogStreamTransactionStats = {
5
5
  readonly rows: number;
6
6
  readonly estimatedBytes: number;
7
- readonly hash: string;
7
+ /** Present only for transactions selected for shadow-write validation. */
8
+ readonly hash?: string | undefined;
8
9
  /**
9
10
  * The cookie mutations this transaction's schema changes folded in, in stream
10
11
  * order. Empty for the overwhelming majority of transactions.
@@ -32,7 +33,7 @@ export declare class ChangeLogStreamInvariantError extends Error {
32
33
  export declare class ChangeLogStreamWriter {
33
34
  #private;
34
35
  constructor(db: StatementRunner);
35
- begin(watermark: string, json: string): void;
36
+ begin(watermark: string, json: string, storedChange?: string, hash?: boolean): void;
36
37
  /**
37
38
  * Appends one data or schema change. The parsed message is taken rather than
38
39
  * just its tag because a schema change also mutates the cookie jar, and the
@@ -43,8 +44,8 @@ export declare class ChangeLogStreamWriter {
43
44
  * has to flush its buffered batch to get the same ordering
44
45
  * (`Storer.#processQueue()`); SQLite gets it from statement order.
45
46
  */
46
- append(json: string, change: DataOrSchemaChange): void;
47
- commit(watermark: string, json: string, writeTimeMs: number): ChangeLogStreamTransactionStats;
47
+ append(json: string, change: DataOrSchemaChange, storedChange?: string): void;
48
+ commit(watermark: string, json: string, writeTimeMs: number, storedChange?: string): ChangeLogStreamTransactionStats;
48
49
  /**
49
50
  * Discards the open transaction, if any. Safe to call when none is open — the
50
51
  * caller rolls back on an interrupted change stream, which can arrive between
@@ -1 +1 @@
1
- {"version":3,"file":"change-log-stream-writer.d.ts","sourceRoot":"","sources":["../../../../../../zero-cache/src/services/replicator/change-log-stream-writer.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAC,eAAe,EAAC,MAAM,wBAAwB,CAAC;AAC5D,OAAO,EAEL,KAAK,kBAAkB,EACxB,MAAM,2CAA2C,CAAC;AAGnD,OAAO,EAAwB,KAAK,WAAW,EAAC,MAAM,yBAAyB,CAAC;AAMhF,MAAM,MAAM,+BAA+B,GAAG;IAC5C,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,cAAc,EAAE,MAAM,CAAC;IAChC,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB;;;OAGG;IACH,QAAQ,CAAC,eAAe,EAAE,SAAS,WAAW,EAAE,CAAC;CAClD,CAAC;AAEF,qBAAa,6BAA8B,SAAQ,KAAK;IACtD,SAAkB,IAAI,mCAAmC;CAC1D;AAWD;;;;;;;;;;;;;;GAcG;AACH,qBAAa,qBAAqB;;IAYhC,YAAY,EAAE,EAAE,eAAe,EAc9B;IAED,KAAK,CAAC,SAAS,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,IAAI,CAiC3C;IAED;;;;;;;;;OASG;IACH,MAAM,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,kBAAkB,GAAG,IAAI,CAwBrD;IAED,MAAM,CACJ,SAAS,EAAE,MAAM,EACjB,IAAI,EAAE,MAAM,EACZ,WAAW,EAAE,MAAM,GAClB,+BAA+B,CA2CjC;IAED;;;;OAIG;IACH,QAAQ,IAAI,IAAI,CAMf;CA2BF"}
1
+ {"version":3,"file":"change-log-stream-writer.d.ts","sourceRoot":"","sources":["../../../../../../zero-cache/src/services/replicator/change-log-stream-writer.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAC,eAAe,EAAC,MAAM,wBAAwB,CAAC;AAC5D,OAAO,EAEL,KAAK,kBAAkB,EACxB,MAAM,2CAA2C,CAAC;AAGnD,OAAO,EAAwB,KAAK,WAAW,EAAC,MAAM,yBAAyB,CAAC;AAMhF,MAAM,MAAM,+BAA+B,GAAG;IAC5C,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,cAAc,EAAE,MAAM,CAAC;IAChC,0EAA0E;IAC1E,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IACnC;;;OAGG;IACH,QAAQ,CAAC,eAAe,EAAE,SAAS,WAAW,EAAE,CAAC;CAClD,CAAC;AAEF,qBAAa,6BAA8B,SAAQ,KAAK;IACtD,SAAkB,IAAI,mCAAmC;CAC1D;AAWD;;;;;;;;;;;;;;GAcG;AACH,qBAAa,qBAAqB;;IAYhC,YAAY,EAAE,EAAE,eAAe,EAc9B;IAED,KAAK,CACH,SAAS,EAAE,MAAM,EACjB,IAAI,EAAE,MAAM,EACZ,YAAY,SAAwC,EACpD,IAAI,UAAO,GACV,IAAI,CAmCN;IAED;;;;;;;;;OASG;IACH,MAAM,CACJ,IAAI,EAAE,MAAM,EACZ,MAAM,EAAE,kBAAkB,EAC1B,YAAY,SAA2C,GACtD,IAAI,CAwBN;IAED,MAAM,CACJ,SAAS,EAAE,MAAM,EACjB,IAAI,EAAE,MAAM,EACZ,WAAW,EAAE,MAAM,EACnB,YAAY,SAAyC,GACpD,+BAA+B,CA2CjC;IAED;;;;OAIG;IACH,QAAQ,IAAI,IAAI,CAMf;CAmBF"}
@@ -50,22 +50,24 @@ var ChangeLogStreamWriter = class {
50
50
  `);
51
51
  this.#cookies = new ChangeLogCookieWriter(db.db);
52
52
  }
53
- begin(watermark, json) {
53
+ begin(watermark, json, storedChange = extractChangeSubstring(json, "begin"), hash = true) {
54
54
  assertInvariant(this.#watermark === void 0, `change-log stream transaction already open at ${this.#watermark}`);
55
55
  this.#db.beginImmediate();
56
56
  this.#watermark = watermark;
57
57
  this.#pos = 0;
58
- const change = extractChangeSubstring(json, "begin");
58
+ const change = storedChange;
59
59
  const estimatedBytes = estimateChangeLogStreamRowBytes(watermark, "begin", change);
60
60
  this.#insertChange.run(watermark, this.#pos, "begin", estimatedBytes, change);
61
- this.#hasher = new ChangeLogTransactionHasher();
62
- this.#hasher.add({
63
- watermark,
64
- pos: this.#pos,
65
- tag: "begin",
66
- change,
67
- precommit: null
68
- });
61
+ if (hash) {
62
+ this.#hasher = new ChangeLogTransactionHasher();
63
+ this.#hasher.add({
64
+ watermark,
65
+ pos: this.#pos,
66
+ tag: "begin",
67
+ change,
68
+ precommit: null
69
+ });
70
+ }
69
71
  this.#estimatedBytes = estimatedBytes;
70
72
  }
71
73
  /**
@@ -78,13 +80,13 @@ var ChangeLogStreamWriter = class {
78
80
  * has to flush its buffered batch to get the same ordering
79
81
  * (`Storer.#processQueue()`); SQLite gets it from statement order.
80
82
  */
81
- append(json, change) {
83
+ append(json, change, storedChange = extractChangeSubstring(json, change.tag)) {
82
84
  const watermark = this.#requireWatermark();
83
85
  const { tag } = change;
84
- const stored = extractChangeSubstring(json, tag);
86
+ const stored = storedChange;
85
87
  const estimatedBytes = estimateChangeLogStreamRowBytes(watermark, tag, stored);
86
88
  this.#insertChange.run(watermark, ++this.#pos, tag, estimatedBytes, stored);
87
- this.#requireHasher().add({
89
+ this.#hasher?.add({
88
90
  watermark,
89
91
  pos: this.#pos,
90
92
  tag,
@@ -94,14 +96,14 @@ var ChangeLogStreamWriter = class {
94
96
  this.#estimatedBytes += estimatedBytes;
95
97
  if (isSchemaChange(change)) for (const op of this.#cookies.apply(change)) this.#cookieMutations.push(op.op);
96
98
  }
97
- commit(watermark, json, writeTimeMs) {
99
+ commit(watermark, json, writeTimeMs, storedChange = extractChangeSubstring(json, "commit")) {
98
100
  const precommit = this.#requireWatermark();
99
101
  assertInvariant(watermark === precommit, `change-log stream commit ${watermark} does not match begin ${precommit}`);
100
- const change = extractChangeSubstring(json, "commit");
102
+ const change = storedChange;
101
103
  const estimatedBytes = estimateChangeLogStreamRowBytes(watermark, "commit", change, precommit, true);
102
104
  this.#insertCommit.run(watermark, ++this.#pos, estimatedBytes, change, precommit, writeTimeMs);
103
- const hasher = this.#requireHasher();
104
- hasher.add({
105
+ const hasher = this.#hasher;
106
+ hasher?.add({
105
107
  watermark,
106
108
  pos: this.#pos,
107
109
  tag: "commit",
@@ -111,7 +113,7 @@ var ChangeLogStreamWriter = class {
111
113
  const stats = {
112
114
  rows: this.#pos + 1,
113
115
  estimatedBytes: this.#estimatedBytes + estimatedBytes,
114
- hash: hasher.digest(),
116
+ hash: hasher?.digest(),
115
117
  cookieMutations: this.#cookieMutations
116
118
  };
117
119
  this.#db.commit();
@@ -139,10 +141,6 @@ var ChangeLogStreamWriter = class {
139
141
  assertInvariant(this.#watermark !== void 0, "change-log stream message received outside of a transaction");
140
142
  return this.#watermark;
141
143
  }
142
- #requireHasher() {
143
- assertInvariant(this.#hasher !== void 0, "change-log stream hash received outside of a transaction");
144
- return this.#hasher;
145
- }
146
144
  };
147
145
  //#endregion
148
146
  export { ChangeLogStreamWriter };
@@ -1 +1 @@
1
- {"version":3,"file":"change-log-stream-writer.js","names":["#db","#insertChange","#insertCommit","#cookies","#watermark","#pos","#hasher","#estimatedBytes","#requireWatermark","#requireHasher","#cookieMutations","#reset"],"sources":["../../../../../../zero-cache/src/services/replicator/change-log-stream-writer.ts"],"sourcesContent":["import type {Statement} from '../../../../zqlite/src/db.ts';\nimport type {StatementRunner} from '../../db/statements.ts';\nimport {\n isSchemaChange,\n type DataOrSchemaChange,\n} from '../change-source/protocol/current/data.ts';\nimport {extractChangeSubstring} from '../change-streamer/change-log-codec.ts';\nimport {ChangeLogTransactionHasher} from '../change-streamer/change-log-transaction-hash.ts';\nimport {ChangeLogCookieWriter, type CookieOpTag} from './change-log-cookies.ts';\nimport {\n CHANGE_LOG_STREAM_TABLE,\n estimateChangeLogStreamRowBytes,\n} from './change-log-db.ts';\n\nexport type ChangeLogStreamTransactionStats = {\n readonly rows: number;\n readonly estimatedBytes: number;\n readonly hash: string;\n /**\n * The cookie mutations this transaction's schema changes folded in, in stream\n * order. Empty for the overwhelming majority of transactions.\n */\n readonly cookieMutations: readonly CookieOpTag[];\n};\n\nexport class ChangeLogStreamInvariantError extends Error {\n override readonly name = 'ChangeLogStreamInvariantError';\n}\n\nfunction assertInvariant(\n condition: unknown,\n message: string,\n): asserts condition {\n if (!condition) {\n throw new ChangeLogStreamInvariantError(message);\n }\n}\n\n/**\n * Appends the canonical downstream stream to the change-log database, which is\n * a separate file from the replica, and folds its schema changes into the log's\n * cookie jar (`change-log-cookies.ts`) as it goes.\n *\n * This class owns the change log's transaction, and its transaction alone. It is\n * driven from the change-streamer's stream loop, which commits it before\n * forwarding a transaction's `commit` message; see `SQLiteChangeLogWriter` in\n * `change-streamer/sqlite-change-log-writer.ts` for the ordering that makes a\n * hole unreachable, and for the fail-soft policy that wraps every call here.\n *\n * Because the cookies are written in that same transaction, they are atomic with\n * the head and {@link rollback} discards them with the rows they were folded\n * from. Neither needs any handling of its own.\n */\nexport class ChangeLogStreamWriter {\n readonly #db: StatementRunner;\n readonly #insertChange: Statement;\n readonly #insertCommit: Statement;\n readonly #cookies: ChangeLogCookieWriter;\n\n #watermark: string | undefined;\n #pos = 0;\n #estimatedBytes = 0;\n #hasher: ChangeLogTransactionHasher | undefined;\n #cookieMutations: CookieOpTag[] = [];\n\n constructor(db: StatementRunner) {\n this.#db = db;\n this.#insertChange = db.db.prepare(/*sql*/ `\n INSERT INTO \"${CHANGE_LOG_STREAM_TABLE}\"\n (\"watermark\", \"pos\", \"tag\", \"estimatedBytes\", \"change\")\n VALUES (?, ?, ?, ?, ?)\n `);\n this.#insertCommit = db.db.prepare(/*sql*/ `\n INSERT INTO \"${CHANGE_LOG_STREAM_TABLE}\"\n (\"watermark\", \"pos\", \"tag\", \"estimatedBytes\", \"change\", \"precommit\",\n \"writeTimeMs\")\n VALUES (?, ?, 'commit', ?, ?, ?, ?)\n `);\n this.#cookies = new ChangeLogCookieWriter(db.db);\n }\n\n begin(watermark: string, json: string): void {\n assertInvariant(\n this.#watermark === undefined,\n `change-log stream transaction already open at ${this.#watermark}`,\n );\n // This process is the sole writer of the change-log database, so the write\n // lock is taken up front rather than risking a failed upgrade from a\n // deferred transaction partway through the append.\n this.#db.beginImmediate();\n this.#watermark = watermark;\n this.#pos = 0;\n const change = extractChangeSubstring(json, 'begin');\n const estimatedBytes = estimateChangeLogStreamRowBytes(\n watermark,\n 'begin',\n change,\n );\n this.#insertChange.run(\n watermark,\n this.#pos,\n 'begin',\n estimatedBytes,\n change,\n );\n this.#hasher = new ChangeLogTransactionHasher();\n this.#hasher.add({\n watermark,\n pos: this.#pos,\n tag: 'begin',\n change,\n precommit: null,\n });\n this.#estimatedBytes = estimatedBytes;\n }\n\n /**\n * Appends one data or schema change. The parsed message is taken rather than\n * just its tag because a schema change also mutates the cookie jar, and the\n * caller already holds it — so the fold costs no re-parse.\n *\n * The cookie statements run here, i.e. inside this transaction and in stream\n * order relative to the rows they were folded from. The Postgres change log\n * has to flush its buffered batch to get the same ordering\n * (`Storer.#processQueue()`); SQLite gets it from statement order.\n */\n append(json: string, change: DataOrSchemaChange): void {\n const watermark = this.#requireWatermark();\n const {tag} = change;\n const stored = extractChangeSubstring(json, tag);\n const estimatedBytes = estimateChangeLogStreamRowBytes(\n watermark,\n tag,\n stored,\n );\n this.#insertChange.run(watermark, ++this.#pos, tag, estimatedBytes, stored);\n this.#requireHasher().add({\n watermark,\n pos: this.#pos,\n tag,\n change: stored,\n precommit: null,\n });\n this.#estimatedBytes += estimatedBytes;\n\n if (isSchemaChange(change)) {\n for (const op of this.#cookies.apply(change)) {\n this.#cookieMutations.push(op.op);\n }\n }\n }\n\n commit(\n watermark: string,\n json: string,\n writeTimeMs: number,\n ): ChangeLogStreamTransactionStats {\n const precommit = this.#requireWatermark();\n assertInvariant(\n watermark === precommit,\n `change-log stream commit ${watermark} does not match begin ${precommit}`,\n );\n const change = extractChangeSubstring(json, 'commit');\n const estimatedBytes = estimateChangeLogStreamRowBytes(\n watermark,\n 'commit',\n change,\n precommit,\n true,\n );\n this.#insertCommit.run(\n watermark,\n ++this.#pos,\n estimatedBytes,\n change,\n precommit,\n writeTimeMs,\n );\n const hasher = this.#requireHasher();\n hasher.add({\n watermark,\n pos: this.#pos,\n tag: 'commit',\n change,\n precommit,\n });\n const stats = {\n rows: this.#pos + 1,\n estimatedBytes: this.#estimatedBytes + estimatedBytes,\n hash: hasher.digest(),\n cookieMutations: this.#cookieMutations,\n };\n // The log is durable at `watermark` from here on, and nothing that can\n // advance the watermark the stream would resume from has run yet. A crash in\n // that window leaves a transaction the resumed stream re-delivers, which\n // reconciliation truncates.\n this.#db.commit();\n this.#reset();\n return stats;\n }\n\n /**\n * Discards the open transaction, if any. Safe to call when none is open — the\n * caller rolls back on an interrupted change stream, which can arrive between\n * transactions as well as inside one.\n */\n rollback(): void {\n const {inTransaction} = this.#db.db;\n this.#reset();\n if (inTransaction) {\n this.#db.rollback();\n }\n }\n\n #reset(): void {\n this.#watermark = undefined;\n this.#pos = 0;\n this.#estimatedBytes = 0;\n this.#hasher = undefined;\n // A fresh array rather than a truncation: the committed stats hold a\n // reference to the previous one.\n this.#cookieMutations = [];\n }\n\n #requireWatermark(): string {\n assertInvariant(\n this.#watermark !== undefined,\n 'change-log stream message received outside of a transaction',\n );\n return this.#watermark;\n }\n\n #requireHasher(): ChangeLogTransactionHasher {\n assertInvariant(\n this.#hasher !== undefined,\n 'change-log stream hash received outside of a transaction',\n );\n return this.#hasher;\n }\n}\n"],"mappings":";;;;;;AAyBA,IAAa,gCAAb,cAAmD,MAAM;CACvD,OAAyB;AAC3B;AAEA,SAAS,gBACP,WACA,SACmB;CACnB,IAAI,CAAC,WACH,MAAM,IAAI,8BAA8B,OAAO;AAEnD;;;;;;;;;;;;;;;;AAiBA,IAAa,wBAAb,MAAmC;CACjC;CACA;CACA;CACA;CAEA;CACA,OAAO;CACP,kBAAkB;CAClB;CACA,mBAAkC,CAAC;CAEnC,YAAY,IAAqB;EAC/B,KAAKA,MAAM;EACX,KAAKC,gBAAgB,GAAG,GAAG,QAAgB;qBAC1B,wBAAwB;;;KAGxC;EACD,KAAKC,gBAAgB,GAAG,GAAG,QAAgB;qBAC1B,wBAAwB;;;;KAIxC;EACD,KAAKC,WAAW,IAAI,sBAAsB,GAAG,EAAE;CACjD;CAEA,MAAM,WAAmB,MAAoB;EAC3C,gBACE,KAAKC,eAAe,KAAA,GACpB,iDAAiD,KAAKA,YACxD;EAIA,KAAKJ,IAAI,eAAe;EACxB,KAAKI,aAAa;EAClB,KAAKC,OAAO;EACZ,MAAM,SAAS,uBAAuB,MAAM,OAAO;EACnD,MAAM,iBAAiB,gCACrB,WACA,SACA,MACF;EACA,KAAKJ,cAAc,IACjB,WACA,KAAKI,MACL,SACA,gBACA,MACF;EACA,KAAKC,UAAU,IAAI,2BAA2B;EAC9C,KAAKA,QAAQ,IAAI;GACf;GACA,KAAK,KAAKD;GACV,KAAK;GACL;GACA,WAAW;EACb,CAAC;EACD,KAAKE,kBAAkB;CACzB;;;;;;;;;;;CAYA,OAAO,MAAc,QAAkC;EACrD,MAAM,YAAY,KAAKC,kBAAkB;EACzC,MAAM,EAAC,QAAO;EACd,MAAM,SAAS,uBAAuB,MAAM,GAAG;EAC/C,MAAM,iBAAiB,gCACrB,WACA,KACA,MACF;EACA,KAAKP,cAAc,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AA,GACjB,0DACF;EACA,OAAO,KAAKA;CACd;AACF"}
1
+ {"version":3,"file":"change-log-stream-writer.js","names":["#db","#insertChange","#insertCommit","#cookies","#watermark","#pos","#hasher","#estimatedBytes","#requireWatermark","#cookieMutations","#reset"],"sources":["../../../../../../zero-cache/src/services/replicator/change-log-stream-writer.ts"],"sourcesContent":["import type {Statement} from '../../../../zqlite/src/db.ts';\nimport type {StatementRunner} from '../../db/statements.ts';\nimport {\n isSchemaChange,\n type DataOrSchemaChange,\n} from '../change-source/protocol/current/data.ts';\nimport {extractChangeSubstring} from '../change-streamer/change-log-codec.ts';\nimport {ChangeLogTransactionHasher} from '../change-streamer/change-log-transaction-hash.ts';\nimport {ChangeLogCookieWriter, type CookieOpTag} from './change-log-cookies.ts';\nimport {\n CHANGE_LOG_STREAM_TABLE,\n estimateChangeLogStreamRowBytes,\n} from './change-log-db.ts';\n\nexport type ChangeLogStreamTransactionStats = {\n readonly rows: number;\n readonly estimatedBytes: number;\n /** Present only for transactions selected for shadow-write validation. */\n readonly hash?: string | undefined;\n /**\n * The cookie mutations this transaction's schema changes folded in, in stream\n * order. Empty for the overwhelming majority of transactions.\n */\n readonly cookieMutations: readonly CookieOpTag[];\n};\n\nexport class ChangeLogStreamInvariantError extends Error {\n override readonly name = 'ChangeLogStreamInvariantError';\n}\n\nfunction assertInvariant(\n condition: unknown,\n message: string,\n): asserts condition {\n if (!condition) {\n throw new ChangeLogStreamInvariantError(message);\n }\n}\n\n/**\n * Appends the canonical downstream stream to the change-log database, which is\n * a separate file from the replica, and folds its schema changes into the log's\n * cookie jar (`change-log-cookies.ts`) as it goes.\n *\n * This class owns the change log's transaction, and its transaction alone. It is\n * driven from the change-streamer's stream loop, which commits it before\n * forwarding a transaction's `commit` message; see `SQLiteChangeLogWriter` in\n * `change-streamer/sqlite-change-log-writer.ts` for the ordering that makes a\n * hole unreachable, and for the fail-soft policy that wraps every call here.\n *\n * Because the cookies are written in that same transaction, they are atomic with\n * the head and {@link rollback} discards them with the rows they were folded\n * from. Neither needs any handling of its own.\n */\nexport class ChangeLogStreamWriter {\n readonly #db: StatementRunner;\n readonly #insertChange: Statement;\n readonly #insertCommit: Statement;\n readonly #cookies: ChangeLogCookieWriter;\n\n #watermark: string | undefined;\n #pos = 0;\n #estimatedBytes = 0;\n #hasher: ChangeLogTransactionHasher | undefined;\n #cookieMutations: CookieOpTag[] = [];\n\n constructor(db: StatementRunner) {\n this.#db = db;\n this.#insertChange = db.db.prepare(/*sql*/ `\n INSERT INTO \"${CHANGE_LOG_STREAM_TABLE}\"\n (\"watermark\", \"pos\", \"tag\", \"estimatedBytes\", \"change\")\n VALUES (?, ?, ?, ?, ?)\n `);\n this.#insertCommit = db.db.prepare(/*sql*/ `\n INSERT INTO \"${CHANGE_LOG_STREAM_TABLE}\"\n (\"watermark\", \"pos\", \"tag\", \"estimatedBytes\", \"change\", \"precommit\",\n \"writeTimeMs\")\n VALUES (?, ?, 'commit', ?, ?, ?, ?)\n `);\n this.#cookies = new ChangeLogCookieWriter(db.db);\n }\n\n begin(\n watermark: string,\n json: string,\n storedChange = extractChangeSubstring(json, 'begin'),\n hash = true,\n ): void {\n assertInvariant(\n this.#watermark === undefined,\n `change-log stream transaction already open at ${this.#watermark}`,\n );\n // This process is the sole writer of the change-log database, so the write\n // lock is taken up front rather than risking a failed upgrade from a\n // deferred transaction partway through the append.\n this.#db.beginImmediate();\n this.#watermark = watermark;\n this.#pos = 0;\n const change = storedChange;\n const estimatedBytes = estimateChangeLogStreamRowBytes(\n watermark,\n 'begin',\n change,\n );\n this.#insertChange.run(\n watermark,\n this.#pos,\n 'begin',\n estimatedBytes,\n change,\n );\n if (hash) {\n this.#hasher = new ChangeLogTransactionHasher();\n this.#hasher.add({\n watermark,\n pos: this.#pos,\n tag: 'begin',\n change,\n precommit: null,\n });\n }\n this.#estimatedBytes = estimatedBytes;\n }\n\n /**\n * Appends one data or schema change. The parsed message is taken rather than\n * just its tag because a schema change also mutates the cookie jar, and the\n * caller already holds it — so the fold costs no re-parse.\n *\n * The cookie statements run here, i.e. inside this transaction and in stream\n * order relative to the rows they were folded from. The Postgres change log\n * has to flush its buffered batch to get the same ordering\n * (`Storer.#processQueue()`); SQLite gets it from statement order.\n */\n append(\n json: string,\n change: DataOrSchemaChange,\n storedChange = extractChangeSubstring(json, change.tag),\n ): void {\n const watermark = this.#requireWatermark();\n const {tag} = change;\n const stored = storedChange;\n const estimatedBytes = estimateChangeLogStreamRowBytes(\n watermark,\n tag,\n stored,\n );\n this.#insertChange.run(watermark, ++this.#pos, tag, estimatedBytes, stored);\n this.#hasher?.add({\n watermark,\n pos: this.#pos,\n tag,\n change: stored,\n precommit: null,\n });\n this.#estimatedBytes += estimatedBytes;\n\n if (isSchemaChange(change)) {\n for (const op of this.#cookies.apply(change)) {\n this.#cookieMutations.push(op.op);\n }\n }\n }\n\n commit(\n watermark: string,\n json: string,\n writeTimeMs: number,\n storedChange = extractChangeSubstring(json, 'commit'),\n ): ChangeLogStreamTransactionStats {\n const precommit = this.#requireWatermark();\n assertInvariant(\n watermark === precommit,\n `change-log stream commit ${watermark} does not match begin ${precommit}`,\n );\n const change = storedChange;\n const estimatedBytes = estimateChangeLogStreamRowBytes(\n watermark,\n 'commit',\n change,\n precommit,\n true,\n );\n this.#insertCommit.run(\n watermark,\n ++this.#pos,\n estimatedBytes,\n change,\n precommit,\n writeTimeMs,\n );\n const hasher = this.#hasher;\n hasher?.add({\n watermark,\n pos: this.#pos,\n tag: 'commit',\n change,\n precommit,\n });\n const stats = {\n rows: this.#pos + 1,\n estimatedBytes: this.#estimatedBytes + estimatedBytes,\n hash: hasher?.digest(),\n cookieMutations: this.#cookieMutations,\n };\n // The log is durable at `watermark` from here on, and nothing that can\n // advance the watermark the stream would resume from has run yet. A crash in\n // that window leaves a transaction the resumed stream re-delivers, which\n // reconciliation truncates.\n this.#db.commit();\n this.#reset();\n return stats;\n }\n\n /**\n * Discards the open transaction, if any. Safe to call when none is open — the\n * caller rolls back on an interrupted change stream, which can arrive between\n * transactions as well as inside one.\n */\n rollback(): void {\n const {inTransaction} = this.#db.db;\n this.#reset();\n if (inTransaction) {\n this.#db.rollback();\n }\n }\n\n #reset(): void {\n this.#watermark = undefined;\n this.#pos = 0;\n this.#estimatedBytes = 0;\n this.#hasher = undefined;\n // A fresh array rather than a truncation: the committed stats hold a\n // reference to the previous one.\n this.#cookieMutations = [];\n }\n\n #requireWatermark(): string {\n assertInvariant(\n this.#watermark !== undefined,\n 'change-log stream message received outside of a transaction',\n );\n return this.#watermark;\n }\n}\n"],"mappings":";;;;;;AA0BA,IAAa,gCAAb,cAAmD,MAAM;CACvD,OAAyB;AAC3B;AAEA,SAAS,gBACP,WACA,SACmB;CACnB,IAAI,CAAC,WACH,MAAM,IAAI,8BAA8B,OAAO;AAEnD;;;;;;;;;;;;;;;;AAiBA,IAAa,wBAAb,MAAmC;CACjC;CACA;CACA;CACA;CAEA;CACA,OAAO;CACP,kBAAkB;CAClB;CACA,mBAAkC,CAAC;CAEnC,YAAY,IAAqB;EAC/B,KAAKA,MAAM;EACX,KAAKC,gBAAgB,GAAG,GAAG,QAAgB;qBAC1B,wBAAwB;;;KAGxC;EACD,KAAKC,gBAAgB,GAAG,GAAG,QAAgB;qBAC1B,wBAAwB;;;;KAIxC;EACD,KAAKC,WAAW,IAAI,sBAAsB,GAAG,EAAE;CACjD;CAEA,MACE,WACA,MACA,eAAe,uBAAuB,MAAM,OAAO,GACnD,OAAO,MACD;EACN,gBACE,KAAKC,eAAe,KAAA,GACpB,iDAAiD,KAAKA,YACxD;EAIA,KAAKJ,IAAI,eAAe;EACxB,KAAKI,aAAa;EAClB,KAAKC,OAAO;EACZ,MAAM,SAAS;EACf,MAAM,iBAAiB,gCACrB,WACA,SACA,MACF;EACA,KAAKJ,cAAc,IACjB,WACA,KAAKI,MACL,SACA,gBACA,MACF;EACA,IAAI,MAAM;GACR,KAAKC,UAAU,IAAI,2BAA2B;GAC9C,KAAKA,QAAQ,IAAI;IACf;IACA,KAAK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I,SAAS;CAEtB;CAEA,SAAe;EACb,KAAKI,aAAa,KAAA;EAClB,KAAKC,OAAO;EACZ,KAAKE,kBAAkB;EACvB,KAAKD,UAAU,KAAA;EAGf,KAAKG,mBAAmB,CAAC;CAC3B;CAEA,oBAA4B;EAC1B,gBACE,KAAKL,eAAe,KAAA,GACpB,6DACF;EACA,OAAO,KAAKA;CACd;AACF"}
@@ -102,14 +102,14 @@ export declare class SQLiteChangeLogObserver {
102
102
  #private;
103
103
  constructor(lc: LogContext, info: SQLiteChangeLogInfo);
104
104
  /**
105
- * Called as each message arrives, before it is written. Hashes the *received*
106
- * stream, which is compared against the hash the writer computes over what it
107
- * *stored*.
105
+ * Called as each message arrives, before it is written. For a sampled
106
+ * transaction, hashes the *received* stream and compares it with the hash the
107
+ * writer computes over what it *stored*.
108
108
  */
109
- messageReceived(data: ChangeStreamData, json: string): void;
109
+ messageReceived(data: ChangeStreamData, json: string, validateHash?: boolean, storedChange?: string): void;
110
110
  /** Called after the message has been written to the log. */
111
- messageProcessed(data: ChangeStreamData, commit: ChangeLogCommit | null, durationMs: number): void;
112
- messageFailed(data: ChangeStreamData, error: unknown, durationMs: number): void;
111
+ messageProcessed(data: ChangeStreamData, commit: ChangeLogCommit | null, durationMs: number | undefined): void;
112
+ messageFailed(data: ChangeStreamData, error: unknown, durationMs: number | undefined): void;
113
113
  /**
114
114
  * A committed transaction folded schema changes into the cookie jar. Reported
115
115
  * separately from {@link messageProcessed} because it costs a read of the
@@ -1 +1 @@
1
- {"version":3,"file":"sqlite-change-log-observability.d.ts","sourceRoot":"","sources":["../../../../../../zero-cache/src/services/replicator/sqlite-change-log-observability.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAGH,OAAO,KAAK,EAAC,UAAU,EAAC,MAAM,kBAAkB,CAAC;AAEjD,OAAO,KAAK,EAAC,QAAQ,EAAC,MAAM,8BAA8B,CAAC;AAQ3D,OAAO,KAAK,EAAC,gBAAgB,EAAC,MAAM,iDAAiD,C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E,MAAM,EAAE,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI,CAEzE;IAED,yDAAyD;IACzD,KAAK,IAAI,IAAI,CAMZ;IAED,4EAA4E;IAC5E,UAAU,CAAC,IAAI,EAAE,mBAAmB,GAAG,IAAI,CAQ1C;IAED,KAAK,IAAI,iCAAiC,CAezC;CA2DF"}
1
+ {"version":3,"file":"sqlite-change-log-observability.d.ts","sourceRoot":"","sources":["../../../../../../zero-cache/src/services/replicator/sqlite-change-log-observability.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAGH,OAAO,KAAK,EAAC,UAAU,EAAC,MAAM,kBAAkB,CAAC;AAEjD,OAAO,KAAK,EAAC,QAAQ,EAAC,MAAM,8BAA8B,CAAC;AAQ3D,OAAO,KAAK,EAAC,gBAAgB,EAAC,MAAM,iDAAiD,CAAC;AAGtF,OAAO,EAEL,KAAK,WAAW,EAChB,KAAK,eAAe,EACrB,MAAM,yBAAyB,CAAC;AACjC,OAAO,EAIL,KAAK,aAAa,EAClB,KAAK,eAAe,EACrB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,KAAK,EAAC,+BAA+B,EAAC,MAAM,+BAA+B,CAAC;AAEnF;;;;;;;;;;;GAWG;AACH,wBAAgB,8BAA8B,CAC5C,EAAE,EAAE,UAAU,EACd,MAAM,EAAE,eAAe,GACtB,IAAI,CAsCN;AAED;;;;GAIG;AACH,MAAM,MAAM,0BAA0B,GAAG,aAAa,GAAG;IACvD,QAAQ,CAAC,YAAY,EAAE,MAAM,CAAC;IAC9B,QAAQ,CAAC,aAAa,EAAE,MAAM,CAAC;CAChC,CAAC;AAEF,MAAM,MAAM,mBAAmB,GAAG,0BAA0B,GAAG;IAC7D,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,cAAc,EAAE,MAAM,CAAC;IAChC,QAAQ,CAAC,UAAU,EAAE,eAAe,CAAC;CACtC,CAAC;AAE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;;IAuElC,YAAY,EAAE,EAAE,UAAU,EAAE,IAAI,EAAE,mBAAmB,EAoDpD;IAED;;;;OAIG;IACH,eAAe,CACb,IAAI,EAAE,gBAAgB,EACtB,IAAI,EAAE,MAAM,EACZ,YAAY,UAAO,EACnB,YAAY,SAA4C,GACvD,IAAI,CA4DN;IAED,4DAA4D;IAC5D,gBAAgB,CACd,IAAI,EAAE,gBAAgB,EACtB,MAAM,EAAE,eAAe,GAAG,IAAI,EAC9B,UAAU,EAAE,MAAM,GAAG,SAAS,GAC7B,IAAI,CA0EN;IAED,aAAa,CACX,IAAI,EAAE,gBAAgB,EACtB,KAAK,EAAE,OAAO,EACd,UAAU,EAAE,MAAM,GAAG,SAAS,GAC7B,IAAI,CAsBN;IAED;;;;OAIG;IACH,cAAc,CAAC,GAAG,EAAE,SAAS,WAAW,EAAE,EAAE,IAAI,EAAE,eAAe,GAAG,IAAI,CAMvE;IAED;;;;;OAKG;IACH,gBAAgB,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI,CAEzE;IAED,yDAAyD;IACzD,KAAK,IAAI,IAAI,CAMZ;IAED,4EAA4E;IAC5E,UAAU,CAAC,IAAI,EAAE,mBAAmB,GAAG,IAAI,CAQ1C;IAED,KAAK,IAAI,iCAAiC,CAezC;CA+DF"}
@@ -137,7 +137,7 @@ var TRANSACTION_ROW_BUCKETS = [
137
137
  */
138
138
  var SQLiteChangeLogObserver = class {
139
139
  #lc;
140
- #messageProcessing = getOrCreateLatencyHistogram("replica", "sqlite_change_log.message_processing_duration", "Time to write a replication message to the SQLite change log.");
140
+ #messageProcessing = getOrCreateLatencyHistogram("replica", "sqlite_change_log.message_processing_duration", "Sampled time to write a replication message to the SQLite change log.");
141
141
  #logCommitDuration = getOrCreateLatencyHistogram("replica", "sqlite_change_log.log_commit_duration", "Time to append the commit row to the SQLite change log and commit its transaction. This is on the forward path: it precedes the forward of that transaction's commit message.");
142
142
  #transactionRows = getOrCreateValueHistogram("replica", "sqlite_change_log.transaction_rows", {
143
143
  description: "Rows stored per committed SQLite change-log transaction.",
@@ -146,7 +146,7 @@ var SQLiteChangeLogObserver = class {
146
146
  });
147
147
  #rollbackCounter = getOrCreateCounter("replica", "sqlite_change_log.rollbacks", "SQLite change-log transactions rolled back before commit.");
148
148
  #invariantFailureCounter = getOrCreateCounter("replica", "sqlite_change_log.invariant_failures", "Detected SQLite change-log writer invariant failures.");
149
- #hashComparisonCounter = getOrCreateCounter("replica", "sqlite_change_log.hash_comparisons", "Ephemeral transaction hash comparisons between the received change stream and SQLite change-log writes.");
149
+ #hashComparisonCounter = getOrCreateCounter("replica", "sqlite_change_log.hash_comparisons", "Sampled ephemeral transaction hash comparisons between the received change stream and SQLite change-log writes.");
150
150
  #hashUnpairedCounter = getOrCreateCounter("replica", "sqlite_change_log.hash_unpaired", "Committed change-log transactions without both ephemeral hashes available for comparison.");
151
151
  #cookieMutationCounter = getOrCreateCounter("replica", "sqlite_change_log.cookie_mutations", "Change-log cookie mutations folded from schema changes, by operation.");
152
152
  #receivedHead;
@@ -190,23 +190,23 @@ var SQLiteChangeLogObserver = class {
190
190
  });
191
191
  }
192
192
  /**
193
- * Called as each message arrives, before it is written. Hashes the *received*
194
- * stream, which is compared against the hash the writer computes over what it
195
- * *stored*.
193
+ * Called as each message arrives, before it is written. For a sampled
194
+ * transaction, hashes the *received* stream and compares it with the hash the
195
+ * writer computes over what it *stored*.
196
196
  */
197
- messageReceived(data, json) {
197
+ messageReceived(data, json, validateHash = true, storedChange = extractChangeSubstring(json, data[1].tag)) {
198
198
  const tag = data[1].tag;
199
199
  if (data[0] === "begin") {
200
200
  if (this.#sourceHasher !== void 0) this.#invariantFailure("Received change-log begin while a source hash is already open", { receivedWatermark: data[2].commitWatermark });
201
201
  const watermark = data[2].commitWatermark;
202
- this.#sourceHasher = new ChangeLogTransactionHasher();
202
+ this.#sourceHasher = validateHash ? new ChangeLogTransactionHasher() : void 0;
203
203
  this.#sourcePos = 0;
204
204
  this.#sourceCommitHash = void 0;
205
- this.#sourceHasher.add({
205
+ this.#sourceHasher?.add({
206
206
  watermark,
207
207
  pos: this.#sourcePos,
208
208
  tag,
209
- change: extractChangeSubstring(json, tag),
209
+ change: storedChange,
210
210
  precommit: null
211
211
  });
212
212
  return;
@@ -216,6 +216,7 @@ var SQLiteChangeLogObserver = class {
216
216
  return;
217
217
  }
218
218
  if (data[0] === "commit") this.#receivedHead = data[2].watermark;
219
+ if (!validateHash) return;
219
220
  const watermark = this.#transactionWatermark;
220
221
  if (this.#sourceHasher === void 0 || watermark === void 0) {
221
222
  this.#invariantFailure("Received change-log message without an observed transaction", { tag });
@@ -226,7 +227,7 @@ var SQLiteChangeLogObserver = class {
226
227
  watermark: commitWatermark,
227
228
  pos: ++this.#sourcePos,
228
229
  tag,
229
- change: extractChangeSubstring(json, tag),
230
+ change: storedChange,
230
231
  precommit: data[0] === "commit" ? watermark : null
231
232
  });
232
233
  if (data[0] === "commit") {
@@ -237,7 +238,7 @@ var SQLiteChangeLogObserver = class {
237
238
  /** Called after the message has been written to the log. */
238
239
  messageProcessed(data, commit, durationMs) {
239
240
  const tag = data[1].tag;
240
- this.#messageProcessing.recordMs(durationMs, {
241
+ if (durationMs !== void 0) this.#messageProcessing.recordMs(durationMs, {
241
242
  tag,
242
243
  outcome: "success"
243
244
  });
@@ -273,7 +274,7 @@ var SQLiteChangeLogObserver = class {
273
274
  this.#rows += commit.stats.rows;
274
275
  this.#estimatedBytes += commit.stats.estimatedBytes;
275
276
  this.#transactionRows.record(commit.stats.rows);
276
- this.#compareHashes(watermark, this.#sourceCommitHash, commit.stats.hash);
277
+ if (this.#sourceCommitHash !== void 0 || commit.stats.hash !== void 0) this.#compareHashes(watermark, this.#sourceCommitHash, commit.stats.hash);
277
278
  }
278
279
  if (watermark < this.#sqliteHead) this.#invariantFailure("SQLite change-log head regressed", {
279
280
  previousHead: this.#sqliteHead,
@@ -285,11 +286,11 @@ var SQLiteChangeLogObserver = class {
285
286
  }
286
287
  messageFailed(data, error, durationMs) {
287
288
  const tag = data[1].tag;
288
- this.#messageProcessing.recordMs(durationMs, {
289
+ if (durationMs !== void 0) this.#messageProcessing.recordMs(durationMs, {
289
290
  tag,
290
291
  outcome: "error"
291
292
  });
292
- if (data[0] === "commit") this.#recordUnpaired(data[2].watermark, "sqlite-commit-failed");
293
+ if (data[0] === "commit" && this.#sourceCommitHash !== void 0) this.#recordUnpaired(data[2].watermark, "sqlite-commit-failed");
293
294
  if (error instanceof Error && error.name === "ChangeLogStreamInvariantError") this.#invariantFailure(error.message);
294
295
  if (this.#transactionWatermark !== void 0 || data[0] === "begin") this.#recordRollback("processing-error");
295
296
  this.#transactionWatermark = void 0;
@@ -364,6 +365,10 @@ var SQLiteChangeLogObserver = class {
364
365
  this.#recordUnpaired(watermark, "missing-source-hash");
365
366
  return;
366
367
  }
368
+ if (sqliteHash === void 0) {
369
+ this.#recordUnpaired(watermark, "missing-sqlite-hash");
370
+ return;
371
+ }
367
372
  if (sourceHash === sqliteHash) {
368
373
  this.#hashMatches++;
369
374
  this.#hashComparisonCounter.add(1, { outcome: "match" });
@@ -1 +1 @@
1
- {"version":3,"file":"sqlite-change-log-observability.js","names":["#lc","#messageProcessing","#logCommitDuration","#transactionRows","#rollbackCounter","#invariantFailureCounter","#hashComparisonCounter","#hashUnpairedCounter","#cookieMutationCounter","#receivedHead","#sqliteHead","#rows","#estimatedBytes","#cookieRows","#sourceHasher","#invariantFailure","#sourcePos","#sourceCommitHash","#resetSourceHash","#transactionWatermark","#recordRollback","#recordUnpaired","#compareHashes","#cookieMutations","#rollbacks","#invariantFailures","#hashMatches","#hashMismatches","#hashUnpaired"],"sources":["../../../../../../zero-cache/src/services/replicator/sqlite-change-log-observability.ts"],"sourcesContent":["/**\n * Observability for the SQLite change log.\n *\n * Everything here now runs in the **change-streamer** process, which is where\n * the writer lives. The module stays beside the rest of the change-log code\n * under `services/replicator/` for the same reason `change-log-db.ts` and\n * `change-log-stream-writer.ts` do: moving files would obscure the topology\n * diff, and the writer's home is a property of who calls it rather than of\n * where it sits. Metric names are unchanged from 7H — only their emitting\n * process, and therefore their resource attributes, moved.\n */\n\nimport {stat} from 'node:fs/promises';\nimport type {LogContext} from '@rocicorp/logger';\nimport {unreachable} from '../../../../shared/src/asserts.ts';\nimport type {Database} from '../../../../zqlite/src/db.ts';\nimport {\n getOrCreateCounter,\n getOrCreateGauge,\n getOrCreateLatencyHistogram,\n getOrCreateValueHistogram,\n} from '../../observability/metrics.ts';\nimport {versionFromLexi} from '../../types/lexi-version.ts';\nimport type {ChangeStreamData} from '../change-source/protocol/current/downstream.ts';\nimport {extractChangeSubstring} from '../change-streamer/change-log-codec.ts';\nimport {ChangeLogTransactionHasher} from '../change-streamer/change-log-transaction-hash.ts';\nimport {\n readCookieRowCounts,\n type CookieOpTag,\n type CookieRowCounts,\n} from './change-log-cookies.ts';\nimport {\n CHANGE_LOG_STREAM_TABLE,\n readChangeLogBounds,\n readChangeLogMeta,\n type ChangeLogMeta,\n type ReconcileResult,\n} from './change-log-db.ts';\nimport type {ChangeLogStreamTransactionStats} from './change-log-stream-writer.ts';\n\n/**\n * Reports the reconciliation of the change-log database against the watermark\n * the stream connection resumes from. This runs once per stream connection, so\n * a reconnect storm is visible here as well as a restart.\n *\n * A wipe is not an error — it is how every abnormal change-log state is\n * collapsed into a correct one — but each wipe costs the retention window, so\n * every reconnecting subscriber below the head gets `too-old`. The `gap` reason\n * in particular means the log neither held the resume watermark nor could be\n * truncated to it, so a nonzero rate in steady state is an alert, not a\n * statistic.\n */\nexport function recordSQLiteChangeLogReconcile(\n lc: LogContext,\n result: ReconcileResult,\n): void {\n switch (result.action) {\n case 'truncated':\n getOrCreateCounter(\n 'replica',\n 'sqlite_change_log.reconcile_truncated_rows',\n 'Phantom change-log rows removed at reconciliation, i.e. rows above ' +\n 'the watermark the change stream resumed from.',\n ).add(result.rows);\n break;\n case 'reseeded':\n getOrCreateCounter(\n 'replica',\n 'sqlite_change_log.reconcile_wipes',\n 'Change-log wipes at reconciliation, by reason. Each one resets the ' +\n 'retention window, so subscribers below the head get `too-old`.',\n ).add(1, {reason: result.reason});\n break;\n case 'none':\n break;\n default:\n unreachable(result);\n }\n if (result.cookiesStale) {\n // The invariant-17 counter: after any reconcile that moved the head, the\n // log's cookie set has to be replaced with the one that belongs to the\n // resume watermark. A nonzero `truncated` series in steady state means\n // phantom truncation is happening on a shard where it should not.\n getOrCreateCounter(\n 'replica',\n 'sqlite_change_log.cookie_reseed',\n 'Change-log cookie sets invalidated at reconciliation, by the ' +\n 'reconcile action that invalidated them.',\n ).add(1, {action: result.action});\n }\n lc.debug?.('SQLite change-log reconciliation', {\n sqliteChangeLogReconcile: result,\n });\n}\n\n/**\n * What the log says about itself. Nothing here reads the replica: after the\n * writer moved to the change-streamer, the replica's state version is a\n * consequence of this log rather than a fact about it.\n */\nexport type SQLiteChangeLogStartupInfo = ChangeLogMeta & {\n readonly minWatermark: string;\n readonly headWatermark: string;\n};\n\nexport type SQLiteChangeLogInfo = SQLiteChangeLogStartupInfo & {\n readonly rows: number;\n readonly estimatedBytes: number;\n readonly cookieRows: CookieRowCounts;\n};\n\n/**\n * Reads the meta row and covered range. Unlike {@link getSQLiteChangeLogInfo}\n * this does not scan the log; see {@link readChangeLogBounds}.\n *\n * Call this after reconciliation, which is the only point at which the head is\n * known to be the resume watermark.\n */\nexport function getSQLiteChangeLogStartupInfo(\n changeLog: Database,\n): SQLiteChangeLogStartupInfo {\n const meta = readChangeLogMeta(changeLog);\n const {minWatermark, headWatermark} = readChangeLogBounds(changeLog);\n if (minWatermark === null || headWatermark === null) {\n throw new Error('the SQLite change log must contain its seed transaction');\n }\n return {...meta, minWatermark, headWatermark};\n}\n\n/**\n * Extends {@link getSQLiteChangeLogStartupInfo} with the retained row and\n * estimated byte totals. Computing these scans the entire change-log table, so\n * only call it when the totals are consumed, i.e. when the writer (and thus the\n * observer) is enabled.\n */\nexport function getSQLiteChangeLogInfo(\n changeLog: Database,\n): SQLiteChangeLogInfo {\n const startup = getSQLiteChangeLogStartupInfo(changeLog);\n const aggregate = changeLog\n .prepare(/*sql*/ `\n SELECT count(*) AS \"rows\",\n coalesce(sum(\"estimatedBytes\"), 0) AS \"estimatedBytes\"\n FROM \"${CHANGE_LOG_STREAM_TABLE}\"\n `)\n .get<{rows: number; estimatedBytes: number}>();\n\n return {\n ...startup,\n rows: aggregate.rows,\n estimatedBytes: aggregate.estimatedBytes,\n cookieRows: readCookieRowCounts(changeLog),\n };\n}\n\nexport function logSQLiteChangeLogStartup(\n lc: LogContext,\n file: string,\n info: SQLiteChangeLogStartupInfo,\n): void {\n lc.info?.('SQLite change-log startup', {\n sqliteChangeLog: {\n file,\n epoch: info.epoch,\n generation: info.generation,\n replicaID: info.replicaID,\n schemaVersion: info.schemaVersion,\n seedWatermark: info.seedWatermark,\n seededAtMs: info.seededAtMs,\n minWatermark: info.minWatermark,\n headWatermark: info.headWatermark,\n },\n });\n}\n\n/**\n * The on-disk footprint of a SQLite database: its main file plus its `-wal` and\n * `-wal2` sidecars, whichever exist. `-shm` is excluded — it is a\n * shared-memory index rather than retained bytes.\n *\n * A missing file counts as zero rather than warning. Which sidecars exist\n * depends on the journal mode, and the change-log database is absent entirely\n * until the writer creates it.\n */\nexport async function sqliteFileBytes(\n lc: LogContext,\n file: string,\n): Promise<number> {\n const sizes = await Promise.all(\n [file, `${file}-wal`, `${file}-wal2`].map(async path => {\n try {\n return (await stat(path)).size;\n } catch (e) {\n if ((e as NodeJS.ErrnoException).code !== 'ENOENT') {\n lc.warn?.(`unable to stat ${path} for size metrics`, e);\n }\n return 0;\n }\n }),\n );\n return sizes.reduce((total, size) => total + size, 0);\n}\n\n/** What the writer reports back for a committed transaction. */\nexport type ChangeLogCommit = {\n readonly watermark: string;\n readonly stats: ChangeLogStreamTransactionStats;\n /**\n * Appending the commit row and committing the log's transaction. This is the\n * cost that sits on the forward path, once per upstream transaction.\n */\n readonly logCommitMs: number;\n};\n\nexport type SQLiteChangeLogObservabilityState = {\n readonly receivedHead: string;\n readonly sqliteHead: string;\n readonly headLag: number | undefined;\n readonly rows: number;\n readonly estimatedBytes: number;\n readonly cookieRows: CookieRowCounts;\n readonly cookieMutations: number;\n readonly rollbacks: number;\n readonly invariantFailures: number;\n readonly hashMatches: number;\n readonly hashMismatches: number;\n readonly hashUnpaired: number;\n};\n\nconst TRANSACTION_ROW_BUCKETS = [2, 3, 5, 10, 25, 50, 100, 250, 1000, 5000];\n\n/**\n * Records writer metrics in the change-streamer process. State changes only\n * after the corresponding write succeeds, except receivedHead, which advances\n * when a commit message arrives so that transient lag behind the log is\n * observable.\n */\nexport class SQLiteChangeLogObserver {\n readonly #lc: LogContext;\n readonly #messageProcessing = getOrCreateLatencyHistogram(\n 'replica',\n 'sqlite_change_log.message_processing_duration',\n 'Time to write a replication message to the SQLite change log.',\n );\n // The commit that sits on the forward path. There is no second commit to\n // order against any more: the replica's belongs to a subscriber downstream of\n // this loop, so `sqlite_change_log.replica_commit_duration` and the phantom\n // window it measured are gone. A failed commit is still timed, by\n // `message_processing_duration` keyed `tag=\"commit\"`.\n readonly #logCommitDuration = getOrCreateLatencyHistogram(\n 'replica',\n 'sqlite_change_log.log_commit_duration',\n 'Time to append the commit row to the SQLite change log and commit its ' +\n 'transaction. This is on the forward path: it precedes the forward of ' +\n \"that transaction's commit message.\",\n );\n readonly #transactionRows = getOrCreateValueHistogram(\n 'replica',\n 'sqlite_change_log.transaction_rows',\n {\n description: 'Rows stored per committed SQLite change-log transaction.',\n unit: '{row}',\n bucketBoundaries: TRANSACTION_ROW_BUCKETS,\n },\n );\n readonly #rollbackCounter = getOrCreateCounter(\n 'replica',\n 'sqlite_change_log.rollbacks',\n 'SQLite change-log transactions rolled back before commit.',\n );\n readonly #invariantFailureCounter = getOrCreateCounter(\n 'replica',\n 'sqlite_change_log.invariant_failures',\n 'Detected SQLite change-log writer invariant failures.',\n );\n readonly #hashComparisonCounter = getOrCreateCounter(\n 'replica',\n 'sqlite_change_log.hash_comparisons',\n 'Ephemeral transaction hash comparisons between the received change stream and SQLite change-log writes.',\n );\n readonly #hashUnpairedCounter = getOrCreateCounter(\n 'replica',\n 'sqlite_change_log.hash_unpaired',\n 'Committed change-log transactions without both ephemeral hashes available for comparison.',\n );\n // Near zero at steady state: cookie state only moves on schema changes.\n readonly #cookieMutationCounter = getOrCreateCounter(\n 'replica',\n 'sqlite_change_log.cookie_mutations',\n 'Change-log cookie mutations folded from schema changes, by operation.',\n );\n\n #receivedHead: string;\n #sqliteHead: string;\n #rows: number;\n #estimatedBytes: number;\n #cookieRows: CookieRowCounts;\n #cookieMutations = 0;\n #transactionWatermark: string | undefined;\n #sourceHasher: ChangeLogTransactionHasher | undefined;\n #sourcePos = 0;\n #sourceCommitHash: string | undefined;\n #rollbacks = 0;\n #invariantFailures = 0;\n #hashMatches = 0;\n #hashMismatches = 0;\n #hashUnpaired = 0;\n\n constructor(lc: LogContext, info: SQLiteChangeLogInfo) {\n this.#lc = lc.withContext('component', 'sqlite-change-log-observer');\n // Reconciliation has just put the head at the resume watermark, which is\n // also the point the stream is about to be received from.\n this.#receivedHead = info.headWatermark;\n this.#sqliteHead = info.headWatermark;\n this.#rows = info.rows;\n this.#estimatedBytes = info.estimatedBytes;\n this.#cookieRows = info.cookieRows;\n\n getOrCreateGauge(\n 'replica',\n 'sqlite_change_log.rows',\n 'Rows retained in the SQLite change log.',\n ).addCallback(result => result.observe(this.#rows));\n // Nonzero with no backfill in flight is a leaked cookie, i.e. a backfill\n // that will be re-requested forever.\n getOrCreateGauge(\n 'replica',\n 'sqlite_change_log.cookie_rows',\n 'Cookie rows retained in the SQLite change log, by cookie table.',\n ).addCallback(result => {\n result.observe(this.#cookieRows.tableMetadata, {table: 'tableMetadata'});\n result.observe(this.#cookieRows.backfilling, {table: 'backfilling'});\n });\n getOrCreateGauge('replica', 'sqlite_change_log.retained_bytes', {\n description:\n 'Estimated UTF-8 payload bytes retained in the SQLite change log.',\n unit: 'By',\n }).addCallback(result => result.observe(this.#estimatedBytes));\n getOrCreateGauge(\n 'replica',\n 'sqlite_change_log.head',\n 'SQLite change-log head converted from its lexicographic watermark.',\n ).addCallback(result => {\n const head = watermarkValue(this.#sqliteHead);\n if (head !== undefined) {\n result.observe(head);\n }\n });\n getOrCreateGauge(\n 'replica',\n 'sqlite_change_log.head_lag',\n 'Distance from the latest received commit to the SQLite change-log ' +\n 'head. The log commits before the forward, so this is zero except ' +\n 'within a transaction.',\n ).addCallback(result => {\n const lag = watermarkDistance(this.#receivedHead, this.#sqliteHead);\n if (lag !== undefined) {\n result.observe(lag);\n }\n });\n }\n\n /**\n * Called as each message arrives, before it is written. Hashes the *received*\n * stream, which is compared against the hash the writer computes over what it\n * *stored*.\n */\n messageReceived(data: ChangeStreamData, json: string): void {\n const tag = data[1].tag;\n if (data[0] === 'begin') {\n if (this.#sourceHasher !== undefined) {\n this.#invariantFailure(\n 'Received change-log begin while a source hash is already open',\n {receivedWatermark: data[2].commitWatermark},\n );\n }\n const watermark = data[2].commitWatermark;\n this.#sourceHasher = new ChangeLogTransactionHasher();\n this.#sourcePos = 0;\n this.#sourceCommitHash = undefined;\n this.#sourceHasher.add({\n watermark,\n pos: this.#sourcePos,\n tag,\n change: extractChangeSubstring(json, tag),\n precommit: null,\n });\n return;\n }\n\n if (tag === 'rollback') {\n this.#resetSourceHash();\n return;\n }\n\n if (data[0] === 'commit') {\n this.#receivedHead = data[2].watermark;\n }\n\n const watermark = this.#transactionWatermark;\n if (this.#sourceHasher === undefined || watermark === undefined) {\n this.#invariantFailure(\n 'Received change-log message without an observed transaction',\n {tag},\n );\n return;\n }\n\n const commitWatermark =\n data[0] === 'commit' ? data[2].watermark : watermark;\n this.#sourceHasher.add({\n watermark: commitWatermark,\n pos: ++this.#sourcePos,\n tag,\n change: extractChangeSubstring(json, tag),\n precommit: data[0] === 'commit' ? watermark : null,\n });\n if (data[0] === 'commit') {\n this.#sourceCommitHash = this.#sourceHasher.digest();\n this.#sourceHasher = undefined;\n }\n }\n\n /** Called after the message has been written to the log. */\n messageProcessed(\n data: ChangeStreamData,\n commit: ChangeLogCommit | null,\n durationMs: number,\n ): void {\n const tag = data[1].tag;\n this.#messageProcessing.recordMs(durationMs, {tag, outcome: 'success'});\n\n if (data[0] === 'begin') {\n if (this.#transactionWatermark !== undefined) {\n this.#invariantFailure('SQLite change-log transaction already open', {\n openWatermark: this.#transactionWatermark,\n receivedWatermark: data[2].commitWatermark,\n });\n }\n this.#transactionWatermark = data[2].commitWatermark;\n return;\n }\n\n if (tag === 'rollback') {\n this.#recordRollback('upstream');\n this.#transactionWatermark = undefined;\n this.#resetSourceHash();\n return;\n }\n\n if (data[0] !== 'commit') {\n return;\n }\n\n const watermark = data[2].watermark;\n if (commit !== null) {\n this.#logCommitDuration.recordMs(commit.logCommitMs);\n }\n if (this.#transactionWatermark !== watermark) {\n this.#invariantFailure(\n 'SQLite change-log commit does not match the observed begin',\n {openWatermark: this.#transactionWatermark, commitWatermark: watermark},\n );\n }\n if (commit === null) {\n this.#invariantFailure(\n 'SQLite change-log commit result is missing writer statistics',\n {commitWatermark: watermark},\n );\n this.#recordUnpaired(watermark, 'missing-sqlite-hash');\n } else {\n if (commit.watermark !== watermark) {\n this.#invariantFailure(\n 'SQLite change-log commit result has an unexpected watermark',\n {commitWatermark: watermark, resultWatermark: commit.watermark},\n );\n }\n this.#rows += commit.stats.rows;\n this.#estimatedBytes += commit.stats.estimatedBytes;\n this.#transactionRows.record(commit.stats.rows);\n this.#compareHashes(watermark, this.#sourceCommitHash, commit.stats.hash);\n }\n if (watermark < this.#sqliteHead) {\n this.#invariantFailure('SQLite change-log head regressed', {\n previousHead: this.#sqliteHead,\n commitWatermark: watermark,\n });\n }\n this.#sqliteHead = watermark;\n this.#transactionWatermark = undefined;\n this.#resetSourceHash();\n }\n\n messageFailed(\n data: ChangeStreamData,\n error: unknown,\n durationMs: number,\n ): void {\n const tag = data[1].tag;\n this.#messageProcessing.recordMs(durationMs, {tag, outcome: 'error'});\n if (data[0] === 'commit') {\n // No commit duration here: a failed commit produces no statistics, so\n // there is nothing to attribute. The attempt is timed by\n // `message_processing_duration{tag=\"commit\",outcome=\"error\"}` above.\n this.#recordUnpaired(data[2].watermark, 'sqlite-commit-failed');\n }\n if (\n error instanceof Error &&\n error.name === 'ChangeLogStreamInvariantError'\n ) {\n this.#invariantFailure(error.message);\n }\n if (this.#transactionWatermark !== undefined || data[0] === 'begin') {\n this.#recordRollback('processing-error');\n }\n this.#transactionWatermark = undefined;\n this.#resetSourceHash();\n }\n\n /**\n * A committed transaction folded schema changes into the cookie jar. Reported\n * separately from {@link messageProcessed} because it costs a read of the\n * cookie tables, which is only worth taking when they actually moved.\n */\n cookiesMutated(ops: readonly CookieOpTag[], rows: CookieRowCounts): void {\n for (const op of ops) {\n this.#cookieMutations++;\n this.#cookieMutationCounter.add(1, {op});\n }\n this.#cookieRows = rows;\n }\n\n /**\n * A missed truncate-above surfaces as a constraint violation on the writer's\n * plain `INSERT`, which the fail-soft policy would otherwise absorb quietly.\n * Classifying it as an invariant failure is what keeps a reconciliation bug\n * from looking like a lost cache.\n */\n invariantFailure(message: string, details?: Record<string, unknown>): void {\n this.#invariantFailure(message, details);\n }\n\n /** The source interrupted the stream mid-transaction. */\n abort(): void {\n if (this.#transactionWatermark !== undefined) {\n this.#recordRollback('source-interruption');\n this.#transactionWatermark = undefined;\n }\n this.#resetSourceHash();\n }\n\n /** Reconciliation moved the head, so the observer's totals are restated. */\n reconciled(info: SQLiteChangeLogInfo): void {\n this.#receivedHead = info.headWatermark;\n this.#sqliteHead = info.headWatermark;\n this.#rows = info.rows;\n this.#estimatedBytes = info.estimatedBytes;\n this.#cookieRows = info.cookieRows;\n this.#transactionWatermark = undefined;\n this.#resetSourceHash();\n }\n\n state(): SQLiteChangeLogObservabilityState {\n return {\n receivedHead: this.#receivedHead,\n sqliteHead: this.#sqliteHead,\n headLag: watermarkDistance(this.#receivedHead, this.#sqliteHead),\n rows: this.#rows,\n estimatedBytes: this.#estimatedBytes,\n cookieRows: this.#cookieRows,\n cookieMutations: this.#cookieMutations,\n rollbacks: this.#rollbacks,\n invariantFailures: this.#invariantFailures,\n hashMatches: this.#hashMatches,\n hashMismatches: this.#hashMismatches,\n hashUnpaired: this.#hashUnpaired,\n };\n }\n\n #recordRollback(\n reason: 'upstream' | 'processing-error' | 'source-interruption',\n ) {\n this.#rollbacks++;\n this.#rollbackCounter.add(1, {reason});\n }\n\n #invariantFailure(message: string, details?: Record<string, unknown>) {\n this.#invariantFailures++;\n this.#invariantFailureCounter.add(1);\n this.#lc.error?.(message, details);\n }\n\n #compareHashes(\n watermark: string,\n sourceHash: string | undefined,\n sqliteHash: string,\n ): void {\n if (sourceHash === undefined) {\n this.#recordUnpaired(watermark, 'missing-source-hash');\n return;\n }\n if (sourceHash === sqliteHash) {\n this.#hashMatches++;\n this.#hashComparisonCounter.add(1, {outcome: 'match'});\n return;\n }\n this.#hashMismatches++;\n this.#hashComparisonCounter.add(1, {outcome: 'mismatch'});\n this.#lc.error?.('SQLite change-log transaction hash mismatch', {\n sqliteChangeLogHashComparison: {\n watermark,\n sourceHash: sourceHash.slice(0, 16),\n sqliteHash: sqliteHash.slice(0, 16),\n },\n });\n }\n\n #recordUnpaired(\n watermark: string,\n reason:\n | 'missing-source-hash'\n | 'missing-sqlite-hash'\n | 'sqlite-commit-failed',\n ): void {\n this.#hashUnpaired++;\n this.#hashUnpairedCounter.add(1, {reason});\n this.#lc.warn?.('SQLite change-log transaction hash was not compared', {\n sqliteChangeLogHashComparison: {watermark, reason},\n });\n }\n\n #resetSourceHash(): void {\n this.#sourceHasher = undefined;\n this.#sourcePos = 0;\n this.#sourceCommitHash = undefined;\n }\n}\n\nfunction watermarkValue(watermark: string): number | undefined {\n try {\n const value = Number(versionFromLexi(watermark));\n return Number.isFinite(value) ? value : undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction watermarkDistance(\n receivedHead: string,\n sqliteHead: string,\n): number | undefined {\n if (receivedHead <= sqliteHead) {\n return 0;\n }\n try {\n const distance =\n versionFromLexi(receivedHead) - versionFromLexi(sqliteHead);\n const value = Number(distance);\n return Number.isFinite(value) ? value : undefined;\n } catch {\n return undefined;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoDA,SAAgB,+BACd,IACA,QACM;CACN,QAAQ,OAAO,QAAf;EACE,KAAK;GACH,mBACE,WACA,8CACA,kHAEF,EAAE,IAAI,OAAO,IAAI;GACjB;EACF,KAAK;GACH,mBACE,WACA,qCACA,mIAEF,EAAE,IAAI,GAAG,EAAC,QAAQ,OAAO,OAAM,CAAC;GAChC;EACF,KAAK,QACH;EACF,SACE,YAAY,MAAM;CACtB;CACA,IAAI,OAAO,cAKT,mBACE,WACA,mCACA,sGAEF,EAAE,IAAI,GAAG,EAAC,QAAQ,OAAO,OAAM,CAAC;CAElC,GAAG,QAAQ,oCAAoC,EAC7C,0BAA0B,OAC5B,CAAC;AACH;;;;;;;;AAyBA,SAAgB,8BACd,WAC4B;CAC5B,MAAM,OAAO,kBAAkB,SAAS;CACxC,MAAM,EAAC,cAAc,kBAAiB,oBAAoB,SAAS;CACnE,IAAI,iBAAiB,QAAQ,kBAAkB,MAC7C,MAAM,IAAI,MAAM,yDAAyD;CAE3E,OAAO;EAAC,GAAG;EAAM;EAAc;CAAa;AAC9C;;;;;;;AAQA,SAAgB,uBACd,WACqB;CACrB,MAAM,UAAU,8BAA8B,SAAS;CACvD,MAAM,YAAY,UACf,QAAgB;;;gBAGL,wBAAwB;KACnC,EACA,IAA4C;CAE/C,OAAO;EACL,GAAG;EACH,MAAM,UAAU;EAChB,gBAAgB,UAAU;EAC1B,YAAY,oBAAoB,SAAS;CAC3C;AACF;AAEA,SAAgB,0BACd,IACA,MACA,MACM;CACN,GAAG,OAAO,6BAA6B,EACrC,iBAAiB;EACf;EACA,OAAO,KAAK;EACZ,YAAY,KAAK;EACjB,WAAW,KAAK;EAChB,eAAe,KA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,QAIM;EACN,KAAK4B;EACL,KAAKrB,qBAAqB,IAAI,GAAG,EAAC,OAAM,CAAC;EACzC,KAAKP,IAAI,OAAO,uDAAuD,EACrE,+BAA+B;GAAC;GAAW;EAAM,EACnD,CAAC;CACH;CAEA,mBAAyB;EACvB,KAAKc,gBAAgB,KAAA;EACrB,KAAKE,aAAa;EAClB,KAAKC,oBAAoB,KAAA;CAC3B;AACF;AAEA,SAAS,eAAe,WAAuC;CAC7D,IAAI;EACF,MAAM,QAAQ,OAAO,gBAAgB,SAAS,CAAC;EAC/C,OAAO,OAAO,SAAS,KAAK,IAAI,QAAQ,KAAA;CAC1C,QAAQ;EACN;CACF;AACF;AAEA,SAAS,kBACP,cACA,YACoB;CACpB,IAAI,gBAAgB,YAClB,OAAO;CAET,IAAI;EACF,MAAM,WACJ,gBAAgB,YAAY,IAAI,gBAAgB,UAAU;EAC5D,MAAM,QAAQ,OAAO,QAAQ;EAC7B,OAAO,OAAO,SAAS,KAAK,IAAI,QAAQ,KAAA;CAC1C,QAAQ;EACN;CACF;AACF"}
1
+ {"version":3,"file":"sqlite-change-log-observability.js","names":["#lc","#messageProcessing","#logCommitDuration","#transactionRows","#rollbackCounter","#invariantFailureCounter","#hashComparisonCounter","#hashUnpairedCounter","#cookieMutationCounter","#receivedHead","#sqliteHead","#rows","#estimatedBytes","#cookieRows","#sourceHasher","#invariantFailure","#sourcePos","#sourceCommitHash","#resetSourceHash","#transactionWatermark","#recordRollback","#recordUnpaired","#compareHashes","#cookieMutations","#rollbacks","#invariantFailures","#hashMatches","#hashMismatches","#hashUnpaired"],"sources":["../../../../../../zero-cache/src/services/replicator/sqlite-change-log-observability.ts"],"sourcesContent":["/**\n * Observability for the SQLite change log.\n *\n * Everything here now runs in the **change-streamer** process, which is where\n * the writer lives. The module stays beside the rest of the change-log code\n * under `services/replicator/` for the same reason `change-log-db.ts` and\n * `change-log-stream-writer.ts` do: moving files would obscure the topology\n * diff, and the writer's home is a property of who calls it rather than of\n * where it sits. Metric names are unchanged from 7H — only their emitting\n * process, and therefore their resource attributes, moved.\n */\n\nimport {stat} from 'node:fs/promises';\nimport type {LogContext} from '@rocicorp/logger';\nimport {unreachable} from '../../../../shared/src/asserts.ts';\nimport type {Database} from '../../../../zqlite/src/db.ts';\nimport {\n getOrCreateCounter,\n getOrCreateGauge,\n getOrCreateLatencyHistogram,\n getOrCreateValueHistogram,\n} from '../../observability/metrics.ts';\nimport {versionFromLexi} from '../../types/lexi-version.ts';\nimport type {ChangeStreamData} from '../change-source/protocol/current/downstream.ts';\nimport {extractChangeSubstring} from '../change-streamer/change-log-codec.ts';\nimport {ChangeLogTransactionHasher} from '../change-streamer/change-log-transaction-hash.ts';\nimport {\n readCookieRowCounts,\n type CookieOpTag,\n type CookieRowCounts,\n} from './change-log-cookies.ts';\nimport {\n CHANGE_LOG_STREAM_TABLE,\n readChangeLogBounds,\n readChangeLogMeta,\n type ChangeLogMeta,\n type ReconcileResult,\n} from './change-log-db.ts';\nimport type {ChangeLogStreamTransactionStats} from './change-log-stream-writer.ts';\n\n/**\n * Reports the reconciliation of the change-log database against the watermark\n * the stream connection resumes from. This runs once per stream connection, so\n * a reconnect storm is visible here as well as a restart.\n *\n * A wipe is not an error — it is how every abnormal change-log state is\n * collapsed into a correct one — but each wipe costs the retention window, so\n * every reconnecting subscriber below the head gets `too-old`. The `gap` reason\n * in particular means the log neither held the resume watermark nor could be\n * truncated to it, so a nonzero rate in steady state is an alert, not a\n * statistic.\n */\nexport function recordSQLiteChangeLogReconcile(\n lc: LogContext,\n result: ReconcileResult,\n): void {\n switch (result.action) {\n case 'truncated':\n getOrCreateCounter(\n 'replica',\n 'sqlite_change_log.reconcile_truncated_rows',\n 'Phantom change-log rows removed at reconciliation, i.e. rows above ' +\n 'the watermark the change stream resumed from.',\n ).add(result.rows);\n break;\n case 'reseeded':\n getOrCreateCounter(\n 'replica',\n 'sqlite_change_log.reconcile_wipes',\n 'Change-log wipes at reconciliation, by reason. Each one resets the ' +\n 'retention window, so subscribers below the head get `too-old`.',\n ).add(1, {reason: result.reason});\n break;\n case 'none':\n break;\n default:\n unreachable(result);\n }\n if (result.cookiesStale) {\n // The invariant-17 counter: after any reconcile that moved the head, the\n // log's cookie set has to be replaced with the one that belongs to the\n // resume watermark. A nonzero `truncated` series in steady state means\n // phantom truncation is happening on a shard where it should not.\n getOrCreateCounter(\n 'replica',\n 'sqlite_change_log.cookie_reseed',\n 'Change-log cookie sets invalidated at reconciliation, by the ' +\n 'reconcile action that invalidated them.',\n ).add(1, {action: result.action});\n }\n lc.debug?.('SQLite change-log reconciliation', {\n sqliteChangeLogReconcile: result,\n });\n}\n\n/**\n * What the log says about itself. Nothing here reads the replica: after the\n * writer moved to the change-streamer, the replica's state version is a\n * consequence of this log rather than a fact about it.\n */\nexport type SQLiteChangeLogStartupInfo = ChangeLogMeta & {\n readonly minWatermark: string;\n readonly headWatermark: string;\n};\n\nexport type SQLiteChangeLogInfo = SQLiteChangeLogStartupInfo & {\n readonly rows: number;\n readonly estimatedBytes: number;\n readonly cookieRows: CookieRowCounts;\n};\n\n/**\n * Reads the meta row and covered range. Unlike {@link getSQLiteChangeLogInfo}\n * this does not scan the log; see {@link readChangeLogBounds}.\n *\n * Call this after reconciliation, which is the only point at which the head is\n * known to be the resume watermark.\n */\nexport function getSQLiteChangeLogStartupInfo(\n changeLog: Database,\n): SQLiteChangeLogStartupInfo {\n const meta = readChangeLogMeta(changeLog);\n const {minWatermark, headWatermark} = readChangeLogBounds(changeLog);\n if (minWatermark === null || headWatermark === null) {\n throw new Error('the SQLite change log must contain its seed transaction');\n }\n return {...meta, minWatermark, headWatermark};\n}\n\n/**\n * Extends {@link getSQLiteChangeLogStartupInfo} with the retained row and\n * estimated byte totals. Computing these scans the entire change-log table, so\n * only call it when the totals are consumed, i.e. when the writer (and thus the\n * observer) is enabled.\n */\nexport function getSQLiteChangeLogInfo(\n changeLog: Database,\n): SQLiteChangeLogInfo {\n const startup = getSQLiteChangeLogStartupInfo(changeLog);\n const aggregate = changeLog\n .prepare(/*sql*/ `\n SELECT count(*) AS \"rows\",\n coalesce(sum(\"estimatedBytes\"), 0) AS \"estimatedBytes\"\n FROM \"${CHANGE_LOG_STREAM_TABLE}\"\n `)\n .get<{rows: number; estimatedBytes: number}>();\n\n return {\n ...startup,\n rows: aggregate.rows,\n estimatedBytes: aggregate.estimatedBytes,\n cookieRows: readCookieRowCounts(changeLog),\n };\n}\n\nexport function logSQLiteChangeLogStartup(\n lc: LogContext,\n file: string,\n info: SQLiteChangeLogStartupInfo,\n): void {\n lc.info?.('SQLite change-log startup', {\n sqliteChangeLog: {\n file,\n epoch: info.epoch,\n generation: info.generation,\n replicaID: info.replicaID,\n schemaVersion: info.schemaVersion,\n seedWatermark: info.seedWatermark,\n seededAtMs: info.seededAtMs,\n minWatermark: info.minWatermark,\n headWatermark: info.headWatermark,\n },\n });\n}\n\n/**\n * The on-disk footprint of a SQLite database: its main file plus its `-wal` and\n * `-wal2` sidecars, whichever exist. `-shm` is excluded — it is a\n * shared-memory index rather than retained bytes.\n *\n * A missing file counts as zero rather than warning. Which sidecars exist\n * depends on the journal mode, and the change-log database is absent entirely\n * until the writer creates it.\n */\nexport async function sqliteFileBytes(\n lc: LogContext,\n file: string,\n): Promise<number> {\n const sizes = await Promise.all(\n [file, `${file}-wal`, `${file}-wal2`].map(async path => {\n try {\n return (await stat(path)).size;\n } catch (e) {\n if ((e as NodeJS.ErrnoException).code !== 'ENOENT') {\n lc.warn?.(`unable to stat ${path} for size metrics`, e);\n }\n return 0;\n }\n }),\n );\n return sizes.reduce((total, size) => total + size, 0);\n}\n\n/** What the writer reports back for a committed transaction. */\nexport type ChangeLogCommit = {\n readonly watermark: string;\n readonly stats: ChangeLogStreamTransactionStats;\n /**\n * Appending the commit row and committing the log's transaction. This is the\n * cost that sits on the forward path, once per upstream transaction.\n */\n readonly logCommitMs: number;\n};\n\nexport type SQLiteChangeLogObservabilityState = {\n readonly receivedHead: string;\n readonly sqliteHead: string;\n readonly headLag: number | undefined;\n readonly rows: number;\n readonly estimatedBytes: number;\n readonly cookieRows: CookieRowCounts;\n readonly cookieMutations: number;\n readonly rollbacks: number;\n readonly invariantFailures: number;\n readonly hashMatches: number;\n readonly hashMismatches: number;\n readonly hashUnpaired: number;\n};\n\nconst TRANSACTION_ROW_BUCKETS = [2, 3, 5, 10, 25, 50, 100, 250, 1000, 5000];\n\n/**\n * Records writer metrics in the change-streamer process. State changes only\n * after the corresponding write succeeds, except receivedHead, which advances\n * when a commit message arrives so that transient lag behind the log is\n * observable.\n */\nexport class SQLiteChangeLogObserver {\n readonly #lc: LogContext;\n readonly #messageProcessing = getOrCreateLatencyHistogram(\n 'replica',\n 'sqlite_change_log.message_processing_duration',\n 'Sampled time to write a replication message to the SQLite change log.',\n );\n // The commit that sits on the forward path. There is no second commit to\n // order against any more: the replica's belongs to a subscriber downstream of\n // this loop, so `sqlite_change_log.replica_commit_duration` and the phantom\n // window it measured are gone. Sampled failed commits are still timed by\n // `message_processing_duration` keyed `tag=\"commit\"`.\n readonly #logCommitDuration = getOrCreateLatencyHistogram(\n 'replica',\n 'sqlite_change_log.log_commit_duration',\n 'Time to append the commit row to the SQLite change log and commit its ' +\n 'transaction. This is on the forward path: it precedes the forward of ' +\n \"that transaction's commit message.\",\n );\n readonly #transactionRows = getOrCreateValueHistogram(\n 'replica',\n 'sqlite_change_log.transaction_rows',\n {\n description: 'Rows stored per committed SQLite change-log transaction.',\n unit: '{row}',\n bucketBoundaries: TRANSACTION_ROW_BUCKETS,\n },\n );\n readonly #rollbackCounter = getOrCreateCounter(\n 'replica',\n 'sqlite_change_log.rollbacks',\n 'SQLite change-log transactions rolled back before commit.',\n );\n readonly #invariantFailureCounter = getOrCreateCounter(\n 'replica',\n 'sqlite_change_log.invariant_failures',\n 'Detected SQLite change-log writer invariant failures.',\n );\n readonly #hashComparisonCounter = getOrCreateCounter(\n 'replica',\n 'sqlite_change_log.hash_comparisons',\n 'Sampled ephemeral transaction hash comparisons between the received change stream and SQLite change-log writes.',\n );\n readonly #hashUnpairedCounter = getOrCreateCounter(\n 'replica',\n 'sqlite_change_log.hash_unpaired',\n 'Committed change-log transactions without both ephemeral hashes available for comparison.',\n );\n // Near zero at steady state: cookie state only moves on schema changes.\n readonly #cookieMutationCounter = getOrCreateCounter(\n 'replica',\n 'sqlite_change_log.cookie_mutations',\n 'Change-log cookie mutations folded from schema changes, by operation.',\n );\n\n #receivedHead: string;\n #sqliteHead: string;\n #rows: number;\n #estimatedBytes: number;\n #cookieRows: CookieRowCounts;\n #cookieMutations = 0;\n #transactionWatermark: string | undefined;\n #sourceHasher: ChangeLogTransactionHasher | undefined;\n #sourcePos = 0;\n #sourceCommitHash: string | undefined;\n #rollbacks = 0;\n #invariantFailures = 0;\n #hashMatches = 0;\n #hashMismatches = 0;\n #hashUnpaired = 0;\n\n constructor(lc: LogContext, info: SQLiteChangeLogInfo) {\n this.#lc = lc.withContext('component', 'sqlite-change-log-observer');\n // Reconciliation has just put the head at the resume watermark, which is\n // also the point the stream is about to be received from.\n this.#receivedHead = info.headWatermark;\n this.#sqliteHead = info.headWatermark;\n this.#rows = info.rows;\n this.#estimatedBytes = info.estimatedBytes;\n this.#cookieRows = info.cookieRows;\n\n getOrCreateGauge(\n 'replica',\n 'sqlite_change_log.rows',\n 'Rows retained in the SQLite change log.',\n ).addCallback(result => result.observe(this.#rows));\n // Nonzero with no backfill in flight is a leaked cookie, i.e. a backfill\n // that will be re-requested forever.\n getOrCreateGauge(\n 'replica',\n 'sqlite_change_log.cookie_rows',\n 'Cookie rows retained in the SQLite change log, by cookie table.',\n ).addCallback(result => {\n result.observe(this.#cookieRows.tableMetadata, {table: 'tableMetadata'});\n result.observe(this.#cookieRows.backfilling, {table: 'backfilling'});\n });\n getOrCreateGauge('replica', 'sqlite_change_log.retained_bytes', {\n description:\n 'Estimated UTF-8 payload bytes retained in the SQLite change log.',\n unit: 'By',\n }).addCallback(result => result.observe(this.#estimatedBytes));\n getOrCreateGauge(\n 'replica',\n 'sqlite_change_log.head',\n 'SQLite change-log head converted from its lexicographic watermark.',\n ).addCallback(result => {\n const head = watermarkValue(this.#sqliteHead);\n if (head !== undefined) {\n result.observe(head);\n }\n });\n getOrCreateGauge(\n 'replica',\n 'sqlite_change_log.head_lag',\n 'Distance from the latest received commit to the SQLite change-log ' +\n 'head. The log commits before the forward, so this is zero except ' +\n 'within a transaction.',\n ).addCallback(result => {\n const lag = watermarkDistance(this.#receivedHead, this.#sqliteHead);\n if (lag !== undefined) {\n result.observe(lag);\n }\n });\n }\n\n /**\n * Called as each message arrives, before it is written. For a sampled\n * transaction, hashes the *received* stream and compares it with the hash the\n * writer computes over what it *stored*.\n */\n messageReceived(\n data: ChangeStreamData,\n json: string,\n validateHash = true,\n storedChange = extractChangeSubstring(json, data[1].tag),\n ): void {\n const tag = data[1].tag;\n if (data[0] === 'begin') {\n if (this.#sourceHasher !== undefined) {\n this.#invariantFailure(\n 'Received change-log begin while a source hash is already open',\n {receivedWatermark: data[2].commitWatermark},\n );\n }\n const watermark = data[2].commitWatermark;\n this.#sourceHasher = validateHash\n ? new ChangeLogTransactionHasher()\n : undefined;\n this.#sourcePos = 0;\n this.#sourceCommitHash = undefined;\n this.#sourceHasher?.add({\n watermark,\n pos: this.#sourcePos,\n tag,\n change: storedChange,\n precommit: null,\n });\n return;\n }\n\n if (tag === 'rollback') {\n this.#resetSourceHash();\n return;\n }\n\n if (data[0] === 'commit') {\n this.#receivedHead = data[2].watermark;\n }\n\n if (!validateHash) {\n return;\n }\n\n const watermark = this.#transactionWatermark;\n if (this.#sourceHasher === undefined || watermark === undefined) {\n this.#invariantFailure(\n 'Received change-log message without an observed transaction',\n {tag},\n );\n return;\n }\n\n const commitWatermark =\n data[0] === 'commit' ? data[2].watermark : watermark;\n this.#sourceHasher.add({\n watermark: commitWatermark,\n pos: ++this.#sourcePos,\n tag,\n change: storedChange,\n precommit: data[0] === 'commit' ? watermark : null,\n });\n if (data[0] === 'commit') {\n this.#sourceCommitHash = this.#sourceHasher.digest();\n this.#sourceHasher = undefined;\n }\n }\n\n /** Called after the message has been written to the log. */\n messageProcessed(\n data: ChangeStreamData,\n commit: ChangeLogCommit | null,\n durationMs: number | undefined,\n ): void {\n const tag = data[1].tag;\n if (durationMs !== undefined) {\n this.#messageProcessing.recordMs(durationMs, {tag, outcome: 'success'});\n }\n\n if (data[0] === 'begin') {\n if (this.#transactionWatermark !== undefined) {\n this.#invariantFailure('SQLite change-log transaction already open', {\n openWatermark: this.#transactionWatermark,\n receivedWatermark: data[2].commitWatermark,\n });\n }\n this.#transactionWatermark = data[2].commitWatermark;\n return;\n }\n\n if (tag === 'rollback') {\n this.#recordRollback('upstream');\n this.#transactionWatermark = undefined;\n this.#resetSourceHash();\n return;\n }\n\n if (data[0] !== 'commit') {\n return;\n }\n\n const watermark = data[2].watermark;\n if (commit !== null) {\n this.#logCommitDuration.recordMs(commit.logCommitMs);\n }\n if (this.#transactionWatermark !== watermark) {\n this.#invariantFailure(\n 'SQLite change-log commit does not match the observed begin',\n {openWatermark: this.#transactionWatermark, commitWatermark: watermark},\n );\n }\n if (commit === null) {\n this.#invariantFailure(\n 'SQLite change-log commit result is missing writer statistics',\n {commitWatermark: watermark},\n );\n this.#recordUnpaired(watermark, 'missing-sqlite-hash');\n } else {\n if (commit.watermark !== watermark) {\n this.#invariantFailure(\n 'SQLite change-log commit result has an unexpected watermark',\n {commitWatermark: watermark, resultWatermark: commit.watermark},\n );\n }\n this.#rows += commit.stats.rows;\n this.#estimatedBytes += commit.stats.estimatedBytes;\n this.#transactionRows.record(commit.stats.rows);\n if (\n this.#sourceCommitHash !== undefined ||\n commit.stats.hash !== undefined\n ) {\n this.#compareHashes(\n watermark,\n this.#sourceCommitHash,\n commit.stats.hash,\n );\n }\n }\n if (watermark < this.#sqliteHead) {\n this.#invariantFailure('SQLite change-log head regressed', {\n previousHead: this.#sqliteHead,\n commitWatermark: watermark,\n });\n }\n this.#sqliteHead = watermark;\n this.#transactionWatermark = undefined;\n this.#resetSourceHash();\n }\n\n messageFailed(\n data: ChangeStreamData,\n error: unknown,\n durationMs: number | undefined,\n ): void {\n const tag = data[1].tag;\n if (durationMs !== undefined) {\n this.#messageProcessing.recordMs(durationMs, {tag, outcome: 'error'});\n }\n if (data[0] === 'commit' && this.#sourceCommitHash !== undefined) {\n // No commit duration here: a failed commit produces no statistics, so\n // there is nothing to attribute. The attempt is timed by\n // `message_processing_duration{tag=\"commit\",outcome=\"error\"}` above.\n this.#recordUnpaired(data[2].watermark, 'sqlite-commit-failed');\n }\n if (\n error instanceof Error &&\n error.name === 'ChangeLogStreamInvariantError'\n ) {\n this.#invariantFailure(error.message);\n }\n if (this.#transactionWatermark !== undefined || data[0] === 'begin') {\n this.#recordRollback('processing-error');\n }\n this.#transactionWatermark = undefined;\n this.#resetSourceHash();\n }\n\n /**\n * A committed transaction folded schema changes into the cookie jar. Reported\n * separately from {@link messageProcessed} because it costs a read of the\n * cookie tables, which is only worth taking when they actually moved.\n */\n cookiesMutated(ops: readonly CookieOpTag[], rows: CookieRowCounts): void {\n for (const op of ops) {\n this.#cookieMutations++;\n this.#cookieMutationCounter.add(1, {op});\n }\n this.#cookieRows = rows;\n }\n\n /**\n * A missed truncate-above surfaces as a constraint violation on the writer's\n * plain `INSERT`, which the fail-soft policy would otherwise absorb quietly.\n * Classifying it as an invariant failure is what keeps a reconciliation bug\n * from looking like a lost cache.\n */\n invariantFailure(message: string, details?: Record<string, unknown>): void {\n this.#invariantFailure(message, details);\n }\n\n /** The source interrupted the stream mid-transaction. */\n abort(): void {\n if (this.#transactionWatermark !== undefined) {\n this.#recordRollback('source-interruption');\n this.#transactionWatermark = undefined;\n }\n this.#resetSourceHash();\n }\n\n /** Reconciliation moved the head, so the observer's totals are restated. */\n reconciled(info: SQLiteChangeLogInfo): void {\n this.#receivedHead = info.headWatermark;\n this.#sqliteHead = info.headWatermark;\n this.#rows = info.rows;\n this.#estimatedBytes = info.estimatedBytes;\n this.#cookieRows = info.cookieRows;\n this.#transactionWatermark = undefined;\n this.#resetSourceHash();\n }\n\n state(): SQLiteChangeLogObservabilityState {\n return {\n receivedHead: this.#receivedHead,\n sqliteHead: this.#sqliteHead,\n headLag: watermarkDistance(this.#receivedHead, this.#sqliteHead),\n rows: this.#rows,\n estimatedBytes: this.#estimatedBytes,\n cookieRows: this.#cookieRows,\n cookieMutations: this.#cookieMutations,\n rollbacks: this.#rollbacks,\n invariantFailures: this.#invariantFailures,\n hashMatches: this.#hashMatches,\n hashMismatches: this.#hashMismatches,\n hashUnpaired: this.#hashUnpaired,\n };\n }\n\n #recordRollback(\n reason: 'upstream' | 'processing-error' | 'source-interruption',\n ) {\n this.#rollbacks++;\n this.#rollbackCounter.add(1, {reason});\n }\n\n #invariantFailure(message: string, details?: Record<string, unknown>) {\n this.#invariantFailures++;\n this.#invariantFailureCounter.add(1);\n this.#lc.error?.(message, details);\n }\n\n #compareHashes(\n watermark: string,\n sourceHash: string | undefined,\n sqliteHash: string | undefined,\n ): void {\n if (sourceHash === undefined) {\n this.#recordUnpaired(watermark, 'missing-source-hash');\n return;\n }\n if (sqliteHash === undefined) {\n this.#recordUnpaired(watermark, 'missing-sqlite-hash');\n return;\n }\n if (sourceHash === sqliteHash) {\n this.#hashMatches++;\n this.#hashComparisonCounter.add(1, {outcome: 'match'});\n return;\n }\n this.#hashMismatches++;\n this.#hashComparisonCounter.add(1, {outcome: 'mismatch'});\n this.#lc.error?.('SQLite change-log transaction hash mismatch', {\n sqliteChangeLogHashComparison: {\n watermark,\n sourceHash: sourceHash.slice(0, 16),\n sqliteHash: sqliteHash.slice(0, 16),\n },\n });\n }\n\n #recordUnpaired(\n watermark: string,\n reason:\n | 'missing-source-hash'\n | 'missing-sqlite-hash'\n | 'sqlite-commit-failed',\n ): void {\n this.#hashUnpaired++;\n this.#hashUnpairedCounter.add(1, {reason});\n this.#lc.warn?.('SQLite change-log transaction hash was not compared', {\n sqliteChangeLogHashComparison: {watermark, reason},\n });\n }\n\n #resetSourceHash(): void {\n this.#sourceHasher = undefined;\n this.#sourcePos = 0;\n this.#sourceCommitHash = undefined;\n }\n}\n\nfunction watermarkValue(watermark: string): number | undefined {\n try {\n const value = Number(versionFromLexi(watermark));\n return Number.isFinite(value) ? value : undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction watermarkDistance(\n receivedHead: string,\n sqliteHead: string,\n): number | undefined {\n if (receivedHead <= sqliteHead) {\n return 0;\n }\n try {\n const distance =\n versionFromLexi(receivedHead) - versionFromLexi(sqliteHead);\n const value = Number(distance);\n return Number.isFinite(value) ? value : undefined;\n } catch {\n return undefined;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoDA,SAAgB,+BACd,IACA,QACM;CACN,QAAQ,OAAO,QAAf;EACE,KAAK;GACH,mBACE,WACA,8CACA,kHAEF,EAAE,IAAI,OAAO,IAAI;GACjB;EACF,KAAK;GACH,mBACE,WACA,qCACA,mIAEF,EAAE,IAAI,GAAG,EAAC,QAAQ,OAAO,OAAM,CAAC;GAChC;EACF,KAAK,QACH;EACF,SACE,YAAY,MAAM;CACtB;CACA,IAAI,OAAO,cAKT,mBACE,WACA,mCACA,sGAEF,EAAE,IAAI,GAAG,EAAC,QAAQ,OAAO,OAAM,CAAC;CAElC,GAAG,QAAQ,oCAAoC,EAC7C,0BAA0B,OAC5B,CAAC;AACH;;;;;;;;AAyBA,SAAgB,8BACd,WAC4B;CAC5B,MAAM,OAAO,kBAAkB,SAAS;CACxC,MAAM,EAAC,cAAc,kBAAiB,oBAAoB,SAAS;CACnE,IAAI,iBAAiB,QAAQ,kBAAkB,MAC7C,MAAM,IAAI,MAAM,yDAAyD;CAE3E,OAAO;EAAC,GAAG;EAAM;EAAc;CAAa;AAC9C;;;;;;;AAQA,SAAgB,uBACd,WACqB;CACrB,MAAM,UAAU,8BAA8B,SAAS;CACvD,MAAM,YAAY,UACf,QAAgB;;;gBAGL,wBAAwB;KACnC,EACA,IAA4C;CAE/C,OAAO;EACL,GAAG;EACH,MA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AAW;GAC5B,KAAKqB,gBAAgB,WAAW,qBAAqB;GACrD;EACF;EACA,IAAI,eAAe,KAAA,GAAW;GAC5B,KAAKA,gBAAgB,WAAW,qBAAqB;GACrD;EACF;EACA,IAAI,eAAe,YAAY;GAC7B,KAAKK;GACL,KAAKpB,uBAAuB,IAAI,GAAG,EAAC,SAAS,QAAO,CAAC;GACrD;EACF;EACA,KAAKqB;EACL,KAAKrB,uBAAuB,IAAI,GAAG,EAAC,SAAS,WAAU,CAAC;EACxD,KAAKN,IAAI,QAAQ,+CAA+C,EAC9D,+BAA+B;GAC7B;GACA,YAAY,WAAW,MAAM,GAAG,EAAE;GAClC,YAAY,WAAW,MAAM,GAAG,EAAE;EACpC,EACF,CAAC;CACH;CAEA,gBACE,WACA,QAIM;EACN,KAAK4B;EACL,KAAKrB,qBAAqB,IAAI,GAAG,EAAC,OAAM,CAAC;EACzC,KAAKP,IAAI,OAAO,uDAAuD,EACrE,+BAA+B;GAAC;GAAW;EAAM,EACnD,CAAC;CACH;CAEA,mBAAyB;EACvB,KAAKc,gBAAgB,KAAA;EACrB,KAAKE,aAAa;EAClB,KAAKC,oBAAoB,KAAA;CAC3B;AACF;AAEA,SAAS,eAAe,WAAuC;CAC7D,IAAI;EACF,MAAM,QAAQ,OAAO,gBAAgB,SAAS,CAAC;EAC/C,OAAO,OAAO,SAAS,KAAK,IAAI,QAAQ,KAAA;CAC1C,QAAQ;EACN;CACF;AACF;AAEA,SAAS,kBACP,cACA,YACoB;CACpB,IAAI,gBAAgB,YAClB,OAAO;CAET,IAAI;EACF,MAAM,WACJ,gBAAgB,YAAY,IAAI,gBAAgB,UAAU;EAC5D,MAAM,QAAQ,OAAO,QAAQ;EAC7B,OAAO,OAAO,SAAS,KAAK,IAAI,QAAQ,KAAA;CAC1C,QAAQ;EACN;CACF;AACF"}
@@ -167,6 +167,23 @@ export declare class CVRQueryDrivenUpdater extends CVRUpdater {
167
167
  * cannot be restored.
168
168
  */
169
169
  removeTrackedQueries(queryIDs: Iterable<string>): PatchToVersion[];
170
+ /**
171
+ * Aborts queries that were tracked as executed but whose hydration was cut
172
+ * short (see the view-syncer's hydration circuit breaker).
173
+ *
174
+ * Rows received for an aborted query in this update have that query's
175
+ * references stripped: a row left with no references is deleted, and the
176
+ * 'del' patch cancels the 'put' the client has already received, while a
177
+ * row still referenced by other queries keeps its patch version. The query
178
+ * is then removed from the CVR. It stays tracked as executed, so
179
+ * {@link deleteUnreferencedRows} also drops the references held by rows that
180
+ * were synced for it before this update, exactly as for a removed query.
181
+ *
182
+ * Like {@link removeTrackedQueries}, this must be called after
183
+ * {@link trackQueries} has established the final version, and after all
184
+ * rows of the aborted queries have been {@link received}.
185
+ */
186
+ abortExecutedQueries(lc: LogContext, queryIDs: readonly string[]): Promise<PatchToVersion[]>;
170
187
  updatedVersion(): CVRVersion;
171
188
  /**
172
189
  * Public alias for {@link _ensureNewVersion}. Forces a `configVersion` bump
@@ -1 +1 @@
1
- {"version":3,"file":"cvr.d.ts","sourceRoot":"","sources":["../../../../../../zero-cache/src/services/view-syncer/cvr.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAC,UAAU,EAAC,MAAM,kBAAkB,CAAC;AAGjD,OAAO,EAAC,KAAK,UAAU,EAAC,MAAM,uCAAuC,CAAC;AAGtE,OAAO,EAEL,KAAK,iBAAiB,EACvB,MAAM,gCAAgC,CAAC;AAQxC,OAAO,KAAK,EAAC,GAAG,EAAC,MAAM,sCAAsC,CAAC;AAC9D,OAAO,KAAK,EAAC,YAAY,EAAC,MAAM,gDAAgD,CAAC;AASjF,OAAO,KAAK,EAAC,WAAW,EAAC,MAAM,6BAA6B,CAAC;AAE7D,OAAO,EAAiB,KAAK,OAAO,EAAC,MAAM,uBAAuB,CAAC;AACnE,OAAO,KAAK,EAAQ,cAAc,EAAC,MAAM,qBAAqB,CAAC;AAC/D,OAAO,EAAC,KAAK,aAAa,EAAE,KAAK,QAAQ,EAAC,MAAM,gBAAgB,CAAC;AAEjE,OAAO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