or3-provider-sqlite 0.0.29 → 0.0.31

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 (34) hide show
  1. package/README.md +93 -3
  2. package/dist/module.json +1 -1
  3. package/dist/runtime/server/admin/adapters/sync-sqlite.js +9 -0
  4. package/dist/runtime/server/background-jobs/sqlite-provider.js +18 -1
  5. package/dist/runtime/server/db/kysely.js +11 -2
  6. package/dist/runtime/server/db/migrate.js +27 -2
  7. package/dist/runtime/server/db/migration-schema.d.ts +2 -0
  8. package/dist/runtime/server/db/migration-schema.js +14 -0
  9. package/dist/runtime/server/db/migrations/006_sync_snapshots.js +10 -21
  10. package/dist/runtime/server/db/migrations/007_device_cursor_ownership.js +2 -1
  11. package/dist/runtime/server/db/migrations/019_background_generation_history.js +5 -16
  12. package/dist/runtime/server/db/migrations/021_background_request_usage.js +2 -1
  13. package/dist/runtime/server/db/migrations/033_tool_result_operation_ids.d.ts +4 -0
  14. package/dist/runtime/server/db/migrations/033_tool_result_operation_ids.js +35 -0
  15. package/dist/runtime/server/db/migrations/034_sync_intent_fingerprint.d.ts +3 -0
  16. package/dist/runtime/server/db/migrations/034_sync_intent_fingerprint.js +8 -0
  17. package/dist/runtime/server/db/migrations/035_sync_unavailable_records.d.ts +3 -0
  18. package/dist/runtime/server/db/migrations/035_sync_unavailable_records.js +24 -0
  19. package/dist/runtime/server/db/migrations/036_sync_history_incarnation.d.ts +3 -0
  20. package/dist/runtime/server/db/migrations/036_sync_history_incarnation.js +28 -0
  21. package/dist/runtime/server/db/schema.d.ts +5 -0
  22. package/dist/runtime/server/sync/canonical-project-ownership.d.ts +1 -1
  23. package/dist/runtime/server/sync/canonical-project-ownership.js +29 -12
  24. package/dist/runtime/server/sync/evidence-maintenance.d.ts +20 -0
  25. package/dist/runtime/server/sync/evidence-maintenance.js +130 -0
  26. package/dist/runtime/server/sync/history-incarnation.d.ts +8 -0
  27. package/dist/runtime/server/sync/history-incarnation.js +54 -0
  28. package/dist/runtime/server/sync/sqlite-sync-gateway-adapter.d.ts +28 -4
  29. package/dist/runtime/server/sync/sqlite-sync-gateway-adapter.js +804 -361
  30. package/dist/runtime/server/sync/unavailable-records.d.ts +30 -0
  31. package/dist/runtime/server/sync/unavailable-records.js +55 -0
  32. package/dist/runtime/server/utils/digest-uuid.d.ts +2 -0
  33. package/dist/runtime/server/utils/digest-uuid.js +7 -0
  34. package/package.json +1 -1
@@ -1,7 +1,10 @@
1
+ import { readHistoryIncarnation, validateExpectedHistory, validHistoryIncarnation, historyChanged, historyAssertion, historyBatch } from "./history-incarnation.js";
2
+ import { maintainEvidence, repairAssertion, repairResolution } from "./evidence-maintenance.js";
1
3
  import { SqliteExternalStorageGenerationUploadCoordinator } from "../storage/sqlite-generation-upload-coordinator.js";
2
4
  import { backgroundFinalizationFingerprint, stableJson } from "./background-history-fingerprint.js";
3
5
  import { hasWorkspaceItemSemantics, WORKSPACE_ITEM_CAPABILITY } from "./workspace-item-capability.js";
4
6
  import { createHash } from "node:crypto";
7
+ import { digestUuid } from "../utils/digest-uuid.js";
5
8
  import { sql } from "kysely";
6
9
  import { canRunSyncHistoryGc } from "./history-gc-policy.js";
7
10
  import { createError } from "h3";
@@ -23,6 +26,9 @@ import { SYNCED_TABLE_MAP, ALLOWED_SYNC_TABLES } from "../db/schema.js";
23
26
  import { emitWebhookSystemHook } from "~~/server/utils/webhooks/runtime";
24
27
  import { incomingRevisionWins } from "~~/shared/sync/revision";
25
28
  import { sanitizePayloadForSync } from "~~/shared/sync/sanitize";
29
+ import { boundedSyncPayload, boundedSyncMetadata, syncMetadataBytes, SYNC_METADATA_BYTES, notificationOwnerSql, syncRows, retainSqlEvidence, unknownNotificationEvidence, evidenceInsert, evidenceLookup } from "./unavailable-records.js";
30
+ import { MAX_SYNC_SNAPSHOT_TOKEN_LENGTH, SyncChangeSchema, SnapshotItemSchema, TABLE_PAYLOAD_SCHEMAS, isLosslessSyncIdentifier, PullResponseSchema, SnapshotResponseSchema, compareSyncTuple, normalizeWirePayloadForTable } from "~~/shared/sync/schemas";
31
+ import { prepareSyncWrite, nextSyncClock } from "~~/shared/sync/prepare-sync-write";
26
32
  import { readRequestUsage } from "~~/shared/chat/compaction";
27
33
  import { matchesToolResultStorage, parseToolResultArtifact, prepareToolResultStorage, toolResultArtifactPrefix } from "~~/shared/chat/tool-result-artifact";
28
34
  import { validateCanonicalChatQuery, encodeCanonicalChatSeek, parseCanonicalChatSeek } from "~~/shared/chat/history-reader";
@@ -67,11 +73,13 @@ const QUOTA_RESERVATIONS_SQL = `SELECT intent.hash, MAX(intent.size_bytes) AS re
67
73
  ON retained.workspace_id = intent.workspace_id AND retained.hash = intent.hash
68
74
  WHERE intent.workspace_id = ? AND intent.status = 'active' AND intent.expires_at > ?
69
75
  GROUP BY intent.hash`;
