or3-provider-sqlite 0.0.30 → 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 (31) hide show
  1. package/README.md +83 -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 +25 -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.js +8 -2
  14. package/dist/runtime/server/db/migrations/034_sync_intent_fingerprint.d.ts +3 -0
  15. package/dist/runtime/server/db/migrations/034_sync_intent_fingerprint.js +8 -0
  16. package/dist/runtime/server/db/migrations/035_sync_unavailable_records.d.ts +3 -0
  17. package/dist/runtime/server/db/migrations/035_sync_unavailable_records.js +24 -0
  18. package/dist/runtime/server/db/migrations/036_sync_history_incarnation.d.ts +3 -0
  19. package/dist/runtime/server/db/migrations/036_sync_history_incarnation.js +28 -0
  20. package/dist/runtime/server/db/schema.d.ts +5 -0
  21. package/dist/runtime/server/sync/canonical-project-ownership.d.ts +1 -1
  22. package/dist/runtime/server/sync/canonical-project-ownership.js +29 -12
  23. package/dist/runtime/server/sync/evidence-maintenance.d.ts +20 -0
  24. package/dist/runtime/server/sync/evidence-maintenance.js +130 -0
  25. package/dist/runtime/server/sync/history-incarnation.d.ts +8 -0
  26. package/dist/runtime/server/sync/history-incarnation.js +54 -0
  27. package/dist/runtime/server/sync/sqlite-sync-gateway-adapter.d.ts +28 -4
  28. package/dist/runtime/server/sync/sqlite-sync-gateway-adapter.js +802 -356
  29. package/dist/runtime/server/sync/unavailable-records.d.ts +30 -0
  30. package/dist/runtime/server/sync/unavailable-records.js +55 -0
  31. package/package.json +1 -1
@@ -1,3 +1,5 @@
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";
@@ -24,6 +26,9 @@ import { SYNCED_TABLE_MAP, ALLOWED_SYNC_TABLES } from "../db/schema.js";
24
26
  import { emitWebhookSystemHook } from "~~/server/utils/webhooks/runtime";
25
27
  import { incomingRevisionWins } from "~~/shared/sync/revision";
26
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";
27
32
  import { readRequestUsage } from "~~/shared/chat/compaction";
28
33
  import { matchesToolResultStorage, parseToolResultArtifact, prepareToolResultStorage, toolResultArtifactPrefix } from "~~/shared/chat/tool-result-artifact";
29
34
  import { validateCanonicalChatQuery, encodeCanonicalChatSeek, parseCanonicalChatSeek } from "~~/shared/chat/history-reader";
@@ -68,11 +73,13 @@ const QUOTA_RESERVATIONS_SQL = `SELECT intent.hash, MAX(intent.size_bytes) AS re
68
73
  ON retained.workspace_id = intent.workspace_id AND retained.hash = intent.hash
69
74
  WHERE intent.workspace_id = ? AND intent.status = 'active' AND intent.expires_at > ?
70
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");
71
78
  function boundedPayloadRowCount(sizes, limit) {
72
79
  let count = 0;
73
80
  let bytes = 0;
74
81
  for (const row of sizes.slice(0, limit)) {
75
- 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);
76
83
  if (count && bytes + size > MAX_SYNC_PAGE_BYTES) break;
77
84
  count++;
78
85
  bytes += size;
@@ -81,58 +88,122 @@ function boundedPayloadRowCount(sizes, limit) {
81
88
  }
82
89
  function snapshotPageSelection(headerId, after) {
83
90
  const clause = `FROM sync_snapshot_items WHERE snapshot_id = ?${after ? `
84
- AND (table_name > ? OR (table_name = ? AND pk > ?)
85
- OR (table_name = ? AND pk = ? AND kind > ?))` : ""}
86
- ORDER BY table_name ASC, pk ASC, kind ASC LIMIT ?`;
87
- 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];
88
94
  return { clause, parameters };
89
95
  }
90
- 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");
91
128
  const items = [];
92
- let itemBytes = 0;
129
+ const unavailable = [];
93
130
  let scanned = 0;
131
+ let itemBytes = 0;
94
132
  let token = null;
133
+ let previous = after ? [after.tableName, after.pk, after.kind] : void 0;
95
134
  for (const row of rows.slice(0, pageSize)) {
96
- const revision = { clock: row.clock, hlc: row.hlc, opId: row.op_id };
97
- const item = row.kind === "row" ? {
98
- kind: "row",
99
- tableName: row.table_name,
100
- pk: row.pk,
101
- payload: JSON.parse(row.payload_json ?? "null"),
102
- revision
103
- } : {
104
- 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 = {
105
152
  tableName: row.table_name,
106
153
  pk: row.pk,
107
- revision,
108
- serverDeletedAt: row.server_deleted_at ?? 0
154
+ originalKind: row.kind,
155
+ snapshotId: header.id,
156
+ highWatermark: header.high_watermark,
157
+ evidenceRef: "",
158
+ reason
109
159
  };
110
160
  const next = encodeSnapshotPageToken({
111
161
  version: 1,
112
162
  snapshotId: header.id,
163
+ historyIncarnation,
113
164
  after: { tableName: row.table_name, pk: row.pk, kind: row.kind }
114
165
  });
115
- const bytes = jsonBytes(item) + (items.length ? 1 : 0);
116
- 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,
117
170
  workspaceId: header.workspace_id,
118
171
  snapshotId: header.id,
119
172
  highWatermark: header.high_watermark,
120
173
  items: [],
174
+ unavailable: [],
121
175
  nextPageToken: next
122
176
  });
123
- if (items.length && envelope + itemBytes + bytes > MAX_SYNC_PAGE_BYTES) break;
124
- 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
+ }
125
191
  itemBytes += bytes;
126
192
  scanned++;
127
193
  token = next;
194
+ previous = key;
128
195
  }
129
- 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,
130
200
  workspaceId: header.workspace_id,
131
201
  snapshotId: header.id,
132
202
  highWatermark: header.high_watermark,
133
203
  items,
204
+ ...unavailable.length ? { unavailable } : {},
134
205
  nextPageToken: availableRows > scanned ? token : null
135
- };
206
+ });
136
207
  }
137
208
  function uid() {
138
209
  return globalThis.crypto.randomUUID();
@@ -166,6 +237,13 @@ export async function pruneExpiredSyncSnapshots() {
166
237
  getRawDb().prepare("DELETE FROM sync_snapshots WHERE expires_at <= ?").run(nowEpoch());
167
238
  }
168
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
+ }
169
247
  function backgroundHistoryOpId(admission, stage) {
170
248
  return digestUuid(createHash("sha256").update(`${admission.workspaceId}\0${admission.generationId}\0${stage}`).digest("hex"));
171
249
  }
@@ -188,16 +266,9 @@ function operationFingerprint(op) {
188
266
  deviceId: op.stamp.deviceId
189
267
  });
190
268
  }
191
- function changeLogFingerprint(row) {
192
- return stableJson({
193
- tableName: row.table_name,
194
- operation: row.op,
195
- pk: row.pk,
196
- payload: fingerprintPayload(row.table_name, row.op, row.payload_json ? JSON.parse(row.payload_json) : void 0),
197
- clock: row.clock,
198
- hlc: row.hlc,
199
- deviceId: row.device_id
200
- });
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 }) };
201
272
  }
202
273
  function notificationPayloadUserId(payload) {
203
274
  if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
@@ -206,11 +277,6 @@ function notificationPayloadUserId(payload) {
206
277
  const userId = payload.user_id;
207
278
  return typeof userId === "string" && userId.trim().length > 0 ? userId : void 0;
208
279
  }
209
- function isNotificationVisibleToUser(change, userId) {
210
- if (change.tableName !== "notifications") return true;
211
- if (!userId) return false;
212
- return notificationPayloadUserId(change.payload) === userId;
213
- }
214
280
  function scopeNotificationWrite(op, userId) {
215
281
  if (op.tableName !== "notifications") return op;
216
282
  if (!userId) {
@@ -253,8 +319,10 @@ function workspaceItemCapabilityAssertion(op, workspaceId) {
253
319
  return {
254
320
  sql: `SELECT json_extract('{}', CASE WHEN EXISTS (
255
321
  SELECT 1 FROM (
256
- SELECT data_json, ${decoded} AS metadata FROM "${SYNCED_TABLE_MAP[op.tableName]}"
257
- 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
+ )
258
326
  ) WHERE ${semantics}
259
327
  ) THEN '${WORKSPACE_ITEM_UPDATE_REQUIRED}' ELSE '$' END)`,
260
328
  parameters: [workspaceId, op.pk]
@@ -276,7 +344,7 @@ function snapshotNotificationOwnerClause(tableName, jsonExpr, userId) {
276
344
  if (tableName !== "notifications") return { sql: "", params: [] };
277
345
  if (!userId) return { sql: " AND 1 = 0", params: [] };
278
346
  return {
279
- sql: ` AND json_extract(${jsonExpr}, '$.user_id') = ?`,
347
+ sql: ` AND ${notificationOwnerSql(jsonExpr)} = ?`,
280
348
  params: [userId]
281
349
  };
282
350
  }
@@ -363,6 +431,7 @@ function encodeSnapshotPageToken(token) {
363
431
  }
364
432
  function decodeSnapshotPageToken(value) {
365
433
  try {
434
+ if (value.length > MAX_SYNC_SNAPSHOT_TOKEN_LENGTH) throw new Error("Token exceeds ceiling");
366
435
  const parsed = JSON.parse(
367
436
  Buffer.from(value, "base64url").toString("utf8")
368
437
  );
@@ -370,6 +439,7 @@ function decodeSnapshotPageToken(value) {
370
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") {
371
440
  throw new Error("Invalid token payload");
372
441
  }
442
+ assertCoverageKey(after.tableName, after.pk);
373
443
  return parsed;
374
444
  } catch {
375
445
  throw createError({
@@ -531,58 +601,188 @@ function incomingWinsRevision(incoming, existing) {
531
601
  opId: existing.opId || existing.op_id || ""
532
602
  });
533
603
  }
534
- function materializedWinner(row, tombstone) {
535
- if (tombstone && (!row || incomingWinsRevision(
536
- { clock: tombstone.clock, hlc: tombstone.hlc, opId: tombstone.op_id },
537
- row
538
- ))) {
539
- return {
540
- kind: "delete",
541
- revision: { clock: tombstone.clock, hlc: tombstone.hlc, opId: tombstone.op_id },
542
- serverDeletedAt: tombstone.deleted_at
543
- };
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 };
544
654
  }
545
655
  if (!row) return void 0;
546
656
  const revision = { clock: row.clock, hlc: row.hlc, opId: row.op_id };
547
- return row.deleted ? {
548
- kind: "delete",
549
- revision,
550
- serverDeletedAt: tombstone?.op_id === row.op_id ? tombstone.deleted_at : row.updated_at
551
- } : { 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);
552
753
  }
553
754
  function currentWinnerNative(raw, workspaceId, tableName, pk) {
554
755
  const materializedTable = SYNCED_TABLE_MAP[tableName];
555
756
  if (!materializedTable) return void 0;
556
757
  const row = raw.prepare(
557
- `SELECT data_json, deleted, clock, hlc, op_id, updated_at
758
+ `SELECT ${WINNER_COLUMNS}
558
759
  FROM ${materializedTable} WHERE id = ? AND workspace_id = ?`
559
760
  ).get(pk, workspaceId);
560
761
  const tombstone = raw.prepare(
561
- `SELECT clock, hlc, op_id, deleted_at FROM tombstones
762
+ `SELECT ${TOMBSTONE_COLUMNS} FROM tombstones
562
763
  WHERE workspace_id = ? AND table_name = ? AND pk = ?`
563
764
  ).get(workspaceId, tableName, pk);
564
- return materializedWinner(row, tombstone);
765
+ return materializedWinner(row, tombstone, workspaceId, tableName, pk);
565
766
  }
566
767
  async function currentWinnerD1(workspaceId, tableName, pk, userId) {
567
768
  const materializedTable = SYNCED_TABLE_MAP[tableName];
568
769
  if (!materializedTable) return void 0;
569
770
  const [row] = await d1All(
570
- `SELECT data_json, deleted, clock, hlc, op_id, updated_at
771
+ `SELECT ${WINNER_COLUMNS}
571
772
  FROM "${materializedTable}" WHERE id = ? AND workspace_id = ?`,
572
773
  pk,
573
774
  workspaceId
574
775
  );
575
- if (tableName === "notifications" && row && notificationPayloadUserId(JSON.parse(row.data_json)) !== userId) {
576
- return void 0;
577
- }
578
776
  const [tombstone] = await d1All(
579
- `SELECT clock, hlc, op_id, deleted_at FROM tombstones
777
+ `SELECT ${TOMBSTONE_COLUMNS} FROM tombstones
580
778
  WHERE workspace_id = ? AND table_name = ? AND pk = ?`,
581
779
  workspaceId,
582
780
  tableName,
583
781
  pk
584
782
  );
585
- 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;
586
786
  }
587
787
  export class SqliteSyncGatewayAdapter {
588
788
  id = "sqlite";
@@ -596,16 +796,26 @@ export class SqliteSyncGatewayAdapter {
596
796
  }
597
797
  const current = watcher;
598
798
  current.listeners.set(onVersion, onError);
599
- if (current.version !== void 0) onVersion(current.version);
799
+ if (current.position) onVersion(current.position);
600
800
  const poll = async () => {
601
801
  if (current.running || this.versionWatchers.get(scope.workspaceId) !== current) return;
602
802
  current.running = true;
603
803
  try {
604
- const row = await getSqliteDb().selectFrom("server_version_counter").select("value").where("workspace_id", "=", scope.workspaceId).executeTakeFirst();
605
- const version = row?.value ?? 0;
606
- if (current.version !== version) {
607
- current.version = version;
608
- 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);
609
819
  }
610
820
  } catch (error) {
611
821
  for (const fail of [...current.listeners.values()]) fail(error);
@@ -640,11 +850,14 @@ export class SqliteSyncGatewayAdapter {
640
850
  get capabilities() {
641
851
  return isD1Driver() ? {
642
852
  snapshotBootstrap: "snapshot-v1",
853
+ unavailableRecords: "v1",
643
854
  historyRetention: "snapshot-v1",
644
855
  retainedStorageMetadata: "v1",
645
856
  atomicUploadQuota: "retained-v1"
646
857
  } : {
858
+ historyIncarnation: "v1",
647
859
  snapshotBootstrap: "snapshot-v1",
860
+ unavailableRecords: "v1",
648
861
  historyRetention: "snapshot-v1",
649
862
  ...this.storageGenerationCoordinator ? { externalStorageGenerations: "v1" } : {},
650
863
  backgroundGenerationHistory: "v1",
@@ -656,6 +869,25 @@ export class SqliteSyncGatewayAdapter {
656
869
  atomicUploadQuota: "retained-v1"
657
870
  };
658
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
+ }
659
891
  get db() {
660
892
  return getSqliteDb();
661
893
  }
@@ -672,7 +904,7 @@ export class SqliteSyncGatewayAdapter {
672
904
  const revision = String(counter?.value ?? 0);
673
905
  const parse = (row) => {
674
906
  const payload = JSON.parse(row.data_json);
675
- 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");
676
908
  return { ...payload, id: row.id, clock: row.clock, deleted: row.deleted === 1 };
677
909
  };
678
910
  if (query.kind === "thread") {
@@ -686,6 +918,7 @@ export class SqliteSyncGatewayAdapter {
686
918
  thread
687
919
  };
688
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) };
689
922
  return {
690
923
  status: "ok",
691
924
  project_ownership: ownership.status,
@@ -771,20 +1004,30 @@ export class SqliteSyncGatewayAdapter {
771
1004
  admission.userMessage ? { table: "messages", materialized: "s_messages", record: admission.userMessage } : null,
772
1005
  { table: "messages", materialized: "s_messages", record: admission.assistantMessage }
773
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
+ });
774
1021
  const counter = raw.prepare("SELECT value FROM server_version_counter WHERE workspace_id = ?").get(admission.workspaceId);
775
1022
  const baseVersion = counter?.value ?? 0;
776
- const finalVersion = baseVersion + records.length;
1023
+ const finalVersion = safeVersionEnd(baseVersion, records.length);
777
1024
  raw.prepare(
778
1025
  `INSERT INTO server_version_counter (workspace_id, value) VALUES (?, ?)
779
1026
  ON CONFLICT(workspace_id) DO UPDATE SET value = excluded.value`
780
1027
  ).run(admission.workspaceId, finalVersion);
781
1028
  const now = nowEpoch();
782
1029
  records.forEach((entry, index) => {
783
- const opId = backgroundHistoryOpId(
784
- admission,
785
- entry.table === "threads" ? "thread" : entry.record.id === admission.messageId ? "assistant" : "user"
786
- );
787
- const hlc = entry.record.hlc ?? `${Date.now().toString(36).padStart(9, "0")}:000:background`;
1030
+ const { stamp: { opId, hlc }, payload } = prepared[index];
788
1031
  const tombstone = raw.prepare(
789
1032
  `SELECT clock, hlc, op_id FROM tombstones
790
1033
  WHERE workspace_id = ? AND table_name = ? AND pk = ?`
@@ -799,19 +1042,7 @@ export class SqliteSyncGatewayAdapter {
799
1042
  )) {
800
1043
  throw Object.assign(new Error("Background history record was superseded"), { code: "SUPERSEDED" });
801
1044
  }
802
- const sanitized = sanitizePayloadForSync(
803
- entry.table,
804
- entry.record,
805
- "put"
806
- );
807
- if (!sanitized) {
808
- throw Object.assign(new Error("Invalid background history payload"), { code: "VALIDATION_ERROR" });
809
- }
810
- const payload = { ...sanitized, hlc, op_id: opId };
811
1045
  const payloadJson = JSON.stringify(payload);
812
- if (new TextEncoder().encode(payloadJson).byteLength > MAX_SYNC_PAYLOAD_BYTES) {
813
- throw Object.assign(new Error("Invalid background history payload size"), { code: "VALIDATION_ERROR" });
814
- }
815
1046
  const version = baseVersion + index + 1;
816
1047
  raw.prepare(
817
1048
  `INSERT INTO change_log
@@ -948,7 +1179,7 @@ export class SqliteSyncGatewayAdapter {
948
1179
  ).run(uid(), admission.workspaceId, admission.generationId, fingerprint, superseded, now);
949
1180
  return { status: "superseded", reason: superseded };
950
1181
  }