76
+ const PULL_METADATA_BYTES = syncMetadataBytes("table_name", "pk", "id", "op", "clock", "hlc", "device_id", "op_id");
77
+ const SNAPSHOT_METADATA_BYTES = syncMetadataBytes("table_name", "pk", "kind", "clock", "hlc", "op_id", "server_deleted_at");
70
78
  function boundedPayloadRowCount(sizes, limit) {
71
79
  let count = 0;
72
80
  let bytes = 0;
73
81
  for (const row of sizes.slice(0, limit)) {
74
- const size = Math.max(0, Number(row.payload_bytes) || 0);
82
+ const size = (row.payload_bytes > MAX_SYNC_PAYLOAD_BYTES ? 1024 : Math.max(0, Number(row.payload_bytes) || 0)) + Math.min(row.metadata_bytes, SYNC_METADATA_BYTES);
75
83
  if (count && bytes + size > MAX_SYNC_PAGE_BYTES) break;
76
84
  count++;
77
85
  bytes += size;
@@ -80,58 +88,122 @@ function boundedPayloadRowCount(sizes, limit) {
80
88
  }
81
89
  function snapshotPageSelection(headerId, after) {
82
90
  const clause = `FROM sync_snapshot_items WHERE snapshot_id = ?${after ? `
83
- AND (table_name > ? OR (table_name = ? AND pk > ?)
84
- OR (table_name = ? AND pk = ? AND kind > ?))` : ""}
85
- ORDER BY table_name ASC, pk ASC, kind ASC LIMIT ?`;
86
- const parameters = after ? [headerId, after.tableName, after.tableName, after.pk, after.tableName, after.pk, after.kind] : [headerId];
91
+ AND (table_name COLLATE BINARY, pk COLLATE BINARY, kind COLLATE BINARY) > (?, ?, ?)` : ""}
92
+ ORDER BY table_name COLLATE BINARY ASC, pk COLLATE BINARY ASC, kind COLLATE BINARY ASC LIMIT ?`;
93
+ const parameters = after ? [headerId, after.tableName, after.pk, after.kind] : [headerId];
87
94
  return { clause, parameters };
88
95
  }
89
- function buildSnapshotPage(header, rows, pageSize, availableRows) {
96
+ function assertCoverageKey(table, pk, pkHex, tableHex) {
97
+ if (typeof table !== "string" || !table || typeof pk !== "string" || !pk || !isLosslessSyncIdentifier(table) || !isLosslessSyncIdentifier(pk) || pkHex !== void 0 && Buffer.from(pk).toString("hex").toUpperCase() !== pkHex || tableHex !== void 0 && Buffer.from(table).toString("hex").toUpperCase() !== tableHex) {
98
+ throw new Error("Untrustworthy sync coverage identity");
99
+ }
100
+ }
101
+ function validReadPayload(table, pk, payload, _clock, hlc) {
102
+ if (!Object.hasOwn(TABLE_PAYLOAD_SCHEMAS, table)) return false;
103
+ const normalized = normalizeWirePayloadForTable(table, payload);
104
+ const validationPayload = table === "messages" && normalized && typeof normalized === "object" && !Array.isArray(normalized) ? { ...normalized, order_key: normalized.order_key || hlc } : normalized;
105
+ if (!TABLE_PAYLOAD_SCHEMAS[table].safeParse(validationPayload).success) return false;
106
+ const row = normalized;
107
+ for (const key of ["id", "hash", "thread_id", "project_id", "user_id", "document_id", "root_thread_id", "summary_message_id"]) {
108
+ if (typeof row[key] === "string" && !isLosslessSyncIdentifier(row[key])) return false;
109
+ }
110
+ return row[table === "file_meta" ? "hash" : "id"] === pk;
111
+ }
112
+ function snapshotEvidence(header, row, historyIncarnation) {
113
+ return {
114
+ historyIncarnation,
115
+ workspaceId: header.workspace_id,
116
+ source: "snapshot",
117
+ locator: JSON.stringify([row.table_name, row.pk]),
118
+ revisionSql: "json_array(kind,clock,hlc,op_id)",
119
+ table: "sync_snapshot_items",
120
+ where: "snapshot_id = ? AND table_name = ? AND pk = ? AND kind = ?",
121
+ parameters: [header.id, row.table_name, row.pk, row.kind],
122
+ payload: "coalesce(source_payload_json,payload_json)",
123
+ metadata: "json_object('snapshot_id',snapshot_id,'table_name',table_name,'pk',pk,'kind',kind,'clock',clock,'hlc',hlc,'op_id',op_id,'server_deleted_at',server_deleted_at)"
124
+ };
125
+ }
126
+ async function buildSnapshotPage(header, rows, pageSize, availableRows, historyIncarnation, after, userId) {
127
+ if (!Number.isSafeInteger(header.high_watermark) || header.high_watermark < 0) throw new Error("Untrustworthy snapshot watermark");
90
128
  const items = [];
91
- let itemBytes = 0;
129
+ const unavailable = [];
92
130
  let scanned = 0;
131
+ let itemBytes = 0;
93
132
  let token = null;
133
+ let previous = after ? [after.tableName, after.pk, after.kind] : void 0;
94
134
  for (const row of rows.slice(0, pageSize)) {
95
- const revision = { clock: row.clock, hlc: row.hlc, opId: row.op_id };
96
- const item = row.kind === "row" ? {
97
- kind: "row",
98
- tableName: row.table_name,
99
- pk: row.pk,
100
- payload: JSON.parse(row.payload_json ?? "null"),
101
- revision
102
- } : {
103
- kind: "tombstone",
135
+ assertCoverageKey(row.table_name, row.pk, row.pk_hex, row.table_hex);
136
+ const key = [row.table_name, row.pk, row.kind];
137
+ if (!["row", "tombstone"].includes(row.kind) || previous && (compareSyncTuple(previous, key) >= 0 || compareSyncTuple(previous.slice(0, 2), key.slice(0, 2)) === 0)) {
138
+ throw new Error("Untrustworthy snapshot ordering");
139
+ }
140
+ let item;
141
+ let reason = row.metadata_bytes > SYNC_METADATA_BYTES ? "metadata_oversized" : row.payload_bytes > MAX_SYNC_PAYLOAD_BYTES ? "payload_oversized" : "invalid_record";
142
+ if (reason === "invalid_record") {
143
+ try {
144
+ const revision = { clock: row.clock, hlc: row.hlc, opId: row.op_id };
145
+ const candidate = row.kind === "row" ? { kind: "row", tableName: row.table_name, pk: row.pk, payload: JSON.parse(row.payload_json ?? "null"), revision } : { kind: "tombstone", tableName: row.table_name, pk: row.pk, revision, serverDeletedAt: row.server_deleted_at };
146
+ if (SnapshotItemSchema.safeParse(candidate).success && Number.isSafeInteger(row.clock) && (row.kind === "row" ? validReadPayload(row.table_name, row.pk, candidate.payload, row.clock, row.hlc) : ALLOWED_SYNC_TABLES.includes(row.table_name))) item = candidate;
147
+ } catch {
148
+ reason = "invalid_json";
149
+ }
150
+ }
151
+ const marker = {
104
152
  tableName: row.table_name,
105
153
  pk: row.pk,
106
- revision,
107
- serverDeletedAt: row.server_deleted_at ?? 0
154
+ originalKind: row.kind,
155
+ snapshotId: header.id,
156
+ highWatermark: header.high_watermark,
157
+ evidenceRef: "",
158
+ reason
108
159
  };
109
160
  const next = encodeSnapshotPageToken({
110
161
  version: 1,
111
162
  snapshotId: header.id,
163
+ historyIncarnation,
112
164
  after: { tableName: row.table_name, pk: row.pk, kind: row.kind }
113
165
  });
114
- const bytes = jsonBytes(item) + (items.length ? 1 : 0);
115
- const envelope = jsonBytes({
166
+ const visible = row.table_name !== "notifications" || row.kind === "tombstone" || !!row.notification_owner && row.notification_owner === userId;
167
+ let bytes = visible ? jsonBytes(item ?? { ...marker, evidenceRef: "x".repeat(36) }) + ((item ? items.length : unavailable.length) ? 1 : 0) : 0;
168
+ const envelopeBytes = jsonBytes({
169
+ historyIncarnation,
116
170
  workspaceId: header.workspace_id,
117
171
  snapshotId: header.id,
118
172
  highWatermark: header.high_watermark,
119
173
  items: [],
174
+ unavailable: [],
120
175
  nextPageToken: next
121
176
  });
122
- if (items.length && envelope + itemBytes + bytes > MAX_SYNC_PAGE_BYTES) break;
123
- items.push(item);
177
+ if (item && envelopeBytes + bytes > MAX_SYNC_PAGE_BYTES) {
178
+ item = void 0;
179
+ reason = marker.reason = "record_oversized";
180
+ bytes = visible ? jsonBytes({ ...marker, evidenceRef: "x".repeat(36) }) + (unavailable.length ? 1 : 0) : 0;
181
+ }
182
+ if (envelopeBytes + itemBytes + bytes > MAX_SYNC_PAGE_BYTES) {
183
+ if (!scanned) throw new Error("Sync identity exceeds page byte budget");
184
+ break;
185
+ }
186
+ if (item && visible) items.push(item);
187
+ else if (!item) {
188
+ marker.evidenceRef = await retainSqlEvidence(snapshotEvidence(header, row, historyIncarnation), reason);
189
+ if (visible) unavailable.push(marker);
190
+ }
124
191
  itemBytes += bytes;
125
192
  scanned++;
126
193
  token = next;
194
+ previous = key;
127
195
  }
128
- return {
196
+ const [retained] = await syncRows("SELECT expires_at FROM sync_snapshots WHERE id = ?", header.id);
197
+ if (!retained || retained.expires_at <= nowEpoch()) throw createError({ statusCode: 410, statusMessage: "Snapshot expired or unavailable" });
198
+ return SnapshotResponseSchema.parse({
199
+ historyIncarnation,
129
200
  workspaceId: header.workspace_id,
130
201
  snapshotId: header.id,
131
202
  highWatermark: header.high_watermark,
132
203
  items,
204
+ ...unavailable.length ? { unavailable } : {},
133
205
  nextPageToken: availableRows > scanned ? token : null
134
- };
206
+ });
135
207
  }
136
208
  function uid() {
137
209
  return globalThis.crypto.randomUUID();
@@ -165,12 +237,15 @@ export async function pruneExpiredSyncSnapshots() {
165
237
  getRawDb().prepare("DELETE FROM sync_snapshots WHERE expires_at <= ?").run(nowEpoch());
166
238
  }
167
239
  }
240
+ function safeVersionEnd(base, count) {
241
+ const end = base + count;
242
+ if (!Number.isSafeInteger(base) || base < 0 || !Number.isSafeInteger(end) || end < 0 || count > 0 && end >= Number.MAX_SAFE_INTEGER) {
243
+ throw Object.assign(new Error("Sync server version exhausted or invalid"), { code: "VALIDATION_ERROR" });
244
+ }
245
+ return end;
246
+ }
168
247
  function backgroundHistoryOpId(admission, stage) {
169
- const hex = createHash("sha256").update(`${admission.workspaceId}\0${admission.generationId}\0${stage}`).digest("hex").slice(0, 32).split("");
170
- hex[12] = "4";
171
- hex[16] = (Number.parseInt(hex[16], 16) & 3 | 8).toString(16);
172
- const value = hex.join("");
173
- return `${value.slice(0, 8)}-${value.slice(8, 12)}-${value.slice(12, 16)}-${value.slice(16, 20)}-${value.slice(20)}`;
248
+ return digestUuid(createHash("sha256").update(`${admission.workspaceId}\0${admission.generationId}\0${stage}`).digest("hex"));
174
249
  }
175
250
  function fingerprintPayload(tableName, operation, payload) {
176
251
  if (tableName !== "notifications" || operation !== "delete") return payload;
@@ -191,16 +266,9 @@ function operationFingerprint(op) {
191
266
  deviceId: op.stamp.deviceId
192
267
  });
193
268
  }
194
- function changeLogFingerprint(row) {
195
- return stableJson({
196
- tableName: row.table_name,
197
- operation: row.op,
198
- pk: row.pk,
199
- payload: fingerprintPayload(row.table_name, row.op, row.payload_json ? JSON.parse(row.payload_json) : void 0),
200
- clock: row.clock,
201
- hlc: row.hlc,
202
- deviceId: row.device_id
203
- });
269
+ function prepareFinalOperation(op) {
270
+ const payload = op.operation === "put" && op.payload && typeof op.payload === "object" ? { ...op.payload, clock: op.stamp.clock, hlc: op.stamp.hlc, op_id: op.stamp.opId } : op.payload;
271
+ return { ...op, ...prepareSyncWrite({ ...op, payload }) };
204
272
  }
205
273
  function notificationPayloadUserId(payload) {
206
274
  if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
@@ -209,11 +277,6 @@ function notificationPayloadUserId(payload) {
209
277
  const userId = payload.user_id;
210
278
  return typeof userId === "string" && userId.trim().length > 0 ? userId : void 0;
211
279
  }
212
- function isNotificationVisibleToUser(change, userId) {
213
- if (change.tableName !== "notifications") return true;
214
- if (!userId) return false;
215
- return notificationPayloadUserId(change.payload) === userId;
216
- }
217
280
  function scopeNotificationWrite(op, userId) {
218
281
  if (op.tableName !== "notifications") return op;
219
282
  if (!userId) {
@@ -256,8 +319,10 @@ function workspaceItemCapabilityAssertion(op, workspaceId) {
256
319
  return {
257
320
  sql: `SELECT json_extract('{}', CASE WHEN EXISTS (
258
321
  SELECT 1 FROM (
259
- SELECT data_json, ${decoded} AS metadata FROM "${SYNCED_TABLE_MAP[op.tableName]}"
260
- WHERE workspace_id = ? AND id = ?
322
+ SELECT data_json, ${decoded} AS metadata FROM (
323
+ SELECT CASE WHEN json_valid(data_json) AND length(cast(data_json AS blob)) <= ${MAX_SYNC_PAYLOAD_BYTES} THEN data_json ELSE '{}' END AS data_json
324
+ FROM "${SYNCED_TABLE_MAP[op.tableName]}" WHERE workspace_id = ? AND id = ?
325
+ )
261
326
  ) WHERE ${semantics}
262
327
  ) THEN '${WORKSPACE_ITEM_UPDATE_REQUIRED}' ELSE '$' END)`,
263
328
  parameters: [workspaceId, op.pk]
@@ -279,7 +344,7 @@ function snapshotNotificationOwnerClause(tableName, jsonExpr, userId) {
279
344
  if (tableName !== "notifications") return { sql: "", params: [] };
280
345
  if (!userId) return { sql: " AND 1 = 0", params: [] };
281
346
  return {
282
- sql: ` AND json_extract(${jsonExpr}, '$.user_id') = ?`,
347
+ sql: ` AND ${notificationOwnerSql(jsonExpr)} = ?`,
283
348
  params: [userId]
284
349
  };
285
350
  }
@@ -366,6 +431,7 @@ function encodeSnapshotPageToken(token) {
366
431
  }
367
432
  function decodeSnapshotPageToken(value) {
368
433
  try {
434
+ if (value.length > MAX_SYNC_SNAPSHOT_TOKEN_LENGTH) throw new Error("Token exceeds ceiling");
369
435
  const parsed = JSON.parse(
370
436
  Buffer.from(value, "base64url").toString("utf8")
371
437
  );
@@ -373,6 +439,7 @@ function decodeSnapshotPageToken(value) {
373
439
  if (parsed.version !== 1 || typeof parsed.snapshotId !== "string" || !parsed.snapshotId || !after || typeof after.tableName !== "string" || typeof after.pk !== "string" || after.kind !== "row" && after.kind !== "tombstone") {
374
440
  throw new Error("Invalid token payload");
375
441
  }
442
+ assertCoverageKey(after.tableName, after.pk);
376
443
  return parsed;
377
444
  } catch {
378
445
  throw createError({
@@ -534,58 +601,188 @@ function incomingWinsRevision(incoming, existing) {
534
601
  opId: existing.opId || existing.op_id || ""
535
602
  });
536
603
  }
537
- function materializedWinner(row, tombstone) {
538
- if (tombstone && (!row || incomingWinsRevision(
539
- { clock: tombstone.clock, hlc: tombstone.hlc, opId: tombstone.op_id },
540
- row
541
- ))) {
542
- return {
543
- kind: "delete",
544
- revision: { clock: tombstone.clock, hlc: tombstone.hlc, opId: tombstone.op_id },
545
- serverDeletedAt: tombstone.deleted_at
546
- };
604
+ class StoredRecordUnavailable extends Error {
605
+ constructor(source, reason, revision) {
606
+ super(reason);
607
+ this.source = source;
608
+ this.reason = reason;
609
+ this.revision = revision;
610
+ }
611
+ }
612
+ function storedCanonicalSource(workspaceId, tableName, pk) {
613
+ return {
614
+ workspaceId,
615
+ source: "canonical",
616
+ locator: JSON.stringify([tableName, pk]),
617
+ table: SYNCED_TABLE_MAP[tableName],
618
+ where: "workspace_id=? AND id=?",
619
+ parameters: [workspaceId, pk],
620
+ revisionSql: "json_array(clock,hlc,op_id,deleted)",
621
+ payload: "data_json",
622
+ metadata: `json_object('table_name','${tableName}','pk',id,'clock',clock,'hlc',hlc,'op_id',op_id,'deleted',deleted)`
623
+ };
624
+ }
625
+ const WINNER_COLUMNS = `${boundedSyncPayload("data_json")} AS data_json,
626
+ ${["clock", "hlc", "op_id", "deleted", "updated_at"].map((c) => `${boundedSyncMetadata(c)} AS ${c}`).join(",")},
627
+ length(cast(data_json AS blob)) AS payload_bytes`;
628
+ const TOMBSTONE_COLUMNS = ["clock", "hlc", "op_id", "deleted_at"].map((c) => `${boundedSyncMetadata(c)} AS ${c}`).join(",");
629
+ function materializedWinner(row, tombstone, workspaceId, tableName, pk) {
630
+ const source = storedCanonicalSource(workspaceId, tableName, pk);
631
+ const revisionValid = (value) => SnapshotItemSchema.safeParse({
632
+ kind: "tombstone",
633
+ tableName,
634
+ pk,
635
+ revision: { clock: value.clock, hlc: value.hlc, opId: value.op_id },
636
+ serverDeletedAt: 0
637
+ }).success && Number.isSafeInteger(value.clock);
638
+ if (row && (!revisionValid(row) || ![0, 1].includes(row.deleted))) throw new StoredRecordUnavailable(source, "invalid_stored_revision");
639
+ if (tombstone && (!revisionValid(tombstone) || !Number.isSafeInteger(tombstone.deleted_at) || tombstone.deleted_at < 0)) {
640
+ throw new StoredRecordUnavailable({
641
+ workspaceId,
642
+ source: "canonical",
643
+ locator: JSON.stringify([tableName, pk, "tombstone"]),
644
+ table: "tombstones",
645
+ where: "workspace_id=? AND table_name=? AND pk=?",
646
+ parameters: [workspaceId, tableName, pk],
647
+ revisionSql: "json_array(clock,hlc,op_id)",
648
+ payload: "NULL",
649
+ metadata: "json_object('table_name',table_name,'pk',pk,'clock',clock,'hlc',hlc,'op_id',op_id,'deleted_at',deleted_at)"
650
+ }, "invalid_stored_revision");
651
+ }
652
+ if (tombstone && (!row || incomingWinsRevision({ clock: tombstone.clock, hlc: tombstone.hlc, opId: tombstone.op_id }, row))) {
653
+ return { kind: "delete", revision: { clock: tombstone.clock, hlc: tombstone.hlc, opId: tombstone.op_id }, serverDeletedAt: tombstone.deleted_at };
547
654
  }
548
655
  if (!row) return void 0;
549
656
  const revision = { clock: row.clock, hlc: row.hlc, opId: row.op_id };
550
- return row.deleted ? {
551
- kind: "delete",
552
- revision,
553
- serverDeletedAt: tombstone?.op_id === row.op_id ? tombstone.deleted_at : row.updated_at
554
- } : { kind: "put", payload: JSON.parse(row.data_json), revision };
657
+ if (row.deleted) {
658
+ if (!Number.isSafeInteger(row.updated_at) || row.updated_at < 0) throw new StoredRecordUnavailable(source, "invalid_stored_revision");
659
+ return { kind: "delete", revision, serverDeletedAt: tombstone?.op_id === row.op_id ? tombstone.deleted_at : row.updated_at };
660
+ }
661
+ if (row.payload_bytes > MAX_SYNC_PAYLOAD_BYTES) throw new StoredRecordUnavailable(source, "payload_oversized", revision);
662
+ let payload;
663
+ try {
664
+ payload = JSON.parse(row.data_json);
665
+ } catch {
666
+ throw new StoredRecordUnavailable(source, "invalid_json", revision);
667
+ }
668
+ if (!validReadPayload(tableName, pk, payload, row.clock, row.hlc)) throw new StoredRecordUnavailable(source, "invalid_stored_payload", revision);
669
+ return { kind: "put", payload, revision };
670
+ }
671
+ const RECEIPT_COLUMNS = `${boundedSyncMetadata("id")} AS id,op_id,server_version,workspace_id,
672
+ ${["table_name", "pk", "op", "clock", "hlc", "device_id"].map((c) => `${boundedSyncMetadata(c)} AS ${c}`).join(",")},
673
+ ${boundedSyncPayload("payload_json")} AS payload_json,length(cast(payload_json AS blob)) AS payload_bytes,
674
+ ${boundedSyncMetadata("intent_fingerprint")} AS intent_fingerprint,length(cast(intent_fingerprint AS blob)) AS fingerprint_bytes`;
675
+ function storedReceiptSource(row) {
676
+ return {
677
+ workspaceId: row.workspace_id,
678
+ source: "pull",
679
+ locator: row.id || row.op_id,
680
+ table: "change_log",
681
+ where: "op_id=?",
682
+ parameters: [row.op_id],
683
+ revisionSql: "cast(server_version AS text)",
684
+ payload: "payload_json",
685
+ metadata: "json_object('table_name',table_name,'pk',pk,'op',op,'clock',clock,'hlc',hlc,'device_id',device_id,'op_id',op_id,'server_version',server_version,'intent_fingerprint',intent_fingerprint)"
686
+ };
687
+ }
688
+ function receiptFingerprint(row) {
689
+ const source = storedReceiptSource(row);
690
+ if (row.fingerprint_bytes > SYNC_METADATA_BYTES || row.payload_bytes > MAX_SYNC_PAYLOAD_BYTES) throw new StoredRecordUnavailable(source, "stored_receipt_oversized");
691
+ let payload;
692
+ try {
693
+ payload = row.payload_json != null ? JSON.parse(row.payload_json) : void 0;
694
+ } catch {
695
+ throw new StoredRecordUnavailable(source, "invalid_json");
696
+ }
697
+ if (!Number.isSafeInteger(row.server_version) || row.server_version < 1 || !SyncChangeSchema.safeParse({
698
+ tableName: row.table_name,
699
+ pk: row.pk,
700
+ op: row.op,
701
+ payload,
702
+ stamp: { clock: row.clock, hlc: row.hlc, opId: row.op_id, deviceId: row.device_id },
703
+ serverVersion: row.server_version
704
+ }).success) {
705
+ throw new StoredRecordUnavailable(source, "invalid_stored_receipt");
706
+ }
707
+ if (row.op === "put" && !validReadPayload(row.table_name, row.pk, payload, row.clock, row.hlc)) throw new StoredRecordUnavailable(source, "invalid_stored_receipt");
708
+ return row.intent_fingerprint ?? stableJson({
709
+ tableName: row.table_name,
710
+ operation: row.op,
711
+ pk: row.pk,
712
+ payload: fingerprintPayload(row.table_name, row.op, payload),
713
+ clock: row.clock,
714
+ hlc: row.hlc,
715
+ deviceId: row.device_id
716
+ });
717
+ }
718
+ function storedRecordCapability(capability) {
719
+ if (capability !== "stored-record-v1") throw createError({
720
+ statusCode: 426,
721
+ statusMessage: "Update OR3 Chat to recover unavailable stored records",
722
+ data: { code: "OR3_SYNC_UPDATE_REQUIRED", requiredCapability: "stored-record-v1" }
723
+ });
724
+ }
725
+ function rejectedIntent(op, source) {
726
+ const lookup = evidenceLookup(source);
727
+ return { sql: `INSERT OR IGNORE INTO sync_unavailable_records
728
+ (id,workspace_id,source,locator,revision,payload_json,metadata_json,reason,status,created_at)
729
+ SELECT ?,?,'push',?,json_array(?,?),?,json_object('historyIncarnation',?,'evidenceRef',id), 'stored_record_unavailable','unresolved',unixepoch()
730
+ FROM (${lookup.sql})`, parameters: [uid(), source.workspaceId, op.stamp.opId, source.historyIncarnation, operationFingerprint(op), JSON.stringify(op), source.historyIncarnation, ...lookup.parameters] };
731
+ }
732
+ function unavailableResult(op, error, evidenceRef) {
733
+ return { opId: op.stamp.opId, success: false, errorCode: "STORED_RECORD_UNAVAILABLE", error: error.reason, evidenceRef };
734
+ }
735
+ function retainPushFailureNative(op, error, input) {
736
+ storedRecordCapability(input.storedRecordCapability);
737
+ const source = { ...error.source, historyIncarnation: input.historyIncarnation };
738
+ const raw = getRawDb();
739
+ for (const statement of [evidenceInsert(source, error.reason), rejectedIntent(op, source)]) raw.prepare(statement.sql).run(...statement.parameters);
740
+ const lookup = evidenceLookup(source);
741
+ const row = raw.prepare(lookup.sql).get(...lookup.parameters);
742
+ if (!row) throw new Error("Push evidence source disappeared");
743
+ return unavailableResult(op, error, row.id);
744
+ }
745
+ async function retainPushFailureD1(op, error, historyIncarnation, capability) {
746
+ storedRecordCapability(capability);
747
+ const source = { ...error.source, historyIncarnation };
748
+ await historyBatch([historyAssertion(historyIncarnation), evidenceInsert(source, error.reason), rejectedIntent(op, source)], historyIncarnation);
749
+ const lookup = evidenceLookup(source);
750
+ const [row] = await d1All(lookup.sql, ...lookup.parameters);
751
+ if (!row) throw new Error("Push evidence source disappeared");
752
+ return unavailableResult(op, error, row.id);
555
753
  }
556
754
  function currentWinnerNative(raw, workspaceId, tableName, pk) {
557
755
  const materializedTable = SYNCED_TABLE_MAP[tableName];
558
756
  if (!materializedTable) return void 0;
559
757
  const row = raw.prepare(
560
- `SELECT data_json, deleted, clock, hlc, op_id, updated_at
758
+ `SELECT ${WINNER_COLUMNS}
561
759
  FROM ${materializedTable} WHERE id = ? AND workspace_id = ?`
562
760
  ).get(pk, workspaceId);
563
761
  const tombstone = raw.prepare(
564
- `SELECT clock, hlc, op_id, deleted_at FROM tombstones
762
+ `SELECT ${TOMBSTONE_COLUMNS} FROM tombstones
565
763
  WHERE workspace_id = ? AND table_name = ? AND pk = ?`
566
764
  ).get(workspaceId, tableName, pk);
567
- return materializedWinner(row, tombstone);
765
+ return materializedWinner(row, tombstone, workspaceId, tableName, pk);
568
766
  }
569
767
  async function currentWinnerD1(workspaceId, tableName, pk, userId) {
570
768
  const materializedTable = SYNCED_TABLE_MAP[tableName];
571
769
  if (!materializedTable) return void 0;
572
770
  const [row] = await d1All(
573
- `SELECT data_json, deleted, clock, hlc, op_id, updated_at
771
+ `SELECT ${WINNER_COLUMNS}
574
772
  FROM "${materializedTable}" WHERE id = ? AND workspace_id = ?`,
575
773
  pk,
576
774
  workspaceId
577
775
  );
578
- if (tableName === "notifications" && row && notificationPayloadUserId(JSON.parse(row.data_json)) !== userId) {
579
- return void 0;
580
- }
581
776
  const [tombstone] = await d1All(
582
- `SELECT clock, hlc, op_id, deleted_at FROM tombstones
777
+ `SELECT ${TOMBSTONE_COLUMNS} FROM tombstones
583
778
  WHERE workspace_id = ? AND table_name = ? AND pk = ?`,
584
779
  workspaceId,
585
780
  tableName,
586
781
  pk
587
782
  );
588
- return materializedWinner(row, tombstone);
783
+ const winner = materializedWinner(row, tombstone, workspaceId, tableName, pk);
784
+ if (tableName === "notifications" && winner?.kind === "put" && notificationPayloadUserId(winner.payload) !== userId) return void 0;
785
+ return winner;
589
786
  }
590
787
  export class SqliteSyncGatewayAdapter {
591
788
  id = "sqlite";
@@ -599,16 +796,26 @@ export class SqliteSyncGatewayAdapter {
599
796
  }
600
797
  const current = watcher;
601
798
  current.listeners.set(onVersion, onError);
602
- if (current.version !== void 0) onVersion(current.version);
799
+ if (current.position) onVersion(current.position);
603
800
  const poll = async () => {
604
801
  if (current.running || this.versionWatchers.get(scope.workspaceId) !== current) return;
605
802
  current.running = true;
606
803
  try {
607
- const row = await getSqliteDb().selectFrom("server_version_counter").select("value").where("workspace_id", "=", scope.workspaceId).executeTakeFirst();
608
- const version = row?.value ?? 0;
609
- if (current.version !== version) {
610
- current.version = version;
611
- for (const notify of [...current.listeners.keys()]) notify(version);
804
+ const [row] = await syncRows(`SELECT incarnation AS historyIncarnation,
805
+ coalesce((SELECT value FROM server_version_counter WHERE workspace_id=?),0) AS version FROM sync_history WHERE id=1`, scope.workspaceId);
806
+ if (!row || !validHistoryIncarnation(row.historyIncarnation)) throw new Error("Invalid sync history singleton");
807
+ if (current.position && current.position.historyIncarnation !== row.historyIncarnation) {
808
+ for (const fail of [...current.listeners.values()]) fail(createError({
809
+ statusCode: 409,
810
+ data: { code: "OR3_SYNC_HISTORY_CHANGED", historyIncarnation: row.historyIncarnation, requiresSnapshot: true }
811
+ }));
812
+ current.listeners.clear();
813
+ this.versionWatchers.delete(scope.workspaceId);
814
+ return;
815
+ }
816
+ if (current.position?.version !== row.version) {
817
+ current.position = row;
818
+ for (const notify of [...current.listeners.keys()]) notify(row);
612
819
  }
613
820
  } catch (error) {
614
821
  for (const fail of [...current.listeners.values()]) fail(error);
@@ -643,11 +850,14 @@ export class SqliteSyncGatewayAdapter {
643
850
  get capabilities() {
644
851
  return isD1Driver() ? {
645
852
  snapshotBootstrap: "snapshot-v1",
853
+ unavailableRecords: "v1",
646
854
  historyRetention: "snapshot-v1",
647
855
  retainedStorageMetadata: "v1",
648
856
  atomicUploadQuota: "retained-v1"
649
857
  } : {
858
+ historyIncarnation: "v1",
650
859
  snapshotBootstrap: "snapshot-v1",
860
+ unavailableRecords: "v1",
651
861
  historyRetention: "snapshot-v1",
652
862
  ...this.storageGenerationCoordinator ? { externalStorageGenerations: "v1" } : {},
653
863
  backgroundGenerationHistory: "v1",
@@ -659,6 +869,25 @@ export class SqliteSyncGatewayAdapter {
659
869
  atomicUploadQuota: "retained-v1"
660
870
  };
661
871
  }
872
+ async getHistoryIncarnation(event, scope) {
873
+ await assertWorkspaceScopeAuthorized(event, scope.workspaceId);
874
+ return readHistoryIncarnation();
875
+ }
876
+ async checkHistory(event, input, discovery = false) {
877
+ await assertWorkspaceScopeAuthorized(event, input.scope.workspaceId);
878
+ const expected = input.historyIncarnation;
879
+ if (expected === void 0 && input.historyIncarnationCapability !== "incarnation-v1") {
880
+ throw createError({
881
+ statusCode: 426,
882
+ statusMessage: "Update OR3 Chat for history recovery",
883
+ data: { code: "OR3_SYNC_UPDATE_REQUIRED", requiredCapability: "incarnation-v1" }
884
+ });
885
+ }
886
+ validateExpectedHistory(expected);
887
+ const current = await readHistoryIncarnation();
888
+ if (!discovery && expected !== current) historyChanged(current);
889
+ return current;
890
+ }
662
891
  get db() {
663
892
  return getSqliteDb();
664
893
  }
@@ -675,7 +904,7 @@ export class SqliteSyncGatewayAdapter {
675
904
  const revision = String(counter?.value ?? 0);
676
905
  const parse = (row) => {
677
906
  const payload = JSON.parse(row.data_json);
678
- if (payload.id !== row.id) throw new Error("Canonical history identity mismatch");
907
+ if (row.deleted !== 1 && payload.id !== row.id) throw new Error("Canonical history identity mismatch");
679
908
  return { ...payload, id: row.id, clock: row.clock, deleted: row.deleted === 1 };
680
909
  };
681
910
  if (query.kind === "thread") {
@@ -689,6 +918,7 @@ export class SqliteSyncGatewayAdapter {
689
918
  thread
690
919
  };
691
920
  const ownership = resolveCanonicalProjectOwnership(raw, actor.workspaceId, query.thread_id, thread.project_id);
921
+ if (ownership.status === "unresolved") return { status: "scope_incomplete", revision: String(threadRevision?.value ?? 0) };
692
922
  return {
693
923
  status: "ok",
694
924
  project_ownership: ownership.status,
@@ -774,20 +1004,30 @@ export class SqliteSyncGatewayAdapter {
774
1004
  admission.userMessage ? { table: "messages", materialized: "s_messages", record: admission.userMessage } : null,
775
1005
  { table: "messages", materialized: "s_messages", record: admission.assistantMessage }
776
1006
  ].filter(Boolean);
1007
+ const prepared = records.map((entry) => {
1008
+ const opId = backgroundHistoryOpId(admission, entry.table === "threads" ? "thread" : entry.record.id === admission.messageId ? "assistant" : "user");
1009
+ const hlc = entry.record.hlc ?? `${Date.now().toString(36).padStart(9, "0")}:000:background`;
1010
+ const normalized = normalizeWirePayloadForTable(entry.table, entry.record);
1011
+ const payload = { ...sanitizePayloadForSync(entry.table, normalized, "put"), hlc, op_id: opId };
1012
+ if (entry.table === "messages" && !payload.order_key) payload.order_key = hlc;
1013
+ return prepareSyncWrite({
1014
+ tableName: entry.table,
1015
+ pk: entry.record.id,
1016
+ operation: "put",
1017
+ payload,
1018
+ stamp: { clock: entry.record.clock, hlc, opId, deviceId: backgroundHistoryDeviceId(admission.generationId) }
1019
+ });
1020
+ });
777
1021
  const counter = raw.prepare("SELECT value FROM server_version_counter WHERE workspace_id = ?").get(admission.workspaceId);
778
1022
  const baseVersion = counter?.value ?? 0;
779
- const finalVersion = baseVersion + records.length;
1023
+ const finalVersion = safeVersionEnd(baseVersion, records.length);
780
1024
  raw.prepare(
781
1025
  `INSERT INTO server_version_counter (workspace_id, value) VALUES (?, ?)
782
1026
  ON CONFLICT(workspace_id) DO UPDATE SET value = excluded.value`
783
1027
  ).run(admission.workspaceId, finalVersion);
784
1028
  const now = nowEpoch();
785
1029
  records.forEach((entry, index) => {
786
- const opId = backgroundHistoryOpId(
787
- admission,
788
- entry.table === "threads" ? "thread" : entry.record.id === admission.messageId ? "assistant" : "user"
789
- );
790
- const hlc = entry.record.hlc ?? `${Date.now().toString(36).padStart(9, "0")}:000:background`;
1030
+ const { stamp: { opId, hlc }, payload } = prepared[index];
791
1031
  const tombstone = raw.prepare(
792
1032
  `SELECT clock, hlc, op_id FROM tombstones
793
1033
  WHERE workspace_id = ? AND table_name = ? AND pk = ?`
@@ -802,19 +1042,7 @@ export class SqliteSyncGatewayAdapter {
802
1042
  )) {
803
1043
  throw Object.assign(new Error("Background history record was superseded"), { code: "SUPERSEDED" });
804
1044
  }
805
- const sanitized = sanitizePayloadForSync(
806
- entry.table,
807
- entry.record,
808
- "put"
809
- );
810
- if (!sanitized) {
811
- throw Object.assign(new Error("Invalid background history payload"), { code: "VALIDATION_ERROR" });
812
- }
813
- const payload = { ...sanitized, hlc, op_id: opId };
814
1045
  const payloadJson = JSON.stringify(payload);
815
- if (new TextEncoder().encode(payloadJson).byteLength > MAX_SYNC_PAYLOAD_BYTES) {
816
- throw Object.assign(new Error("Invalid background history payload size"), { code: "VALIDATION_ERROR" });
817
- }
818
1046
  const version = baseVersion + index + 1;
819
1047
  raw.prepare(
820
1048
  `INSERT INTO change_log
@@ -951,7 +1179,7 @@ export class SqliteSyncGatewayAdapter {
951
1179
  ).run(uid(), admission.workspaceId, admission.generationId, fingerprint, superseded, now);
952
1180
  return { status: "superseded", reason: superseded };
953
1181
  }
954
- const nextClock = row.clock + 1;
1182
+ const nextClock = nextSyncClock(row.clock);
955
1183
  const hlc = `${Date.now().toString(36).padStart(9, "0")}:000:background`;
956
1184
  const opId = backgroundHistoryOpId(admission, "finalize");
957
1185
  const terminalState = input.snapshot.status === "complete" ? "complete" : input.snapshot.status === "aborted" ? "aborted" : "failed";
@@ -976,12 +1204,18 @@ export class SqliteSyncGatewayAdapter {
976
1204
  error: input.snapshot.error ?? null
977
1205
  }
978
1206
  };
979
- const payloadJson = JSON.stringify(payload);
980
- if (new TextEncoder().encode(payloadJson).byteLength > MAX_SYNC_PAYLOAD_BYTES) {
981
- throw Object.assign(new Error("Invalid background history payload size"), { code: "VALIDATION_ERROR" });
982
- }
1207
+ const finalPayload = normalizeWirePayloadForTable("messages", payload);
1208
+ if (!finalPayload.order_key) finalPayload.order_key = hlc;
1209
+ const prepared = prepareSyncWrite({
1210
+ tableName: "messages",
1211
+ pk: admission.messageId,
1212
+ operation: "put",
1213
+ payload: finalPayload,
1214
+ stamp: { clock: nextClock, hlc, opId, deviceId: backgroundHistoryDeviceId(admission.generationId) }
1215
+ });
1216
+ const payloadJson = JSON.stringify(prepared.payload);
983
1217
  const counter = raw.prepare("SELECT value FROM server_version_counter WHERE workspace_id = ?").get(admission.workspaceId);
984
- const serverVersion = (counter?.value ?? 0) + 1;
1218
+ const serverVersion = safeVersionEnd(counter?.value ?? 0, 1);
985
1219
  raw.prepare(
986
1220
  `INSERT INTO server_version_counter (workspace_id, value) VALUES (?, ?)
987
1221
  ON CONFLICT(workspace_id) DO UPDATE SET value = excluded.value`
@@ -1070,19 +1304,25 @@ export class SqliteSyncGatewayAdapter {
1070
1304
  } else newRows.push(row);
1071
1305
  }
1072
1306
  if (!newRows.length) return;
1307
+ const prepared = newRows.map((row) => {
1308
+ const opId = digestUuid(createHash("sha256").update(JSON.stringify([admission.workspaceId, admission.generationId, row.id])).digest("hex"));
1309
+ const hlc = `${Date.now().toString(36).padStart(9, "0")}:000:background`;
1310
+ return prepareSyncWrite({
1311
+ tableName: "kv",
1312
+ pk: row.id,
1313
+ operation: "put",
1314
+ payload: { ...sanitizePayloadForSync("kv", row, "put"), hlc, op_id: opId },
1315
+ stamp: { clock: row.clock, hlc, opId, deviceId: backgroundHistoryDeviceId(admission.generationId) }
1316
+ });
1317
+ });
1073
1318
  const counter = raw.prepare("SELECT value FROM server_version_counter WHERE workspace_id = ?").get(admission.workspaceId);
1074
1319
  const baseVersion = counter?.value ?? 0;
1075
1320
  raw.prepare(`INSERT INTO server_version_counter (workspace_id, value) VALUES (?, ?)
1076
- ON CONFLICT(workspace_id) DO UPDATE SET value = excluded.value`).run(admission.workspaceId, baseVersion + newRows.length);
1321
+ ON CONFLICT(workspace_id) DO UPDATE SET value = excluded.value`).run(admission.workspaceId, safeVersionEnd(baseVersion, newRows.length));
1077
1322
  const now = nowEpoch();
1078
1323
  newRows.forEach((row, index) => {
1079
- const opId = `background-tool:${createHash("sha256").update(JSON.stringify([admission.workspaceId, admission.generationId, row.id])).digest("hex")}`;
1080
- const hlc = `${Date.now().toString(36).padStart(9, "0")}:000:background`;
1081
- const sanitized = sanitizePayloadForSync("kv", row, "put");
1082
- if (!sanitized) throw Object.assign(new Error("Invalid tool result payload"), { code: "VALIDATION_ERROR" });
1083
- const payloadJson = JSON.stringify({ ...sanitized, hlc, op_id: opId });
1084
- if (new TextEncoder().encode(payloadJson).length > MAX_SYNC_PAYLOAD_BYTES)
1085
- throw Object.assign(new Error("Invalid tool result payload size"), { code: "VALIDATION_ERROR" });
1324
+ const { stamp: { opId, hlc }, payload } = prepared[index];
1325
+ const payloadJson = JSON.stringify(payload);
1086
1326
  raw.prepare(`INSERT INTO s_kv (id, workspace_id, data_json, clock, hlc, device_id, op_id, deleted, created_at, updated_at)
1087
1327
  VALUES (?, ?, ?, ?, ?, ?, ?, 0, ?, ?)`).run(
1088
1328
  row.id,
@@ -1437,12 +1677,13 @@ export class SqliteSyncGatewayAdapter {
1437
1677
  } : {}
1438
1678
  };
1439
1679
  }
1440
- async push(event, input) {
1680
+ async push(event, input, repair) {
1441
1681
  const { scope, ops } = input;
1442
1682
  const workspaceId = scope.workspaceId;
1443
1683
  await assertWorkspaceScopeAuthorized(event, workspaceId);
1684
+ const historyIncarnation = await this.checkHistory(event, input);
1444
1685
  if (!ops.length) {
1445
- return { results: [], serverVersion: 0 };
1686
+ return { results: [], serverVersion: 0, historyIncarnation };
1446
1687
  }
1447
1688
  const userId = resolveSessionUserId(event);
1448
1689
  const resultSlots = new Array(ops.length);
@@ -1478,7 +1719,7 @@ export class SqliteSyncGatewayAdapter {
1478
1719
  }
1479
1720
  continue;
1480
1721
  }
1481
- uniqueOps.push(scoped);
1722
+ uniqueOps.push({ ...scoped });
1482
1723
  indicesByOpId.set(group.op.stamp.opId, group.indices);
1483
1724
  }
1484
1725
  if (isD1Driver()) {
@@ -1489,7 +1730,10 @@ export class SqliteSyncGatewayAdapter {
1489
1730
  resultSlots,
1490
1731
  indicesByOpId,
1491
1732
  userId,
1492
- workspaceItemCapability: input.workspaceItemCapability
1733
+ workspaceItemCapability: input.workspaceItemCapability,
1734
+ storedRecordCapability: input.storedRecordCapability,
1735
+ historyIncarnation,
1736
+ repair
1493
1737
  });
1494
1738
  }
1495
1739
  const raw = getRawDb();
@@ -1498,45 +1742,66 @@ export class SqliteSyncGatewayAdapter {
1498
1742
  let finalServerVersion = 0;
1499
1743
  const hookEmissions = [];
1500
1744
  const runTx = raw.transaction(() => {
1745
+ const current = raw.prepare("SELECT incarnation FROM sync_history WHERE id=1").get();
1746
+ if (current?.incarnation !== historyIncarnation) {
1747
+ if (!validHistoryIncarnation(current?.incarnation)) throw new Error("Invalid sync history singleton");
1748
+ historyChanged(current.incarnation);
1749
+ }
1750
+ if (repair) {
1751
+ const assertion = repairAssertion(repair);
1752
+ raw.prepare(assertion.sql).get(...assertion.parameters ?? []);
1753
+ }
1754
+ const existingOps = /* @__PURE__ */ new Map();
1755
+ const failedBeforeAlloc = /* @__PURE__ */ new Set();
1756
+ for (const op of uniqueOps) {
1757
+ try {
1758
+ const receipt = raw.prepare(`SELECT ${RECEIPT_COLUMNS} FROM change_log WHERE op_id=?`).get(op.stamp.opId);
1759
+ if (receipt) {
1760
+ const fingerprint = receipt.workspace_id === workspaceId ? receiptFingerprint(receipt) : "";
1761
+ existingOps.set(op.stamp.opId, { ...receipt, fingerprint });
1762
+ if (receipt.workspace_id !== workspaceId) continue;
1763
+ }
1764
+ if (receipt && existingOps.get(op.stamp.opId).fingerprint !== operationFingerprint(op)) continue;
1765
+ if (!repair && !currentWinnerNative(raw, workspaceId, op.tableName, op.pk) && receipt) throw new StoredRecordUnavailable(storedReceiptSource(receipt), "stored_winner_missing");
1766
+ } catch (error) {
1767
+ if (!(error instanceof StoredRecordUnavailable)) throw error;
1768
+ if (error.revision && op.tableName !== "notifications" && incomingWinsRevision(op.stamp, error.revision)) {
1769
+ const statement = evidenceInsert({ ...error.source, historyIncarnation }, error.reason);
1770
+ raw.prepare(statement.sql).run(...statement.parameters);
1771
+ continue;
1772
+ }
1773
+ uniqueResults.push(retainPushFailureNative(op, error, input));
1774
+ failedBeforeAlloc.add(op.stamp.opId);
1775
+ }
1776
+ }
1501
1777
  if (input.workspaceItemCapability !== WORKSPACE_ITEM_CAPABILITY) {
1502
1778
  for (const op of uniqueOps) {
1779
+ if (failedBeforeAlloc.has(op.stamp.opId)) continue;
1503
1780
  const table = SYNCED_TABLE_MAP[op.tableName];
1504
1781
  if (!table || !["posts", "projects"].includes(op.tableName)) continue;
1505
- const canonical = raw.prepare("SELECT data_json FROM " + table + " WHERE id = ? AND workspace_id = ?").get(op.pk, workspaceId);
1506
- if (hasWorkspaceItemSemantics(op.tableName, op.payload) || hasWorkspaceItemSemantics(op.tableName, canonical ? JSON.parse(canonical.data_json) : void 0)) {
1782
+ const canonical = raw.prepare(`SELECT CASE WHEN json_valid(data_json) THEN ${boundedSyncPayload("data_json")} END AS data_json FROM ${table} WHERE id = ? AND workspace_id = ?`).get(op.pk, workspaceId);
1783
+ if (hasWorkspaceItemSemantics(op.tableName, op.payload) || hasWorkspaceItemSemantics(op.tableName, canonical?.data_json ? JSON.parse(canonical.data_json) : void 0)) {
1507
1784
  throw workspaceItemUpdateRequired();
1508
1785
  }
1509
1786
  }
1510
1787
  }
1511
- const opIds = uniqueOps.map((o) => o.stamp.opId);
1512
- const existingOps = /* @__PURE__ */ new Map();
1513
- const chunkSize = 500;
1514
- for (let i = 0; i < opIds.length; i += chunkSize) {
1515
- const chunk = opIds.slice(i, i + chunkSize);
1516
- const placeholders = chunk.map(() => "?").join(",");
1517
- const rows = raw.prepare(
1518
- `SELECT op_id, server_version, workspace_id, table_name, pk, op,
1519
- payload_json, clock, hlc, device_id
1520
- FROM change_log WHERE op_id IN (${placeholders})`
1521
- ).all(...chunk);
1522
- for (const row of rows) {
1523
- existingOps.set(row.op_id, {
1524
- server_version: row.server_version,
1525
- workspace_id: row.workspace_id,
1526
- fingerprint: changeLogFingerprint(row),
1527
- op_id: row.op_id
1528
- });
1529
- }
1530
- }
1531
- const failedBeforeAlloc = /* @__PURE__ */ new Set();
1532
1788
  for (const op of uniqueOps) {
1789
+ if (failedBeforeAlloc.has(op.stamp.opId)) continue;
1533
1790
  if (op.tableName !== "notifications") continue;
1534
1791
  const materializedTable = SYNCED_TABLE_MAP[op.tableName];
1535
1792
  if (!materializedTable) continue;
1536
1793
  const owned = raw.prepare(
1537
- `SELECT data_json FROM ${materializedTable} WHERE id = ? AND workspace_id = ?`
1794
+ `SELECT ${notificationOwnerSql("data_json")} AS owner FROM ${materializedTable} WHERE id = ? AND workspace_id = ?`
1538
1795
  ).get(op.pk, workspaceId);
1539
- const owner = owned ? notificationPayloadUserId(JSON.parse(owned.data_json)) : void 0;
1796
+ const owner = owned?.owner;
1797
+ if (owned && !owner) {
1798
+ uniqueResults.push(retainPushFailureNative(op, new StoredRecordUnavailable(
1799
+ storedCanonicalSource(workspaceId, op.tableName, op.pk),
1800
+ "notification_owner_unavailable"
1801
+ ), input));
1802
+ failedBeforeAlloc.add(op.stamp.opId);
1803
+ continue;
1804
+ }
1540
1805
  if (owned && owner !== userId || !owned && op.operation === "delete") {
1541
1806
  failedBeforeAlloc.add(op.stamp.opId);
1542
1807
  uniqueResults.push({
@@ -1547,6 +1812,21 @@ export class SqliteSyncGatewayAdapter {
1547
1812
  });
1548
1813
  }
1549
1814
  }
1815
+ const intentFingerprints = new Map(uniqueOps.map((op) => [op.stamp.opId, operationFingerprint(op)]));
1816
+ for (const op of uniqueOps) {
1817
+ if (existingOps.has(op.stamp.opId) || failedBeforeAlloc.has(op.stamp.opId)) continue;
1818
+ try {
1819
+ Object.assign(op, prepareFinalOperation(op));
1820
+ } catch (error) {
1821
+ failedBeforeAlloc.add(op.stamp.opId);
1822
+ uniqueResults.push({
1823
+ opId: op.stamp.opId,
1824
+ success: false,
1825
+ error: error.message,
1826
+ errorCode: "VALIDATION_ERROR"
1827
+ });
1828
+ }
1829
+ }
1550
1830
  const uniqueNewOpIds = /* @__PURE__ */ new Set();
1551
1831
  for (const op of uniqueOps) {
1552
1832
  if (existingOps.has(op.stamp.opId)) continue;
@@ -1555,6 +1835,7 @@ export class SqliteSyncGatewayAdapter {
1555
1835
  }
1556
1836
  let baseVersion;
1557
1837
  const counterRow = raw.prepare("SELECT value FROM server_version_counter WHERE workspace_id = ?").get(workspaceId);
1838
+ safeVersionEnd(counterRow?.value ?? 0, uniqueNewOpIds.size);
1558
1839
  if (counterRow) {
1559
1840
  baseVersion = counterRow.value;
1560
1841
  raw.prepare(
@@ -1562,7 +1843,7 @@ export class SqliteSyncGatewayAdapter {
1562
1843
  ).run(baseVersion + uniqueNewOpIds.size, workspaceId);
1563
1844
  } else {
1564
1845
  baseVersion = 0;
1565
- raw.prepare(
1846
+ if (uniqueNewOpIds.size) raw.prepare(
1566
1847
  "INSERT INTO server_version_counter (workspace_id, value) VALUES (?, ?)"
1567
1848
  ).run(workspaceId, uniqueNewOpIds.size);
1568
1849
  }
@@ -1586,7 +1867,7 @@ export class SqliteSyncGatewayAdapter {
1586
1867
  if (failedBeforeAlloc.has(opId)) continue;
1587
1868
  const existingLog = existingOps.get(opId);
1588
1869
  if (existingLog !== void 0) {
1589
- if (existingLog.workspace_id !== workspaceId || existingLog.fingerprint !== operationFingerprint(op)) {
1870
+ if (existingLog.workspace_id !== workspaceId || existingLog.fingerprint !== intentFingerprints.get(opId)) {
1590
1871
  uniqueResults.push({
1591
1872
  opId,
1592
1873
  success: false,
@@ -1630,21 +1911,6 @@ export class SqliteSyncGatewayAdapter {
1630
1911
  continue;
1631
1912
  }
1632
1913
  const pkValue = op.pk;
1633
- if (op.tableName === "notifications" && op.operation === "delete") {
1634
- const owned = raw.prepare(
1635
- `SELECT data_json FROM ${materializedTable} WHERE id = ? AND workspace_id = ?`
1636
- ).get(pkValue, workspaceId);
1637
- const owner = owned ? notificationPayloadUserId(JSON.parse(owned.data_json)) : void 0;
1638
- if (!owned || owner !== userId) {
1639
- uniqueResults.push({
1640
- opId,
1641
- success: false,
1642
- error: "Forbidden: notification owner mismatch",
1643
- errorCode: "UNAUTHORIZED"
1644
- });
1645
- continue;
1646
- }
1647
- }
1648
1914
  const payloadJson = op.payload != null ? JSON.stringify(op.payload) : null;
1649
1915
  insertChangeLog.run(
1650
1916
  uid(),
@@ -1660,6 +1926,7 @@ export class SqliteSyncGatewayAdapter {
1660
1926
  opId,
1661
1927
  now
1662
1928
  );
1929
+ raw.prepare("UPDATE change_log SET intent_fingerprint = ? WHERE op_id = ?").run(intentFingerprints.get(opId), opId);
1663
1930
  const incomingRev = {
1664
1931
  clock: op.stamp.clock,
1665
1932
  hlc: op.stamp.hlc,
@@ -1667,7 +1934,7 @@ export class SqliteSyncGatewayAdapter {
1667
1934
  };
1668
1935
  if (op.operation === "put") {
1669
1936
  const existing = raw.prepare(
1670
- `SELECT clock, hlc, op_id, data_json FROM ${materializedTable} WHERE id = ? AND workspace_id = ?`
1937
+ `SELECT clock, hlc, op_id, deleted, ${boundedSyncPayload("data_json")} AS data_json FROM ${materializedTable} WHERE id = ? AND workspace_id = ?`
1671
1938
  ).get(pkValue, workspaceId);
1672
1939
  const tombstone = !existing ? raw.prepare(
1673
1940
  `SELECT clock, hlc, op_id FROM tombstones
@@ -1712,7 +1979,7 @@ export class SqliteSyncGatewayAdapter {
1712
1979
  );
1713
1980
  applied = true;
1714
1981
  } else {
1715
- winnerPayload = JSON.parse(existing.data_json);
1982
+ winnerPayload = existing.deleted ? void 0 : JSON.parse(existing.data_json);
1716
1983
  }
1717
1984
  const emission = resolveHookEmission({
1718
1985
  op,
@@ -1737,7 +2004,7 @@ export class SqliteSyncGatewayAdapter {
1737
2004
  });
1738
2005
  } else if (op.operation === "delete") {
1739
2006
  const existing = raw.prepare(
1740
- `SELECT clock, hlc, op_id, data_json FROM ${materializedTable} WHERE id = ? AND workspace_id = ?`
2007
+ `SELECT clock, hlc, op_id, deleted, ${boundedSyncPayload("data_json")} AS data_json FROM ${materializedTable} WHERE id = ? AND workspace_id = ?`
1741
2008
  ).get(pkValue, workspaceId);
1742
2009
  let applied = false;
1743
2010
  if (!existing) {
@@ -1809,13 +2076,18 @@ export class SqliteSyncGatewayAdapter {
1809
2076
  success: true,
1810
2077
  serverVersion,
1811
2078
  applied,
1812
- ...applied || !existing ? {} : { payload: JSON.parse(existing.data_json) },
2079
+ ...applied || !existing ? {} : { payload: existing.deleted ? void 0 : JSON.parse(existing.data_json) },
1813
2080
  ...applied ? {} : {
1814
2081
  winner: currentWinnerNative(raw, workspaceId, op.tableName, pkValue)
1815
2082
  }
1816
2083
  });
1817
2084
  }
1818
2085
  }
2086
+ if (repair) {
2087
+ if (!uniqueResults[0]?.success || uniqueResults[0]?.applied === false) throw new Error("Repair did not win");
2088
+ const resolution = repairResolution(repair, uniqueOps[0].stamp.opId);
2089
+ raw.prepare(resolution.sql).run(...resolution.parameters ?? []);
2090
+ }
1819
2091
  });
1820
2092
  runTx.immediate();
1821
2093
  for (const result of uniqueResults) {
@@ -1830,74 +2102,215 @@ export class SqliteSyncGatewayAdapter {
1830
2102
  results: resultSlots.filter(
1831
2103
  (result) => Boolean(result)
1832
2104
  ),
1833
- serverVersion: finalServerVersion
2105
+ serverVersion: finalServerVersion,
2106
+ historyIncarnation
1834
2107
  };
1835
2108
  }
1836
2109
  async pull(event, input) {
1837
2110
  const db = this.db;
1838
2111
  const { scope, cursor, limit, tables } = input;
1839
2112
  await assertWorkspaceScopeAuthorized(event, scope.workspaceId);
2113
+ const historyIncarnation = await this.checkHistory(event, input, true);
1840
2114
  const fetchLimit = resolvePullLimit(limit);
1841
- let query = db.selectFrom("change_log").where("workspace_id", "=", scope.workspaceId).where("server_version", ">", cursor).orderBy("server_version", "asc");
1842
- if (tables?.length) {
1843
- query = query.where("table_name", "in", tables);
1844
- }
1845
- const sizes = await query.select(sql`coalesce(length(cast(payload_json as blob)), 0)`.as("payload_bytes")).limit(fetchLimit + 1).execute();
1846
- const selected = boundedPayloadRowCount(sizes, fetchLimit);
1847
- const rows = selected ? await query.selectAll().limit(selected).execute() : [];
1848
2115
  const minLog = await db.selectFrom("change_log").select("server_version").where("workspace_id", "=", scope.workspaceId).orderBy("server_version", "asc").limit(1).executeTakeFirst();
1849
2116
  const counter = await db.selectFrom("server_version_counter").select("value").where("workspace_id", "=", scope.workspaceId).executeTakeFirst();
2117
+ if (!Number.isSafeInteger(counter?.value ?? 0) || (counter?.value ?? 0) < 0 || minLog && (!Number.isSafeInteger(minLog.server_version) || minLog.server_version <= 0)) throw new Error("Untrustworthy sync retention version");
1850
2118
  const retention = computePullRetention({
1851
2119
  cursor,
1852
2120
  oldestLogVersion: minLog?.server_version ?? null,
1853
2121
  highWatermark: counter?.value ?? 0
1854
2122
  });
2123
+ if (input.historyIncarnation !== historyIncarnation || retention.requiresSnapshot || cursor > (counter?.value ?? 0)) {
2124
+ return { historyIncarnation, changes: [], unavailable: [], nextCursor: cursor, hasMore: false, ...retention, requiresSnapshot: true };
2125
+ }
2126
+ let query = db.selectFrom("change_log").where("workspace_id", "=", scope.workspaceId).where("server_version", ">", cursor).orderBy("server_version", "asc");
2127
+ if (tables?.length) {
2128
+ query = query.where("table_name", "in", tables);
2129
+ }
2130
+ const sizes = await query.select(["server_version", sql`coalesce(length(cast(payload_json as blob)), 0)`.as("payload_bytes"), sql`${sql.raw(PULL_METADATA_BYTES)}`.as("metadata_bytes")]).limit(fetchLimit + 1).execute();
2131
+ let previousVersion = cursor;
2132
+ for (const row of sizes) {
2133
+ if (!Number.isSafeInteger(row.server_version) || row.server_version <= previousVersion || row.server_version > (counter?.value ?? 0)) {
2134
+ throw new Error("Untrustworthy sync server version");
2135
+ }
2136
+ previousVersion = row.server_version;
2137
+ }
2138
+ const selected = boundedPayloadRowCount(sizes, fetchLimit);
2139
+ const rows = selected ? await query.select([
2140
+ "server_version",
2141
+ sql`${sql.raw(boundedSyncMetadata("clock", PULL_METADATA_BYTES))}`.as("clock"),
2142
+ ...["id", "table_name", "pk", "op"].map((column) => sql`${sql.raw(boundedSyncMetadata(column))}`.as(column)),
2143
+ ...["hlc", "device_id", "op_id"].map((column) => sql`${sql.raw(boundedSyncMetadata(column, PULL_METADATA_BYTES))}`.as(column)),
2144
+ sql`${sql.raw(PULL_METADATA_BYTES)}`.as("metadata_bytes"),
2145
+ sql`${sql.raw(boundedSyncPayload("payload_json"))}`.as("payload_json"),
2146
+ sql`coalesce(length(cast(payload_json AS blob)),0)`.as("payload_bytes"),
2147
+ sql`${sql.raw(`hex(cast(${boundedSyncMetadata("pk")} AS blob))`)}`.as("pk_hex"),
2148
+ sql`${sql.raw(`hex(cast(${boundedSyncMetadata("table_name")} AS blob))`)}`.as("table_hex"),
2149
+ sql`${sql.raw(`CASE WHEN table_name = 'notifications' THEN ${notificationOwnerSql("payload_json")} END`)}`.as("notification_owner")
2150
+ ]).limit(selected).execute() : [];
1855
2151
  const changes = [];
1856
- let itemBytes = 0;
2152
+ const unavailable = [];
1857
2153
  let scanned = 0;
2154
+ let itemBytes = 0;
1858
2155
  let nextCursor = cursor;
1859
- for (const row of rows.slice(0, fetchLimit)) {
1860
- const change = {
1861
- serverVersion: row.server_version,
2156
+ for (const row of rows) {
2157
+ if (!Number.isSafeInteger(row.server_version) || row.server_version <= nextCursor || row.server_version > (counter?.value ?? 0)) {
2158
+ throw new Error("Untrustworthy sync server version");
2159
+ }
2160
+ assertCoverageKey(row.table_name, row.pk, row.pk_hex, row.table_hex);
2161
+ if (row.op !== "put" && row.op !== "delete") throw new Error("Untrustworthy sync operation kind");
2162
+ const visible = row.table_name !== "notifications" || !!row.notification_owner && row.notification_owner === resolveSessionUserId(event);
2163
+ let change;
2164
+ let reason = row.metadata_bytes > SYNC_METADATA_BYTES ? "metadata_oversized" : row.payload_bytes > MAX_SYNC_PAYLOAD_BYTES ? "payload_oversized" : "invalid_record";
2165
+ if (reason === "invalid_record") {
2166
+ try {
2167
+ const candidate = {
2168
+ serverVersion: row.server_version,
2169
+ tableName: row.table_name,
2170
+ pk: row.pk,
2171
+ op: row.op,
2172
+ payload: row.payload_json ? JSON.parse(row.payload_json) : void 0,
2173
+ stamp: { clock: row.clock, hlc: row.hlc, deviceId: row.device_id, opId: row.op_id }
2174
+ };
2175
+ if (SyncChangeSchema.safeParse(candidate).success && Number.isSafeInteger(row.clock) && (row.op === "put" ? validReadPayload(row.table_name, row.pk, candidate.payload, row.clock, row.hlc) : ALLOWED_SYNC_TABLES.includes(row.table_name))) change = candidate;
2176
+ } catch {
2177
+ reason = "invalid_json";
2178
+ }
2179
+ }
2180
+ const marker = {
1862
2181
  tableName: row.table_name,
1863
2182
  pk: row.pk,
1864
- op: row.op,
1865
- payload: row.payload_json ? JSON.parse(row.payload_json) : void 0,
1866
- stamp: { clock: row.clock, hlc: row.hlc, deviceId: row.device_id, opId: row.op_id }
2183
+ originalKind: row.op,
2184
+ serverVersion: row.server_version,
2185
+ evidenceRef: "",
2186
+ reason
1867
2187
  };
1868
- if (isNotificationVisibleToUser(change, resolveSessionUserId(event))) {
1869
- const bytes = jsonBytes(change) + (changes.length ? 1 : 0);
1870
- const envelope = jsonBytes({ changes: [], nextCursor: row.server_version, hasMore: false, ...retention });
1871
- if (changes.length && envelope + itemBytes + bytes > MAX_SYNC_PAGE_BYTES) break;
1872
- changes.push(change);
1873
- itemBytes += bytes;
2188
+ const bytes = visible ? jsonBytes(change ?? { ...marker, evidenceRef: "x".repeat(36) }) + ((change ? changes.length : unavailable.length) ? 1 : 0) : 0;
2189
+ const envelopeBytes = jsonBytes({ historyIncarnation, changes: [], unavailable: [], nextCursor: row.server_version, hasMore: false, ...retention });
2190
+ if (envelopeBytes + itemBytes + bytes > MAX_SYNC_PAGE_BYTES) {
2191
+ if (!scanned) throw new Error("Sync identity exceeds page byte budget");
2192
+ break;
1874
2193
  }
2194
+ if (!change) {
2195
+ marker.evidenceRef = await retainSqlEvidence({
2196
+ historyIncarnation,
2197
+ workspaceId: scope.workspaceId,
2198
+ source: "pull",
2199
+ locator: row.id,
2200
+ revisionSql: "cast(server_version AS text)",
2201
+ table: "change_log",
2202
+ where: "workspace_id = ? AND id = ? AND server_version = ?",
2203
+ parameters: [scope.workspaceId, row.id, row.server_version],
2204
+ payload: "payload_json",
2205
+ metadata: "json_object('id',id,'table_name',table_name,'pk',pk,'op',op,'clock',clock,'hlc',hlc,'device_id',device_id,'op_id',op_id,'server_version',server_version,'created_at',created_at)"
2206
+ }, reason);
2207
+ if (visible) unavailable.push(marker);
2208
+ } else if (visible) changes.push(change);
2209
+ itemBytes += bytes;
1875
2210
  scanned++;
1876
2211
  nextCursor = row.server_version;
1877
2212
  }
1878
- return { changes, nextCursor, hasMore: sizes.length > scanned, ...retention };
2213
+ return PullResponseSchema.parse({
2214
+ historyIncarnation,
2215
+ changes,
2216
+ ...unavailable.length ? { unavailable } : {},
2217
+ nextCursor,
2218
+ hasMore: sizes.length > scanned,
2219
+ ...retention
2220
+ });
2221
+ }
2222
+ async retainUnavailableRecord(event, input) {
2223
+ await assertWorkspaceScopeAuthorized(event, input.scope.workspaceId);
2224
+ const historyIncarnation = await this.checkHistory(event, input);
2225
+ const marker = input.marker;
2226
+ assertCoverageKey(marker.tableName, marker.pk);
2227
+ let source;
2228
+ let record;
2229
+ if (input.source === "pull" && "serverVersion" in marker) {
2230
+ const [row] = await syncRows(
2231
+ `SELECT id,table_name,pk,op,clock,hlc,device_id,op_id,${boundedSyncPayload("payload_json")} AS payload_json,
2232
+ ${notificationOwnerSql("payload_json")} AS owner FROM change_log WHERE workspace_id = ? AND server_version = ?`,
2233
+ input.scope.workspaceId,
2234
+ marker.serverVersion
2235
+ );
2236
+ if (!row || row.table_name !== marker.tableName || row.pk !== marker.pk || row.op !== marker.originalKind || row.table_name === "notifications" && (!row.owner || row.owner !== resolveSessionUserId(event))) throw new Error("Evidence source identity or visibility mismatch");
2237
+ record = {
2238
+ serverVersion: marker.serverVersion,
2239
+ tableName: row.table_name,
2240
+ pk: row.pk,
2241
+ op: row.op,
2242
+ payload: row.payload_json ? JSON.parse(row.payload_json) : void 0,
2243
+ stamp: { clock: row.clock, hlc: row.hlc, deviceId: row.device_id, opId: row.op_id }
2244
+ };
2245
+ source = {
2246
+ historyIncarnation,
2247
+ workspaceId: input.scope.workspaceId,
2248
+ source: "pull",
2249
+ locator: row.id,
2250
+ revisionSql: "cast(server_version AS text)",
2251
+ table: "change_log",
2252
+ where: "workspace_id = ? AND id = ? AND server_version = ?",
2253
+ parameters: [input.scope.workspaceId, row.id, marker.serverVersion],
2254
+ payload: "payload_json",
2255
+ metadata: "json_object('id',id,'table_name',table_name,'pk',pk,'op',op,'clock',clock,'hlc',hlc,'device_id',device_id,'op_id',op_id,'server_version',server_version)"
2256
+ };
2257
+ } else if (input.source === "snapshot" && "snapshotId" in marker) {
2258
+ const [header] = await syncRows("SELECT * FROM sync_snapshots WHERE workspace_id = ? AND id = ?", input.scope.workspaceId, marker.snapshotId);
2259
+ if (!header || header.expires_at <= nowEpoch() || header.high_watermark !== marker.highWatermark) throw new Error("Evidence snapshot unavailable");
2260
+ assertSnapshotOwner(header.id, resolveSessionUserId(event));
2261
+ const [row] = await syncRows(`SELECT table_name,pk,kind,${boundedSyncPayload("payload_json")} AS payload_json,clock,hlc,op_id,server_deleted_at
2262
+ FROM sync_snapshot_items WHERE snapshot_id = ? AND table_name = ? AND pk = ? AND kind = ?`, header.id, marker.tableName, marker.pk, marker.originalKind);
2263
+ if (!row) throw new Error("Evidence snapshot source unavailable");
2264
+ const payload = row.payload_json ? JSON.parse(row.payload_json) : void 0;
2265
+ if (row.table_name === "notifications" && row.kind === "row" && notificationPayloadUserId(payload) !== resolveSessionUserId(event)) throw new Error("Evidence notification visibility mismatch");
2266
+ record = {
2267
+ kind: row.kind,
2268
+ tableName: row.table_name,
2269
+ pk: row.pk,
2270
+ revision: { clock: row.clock, hlc: row.hlc, opId: row.op_id },
2271
+ ...row.kind === "row" ? { payload } : { serverDeletedAt: row.server_deleted_at }
2272
+ };
2273
+ source = snapshotEvidence(header, row, historyIncarnation);
2274
+ } else throw new Error("Evidence source mismatch");
2275
+ if (stableJson(record) !== stableJson(input.record)) throw new Error("Evidence source record mismatch");
2276
+ return { evidenceRef: await retainSqlEvidence(source, "reader_invalid") };
2277
+ }
2278
+ async maintainUnavailableRecords(event, workspaceId, action, input) {
2279
+ await assertWorkspaceScopeAuthorized(event, workspaceId);
2280
+ return maintainEvidence(event, workspaceId, action, input, (event2, op, guard) => this.push(
2281
+ event2,
2282
+ { scope: { workspaceId }, ops: [op], historyIncarnation: guard.historyIncarnation, workspaceItemCapability: WORKSPACE_ITEM_CAPABILITY },
2283
+ guard
2284
+ ), validReadPayload);
1879
2285
  }
1880
2286
  async snapshot(event, input) {
1881
2287
  return this.captureSnapshot(event, input, false);
1882
2288
  }
1883
2289
  /** Archives retain full Trash metadata; normal sync still emits tombstones. */
1884
2290
  async backupSnapshot(event, input) {
1885
- return this.captureSnapshot(event, input, true);
2291
+ const historyIncarnation = input.historyIncarnation === void 0 ? input.pageToken ? decodeSnapshotPageToken(input.pageToken).historyIncarnation ?? null : null : input.historyIncarnation;
2292
+ return this.captureSnapshot(event, { ...input, historyIncarnation }, true);
1886
2293
  }
1887
2294
  async captureSnapshot(event, input, retainedFiles) {
1888
2295
  const workspaceId = input.scope.workspaceId;
1889
2296
  await assertWorkspaceScopeAuthorized(event, workspaceId);
2297
+ const historyIncarnation = await this.checkHistory(
2298
+ event,
2299
+ input,
2300
+ input.historyIncarnation === null && !input.pageToken
2301
+ );
2302
+ if (input.pageToken && decodeSnapshotPageToken(input.pageToken).historyIncarnation !== historyIncarnation) historyChanged(historyIncarnation);
1890
2303
  const pageSize = resolveSnapshotPageSize(input.pageSize);
1891
2304
  const snapshotUserId = resolveSessionUserId(event);
1892
2305
  if (isD1Driver()) {
1893
- return this.snapshotInD1(workspaceId, input, pageSize, snapshotUserId, retainedFiles);
2306
+ return this.snapshotInD1(workspaceId, input, pageSize, snapshotUserId, retainedFiles, historyIncarnation);
1894
2307
  }
1895
2308
  const raw = getRawDb();
1896
2309
  const now = nowEpoch();
1897
2310
  let header;
1898
2311
  let after;
1899
2312
  if (input.pageToken) {
1900
- if (input.pageToken.length > 4096) {
2313
+ if (input.pageToken.length > MAX_SYNC_SNAPSHOT_TOKEN_LENGTH) {
1901
2314
  throw createError({
1902
2315
  statusCode: 400,
1903
2316
  statusMessage: "Invalid snapshot page token"
@@ -1966,6 +2379,10 @@ export class SqliteSyncGatewayAdapter {
1966
2379
  now,
1967
2380
  expiresAt
1968
2381
  );
2382
+ if (tables.includes("notifications")) {
2383
+ const evidence = unknownNotificationEvidence(workspaceId);
2384
+ raw.prepare(evidence.sql).run(...evidence.parameters ?? []);
2385
+ }
1969
2386
  for (const tableName of tables) {
1970
2387
  const materializedTable = SYNCED_TABLE_MAP[tableName];
1971
2388
  if (!materializedTable) {
@@ -2001,11 +2418,11 @@ export class SqliteSyncGatewayAdapter {
2001
2418
  raw.prepare(`
2002
2419
  INSERT INTO sync_snapshot_items (
2003
2420
  snapshot_id, table_name, pk, kind, payload_json,
2004
- clock, hlc, op_id, server_deleted_at
2421
+ clock, hlc, op_id, server_deleted_at, source_payload_json
2005
2422
  )
2006
2423
  SELECT
2007
2424
  ?, ?, materialized.id, '${retainedFiles && tableName === "file_meta" ? "row" : "tombstone"}',
2008
- ${retainedFiles && tableName === "file_meta" ? "json_set(materialized.data_json, '$.deleted', json('true'), '$.clock', materialized.clock, '$.hlc', materialized.hlc, '$.updated_at', materialized.updated_at)" : "NULL"},
2425
+ ${retainedFiles && tableName === "file_meta" ? "CASE WHEN length(cast(materialized.data_json AS blob)) <= 262144 AND json_valid(materialized.data_json) THEN json_set(materialized.data_json, '$.deleted', json('true'), '$.clock', materialized.clock, '$.hlc', materialized.hlc, '$.op_id', materialized.op_id, '$.updated_at', materialized.updated_at) ELSE materialized.data_json END" : "NULL"},
2009
2426
  materialized.clock,
2010
2427
  CASE
2011
2428
  WHEN materialized.hlc <> '' THEN materialized.hlc
@@ -2027,7 +2444,8 @@ export class SqliteSyncGatewayAdapter {
2027
2444
  materialized.updated_at,
2028
2445
  materialized.created_at,
2029
2446
  0
2030
- ))
2447
+ )),
2448
+ ${retainedFiles && tableName === "file_meta" ? "materialized.data_json" : "NULL"}
2031
2449
  FROM "${materializedTable}" AS materialized
2032
2450
  WHERE materialized.workspace_id = ? AND materialized.deleted <> 0${deletedOwner.sql}
2033
2451
  `).run(snapshotId, tableName, tableName, workspaceId, ...deletedOwner.params);
@@ -2068,14 +2486,20 @@ export class SqliteSyncGatewayAdapter {
2068
2486
  header = capture.immediate();
2069
2487
  }
2070
2488
  const selection = snapshotPageSelection(header.id, after);
2071
- const sizes = raw.prepare(`SELECT coalesce(length(cast(payload_json as blob)), 0) AS payload_bytes ${selection.clause}`).all(...selection.parameters, pageSize + 1);
2489
+ const sizes = raw.prepare(`SELECT coalesce(length(cast(payload_json as blob)), 0) AS payload_bytes, ${SNAPSHOT_METADATA_BYTES} AS metadata_bytes ${selection.clause}`).all(...selection.parameters, pageSize + 1);
2072
2490
  const selected = boundedPayloadRowCount(sizes, pageSize);
2073
- const rows = selected ? raw.prepare(`SELECT table_name, pk, kind, payload_json, clock, hlc, op_id, server_deleted_at ${selection.clause}`).all(...selection.parameters, selected) : [];
2074
- return buildSnapshotPage(header, rows, pageSize, sizes.length);
2491
+ const rows = selected ? raw.prepare(`SELECT ${boundedSyncMetadata("table_name")} AS table_name, ${boundedSyncMetadata("pk")} AS pk, ${boundedSyncMetadata("kind")} AS kind,
2492
+ ${boundedSyncPayload("payload_json")} AS payload_json, length(cast(payload_json AS blob)) AS payload_bytes,
2493
+ ${SNAPSHOT_METADATA_BYTES} AS metadata_bytes,
2494
+ hex(cast(${boundedSyncMetadata("pk")} AS blob)) AS pk_hex, hex(cast(${boundedSyncMetadata("table_name")} AS blob)) AS table_hex,
2495
+ CASE WHEN table_name = 'notifications' AND kind = 'row' THEN ${notificationOwnerSql("payload_json")} END AS notification_owner,
2496
+ ${boundedSyncMetadata("clock", SNAPSHOT_METADATA_BYTES)} AS clock, ${boundedSyncMetadata("hlc", SNAPSHOT_METADATA_BYTES)} AS hlc, ${boundedSyncMetadata("op_id", SNAPSHOT_METADATA_BYTES)} AS op_id, ${boundedSyncMetadata("server_deleted_at", SNAPSHOT_METADATA_BYTES)} AS server_deleted_at ${selection.clause}`).all(...selection.parameters, selected) : [];
2497
+ return buildSnapshotPage(header, rows, pageSize, sizes.length, historyIncarnation, after, snapshotUserId);
2075
2498
  }
2076
2499
  async updateCursor(event, input) {
2077
2500
  await assertWorkspaceScopeAuthorized(event, input.scope.workspaceId);
2078
2501
  const now = nowEpoch();
2502
+ const historyIncarnation = await this.checkHistory(event, input);
2079
2503
  const deviceId = input.deviceId.trim();
2080
2504
  if (!deviceId || deviceId.length > 256) {
2081
2505
  throw createError({ statusCode: 400, statusMessage: "Invalid device cursor" });
@@ -2088,10 +2512,15 @@ export class SqliteSyncGatewayAdapter {
2088
2512
  throw createError({ statusCode: 401, statusMessage: "Unauthorized" });
2089
2513
  }
2090
2514
  if (isD1Driver()) {
2091
- return this.updateCursorInD1(input.scope.workspaceId, deviceId, input.version, ownerUserId, now);
2515
+ return this.updateCursorInD1(input.scope.workspaceId, deviceId, input.version, ownerUserId, now, historyIncarnation);
2092
2516
  }
2093
2517
  const raw = getRawDb();
2094
2518
  const update = raw.transaction(() => {
2519
+ const current = raw.prepare("SELECT incarnation FROM sync_history WHERE id=1").get();
2520
+ if (current?.incarnation !== historyIncarnation) {
2521
+ if (!validHistoryIncarnation(current?.incarnation)) throw new Error("Invalid sync history singleton");
2522
+ historyChanged(current.incarnation);
2523
+ }
2095
2524
  const counter = raw.prepare(
2096
2525
  "SELECT value FROM server_version_counter WHERE workspace_id = ?"
2097
2526
  ).get(input.scope.workspaceId);
@@ -2115,7 +2544,7 @@ export class SqliteSyncGatewayAdapter {
2115
2544
  updated_at = excluded.updated_at`
2116
2545
  ).run(uid(), input.scope.workspaceId, deviceId, ownerUserId, input.version, now);
2117
2546
  });
2118
- update();
2547
+ update.immediate();
2119
2548
  }
2120
2549
  async gcTombstones(event, input) {
2121
2550
  await assertWorkspaceScopeAuthorized(event, input.scope.workspaceId);
@@ -2186,60 +2615,27 @@ export class SqliteSyncGatewayAdapter {
2186
2615
  }
2187
2616
  if (!canRunSyncHistoryGc()) return;
2188
2617
  const cutoff = nowEpoch() - input.retentionSeconds;
2618
+ const deletePrefix = `DELETE FROM change_log
2619
+ WHERE workspace_id = ? AND server_version < COALESCE((
2620
+ SELECT MIN(server_version) FROM change_log
2621
+ WHERE workspace_id = ? AND created_at >= ?
2622
+ ), 9223372036854775807)
2623
+ AND server_version <= COALESCE((
2624
+ SELECT MIN(last_seen_version) FROM device_cursors WHERE workspace_id = ?
2625
+ ), 9223372036854775807)`;
2626
+ const workspaceId = input.scope.workspaceId;
2189
2627
  if (isD1Driver()) {
2190
2628
  await d1Batch([
2191
- {
2192
- sql: `DELETE FROM device_cursors
2193
- WHERE workspace_id = ? AND updated_at < ?`,
2194
- parameters: [input.scope.workspaceId, cutoff]
2195
- },
2196
- {
2197
- sql: `DELETE FROM change_log
2198
- WHERE workspace_id = ?
2199
- AND created_at < ?
2200
- AND (
2201
- NOT EXISTS (
2202
- SELECT 1 FROM device_cursors
2203
- WHERE workspace_id = ?
2204
- )
2205
- OR server_version <= (
2206
- SELECT MIN(last_seen_version)
2207
- FROM device_cursors
2208
- WHERE workspace_id = ?
2209
- )
2210
- )`,
2211
- parameters: [
2212
- input.scope.workspaceId,
2213
- cutoff,
2214
- input.scope.workspaceId,
2215
- input.scope.workspaceId
2216
- ]
2217
- }
2629
+ { sql: "DELETE FROM device_cursors WHERE workspace_id = ? AND updated_at < ?", parameters: [workspaceId, cutoff] },
2630
+ { sql: deletePrefix, parameters: [workspaceId, workspaceId, cutoff, workspaceId] }
2218
2631
  ]);
2219
2632
  return;
2220
2633
  }
2221
2634
  const raw = getRawDb();
2222
2635
  raw.transaction(() => {
2223
- raw.prepare(
2224
- `DELETE FROM device_cursors
2225
- WHERE workspace_id = ? AND updated_at < ?`
2226
- ).run(input.scope.workspaceId, cutoff);
2227
- const cursor = raw.prepare(
2228
- `SELECT MIN(last_seen_version) AS min_version
2229
- FROM device_cursors WHERE workspace_id = ?`
2230
- ).get(input.scope.workspaceId);
2231
- if (cursor.min_version === null) {
2232
- raw.prepare(
2233
- `DELETE FROM change_log
2234
- WHERE workspace_id = ? AND created_at < ?`
2235
- ).run(input.scope.workspaceId, cutoff);
2236
- } else {
2237
- raw.prepare(
2238
- `DELETE FROM change_log
2239
- WHERE workspace_id = ? AND created_at < ? AND server_version <= ?`
2240
- ).run(input.scope.workspaceId, cutoff, cursor.min_version);
2241
- }
2242
- })();
2636
+ raw.prepare("DELETE FROM device_cursors WHERE workspace_id = ? AND updated_at < ?").run(workspaceId, cutoff);
2637
+ raw.prepare(deletePrefix).run(workspaceId, workspaceId, cutoff, workspaceId);
2638
+ }).immediate();
2243
2639
  }
2244
2640
  async reserveUploadIntentInD1(input, hash) {
2245
2641
  const now = nowEpoch();
@@ -2288,12 +2684,12 @@ export class SqliteSyncGatewayAdapter {
2288
2684
  throw createError({ statusCode: 413, statusMessage: "Workspace storage quota exceeded" });
2289
2685
  }
2290
2686
  }
2291
- async snapshotInD1(workspaceId, input, pageSize, snapshotUserId, retainedFiles) {
2687
+ async snapshotInD1(workspaceId, input, pageSize, snapshotUserId, retainedFiles, historyIncarnation) {
2292
2688
  const now = nowEpoch();
2293
2689
  let header;
2294
2690
  let after;
2295
2691
  if (input.pageToken) {
2296
- if (input.pageToken.length > 4096) {
2692
+ if (input.pageToken.length > MAX_SYNC_SNAPSHOT_TOKEN_LENGTH) {
2297
2693
  throw createError({ statusCode: 400, statusMessage: "Invalid snapshot page token" });
2298
2694
  }
2299
2695
  const token = decodeSnapshotPageToken(input.pageToken);
@@ -2358,6 +2754,7 @@ export class SqliteSyncGatewayAdapter {
2358
2754
  ]
2359
2755
  }
2360
2756
  ];
2757
+ if (tables.includes("notifications")) statements.push(unknownNotificationEvidence(workspaceId));
2361
2758
  for (const tableName of tables) {
2362
2759
  const materializedTable = SYNCED_TABLE_MAP[tableName];
2363
2760
  if (!materializedTable) {
@@ -2396,11 +2793,11 @@ export class SqliteSyncGatewayAdapter {
2396
2793
  {
2397
2794
  sql: `INSERT INTO sync_snapshot_items (
2398
2795
  snapshot_id, table_name, pk, kind, payload_json,
2399
- clock, hlc, op_id, server_deleted_at
2796
+ clock, hlc, op_id, server_deleted_at, source_payload_json
2400
2797
  )
2401
2798
  SELECT
2402
2799
  ?, ?, materialized.id, '${retainedFiles && tableName === "file_meta" ? "row" : "tombstone"}',
2403
- ${retainedFiles && tableName === "file_meta" ? "json_set(materialized.data_json, '$.deleted', json('true'), '$.clock', materialized.clock, '$.hlc', materialized.hlc, '$.updated_at', materialized.updated_at)" : "NULL"},
2800
+ ${retainedFiles && tableName === "file_meta" ? "CASE WHEN length(cast(materialized.data_json AS blob)) <= 262144 AND json_valid(materialized.data_json) THEN json_set(materialized.data_json, '$.deleted', json('true'), '$.clock', materialized.clock, '$.hlc', materialized.hlc, '$.op_id', materialized.op_id, '$.updated_at', materialized.updated_at) ELSE materialized.data_json END" : "NULL"},
2404
2801
  materialized.clock,
2405
2802
  CASE
2406
2803
  WHEN materialized.hlc <> '' THEN materialized.hlc
@@ -2422,7 +2819,8 @@ export class SqliteSyncGatewayAdapter {
2422
2819
  materialized.updated_at,
2423
2820
  materialized.created_at,
2424
2821
  0
2425
- ))
2822
+ )),
2823
+ ${retainedFiles && tableName === "file_meta" ? "materialized.data_json" : "NULL"}
2426
2824
  FROM "${materializedTable}" AS materialized
2427
2825
  WHERE materialized.workspace_id = ? AND materialized.deleted <> 0${deletedOwner.sql}`,
2428
2826
  parameters: [
@@ -2471,13 +2869,18 @@ export class SqliteSyncGatewayAdapter {
2471
2869
  }
2472
2870
  const selection = snapshotPageSelection(header.id, after);
2473
2871
  const sizes = await d1All(
2474
- `SELECT coalesce(length(cast(payload_json as blob)), 0) AS payload_bytes ${selection.clause}`,
2872
+ `SELECT coalesce(length(cast(payload_json as blob)), 0) AS payload_bytes, ${SNAPSHOT_METADATA_BYTES} AS metadata_bytes ${selection.clause}`,
2475
2873
  ...selection.parameters,
2476
2874
  pageSize + 1
2477
2875
  );
2478
2876
  const selected = boundedPayloadRowCount(sizes, pageSize);
2479
2877
  const rows = selected ? await d1All(
2480
- `SELECT table_name, pk, kind, payload_json, clock, hlc, op_id, server_deleted_at ${selection.clause}`,
2878
+ `SELECT ${boundedSyncMetadata("table_name")} AS table_name, ${boundedSyncMetadata("pk")} AS pk, ${boundedSyncMetadata("kind")} AS kind,
2879
+ ${boundedSyncPayload("payload_json")} AS payload_json, length(cast(payload_json AS blob)) AS payload_bytes,
2880
+ ${SNAPSHOT_METADATA_BYTES} AS metadata_bytes,
2881
+ hex(cast(${boundedSyncMetadata("pk")} AS blob)) AS pk_hex, hex(cast(${boundedSyncMetadata("table_name")} AS blob)) AS table_hex,
2882
+ CASE WHEN table_name = 'notifications' AND kind = 'row' THEN ${notificationOwnerSql("payload_json")} END AS notification_owner,
2883
+ ${boundedSyncMetadata("clock", SNAPSHOT_METADATA_BYTES)} AS clock, ${boundedSyncMetadata("hlc", SNAPSHOT_METADATA_BYTES)} AS hlc, ${boundedSyncMetadata("op_id", SNAPSHOT_METADATA_BYTES)} AS op_id, ${boundedSyncMetadata("server_deleted_at", SNAPSHOT_METADATA_BYTES)} AS server_deleted_at ${selection.clause}`,
2481
2884
  ...selection.parameters,
2482
2885
  selected
2483
2886
  ) : [];
@@ -2488,9 +2891,9 @@ export class SqliteSyncGatewayAdapter {
2488
2891
  if (!retained || retained.expires_at <= nowEpoch()) {
2489
2892
  throw createError({ statusCode: 410, statusMessage: "Snapshot expired or unavailable" });
2490
2893
  }
2491
- return buildSnapshotPage(header, rows, pageSize, sizes.length);
2894
+ return buildSnapshotPage(header, rows, pageSize, sizes.length, historyIncarnation, after, snapshotUserId);
2492
2895
  }
2493
- async updateCursorInD1(workspaceId, deviceId, version, ownerUserId, now) {
2896
+ async updateCursorInD1(workspaceId, deviceId, version, ownerUserId, now, historyIncarnation) {
2494
2897
  const [counter] = await d1All(
2495
2898
  "SELECT value FROM server_version_counter WHERE workspace_id = ?",
2496
2899
  workspaceId
@@ -2508,49 +2911,58 @@ export class SqliteSyncGatewayAdapter {
2508
2911
  if (existing && version < existing.last_seen_version) {
2509
2912
  throw createError({ statusCode: 409, statusMessage: "Device cursor cannot regress" });
2510
2913
  }
2511
- const result = await d1Run(
2512
- `INSERT INTO device_cursors (
2914
+ const results = await d1Batch([
2915
+ historyAssertion(historyIncarnation),
2916
+ { sql: `SELECT json_extract('{}',CASE WHEN ? <= coalesce((SELECT value FROM server_version_counter WHERE workspace_id=?),0)
2917
+ AND ? >= coalesce((SELECT last_seen_version FROM device_cursors WHERE workspace_id=? AND owner_user_id=? AND device_id=?),0)
2918
+ THEN '$' ELSE 'OR3_SYNC_CURSOR_CHANGED' END)`, parameters: [version, workspaceId, version, workspaceId, ownerUserId, deviceId] },
2919
+ {
2920
+ sql: `INSERT INTO device_cursors (
2513
2921
  id, workspace_id, device_id, owner_user_id, last_seen_version, updated_at
2514
2922
  ) VALUES (?, ?, ?, ?, ?, ?)
2515
2923
  ON CONFLICT(workspace_id, owner_user_id, device_id) DO UPDATE SET
2516
2924
  last_seen_version = excluded.last_seen_version,
2517
2925
  updated_at = excluded.updated_at
2518
2926
  WHERE excluded.last_seen_version >= device_cursors.last_seen_version`,
2519
- uid(),
2520
- workspaceId,
2521
- deviceId,
2522
- ownerUserId,
2523
- version,
2524
- now
2525
- );
2526
- if ((result.meta?.changes ?? 0) !== 1) {
2927
+ parameters: [uid(), workspaceId, deviceId, ownerUserId, version, now]
2928
+ }
2929
+ ]).catch(async (error) => {
2930
+ if (String(error).includes("OR3_SYNC_HISTORY_CHANGED")) historyChanged(await readHistoryIncarnation());
2931
+ if (String(error).includes("OR3_SYNC_CURSOR_CHANGED")) throw createError({ statusCode: 409, statusMessage: "Device cursor changed concurrently" });
2932
+ throw error;
2933
+ });
2934
+ if ((results[2]?.meta?.changes ?? 0) !== 1) {
2527
2935
  throw createError({ statusCode: 409, statusMessage: "Device cursor changed concurrently" });
2528
2936
  }
2529
2937
  }
2530
2938
  async pushInD1(input) {
2531
- const { workspaceId, uniqueOps, resultSlots, indicesByOpId, userId } = input;
2939
+ const { workspaceId, uniqueOps, resultSlots, indicesByOpId, userId, historyIncarnation } = input;
2940
+ const originalOps = new Map(uniqueOps.map((op) => [op.stamp.opId, { ...op }]));
2532
2941
  const existingOps = /* @__PURE__ */ new Map();
2533
- const opIds = uniqueOps.map((op) => op.stamp.opId);
2534
- for (let offset = 0; offset < opIds.length; offset += 500) {
2535
- const chunk = opIds.slice(offset, offset + 500);
2536
- if (chunk.length === 0) continue;
2537
- const placeholders = chunk.map(() => "?").join(",");
2538
- const rows = await d1All(
2539
- `SELECT op_id, server_version, workspace_id, table_name, pk, op,
2540
- payload_json, clock, hlc, device_id
2541
- FROM change_log WHERE op_id IN (${placeholders})`,
2542
- ...chunk
2543
- );
2544
- for (const row of rows) {
2545
- existingOps.set(row.op_id, {
2546
- server_version: row.server_version,
2547
- workspace_id: row.workspace_id,
2548
- fingerprint: changeLogFingerprint(row)
2549
- });
2942
+ const rejected = /* @__PURE__ */ new Set();
2943
+ for (const op of uniqueOps) {
2944
+ try {
2945
+ const [receipt] = await d1All(`SELECT ${RECEIPT_COLUMNS} FROM change_log WHERE op_id=?`, op.stamp.opId);
2946
+ if (receipt) {
2947
+ const fingerprint = receipt.workspace_id === workspaceId ? receiptFingerprint(receipt) : "";
2948
+ existingOps.set(op.stamp.opId, { ...receipt, fingerprint });
2949
+ if (receipt.workspace_id !== workspaceId) continue;
2950
+ }
2951
+ if (receipt && existingOps.get(op.stamp.opId).fingerprint !== operationFingerprint(op)) continue;
2952
+ if (!input.repair && !await currentWinnerD1(workspaceId, op.tableName, op.pk, userId) && receipt && op.tableName !== "notifications") throw new StoredRecordUnavailable(storedReceiptSource(receipt), "stored_winner_missing");
2953
+ } catch (error) {
2954
+ if (!(error instanceof StoredRecordUnavailable)) throw error;
2955
+ if (error.revision && op.tableName !== "notifications" && incomingWinsRevision(op.stamp, error.revision)) {
2956
+ await historyBatch([historyAssertion(historyIncarnation), evidenceInsert({ ...error.source, historyIncarnation }, error.reason)], historyIncarnation);
2957
+ continue;
2958
+ }
2959
+ const result = await retainPushFailureD1(originalOps.get(op.stamp.opId), error, historyIncarnation, input.storedRecordCapability);
2960
+ rejected.add(op.stamp.opId);
2961
+ for (const index of indicesByOpId.get(op.stamp.opId) ?? []) resultSlots[index] = result;
2550
2962
  }
2551
2963
  }
2552
- const rejected = /* @__PURE__ */ new Set();
2553
2964
  for (const op of uniqueOps) {
2965
+ if (rejected.has(op.stamp.opId)) continue;
2554
2966
  const existing = existingOps.get(op.stamp.opId);
2555
2967
  if (!existing) continue;
2556
2968
  if (existing.workspace_id !== workspaceId || existing.fingerprint !== operationFingerprint(op)) {
@@ -2571,11 +2983,17 @@ export class SqliteSyncGatewayAdapter {
2571
2983
  const materializedTable = SYNCED_TABLE_MAP[op.tableName];
2572
2984
  if (!materializedTable) continue;
2573
2985
  const [owned] = await d1All(
2574
- `SELECT data_json FROM "${materializedTable}" WHERE id = ? AND workspace_id = ?`,
2986
+ `SELECT ${notificationOwnerSql("data_json")} AS owner FROM "${materializedTable}" WHERE id = ? AND workspace_id = ?`,
2575
2987
  op.pk,
2576
2988
  workspaceId
2577
2989
  );
2578
- const owner = owned ? notificationPayloadUserId(JSON.parse(owned.data_json)) : void 0;
2990
+ const owner = owned?.owner;
2991
+ if (owned && !owner) {
2992
+ const result = await retainPushFailureD1(originalOps.get(op.stamp.opId), new StoredRecordUnavailable(storedCanonicalSource(workspaceId, op.tableName, op.pk), "notification_owner_unavailable"), historyIncarnation, input.storedRecordCapability);
2993
+ rejected.add(op.stamp.opId);
2994
+ for (const index of indicesByOpId.get(op.stamp.opId) ?? []) resultSlots[index] = result;
2995
+ continue;
2996
+ }
2579
2997
  if (owned && owner !== userId || !owned && op.operation === "delete") {
2580
2998
  rejected.add(op.stamp.opId);
2581
2999
  for (const index of indicesByOpId.get(op.stamp.opId) ?? []) {
@@ -2588,9 +3006,23 @@ export class SqliteSyncGatewayAdapter {
2588
3006
  }
2589
3007
  }
2590
3008
  }
2591
- const newOps = uniqueOps.filter(
2592
- (op) => !existingOps.has(op.stamp.opId) && !rejected.has(op.stamp.opId)
2593
- );
3009
+ const intentFingerprints = new Map(uniqueOps.map((op) => [op.stamp.opId, operationFingerprint(op)]));
3010
+ const newOps = uniqueOps.filter((op) => {
3011
+ if (existingOps.has(op.stamp.opId) || rejected.has(op.stamp.opId)) return false;
3012
+ try {
3013
+ Object.assign(op, prepareFinalOperation(op));
3014
+ return true;
3015
+ } catch (error) {
3016
+ rejected.add(op.stamp.opId);
3017
+ for (const index of indicesByOpId.get(op.stamp.opId) ?? []) resultSlots[index] = {
3018
+ opId: op.stamp.opId,
3019
+ success: false,
3020
+ error: error.message,
3021
+ errorCode: "VALIDATION_ERROR"
3022
+ };
3023
+ return false;
3024
+ }
3025
+ });
2594
3026
  const existingMaterializedKeys = /* @__PURE__ */ new Set();
2595
3027
  const opsByTable = /* @__PURE__ */ new Map();
2596
3028
  for (const op of newOps) {
@@ -2643,10 +3075,11 @@ export class SqliteSyncGatewayAdapter {
2643
3075
  }
2644
3076
  }
2645
3077
  const now = nowEpoch();
2646
- const statements = [];
3078
+ const statements = [historyAssertion(historyIncarnation)];
3079
+ if (input.repair) statements.push(repairAssertion(input.repair));
2647
3080
  if (input.workspaceItemCapability !== WORKSPACE_ITEM_CAPABILITY) {
2648
3081
  for (const op of uniqueOps) {
2649
- if (!["posts", "projects"].includes(op.tableName)) continue;
3082
+ if (rejected.has(op.stamp.opId) || !["posts", "projects"].includes(op.tableName)) continue;
2650
3083
  if (hasWorkspaceItemSemantics(op.tableName, op.payload)) {
2651
3084
  throw workspaceItemUpdateRequired();
2652
3085
  }
@@ -2660,6 +3093,12 @@ export class SqliteSyncGatewayAdapter {
2660
3093
  parameters: [workspaceId]
2661
3094
  });
2662
3095
  }
3096
+ if (newOps.length > 0) statements.push({
3097
+ sql: `SELECT json_extract('{}', CASE WHEN typeof(value) = 'integer'
3098
+ AND value >= 0 AND value <= ? THEN '$' ELSE 'OR3_SYNC_VERSION_EXHAUSTED' END)
3099
+ FROM server_version_counter WHERE workspace_id = ?`,
3100
+ parameters: [Number.MAX_SAFE_INTEGER - 1 - newOps.length, workspaceId]
3101
+ });
2663
3102
  const materializedStatementIndex = /* @__PURE__ */ new Map();
2664
3103
  const materializedWasExisting = /* @__PURE__ */ new Map();
2665
3104
  const seenMaterializedKeys = /* @__PURE__ */ new Set();
@@ -2676,14 +3115,14 @@ export class SqliteSyncGatewayAdapter {
2676
3115
  statements.push({
2677
3116
  sql: `INSERT INTO change_log (
2678
3117
  id, workspace_id, server_version, table_name, pk, op,
2679
- payload_json, clock, hlc, device_id, op_id, created_at
3118
+ payload_json, clock, hlc, device_id, op_id, created_at, intent_fingerprint
2680
3119
  ) SELECT
2681
3120
  ?, ?,
2682
3121
  (SELECT value + 1 FROM server_version_counter WHERE workspace_id = ?),
2683
- ?, ?, ?, ?, ?, ?, ?, ?, ?
3122
+ ?, ?, ?, ?, ?, ?, ?, ?, ?, ?
2684
3123
  ${op.tableName === "notifications" ? `WHERE NOT EXISTS (
2685
3124
  SELECT 1 FROM s_notifications WHERE id = ? AND workspace_id = ?
2686
- AND json_extract(data_json, '$.user_id') IS NOT ?
3125
+ AND ${notificationOwnerSql("data_json")} IS NOT ?
2687
3126
  )` : ""}`,
2688
3127
  parameters: [
2689
3128
  uid(),
@@ -2698,6 +3137,7 @@ export class SqliteSyncGatewayAdapter {
2698
3137
  op.stamp.deviceId,
2699
3138
  op.stamp.opId,
2700
3139
  now,
3140
+ intentFingerprints.get(op.stamp.opId),
2701
3141
  ...op.tableName === "notifications" ? [op.pk, workspaceId, userId] : []
2702
3142
  ]
2703
3143
  });
@@ -2722,7 +3162,7 @@ export class SqliteSyncGatewayAdapter {
2722
3162
  deleted = 0,
2723
3163
  updated_at = excluded.updated_at
2724
3164
  WHERE ${lwwExcludedWins(`"${materializedTable}"`)}
2725
- ${op.tableName === "notifications" ? `AND json_extract("${materializedTable}".data_json, '$.user_id') = json_extract(excluded.data_json, '$.user_id')` : ""}`,
3165
+ ${op.tableName === "notifications" ? `AND ${notificationOwnerSql(`"${materializedTable}".data_json`)} = json_extract(excluded.data_json, '$.user_id')` : ""}`,
2726
3166
  parameters: [
2727
3167
  op.pk,
2728
3168
  workspaceId,
@@ -2748,7 +3188,8 @@ export class SqliteSyncGatewayAdapter {
2748
3188
  op_id = excluded.op_id,
2749
3189
  deleted = 1,
2750
3190
  updated_at = excluded.updated_at
2751
- WHERE ${lwwExcludedWins(`"${materializedTable}"`)}`,
3191
+ WHERE ${lwwExcludedWins(`"${materializedTable}"`)}
3192
+ ${op.tableName === "notifications" ? "AND EXISTS (SELECT 1 FROM change_log WHERE op_id=?)" : ""}`,
2752
3193
  parameters: [
2753
3194
  op.pk,
2754
3195
  workspaceId,
@@ -2757,18 +3198,19 @@ export class SqliteSyncGatewayAdapter {
2757
3198
  op.stamp.deviceId,
2758
3199
  op.stamp.opId,
2759
3200
  now,
2760
- now
3201
+ now,
3202
+ ...op.tableName === "notifications" ? [op.stamp.opId] : []
2761
3203
  ]
2762
3204
  });
2763
3205
  statements.push({
2764
3206
  sql: `INSERT INTO tombstones (
2765
3207
  id, workspace_id, table_name, pk, deleted_at, clock,
2766
3208
  hlc, op_id, server_version, created_at
2767
- ) VALUES (
3209
+ ) SELECT
2768
3210
  ?, ?, ?, ?, ?, ?, ?, ?,
2769
3211
  (SELECT value FROM server_version_counter WHERE workspace_id = ?),
2770
3212
  ?
2771
- )
3213
+ WHERE ${op.tableName === "notifications" ? "EXISTS (SELECT 1 FROM change_log WHERE op_id=?)" : "1"}
2772
3214
  ON CONFLICT(workspace_id, table_name, pk) DO UPDATE SET
2773
3215
  deleted_at = excluded.deleted_at,
2774
3216
  clock = excluded.clock,
@@ -2786,7 +3228,8 @@ export class SqliteSyncGatewayAdapter {
2786
3228
  op.stamp.hlc,
2787
3229
  op.stamp.opId,
2788
3230
  workspaceId,
2789
- now
3231
+ now,
3232
+ ...op.tableName === "notifications" ? [op.stamp.opId] : []
2790
3233
  ]
2791
3234
  });
2792
3235
  }
@@ -2800,9 +3243,13 @@ export class SqliteSyncGatewayAdapter {
2800
3243
  }
2801
3244
  let batchResults;
2802
3245
  try {
2803
- batchResults = statements.length > 0 ? await d1Batch(statements) : [];
3246
+ batchResults = statements.length > 0 ? await d1Batch(input.repair && newOps.length ? [...statements, repairResolution(input.repair, newOps[0].stamp.opId)] : statements) : [];
2804
3247
  } catch (error) {
2805
3248
  const message = error instanceof Error ? error.message : String(error);
3249
+ if (message.includes("OR3_SYNC_HISTORY_CHANGED")) historyChanged(await readHistoryIncarnation());
3250
+ if (/JSON path/i.test(message) && message.includes("OR3_SYNC_VERSION_EXHAUSTED")) {
3251
+ throw Object.assign(new Error("Sync server version exhausted or invalid"), { code: "VALIDATION_ERROR" });
3252
+ }
2806
3253
  if (/JSON path/i.test(message) && message.includes(WORKSPACE_ITEM_UPDATE_REQUIRED)) {
2807
3254
  throw workspaceItemUpdateRequired();
2808
3255
  }
@@ -2822,6 +3269,7 @@ export class SqliteSyncGatewayAdapter {
2822
3269
  );
2823
3270
  finalServerVersion = counter?.value ?? 0;
2824
3271
  }
3272
+ const opIds = uniqueOps.filter((op) => !rejected.has(op.stamp.opId)).map((op) => op.stamp.opId);
2825
3273
  const resolvedOps = /* @__PURE__ */ new Map();
2826
3274
  for (let offset = 0; offset < opIds.length; offset += 500) {
2827
3275
  const chunk = opIds.slice(offset, offset + 500);
@@ -2836,81 +3284,75 @@ export class SqliteSyncGatewayAdapter {
2836
3284
  const emissions = [];
2837
3285
  for (const op of uniqueOps) {
2838
3286
  if (rejected.has(op.stamp.opId)) continue;
2839
- if (op.tableName === "notifications") {
2840
- const [owned] = await d1All(
2841
- "SELECT data_json FROM s_notifications WHERE id = ? AND workspace_id = ?",
2842
- op.pk,
2843
- workspaceId
2844
- );
2845
- if (owned && notificationPayloadUserId(JSON.parse(owned.data_json)) !== userId) {
3287
+ try {
3288
+ const winner = await currentWinnerD1(workspaceId, op.tableName, op.pk, userId);
3289
+ if (op.tableName === "notifications") {
3290
+ const [owned] = await d1All(
3291
+ `SELECT ${notificationOwnerSql("data_json")} AS owner FROM s_notifications WHERE id = ? AND workspace_id = ?`,
3292
+ op.pk,
3293
+ workspaceId
3294
+ );
3295
+ if (owned && !owned.owner) throw new StoredRecordUnavailable(storedCanonicalSource(workspaceId, op.tableName, op.pk), "notification_owner_unavailable");
3296
+ if (owned && owned.owner !== userId) {
3297
+ for (const index of indicesByOpId.get(op.stamp.opId) ?? []) {
3298
+ resultSlots[index] = { opId: op.stamp.opId, success: false, error: "Forbidden: notification owner mismatch", errorCode: "UNAUTHORIZED" };
3299
+ }
3300
+ continue;
3301
+ }
3302
+ }
3303
+ const existing = existingOps.get(op.stamp.opId);
3304
+ if (existing) {
3305
+ if (!winner) throw new StoredRecordUnavailable(storedReceiptSource(existing), "stored_winner_missing");
3306
+ const applied2 = winner?.revision.opId === op.stamp.opId;
3307
+ const result2 = {
3308
+ opId: op.stamp.opId,
3309
+ success: true,
3310
+ serverVersion: existing.server_version,
3311
+ replayed: true,
3312
+ applied: applied2,
3313
+ ...applied2 ? {} : { winner }
3314
+ };
2846
3315
  for (const index of indicesByOpId.get(op.stamp.opId) ?? []) {
2847
- resultSlots[index] = { opId: op.stamp.opId, success: false, error: "Forbidden: notification owner mismatch", errorCode: "UNAUTHORIZED" };
3316
+ resultSlots[index] = result2;
2848
3317
  }
2849
3318
  continue;
2850
3319
  }
2851
- }
2852
- const existing = existingOps.get(op.stamp.opId);
2853
- if (existing) {
2854
- const winner = await currentWinnerD1(workspaceId, op.tableName, op.pk, userId);
2855
- const applied2 = winner?.revision.opId === op.stamp.opId;
2856
- const result2 = {
3320
+ const serverVersion = resolvedOps.get(op.stamp.opId);
3321
+ if (serverVersion === void 0) {
3322
+ throw new Error(`D1 failed to resolve sync operation ${op.stamp.opId}.`);
3323
+ }
3324
+ const skipApply = skipMaterialize.has(op.stamp.opId);
3325
+ const materializedResult = batchResults[materializedStatementIndex.get(op.stamp.opId) ?? -1];
3326
+ const applied = !skipApply && (materializedResult?.meta?.changes ?? 0) > 0;
3327
+ const winnerPayload = winner?.kind === "put" ? winner.payload : void 0;
3328
+ const result = {
2857
3329
  opId: op.stamp.opId,
2858
3330
  success: true,
2859
- serverVersion: existing.server_version,
2860
- replayed: true,
2861
- applied: applied2,
2862
- ...applied2 ? {} : { winner }
3331
+ serverVersion,
3332
+ applied,
3333
+ ...applied ? {} : { payload: winnerPayload },
3334
+ ...applied ? {} : {
3335
+ winner
3336
+ }
2863
3337
  };
2864
3338
  for (const index of indicesByOpId.get(op.stamp.opId) ?? []) {
2865
- resultSlots[index] = result2;
3339
+ resultSlots[index] = result;
2866
3340
  }
2867
- continue;
2868
- }
2869
- const serverVersion = resolvedOps.get(op.stamp.opId);
2870
- if (serverVersion === void 0) {
2871
- throw new Error(`D1 failed to resolve sync operation ${op.stamp.opId}.`);
2872
- }
2873
- const skipApply = skipMaterialize.has(op.stamp.opId);
2874
- const materializedResult = batchResults[materializedStatementIndex.get(op.stamp.opId) ?? -1];
2875
- const applied = !skipApply && (materializedResult?.meta?.changes ?? 0) > 0;
2876
- let winnerPayload;
2877
- if (!applied && !skipApply) {
2878
- const materializedTable = SYNCED_TABLE_MAP[op.tableName];
2879
- if (materializedTable) {
2880
- const [winner] = await d1All(
2881
- `SELECT data_json FROM "${materializedTable}" WHERE id = ? AND workspace_id = ?`,
2882
- op.pk,
2883
- workspaceId
2884
- );
2885
- if (winner?.data_json) {
2886
- const payload = JSON.parse(winner.data_json);
2887
- if (op.tableName !== "notifications" || notificationPayloadUserId(payload) === userId) winnerPayload = payload;
2888
- }
2889
- }
2890
- }
2891
- const result = {
2892
- opId: op.stamp.opId,
2893
- success: true,
2894
- serverVersion,
2895
- applied,
2896
- ...applied ? {} : { payload: winnerPayload },
2897
- ...applied ? {} : {
2898
- winner: await currentWinnerD1(workspaceId, op.tableName, op.pk, userId)
3341
+ if (applied) {
3342
+ const emission = resolveHookEmission({
3343
+ op,
3344
+ workspaceId,
3345
+ now,
3346
+ userId,
3347
+ wasExisting: materializedWasExisting.get(op.stamp.opId) ?? false,
3348
+ applied: true
3349
+ });
3350
+ if (emission) emissions.push(emission);
2899
3351
  }
2900
- };
2901
- for (const index of indicesByOpId.get(op.stamp.opId) ?? []) {
2902
- resultSlots[index] = result;
2903
- }
2904
- if (applied) {
2905
- const emission = resolveHookEmission({
2906
- op,
2907
- workspaceId,
2908
- now,
2909
- userId,
2910
- wasExisting: materializedWasExisting.get(op.stamp.opId) ?? false,
2911
- applied: true
2912
- });
2913
- if (emission) emissions.push(emission);
3352
+ } catch (error) {
3353
+ if (!(error instanceof StoredRecordUnavailable)) throw error;
3354
+ const result = await retainPushFailureD1(originalOps.get(op.stamp.opId), error, historyIncarnation, input.storedRecordCapability);
3355
+ for (const index of indicesByOpId.get(op.stamp.opId) ?? []) resultSlots[index] = result;
2914
3356
  }
2915
3357
  }
2916
3358
  for (const emission of emissions) {
@@ -2920,7 +3362,8 @@ export class SqliteSyncGatewayAdapter {
2920
3362
  results: resultSlots.filter(
2921
3363
  (result) => Boolean(result)
2922
3364
  ),
2923
- serverVersion: finalServerVersion
3365
+ serverVersion: finalServerVersion,
3366
+ historyIncarnation
2924
3367
  };
2925
3368
  }
2926
3369
  async listWorkspaceIds() {