951
- const nextClock = row.clock + 1;
1182
+ const nextClock = nextSyncClock(row.clock);
952
1183
  const hlc = `${Date.now().toString(36).padStart(9, "0")}:000:background`;
953
1184
  const opId = backgroundHistoryOpId(admission, "finalize");
954
1185
  const terminalState = input.snapshot.status === "complete" ? "complete" : input.snapshot.status === "aborted" ? "aborted" : "failed";
@@ -973,12 +1204,18 @@ export class SqliteSyncGatewayAdapter {
973
1204
  error: input.snapshot.error ?? null
974
1205
  }
975
1206
  };
976
- const payloadJson = JSON.stringify(payload);
977
- if (new TextEncoder().encode(payloadJson).byteLength > MAX_SYNC_PAYLOAD_BYTES) {
978
- throw Object.assign(new Error("Invalid background history payload size"), { code: "VALIDATION_ERROR" });
979
- }
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);
980
1217
  const counter = raw.prepare("SELECT value FROM server_version_counter WHERE workspace_id = ?").get(admission.workspaceId);
981
- const serverVersion = (counter?.value ?? 0) + 1;
1218
+ const serverVersion = safeVersionEnd(counter?.value ?? 0, 1);
982
1219
  raw.prepare(
983
1220
  `INSERT INTO server_version_counter (workspace_id, value) VALUES (?, ?)
984
1221
  ON CONFLICT(workspace_id) DO UPDATE SET value = excluded.value`
@@ -1067,19 +1304,25 @@ export class SqliteSyncGatewayAdapter {
1067
1304
  } else newRows.push(row);
1068
1305
  }
1069
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
+ });
1070
1318
  const counter = raw.prepare("SELECT value FROM server_version_counter WHERE workspace_id = ?").get(admission.workspaceId);
1071
1319
  const baseVersion = counter?.value ?? 0;
1072
1320
  raw.prepare(`INSERT INTO server_version_counter (workspace_id, value) VALUES (?, ?)
1073
- 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));
1074
1322
  const now = nowEpoch();
1075
1323
  newRows.forEach((row, index) => {
1076
- const opId = digestUuid(createHash("sha256").update(JSON.stringify([admission.workspaceId, admission.generationId, row.id])).digest("hex"));
1077
- const hlc = `${Date.now().toString(36).padStart(9, "0")}:000:background`;
1078
- const sanitized = sanitizePayloadForSync("kv", row, "put");
1079
- if (!sanitized) throw Object.assign(new Error("Invalid tool result payload"), { code: "VALIDATION_ERROR" });
1080
- const payloadJson = JSON.stringify({ ...sanitized, hlc, op_id: opId });
1081
- if (new TextEncoder().encode(payloadJson).length > MAX_SYNC_PAYLOAD_BYTES)
1082
- 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);
1083
1326
  raw.prepare(`INSERT INTO s_kv (id, workspace_id, data_json, clock, hlc, device_id, op_id, deleted, created_at, updated_at)
1084
1327
  VALUES (?, ?, ?, ?, ?, ?, ?, 0, ?, ?)`).run(
1085
1328
  row.id,
@@ -1434,12 +1677,13 @@ export class SqliteSyncGatewayAdapter {
1434
1677
  } : {}
1435
1678
  };
1436
1679
  }
1437
- async push(event, input) {
1680
+ async push(event, input, repair) {
1438
1681
  const { scope, ops } = input;
1439
1682
  const workspaceId = scope.workspaceId;
1440
1683
  await assertWorkspaceScopeAuthorized(event, workspaceId);
1684
+ const historyIncarnation = await this.checkHistory(event, input);
1441
1685
  if (!ops.length) {
1442
- return { results: [], serverVersion: 0 };
1686
+ return { results: [], serverVersion: 0, historyIncarnation };
1443
1687
  }
1444
1688
  const userId = resolveSessionUserId(event);
1445
1689
  const resultSlots = new Array(ops.length);
@@ -1475,7 +1719,7 @@ export class SqliteSyncGatewayAdapter {
1475
1719
  }
1476
1720
  continue;
1477
1721
  }
1478
- uniqueOps.push(scoped);
1722
+ uniqueOps.push({ ...scoped });
1479
1723
  indicesByOpId.set(group.op.stamp.opId, group.indices);
1480
1724
  }
1481
1725
  if (isD1Driver()) {
@@ -1486,7 +1730,10 @@ export class SqliteSyncGatewayAdapter {
1486
1730
  resultSlots,
1487
1731
  indicesByOpId,
1488
1732
  userId,
1489
- workspaceItemCapability: input.workspaceItemCapability
1733
+ workspaceItemCapability: input.workspaceItemCapability,
1734
+ storedRecordCapability: input.storedRecordCapability,
1735
+ historyIncarnation,
1736
+ repair
1490
1737
  });
1491
1738
  }
1492
1739
  const raw = getRawDb();
@@ -1495,45 +1742,66 @@ export class SqliteSyncGatewayAdapter {
1495
1742
  let finalServerVersion = 0;
1496
1743
  const hookEmissions = [];
1497
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
+ }
1498
1777
  if (input.workspaceItemCapability !== WORKSPACE_ITEM_CAPABILITY) {
1499
1778
  for (const op of uniqueOps) {
1779
+ if (failedBeforeAlloc.has(op.stamp.opId)) continue;
1500
1780
  const table = SYNCED_TABLE_MAP[op.tableName];
1501
1781
  if (!table || !["posts", "projects"].includes(op.tableName)) continue;
1502
- const canonical = raw.prepare("SELECT data_json FROM " + table + " WHERE id = ? AND workspace_id = ?").get(op.pk, workspaceId);
1503
- 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)) {
1504
1784
  throw workspaceItemUpdateRequired();
1505
1785
  }
1506
1786
  }
1507
1787
  }
1508
- const opIds = uniqueOps.map((o) => o.stamp.opId);
1509
- const existingOps = /* @__PURE__ */ new Map();
1510
- const chunkSize = 500;
1511
- for (let i = 0; i < opIds.length; i += chunkSize) {
1512
- const chunk = opIds.slice(i, i + chunkSize);
1513
- const placeholders = chunk.map(() => "?").join(",");
1514
- const rows = raw.prepare(
1515
- `SELECT op_id, server_version, workspace_id, table_name, pk, op,
1516
- payload_json, clock, hlc, device_id
1517
- FROM change_log WHERE op_id IN (${placeholders})`
1518
- ).all(...chunk);
1519
- for (const row of rows) {
1520
- existingOps.set(row.op_id, {
1521
- server_version: row.server_version,
1522
- workspace_id: row.workspace_id,
1523
- fingerprint: changeLogFingerprint(row),
1524
- op_id: row.op_id
1525
- });
1526
- }
1527
- }
1528
- const failedBeforeAlloc = /* @__PURE__ */ new Set();
1529
1788
  for (const op of uniqueOps) {
1789
+ if (failedBeforeAlloc.has(op.stamp.opId)) continue;
1530
1790
  if (op.tableName !== "notifications") continue;
1531
1791
  const materializedTable = SYNCED_TABLE_MAP[op.tableName];
1532
1792
  if (!materializedTable) continue;
1533
1793
  const owned = raw.prepare(
1534
- `SELECT data_json FROM ${materializedTable} WHERE id = ? AND workspace_id = ?`
1794
+ `SELECT ${notificationOwnerSql("data_json")} AS owner FROM ${materializedTable} WHERE id = ? AND workspace_id = ?`
1535
1795
  ).get(op.pk, workspaceId);
1536
- 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
+ }
1537
1805
  if (owned && owner !== userId || !owned && op.operation === "delete") {
1538
1806
  failedBeforeAlloc.add(op.stamp.opId);
1539
1807
  uniqueResults.push({
@@ -1544,6 +1812,21 @@ export class SqliteSyncGatewayAdapter {
1544
1812
  });
1545
1813
  }
1546
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
+ }
1547
1830
  const uniqueNewOpIds = /* @__PURE__ */ new Set();
1548
1831
  for (const op of uniqueOps) {
1549
1832
  if (existingOps.has(op.stamp.opId)) continue;
@@ -1552,6 +1835,7 @@ export class SqliteSyncGatewayAdapter {
1552
1835
  }
1553
1836
  let baseVersion;
1554
1837
  const counterRow = raw.prepare("SELECT value FROM server_version_counter WHERE workspace_id = ?").get(workspaceId);
1838
+ safeVersionEnd(counterRow?.value ?? 0, uniqueNewOpIds.size);
1555
1839
  if (counterRow) {
1556
1840
  baseVersion = counterRow.value;
1557
1841
  raw.prepare(
@@ -1559,7 +1843,7 @@ export class SqliteSyncGatewayAdapter {
1559
1843
  ).run(baseVersion + uniqueNewOpIds.size, workspaceId);
1560
1844
  } else {
1561
1845
  baseVersion = 0;
1562
- raw.prepare(
1846
+ if (uniqueNewOpIds.size) raw.prepare(
1563
1847
  "INSERT INTO server_version_counter (workspace_id, value) VALUES (?, ?)"
1564
1848
  ).run(workspaceId, uniqueNewOpIds.size);
1565
1849
  }
@@ -1583,7 +1867,7 @@ export class SqliteSyncGatewayAdapter {
1583
1867
  if (failedBeforeAlloc.has(opId)) continue;
1584
1868
  const existingLog = existingOps.get(opId);
1585
1869
  if (existingLog !== void 0) {
1586
- if (existingLog.workspace_id !== workspaceId || existingLog.fingerprint !== operationFingerprint(op)) {
1870
+ if (existingLog.workspace_id !== workspaceId || existingLog.fingerprint !== intentFingerprints.get(opId)) {
1587
1871
  uniqueResults.push({
1588
1872
  opId,
1589
1873
  success: false,
@@ -1627,21 +1911,6 @@ export class SqliteSyncGatewayAdapter {
1627
1911
  continue;
1628
1912
  }
1629
1913
  const pkValue = op.pk;
1630
- if (op.tableName === "notifications" && op.operation === "delete") {
1631
- const owned = raw.prepare(
1632
- `SELECT data_json FROM ${materializedTable} WHERE id = ? AND workspace_id = ?`
1633
- ).get(pkValue, workspaceId);
1634
- const owner = owned ? notificationPayloadUserId(JSON.parse(owned.data_json)) : void 0;
1635
- if (!owned || owner !== userId) {
1636
- uniqueResults.push({
1637
- opId,
1638
- success: false,
1639
- error: "Forbidden: notification owner mismatch",
1640
- errorCode: "UNAUTHORIZED"
1641
- });
1642
- continue;
1643
- }
1644
- }
1645
1914
  const payloadJson = op.payload != null ? JSON.stringify(op.payload) : null;
1646
1915
  insertChangeLog.run(
1647
1916
  uid(),
@@ -1657,6 +1926,7 @@ export class SqliteSyncGatewayAdapter {
1657
1926
  opId,
1658
1927
  now
1659
1928
  );
1929
+ raw.prepare("UPDATE change_log SET intent_fingerprint = ? WHERE op_id = ?").run(intentFingerprints.get(opId), opId);
1660
1930
  const incomingRev = {
1661
1931
  clock: op.stamp.clock,
1662
1932
  hlc: op.stamp.hlc,
@@ -1664,7 +1934,7 @@ export class SqliteSyncGatewayAdapter {
1664
1934
  };
1665
1935
  if (op.operation === "put") {
1666
1936
  const existing = raw.prepare(
1667
- `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 = ?`
1668
1938
  ).get(pkValue, workspaceId);
1669
1939
  const tombstone = !existing ? raw.prepare(
1670
1940
  `SELECT clock, hlc, op_id FROM tombstones
@@ -1709,7 +1979,7 @@ export class SqliteSyncGatewayAdapter {
1709
1979
  );
1710
1980
  applied = true;
1711
1981
  } else {
1712
- winnerPayload = JSON.parse(existing.data_json);
1982
+ winnerPayload = existing.deleted ? void 0 : JSON.parse(existing.data_json);
1713
1983
  }
1714
1984
  const emission = resolveHookEmission({
1715
1985
  op,
@@ -1734,7 +2004,7 @@ export class SqliteSyncGatewayAdapter {
1734
2004
  });
1735
2005
  } else if (op.operation === "delete") {
1736
2006
  const existing = raw.prepare(
1737
- `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 = ?`
1738
2008
  ).get(pkValue, workspaceId);
1739
2009
  let applied = false;
1740
2010
  if (!existing) {
@@ -1806,13 +2076,18 @@ export class SqliteSyncGatewayAdapter {
1806
2076
  success: true,
1807
2077
  serverVersion,
1808
2078
  applied,
1809
- ...applied || !existing ? {} : { payload: JSON.parse(existing.data_json) },
2079
+ ...applied || !existing ? {} : { payload: existing.deleted ? void 0 : JSON.parse(existing.data_json) },
1810
2080
  ...applied ? {} : {
1811
2081
  winner: currentWinnerNative(raw, workspaceId, op.tableName, pkValue)
1812
2082
  }
1813
2083
  });
1814
2084
  }
1815
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
+ }
1816
2091
  });
1817
2092
  runTx.immediate();
1818
2093
  for (const result of uniqueResults) {
@@ -1827,74 +2102,215 @@ export class SqliteSyncGatewayAdapter {
1827
2102
  results: resultSlots.filter(
1828
2103
  (result) => Boolean(result)
1829
2104
  ),
1830
- serverVersion: finalServerVersion
2105
+ serverVersion: finalServerVersion,
2106
+ historyIncarnation
1831
2107
  };
1832
2108
  }
1833
2109
  async pull(event, input) {
1834
2110
  const db = this.db;
1835
2111
  const { scope, cursor, limit, tables } = input;
1836
2112
  await assertWorkspaceScopeAuthorized(event, scope.workspaceId);
2113
+ const historyIncarnation = await this.checkHistory(event, input, true);
1837
2114
  const fetchLimit = resolvePullLimit(limit);
1838
- let query = db.selectFrom("change_log").where("workspace_id", "=", scope.workspaceId).where("server_version", ">", cursor).orderBy("server_version", "asc");
1839
- if (tables?.length) {
1840
- query = query.where("table_name", "in", tables);
1841
- }
1842
- const sizes = await query.select(sql`coalesce(length(cast(payload_json as blob)), 0)`.as("payload_bytes")).limit(fetchLimit + 1).execute();
1843
- const selected = boundedPayloadRowCount(sizes, fetchLimit);
1844
- const rows = selected ? await query.selectAll().limit(selected).execute() : [];
1845
2115
  const minLog = await db.selectFrom("change_log").select("server_version").where("workspace_id", "=", scope.workspaceId).orderBy("server_version", "asc").limit(1).executeTakeFirst();
1846
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");
1847
2118
  const retention = computePullRetention({
1848
2119
  cursor,
1849
2120
  oldestLogVersion: minLog?.server_version ?? null,
1850
2121
  highWatermark: counter?.value ?? 0
1851
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() : [];
1852
2151
  const changes = [];
1853
- let itemBytes = 0;
2152
+ const unavailable = [];
1854
2153
  let scanned = 0;
2154
+ let itemBytes = 0;
1855
2155
  let nextCursor = cursor;
1856
- for (const row of rows.slice(0, fetchLimit)) {
1857
- const change = {
1858
- 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 = {
1859
2181
  tableName: row.table_name,
1860
2182
  pk: row.pk,
1861
- op: row.op,
1862
- payload: row.payload_json ? JSON.parse(row.payload_json) : void 0,
1863
- 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
1864
2187
  };
1865
- if (isNotificationVisibleToUser(change, resolveSessionUserId(event))) {
1866
- const bytes = jsonBytes(change) + (changes.length ? 1 : 0);
1867
- const envelope = jsonBytes({ changes: [], nextCursor: row.server_version, hasMore: false, ...retention });
1868
- if (changes.length && envelope + itemBytes + bytes > MAX_SYNC_PAGE_BYTES) break;
1869
- changes.push(change);
1870
- 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;
1871
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;
1872
2210
  scanned++;
1873
2211
  nextCursor = row.server_version;
1874
2212
  }
1875
- 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);
1876
2285
  }
1877
2286
  async snapshot(event, input) {
1878
2287
  return this.captureSnapshot(event, input, false);
1879
2288
  }
1880
2289
  /** Archives retain full Trash metadata; normal sync still emits tombstones. */
1881
2290
  async backupSnapshot(event, input) {
1882
- 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);
1883
2293
  }
1884
2294
  async captureSnapshot(event, input, retainedFiles) {
1885
2295
  const workspaceId = input.scope.workspaceId;
1886
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);
1887
2303
  const pageSize = resolveSnapshotPageSize(input.pageSize);
1888
2304
  const snapshotUserId = resolveSessionUserId(event);
1889
2305
  if (isD1Driver()) {
1890
- return this.snapshotInD1(workspaceId, input, pageSize, snapshotUserId, retainedFiles);
2306
+ return this.snapshotInD1(workspaceId, input, pageSize, snapshotUserId, retainedFiles, historyIncarnation);
1891
2307
  }
1892
2308
  const raw = getRawDb();
1893
2309
  const now = nowEpoch();
1894
2310
  let header;
1895
2311
  let after;
1896
2312
  if (input.pageToken) {
1897
- if (input.pageToken.length > 4096) {
2313
+ if (input.pageToken.length > MAX_SYNC_SNAPSHOT_TOKEN_LENGTH) {
1898
2314
  throw createError({
1899
2315
  statusCode: 400,
1900
2316
  statusMessage: "Invalid snapshot page token"
@@ -1963,6 +2379,10 @@ export class SqliteSyncGatewayAdapter {
1963
2379
  now,
1964
2380
  expiresAt
1965
2381
  );
2382
+ if (tables.includes("notifications")) {
2383
+ const evidence = unknownNotificationEvidence(workspaceId);
2384
+ raw.prepare(evidence.sql).run(...evidence.parameters ?? []);
2385
+ }
1966
2386
  for (const tableName of tables) {
1967
2387
  const materializedTable = SYNCED_TABLE_MAP[tableName];
1968
2388
  if (!materializedTable) {
@@ -1998,11 +2418,11 @@ export class SqliteSyncGatewayAdapter {
1998
2418
  raw.prepare(`
1999
2419
  INSERT INTO sync_snapshot_items (
2000
2420
  snapshot_id, table_name, pk, kind, payload_json,
2001
- clock, hlc, op_id, server_deleted_at
2421
+ clock, hlc, op_id, server_deleted_at, source_payload_json
2002
2422
  )
2003
2423
  SELECT
2004
2424
  ?, ?, materialized.id, '${retainedFiles && tableName === "file_meta" ? "row" : "tombstone"}',
2005
- ${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"},
2006
2426
  materialized.clock,
2007
2427
  CASE
2008
2428
  WHEN materialized.hlc <> '' THEN materialized.hlc
@@ -2024,7 +2444,8 @@ export class SqliteSyncGatewayAdapter {
2024
2444
  materialized.updated_at,
2025
2445
  materialized.created_at,
2026
2446
  0
2027
- ))
2447
+ )),
2448
+ ${retainedFiles && tableName === "file_meta" ? "materialized.data_json" : "NULL"}
2028
2449
  FROM "${materializedTable}" AS materialized
2029
2450
  WHERE materialized.workspace_id = ? AND materialized.deleted <> 0${deletedOwner.sql}
2030
2451
  `).run(snapshotId, tableName, tableName, workspaceId, ...deletedOwner.params);
@@ -2065,14 +2486,20 @@ export class SqliteSyncGatewayAdapter {
2065
2486
  header = capture.immediate();
2066
2487
  }
2067
2488
  const selection = snapshotPageSelection(header.id, after);
2068
- 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);
2069
2490
  const selected = boundedPayloadRowCount(sizes, pageSize);
2070
- 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) : [];
2071
- 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);
2072
2498
  }
2073
2499
  async updateCursor(event, input) {
2074
2500
  await assertWorkspaceScopeAuthorized(event, input.scope.workspaceId);
2075
2501
  const now = nowEpoch();
2502
+ const historyIncarnation = await this.checkHistory(event, input);
2076
2503
  const deviceId = input.deviceId.trim();
2077
2504
  if (!deviceId || deviceId.length > 256) {
2078
2505
  throw createError({ statusCode: 400, statusMessage: "Invalid device cursor" });
@@ -2085,10 +2512,15 @@ export class SqliteSyncGatewayAdapter {
2085
2512
  throw createError({ statusCode: 401, statusMessage: "Unauthorized" });
2086
2513
  }
2087
2514
  if (isD1Driver()) {
2088
- return this.updateCursorInD1(input.scope.workspaceId, deviceId, input.version, ownerUserId, now);
2515
+ return this.updateCursorInD1(input.scope.workspaceId, deviceId, input.version, ownerUserId, now, historyIncarnation);
2089
2516
  }
2090
2517
  const raw = getRawDb();
2091
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
+ }
2092
2524
  const counter = raw.prepare(
2093
2525
  "SELECT value FROM server_version_counter WHERE workspace_id = ?"
2094
2526
  ).get(input.scope.workspaceId);
@@ -2112,7 +2544,7 @@ export class SqliteSyncGatewayAdapter {
2112
2544
  updated_at = excluded.updated_at`
2113
2545
  ).run(uid(), input.scope.workspaceId, deviceId, ownerUserId, input.version, now);
2114
2546
  });
2115
- update();
2547
+ update.immediate();
2116
2548
  }
2117
2549
  async gcTombstones(event, input) {
2118
2550
  await assertWorkspaceScopeAuthorized(event, input.scope.workspaceId);
@@ -2183,60 +2615,27 @@ export class SqliteSyncGatewayAdapter {
2183
2615
  }
2184
2616
  if (!canRunSyncHistoryGc()) return;
2185
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;
2186
2627
  if (isD1Driver()) {
2187
2628
  await d1Batch([
2188
- {
2189
- sql: `DELETE FROM device_cursors
2190
- WHERE workspace_id = ? AND updated_at < ?`,
2191
- parameters: [input.scope.workspaceId, cutoff]
2192
- },
2193
- {
2194
- sql: `DELETE FROM change_log
2195
- WHERE workspace_id = ?
2196
- AND created_at < ?
2197
- AND (
2198
- NOT EXISTS (
2199
- SELECT 1 FROM device_cursors
2200
- WHERE workspace_id = ?
2201
- )
2202
- OR server_version <= (
2203
- SELECT MIN(last_seen_version)
2204
- FROM device_cursors
2205
- WHERE workspace_id = ?
2206
- )
2207
- )`,
2208
- parameters: [
2209
- input.scope.workspaceId,
2210
- cutoff,
2211
- input.scope.workspaceId,
2212
- input.scope.workspaceId
2213
- ]
2214
- }
2629
+ { sql: "DELETE FROM device_cursors WHERE workspace_id = ? AND updated_at < ?", parameters: [workspaceId, cutoff] },
2630
+ { sql: deletePrefix, parameters: [workspaceId, workspaceId, cutoff, workspaceId] }
2215
2631
  ]);
2216
2632
  return;
2217
2633
  }
2218
2634
  const raw = getRawDb();
2219
2635
  raw.transaction(() => {
2220
- raw.prepare(
2221
- `DELETE FROM device_cursors
2222
- WHERE workspace_id = ? AND updated_at < ?`
2223
- ).run(input.scope.workspaceId, cutoff);
2224
- const cursor = raw.prepare(
2225
- `SELECT MIN(last_seen_version) AS min_version
2226
- FROM device_cursors WHERE workspace_id = ?`
2227
- ).get(input.scope.workspaceId);
2228
- if (cursor.min_version === null) {
2229
- raw.prepare(
2230
- `DELETE FROM change_log
2231
- WHERE workspace_id = ? AND created_at < ?`
2232
- ).run(input.scope.workspaceId, cutoff);
2233
- } else {
2234
- raw.prepare(
2235
- `DELETE FROM change_log
2236
- WHERE workspace_id = ? AND created_at < ? AND server_version <= ?`
2237
- ).run(input.scope.workspaceId, cutoff, cursor.min_version);
2238
- }
2239
- })();
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();
2240
2639
  }
2241
2640
  async reserveUploadIntentInD1(input, hash) {
2242
2641
  const now = nowEpoch();
@@ -2285,12 +2684,12 @@ export class SqliteSyncGatewayAdapter {
2285
2684
  throw createError({ statusCode: 413, statusMessage: "Workspace storage quota exceeded" });
2286
2685
  }
2287
2686
  }
2288
- async snapshotInD1(workspaceId, input, pageSize, snapshotUserId, retainedFiles) {
2687
+ async snapshotInD1(workspaceId, input, pageSize, snapshotUserId, retainedFiles, historyIncarnation) {
2289
2688
  const now = nowEpoch();
2290
2689
  let header;
2291
2690
  let after;
2292
2691
  if (input.pageToken) {
2293
- if (input.pageToken.length > 4096) {
2692
+ if (input.pageToken.length > MAX_SYNC_SNAPSHOT_TOKEN_LENGTH) {
2294
2693
  throw createError({ statusCode: 400, statusMessage: "Invalid snapshot page token" });
2295
2694
  }
2296
2695
  const token = decodeSnapshotPageToken(input.pageToken);
@@ -2355,6 +2754,7 @@ export class SqliteSyncGatewayAdapter {
2355
2754
  ]
2356
2755
  }
2357
2756
  ];
2757
+ if (tables.includes("notifications")) statements.push(unknownNotificationEvidence(workspaceId));
2358
2758
  for (const tableName of tables) {
2359
2759
  const materializedTable = SYNCED_TABLE_MAP[tableName];
2360
2760
  if (!materializedTable) {
@@ -2393,11 +2793,11 @@ export class SqliteSyncGatewayAdapter {
2393
2793
  {
2394
2794
  sql: `INSERT INTO sync_snapshot_items (
2395
2795
  snapshot_id, table_name, pk, kind, payload_json,
2396
- clock, hlc, op_id, server_deleted_at
2796
+ clock, hlc, op_id, server_deleted_at, source_payload_json
2397
2797
  )
2398
2798
  SELECT
2399
2799
  ?, ?, materialized.id, '${retainedFiles && tableName === "file_meta" ? "row" : "tombstone"}',
2400
- ${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"},
2401
2801
  materialized.clock,
2402
2802
  CASE
2403
2803
  WHEN materialized.hlc <> '' THEN materialized.hlc
@@ -2419,7 +2819,8 @@ export class SqliteSyncGatewayAdapter {
2419
2819
  materialized.updated_at,
2420
2820
  materialized.created_at,
2421
2821
  0
2422
- ))
2822
+ )),
2823
+ ${retainedFiles && tableName === "file_meta" ? "materialized.data_json" : "NULL"}
2423
2824
  FROM "${materializedTable}" AS materialized
2424
2825
  WHERE materialized.workspace_id = ? AND materialized.deleted <> 0${deletedOwner.sql}`,
2425
2826
  parameters: [
@@ -2468,13 +2869,18 @@ export class SqliteSyncGatewayAdapter {
2468
2869
  }
2469
2870
  const selection = snapshotPageSelection(header.id, after);
2470
2871
  const sizes = await d1All(
2471
- `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}`,
2472
2873
  ...selection.parameters,
2473
2874
  pageSize + 1
2474
2875
  );
2475
2876
  const selected = boundedPayloadRowCount(sizes, pageSize);
2476
2877
  const rows = selected ? await d1All(
2477
- `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}`,
2478
2884
  ...selection.parameters,
2479
2885
  selected
2480
2886
  ) : [];
@@ -2485,9 +2891,9 @@ export class SqliteSyncGatewayAdapter {
2485
2891
  if (!retained || retained.expires_at <= nowEpoch()) {
2486
2892
  throw createError({ statusCode: 410, statusMessage: "Snapshot expired or unavailable" });
2487
2893
  }
2488
- return buildSnapshotPage(header, rows, pageSize, sizes.length);
2894
+ return buildSnapshotPage(header, rows, pageSize, sizes.length, historyIncarnation, after, snapshotUserId);
2489
2895
  }
2490
- async updateCursorInD1(workspaceId, deviceId, version, ownerUserId, now) {
2896
+ async updateCursorInD1(workspaceId, deviceId, version, ownerUserId, now, historyIncarnation) {
2491
2897
  const [counter] = await d1All(
2492
2898
  "SELECT value FROM server_version_counter WHERE workspace_id = ?",
2493
2899
  workspaceId
@@ -2505,49 +2911,58 @@ export class SqliteSyncGatewayAdapter {
2505
2911
  if (existing && version < existing.last_seen_version) {
2506
2912
  throw createError({ statusCode: 409, statusMessage: "Device cursor cannot regress" });
2507
2913
  }
2508
- const result = await d1Run(
2509
- `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 (
2510
2921
  id, workspace_id, device_id, owner_user_id, last_seen_version, updated_at
2511
2922
  ) VALUES (?, ?, ?, ?, ?, ?)
2512
2923
  ON CONFLICT(workspace_id, owner_user_id, device_id) DO UPDATE SET
2513
2924
  last_seen_version = excluded.last_seen_version,
2514
2925
  updated_at = excluded.updated_at
2515
2926
  WHERE excluded.last_seen_version >= device_cursors.last_seen_version`,
2516
- uid(),
2517
- workspaceId,
2518
- deviceId,
2519
- ownerUserId,
2520
- version,
2521
- now
2522
- );
2523
- 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) {
2524
2935
  throw createError({ statusCode: 409, statusMessage: "Device cursor changed concurrently" });
2525
2936
  }
2526
2937
  }
2527
2938
  async pushInD1(input) {
2528
- 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 }]));
2529
2941
  const existingOps = /* @__PURE__ */ new Map();
2530
- const opIds = uniqueOps.map((op) => op.stamp.opId);
2531
- for (let offset = 0; offset < opIds.length; offset += 500) {
2532
- const chunk = opIds.slice(offset, offset + 500);
2533
- if (chunk.length === 0) continue;
2534
- const placeholders = chunk.map(() => "?").join(",");
2535
- const rows = await d1All(
2536
- `SELECT op_id, server_version, workspace_id, table_name, pk, op,
2537
- payload_json, clock, hlc, device_id
2538
- FROM change_log WHERE op_id IN (${placeholders})`,
2539
- ...chunk
2540
- );
2541
- for (const row of rows) {
2542
- existingOps.set(row.op_id, {
2543
- server_version: row.server_version,
2544
- workspace_id: row.workspace_id,
2545
- fingerprint: changeLogFingerprint(row)
2546
- });
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;
2547
2962
  }
2548
2963
  }
2549
- const rejected = /* @__PURE__ */ new Set();
2550
2964
  for (const op of uniqueOps) {
2965
+ if (rejected.has(op.stamp.opId)) continue;
2551
2966
  const existing = existingOps.get(op.stamp.opId);
2552
2967
  if (!existing) continue;
2553
2968
  if (existing.workspace_id !== workspaceId || existing.fingerprint !== operationFingerprint(op)) {
@@ -2568,11 +2983,17 @@ export class SqliteSyncGatewayAdapter {
2568
2983
  const materializedTable = SYNCED_TABLE_MAP[op.tableName];
2569
2984
  if (!materializedTable) continue;
2570
2985
  const [owned] = await d1All(
2571
- `SELECT data_json FROM "${materializedTable}" WHERE id = ? AND workspace_id = ?`,
2986
+ `SELECT ${notificationOwnerSql("data_json")} AS owner FROM "${materializedTable}" WHERE id = ? AND workspace_id = ?`,
2572
2987
  op.pk,
2573
2988
  workspaceId
2574
2989
  );
2575
- 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
+ }
2576
2997
  if (owned && owner !== userId || !owned && op.operation === "delete") {
2577
2998
  rejected.add(op.stamp.opId);
2578
2999
  for (const index of indicesByOpId.get(op.stamp.opId) ?? []) {
@@ -2585,9 +3006,23 @@ export class SqliteSyncGatewayAdapter {
2585
3006
  }
2586
3007
  }
2587
3008
  }
2588
- const newOps = uniqueOps.filter(
2589
- (op) => !existingOps.has(op.stamp.opId) && !rejected.has(op.stamp.opId)
2590
- );
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
+ });
2591
3026
  const existingMaterializedKeys = /* @__PURE__ */ new Set();
2592
3027
  const opsByTable = /* @__PURE__ */ new Map();
2593
3028
  for (const op of newOps) {
@@ -2640,10 +3075,11 @@ export class SqliteSyncGatewayAdapter {
2640
3075
  }
2641
3076
  }
2642
3077
  const now = nowEpoch();
2643
- const statements = [];
3078
+ const statements = [historyAssertion(historyIncarnation)];
3079
+ if (input.repair) statements.push(repairAssertion(input.repair));
2644
3080
  if (input.workspaceItemCapability !== WORKSPACE_ITEM_CAPABILITY) {
2645
3081
  for (const op of uniqueOps) {
2646
- if (!["posts", "projects"].includes(op.tableName)) continue;
3082
+ if (rejected.has(op.stamp.opId) || !["posts", "projects"].includes(op.tableName)) continue;
2647
3083
  if (hasWorkspaceItemSemantics(op.tableName, op.payload)) {
2648
3084
  throw workspaceItemUpdateRequired();
2649
3085
  }
@@ -2657,6 +3093,12 @@ export class SqliteSyncGatewayAdapter {
2657
3093
  parameters: [workspaceId]
2658
3094
  });
2659
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
+ });
2660
3102
  const materializedStatementIndex = /* @__PURE__ */ new Map();
2661
3103
  const materializedWasExisting = /* @__PURE__ */ new Map();
2662
3104
  const seenMaterializedKeys = /* @__PURE__ */ new Set();
@@ -2673,14 +3115,14 @@ export class SqliteSyncGatewayAdapter {
2673
3115
  statements.push({
2674
3116
  sql: `INSERT INTO change_log (
2675
3117
  id, workspace_id, server_version, table_name, pk, op,
2676
- payload_json, clock, hlc, device_id, op_id, created_at
3118
+ payload_json, clock, hlc, device_id, op_id, created_at, intent_fingerprint
2677
3119
  ) SELECT
2678
3120
  ?, ?,
2679
3121
  (SELECT value + 1 FROM server_version_counter WHERE workspace_id = ?),
2680
- ?, ?, ?, ?, ?, ?, ?, ?, ?
3122
+ ?, ?, ?, ?, ?, ?, ?, ?, ?, ?
2681
3123
  ${op.tableName === "notifications" ? `WHERE NOT EXISTS (
2682
3124
  SELECT 1 FROM s_notifications WHERE id = ? AND workspace_id = ?
2683
- AND json_extract(data_json, '$.user_id') IS NOT ?
3125
+ AND ${notificationOwnerSql("data_json")} IS NOT ?
2684
3126
  )` : ""}`,
2685
3127
  parameters: [
2686
3128
  uid(),
@@ -2695,6 +3137,7 @@ export class SqliteSyncGatewayAdapter {
2695
3137
  op.stamp.deviceId,
2696
3138
  op.stamp.opId,
2697
3139
  now,
3140
+ intentFingerprints.get(op.stamp.opId),
2698
3141
  ...op.tableName === "notifications" ? [op.pk, workspaceId, userId] : []
2699
3142
  ]
2700
3143
  });
@@ -2719,7 +3162,7 @@ export class SqliteSyncGatewayAdapter {
2719
3162
  deleted = 0,
2720
3163
  updated_at = excluded.updated_at
2721
3164
  WHERE ${lwwExcludedWins(`"${materializedTable}"`)}
2722
- ${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')` : ""}`,
2723
3166
  parameters: [
2724
3167
  op.pk,
2725
3168
  workspaceId,
@@ -2745,7 +3188,8 @@ export class SqliteSyncGatewayAdapter {
2745
3188
  op_id = excluded.op_id,
2746
3189
  deleted = 1,
2747
3190
  updated_at = excluded.updated_at
2748
- WHERE ${lwwExcludedWins(`"${materializedTable}"`)}`,
3191
+ WHERE ${lwwExcludedWins(`"${materializedTable}"`)}
3192
+ ${op.tableName === "notifications" ? "AND EXISTS (SELECT 1 FROM change_log WHERE op_id=?)" : ""}`,
2749
3193
  parameters: [
2750
3194
  op.pk,
2751
3195
  workspaceId,
@@ -2754,18 +3198,19 @@ export class SqliteSyncGatewayAdapter {
2754
3198
  op.stamp.deviceId,
2755
3199
  op.stamp.opId,
2756
3200
  now,
2757
- now
3201
+ now,
3202
+ ...op.tableName === "notifications" ? [op.stamp.opId] : []
2758
3203
  ]
2759
3204
  });
2760
3205
  statements.push({
2761
3206
  sql: `INSERT INTO tombstones (
2762
3207
  id, workspace_id, table_name, pk, deleted_at, clock,
2763
3208
  hlc, op_id, server_version, created_at
2764
- ) VALUES (
3209
+ ) SELECT
2765
3210
  ?, ?, ?, ?, ?, ?, ?, ?,
2766
3211
  (SELECT value FROM server_version_counter WHERE workspace_id = ?),
2767
3212
  ?
2768
- )
3213
+ WHERE ${op.tableName === "notifications" ? "EXISTS (SELECT 1 FROM change_log WHERE op_id=?)" : "1"}
2769
3214
  ON CONFLICT(workspace_id, table_name, pk) DO UPDATE SET
2770
3215
  deleted_at = excluded.deleted_at,
2771
3216
  clock = excluded.clock,
@@ -2783,7 +3228,8 @@ export class SqliteSyncGatewayAdapter {
2783
3228
  op.stamp.hlc,
2784
3229
  op.stamp.opId,
2785
3230
  workspaceId,
2786
- now
3231
+ now,
3232
+ ...op.tableName === "notifications" ? [op.stamp.opId] : []
2787
3233
  ]
2788
3234
  });
2789
3235
  }
@@ -2797,9 +3243,13 @@ export class SqliteSyncGatewayAdapter {
2797
3243
  }
2798
3244
  let batchResults;
2799
3245
  try {
2800
- 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) : [];
2801
3247
  } catch (error) {
2802
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
+ }
2803
3253
  if (/JSON path/i.test(message) && message.includes(WORKSPACE_ITEM_UPDATE_REQUIRED)) {
2804
3254
  throw workspaceItemUpdateRequired();
2805
3255
  }
@@ -2819,6 +3269,7 @@ export class SqliteSyncGatewayAdapter {
2819
3269
  );
2820
3270
  finalServerVersion = counter?.value ?? 0;
2821
3271
  }
3272
+ const opIds = uniqueOps.filter((op) => !rejected.has(op.stamp.opId)).map((op) => op.stamp.opId);
2822
3273
  const resolvedOps = /* @__PURE__ */ new Map();
2823
3274
  for (let offset = 0; offset < opIds.length; offset += 500) {
2824
3275
  const chunk = opIds.slice(offset, offset + 500);
@@ -2833,81 +3284,75 @@ export class SqliteSyncGatewayAdapter {
2833
3284
  const emissions = [];
2834
3285
  for (const op of uniqueOps) {
2835
3286
  if (rejected.has(op.stamp.opId)) continue;
2836
- if (op.tableName === "notifications") {
2837
- const [owned] = await d1All(
2838
- "SELECT data_json FROM s_notifications WHERE id = ? AND workspace_id = ?",
2839
- op.pk,
2840
- workspaceId
2841
- );
2842
- 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
+ };
2843
3315
  for (const index of indicesByOpId.get(op.stamp.opId) ?? []) {
2844
- resultSlots[index] = { opId: op.stamp.opId, success: false, error: "Forbidden: notification owner mismatch", errorCode: "UNAUTHORIZED" };
3316
+ resultSlots[index] = result2;
2845
3317
  }
2846
3318
  continue;
2847
3319
  }
2848
- }
2849
- const existing = existingOps.get(op.stamp.opId);
2850
- if (existing) {
2851
- const winner = await currentWinnerD1(workspaceId, op.tableName, op.pk, userId);
2852
- const applied2 = winner?.revision.opId === op.stamp.opId;
2853
- 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 = {
2854
3329
  opId: op.stamp.opId,
2855
3330
  success: true,
2856
- serverVersion: existing.server_version,
2857
- replayed: true,
2858
- applied: applied2,
2859
- ...applied2 ? {} : { winner }
3331
+ serverVersion,
3332
+ applied,
3333
+ ...applied ? {} : { payload: winnerPayload },
3334
+ ...applied ? {} : {
3335
+ winner
3336
+ }
2860
3337
  };
2861
3338
  for (const index of indicesByOpId.get(op.stamp.opId) ?? []) {
2862
- resultSlots[index] = result2;
3339
+ resultSlots[index] = result;
2863
3340
  }
2864
- continue;
2865
- }
2866
- const serverVersion = resolvedOps.get(op.stamp.opId);
2867
- if (serverVersion === void 0) {
2868
- throw new Error(`D1 failed to resolve sync operation ${op.stamp.opId}.`);
2869
- }
2870
- const skipApply = skipMaterialize.has(op.stamp.opId);
2871
- const materializedResult = batchResults[materializedStatementIndex.get(op.stamp.opId) ?? -1];
2872
- const applied = !skipApply && (materializedResult?.meta?.changes ?? 0) > 0;
2873
- let winnerPayload;
2874
- if (!applied && !skipApply) {
2875
- const materializedTable = SYNCED_TABLE_MAP[op.tableName];
2876
- if (materializedTable) {
2877
- const [winner] = await d1All(
2878
- `SELECT data_json FROM "${materializedTable}" WHERE id = ? AND workspace_id = ?`,
2879
- op.pk,
2880
- workspaceId
2881
- );
2882
- if (winner?.data_json) {
2883
- const payload = JSON.parse(winner.data_json);
2884
- if (op.tableName !== "notifications" || notificationPayloadUserId(payload) === userId) winnerPayload = payload;
2885
- }
2886
- }
2887
- }
2888
- const result = {
2889
- opId: op.stamp.opId,
2890
- success: true,
2891
- serverVersion,
2892
- applied,
2893
- ...applied ? {} : { payload: winnerPayload },
2894
- ...applied ? {} : {
2895
- 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);
2896
3351
  }
2897
- };
2898
- for (const index of indicesByOpId.get(op.stamp.opId) ?? []) {
2899
- resultSlots[index] = result;
2900
- }
2901
- if (applied) {
2902
- const emission = resolveHookEmission({
2903
- op,
2904
- workspaceId,
2905
- now,
2906
- userId,
2907
- wasExisting: materializedWasExisting.get(op.stamp.opId) ?? false,
2908
- applied: true
2909
- });
2910
- 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;
2911
3356
  }
2912
3357
  }
2913
3358
  for (const emission of emissions) {
@@ -2917,7 +3362,8 @@ export class SqliteSyncGatewayAdapter {
2917
3362
  results: resultSlots.filter(
2918
3363
  (result) => Boolean(result)
2919
3364
  ),
2920
- serverVersion: finalServerVersion
3365
+ serverVersion: finalServerVersion,
3366
+ historyIncarnation
2921
3367
  };
2922
3368
  }
2923
3369
  async listWorkspaceIds() {