@syncular/client 0.86.0 → 0.90.0

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 (45) hide show
  1. package/README.md +3 -1
  2. package/dist/blob.d.ts +0 -4
  3. package/dist/blob.js +7 -22
  4. package/dist/client.d.ts +12 -1
  5. package/dist/client.js +441 -422
  6. package/dist/diagnostics.d.ts +2 -4
  7. package/dist/diagnostics.js +3 -17
  8. package/dist/encryption.js +2 -21
  9. package/dist/errors.d.ts +2 -0
  10. package/dist/errors.js +4 -0
  11. package/dist/failed-overlay.js +2 -2
  12. package/dist/local-purge.d.ts +1 -0
  13. package/dist/local-purge.js +1 -1
  14. package/dist/local-rebootstrap-receipt.js +2 -2
  15. package/dist/local-rebootstrap.js +1 -1
  16. package/dist/native-bridge.d.ts +6 -2
  17. package/dist/native-bridge.js +24 -11
  18. package/dist/outcomes.d.ts +11 -0
  19. package/dist/outcomes.js +19 -16
  20. package/dist/previous-version.js +23 -35
  21. package/dist/schema.js +14 -13
  22. package/dist/state.d.ts +16 -4
  23. package/dist/state.js +83 -44
  24. package/dist/worker-core.js +7 -8
  25. package/dist/worker-host.d.ts +5 -2
  26. package/dist/worker-host.js +9 -0
  27. package/dist/worker-protocol.d.ts +2 -1
  28. package/package.json +3 -3
  29. package/src/blob.ts +7 -24
  30. package/src/client.ts +615 -501
  31. package/src/diagnostics.ts +3 -19
  32. package/src/encryption.ts +7 -25
  33. package/src/errors.ts +5 -0
  34. package/src/failed-overlay.ts +2 -6
  35. package/src/local-purge.ts +1 -1
  36. package/src/local-rebootstrap-receipt.ts +2 -5
  37. package/src/local-rebootstrap.ts +1 -2
  38. package/src/native-bridge.ts +35 -13
  39. package/src/outcomes.ts +34 -25
  40. package/src/previous-version.ts +31 -40
  41. package/src/schema.ts +13 -13
  42. package/src/state.ts +107 -64
  43. package/src/worker-core.ts +9 -16
  44. package/src/worker-host.ts +17 -1
  45. package/src/worker-protocol.ts +2 -0
package/src/client.ts CHANGED
@@ -111,7 +111,6 @@ import {
111
111
  MAX_DIAGNOSTIC_QUERY_FAILURES,
112
112
  type RealtimePolicy,
113
113
  type RealtimeState,
114
- type TransportCauseKind,
115
114
  } from './diagnostics';
116
115
  import type { EncryptionConfig } from './encryption';
117
116
  import {
@@ -122,6 +121,7 @@ import {
122
121
  REALTIME_LOST_CODE,
123
122
  RealtimeUnavailableError,
124
123
  transportFailed,
124
+ localStateCorrupt,
125
125
  } from './errors';
126
126
  import {
127
127
  ChangeAccumulator,
@@ -189,6 +189,8 @@ import {
189
189
  type RetainedCommitRow,
190
190
  type ResolveCommitOutcomeInput,
191
191
  commitOutcome as readCommitOutcome,
192
+ type PendingDecision,
193
+ pendingDecisions,
192
194
  recordCommitOutcome,
193
195
  scrubPurgedOutcomes,
194
196
  } from './outcomes';
@@ -264,9 +266,11 @@ import {
264
266
  replicaCursor,
265
267
  saveUnit,
266
268
  saveUnitScopeSchema,
269
+ UNITS_TABLE,
267
270
  setMeta,
268
271
  type UnitRecord,
269
272
  unitOwners,
273
+ unitStateCorrupt,
270
274
  } from './state';
271
275
  import type {
272
276
  RealtimeConnector,
@@ -315,6 +319,13 @@ export type {
315
319
  ResolveCommitOutcomeInput,
316
320
  } from './outcomes';
317
321
 
322
+ /** §7.2.2: without `replacement`, the decision keeps the local intent. */
323
+ export interface ReplaceCommitOutcomeInput {
324
+ readonly clientCommitId: string;
325
+ readonly sequence: number;
326
+ readonly replacement?: readonly MutationInput[] | undefined;
327
+ }
328
+
318
329
  export interface SchemaFloor {
319
330
  readonly requiredSchemaVersion?: number;
320
331
  readonly latestSchemaVersion?: number;
@@ -730,6 +741,7 @@ const ACCEPT_SIGNED_URLS = 1 << 3;
730
741
  * Never a wire code (§10.3) — surfaced through the rejection channel.
731
742
  */
732
743
  const OUTBOX_INCOMPATIBLE_CODE = 'sync.outbox_incompatible';
744
+ const REPLACEMENT_REFUSED_CODE = 'sync.replacement_refused';
733
745
  /** §7.4.4: static text for a persisted commit the current codec refuses. */
734
746
  const LEGACY_VALUE_REFUSAL_MESSAGE =
735
747
  'the persisted commit carries values the current codec refuses';
@@ -741,19 +753,67 @@ const INVALID_STORED_VALUES_REASON = 'invalid_stored_values';
741
753
  * commit order up to this cap and defers the rest to the next round. */
742
754
  const MAX_OPS_PER_REQUEST = 500;
743
755
 
744
- async function sha256Hex(bytes: Uint8Array): Promise<string> {
745
- const digest = await crypto.subtle.digest(
746
- 'SHA-256',
747
- bytes.slice().buffer as ArrayBuffer,
748
- );
749
- return [...new Uint8Array(digest)]
750
- .map((b) => b.toString(16).padStart(2, '0'))
751
- .join('');
752
- }
753
-
754
756
  const invalidHostResponse = (message: string) =>
755
757
  new ClientSyncError('client.invalid_host_response', message);
756
758
 
759
+ /** A field of the structured `details` any thrown value carries. */
760
+ const errorDetail = (error: unknown, key: string): unknown => {
761
+ const details =
762
+ typeof error === 'object' && error !== null && 'details' in error
763
+ ? error.details
764
+ : undefined;
765
+ return typeof details === 'object' && details !== null
766
+ ? (details as Readonly<Record<string, unknown>>)[key]
767
+ : undefined;
768
+ };
769
+
770
+ /** §4.6: the unit state a reset, revocation or rearm starts over from. */
771
+ const UNIT_RESTART = {
772
+ cursor: -1,
773
+ bootstrapState: undefined,
774
+ seeded: [],
775
+ restrict: undefined,
776
+ } as const;
777
+
778
+ /** An overlay row key (`JSON [table,rowId]`). */
779
+ const rowKey = (operation: OutboxOperation) =>
780
+ JSON.stringify([operation.table, operation.rowId]);
781
+
782
+ const unproven = (
783
+ reason: Extract<CurrentBaseProof, { proven: false }>['reason'],
784
+ ): CurrentBaseProof => ({ proven: false, reason });
785
+
786
+ const replacementPending = () =>
787
+ new ClientSyncError(
788
+ 'client.replacement_pending',
789
+ 'the outcome has a pending replacement',
790
+ false,
791
+ );
792
+
793
+ /** §7.2.1: an active failure with a complete retained aggregate. */
794
+ const provable = (
795
+ candidate: CommitOutcome | undefined,
796
+ sequence: number,
797
+ ): candidate is CommitOutcome & {
798
+ readonly operations: readonly OutboxOperation[];
799
+ readonly retainedRows: readonly RetainedCommitRow[];
800
+ } =>
801
+ candidate !== undefined &&
802
+ candidate.sequence === sequence &&
803
+ candidate.resolution === 'active' &&
804
+ (candidate.status === 'conflict' || candidate.status === 'rejected') &&
805
+ candidate.operations !== undefined &&
806
+ candidate.retainedRows !== undefined &&
807
+ candidate.operations.length === candidate.retainedRows.length &&
808
+ candidate.retainedRows.length > 0;
809
+
810
+ interface DriveStart {
811
+ readonly before: readonly UnitRecord[];
812
+ readonly epoch: number;
813
+ readonly registrationEpoch: number;
814
+ readonly securityEpoch: number;
815
+ }
816
+
757
817
  const outcomeNotFound = () =>
758
818
  new ClientSyncError(
759
819
  'sync.outcome_not_found',
@@ -900,8 +960,8 @@ function isFinalPushResult(frame: PushResultFrame): boolean {
900
960
  );
901
961
  }
902
962
 
903
- /** The stable `code` of a thrown realtime transport error, when it has one. */
904
- function realtimeErrorCode(error: unknown): string | undefined {
963
+ /** The stable `code` a thrown value carries, when it has one. */
964
+ function thrownCode(error: unknown): string | undefined {
905
965
  const code = (error as { code?: unknown } | undefined)?.code;
906
966
  return typeof code === 'string' ? code : undefined;
907
967
  }
@@ -918,6 +978,7 @@ export type ClientSnapshotMethods = Pick<
918
978
  | 'commitOutcome'
919
979
  | 'commitOutcomes'
920
980
  | 'resolveCommitOutcome'
981
+ | 'commitDelivery'
921
982
  >;
922
983
 
923
984
  /** Project a method contract across an asynchronous host boundary. */
@@ -1099,21 +1160,18 @@ export class SyncClient {
1099
1160
  throw invalidRequest('transportEnabled must be a boolean');
1100
1161
  }
1101
1162
  this.#transportEnabled = config.transportEnabled !== false;
1102
- for (const [name, value] of [
1103
- ['maxPushCommitsPerRequest', config.limits?.maxPushCommitsPerRequest],
1104
- [
1105
- 'maxPushOperationsPerRequest',
1106
- config.limits?.maxPushOperationsPerRequest,
1107
- ],
1108
- ['maxPushRequestBytes', config.limits?.maxPushRequestBytes],
1109
- ['segmentPrefetch', config.limits?.segmentPrefetch],
1163
+ for (const name of [
1164
+ 'maxPushCommitsPerRequest',
1165
+ 'maxPushOperationsPerRequest',
1166
+ 'maxPushRequestBytes',
1167
+ 'segmentPrefetch',
1110
1168
  ] as const) {
1169
+ const value = config.limits?.[name];
1111
1170
  if (
1112
1171
  value !== undefined &&
1113
1172
  (!Number.isInteger(value) || value < 1 || value > 0xffffffff)
1114
1173
  ) {
1115
- throw new ClientSyncError(
1116
- 'sync.invalid_request',
1174
+ throw invalidRequest(
1117
1175
  'limit must be an integer in 1..=4294967295',
1118
1176
  false,
1119
1177
  { limit: name },
@@ -1224,39 +1282,35 @@ export class SyncClient {
1224
1282
  "SELECT type FROM sqlite_master WHERE name = '_syncular_meta'",
1225
1283
  )[0];
1226
1284
  if (meta !== undefined) {
1227
- if (meta.type !== 'table')
1228
- throw new Error('invalid metadata table');
1229
- const rows = this.#db.query(
1230
- 'SELECT value FROM _syncular_meta WHERE key = ?',
1231
- [LOCAL_SCHEMA_VERSION_KEY],
1232
- );
1233
- // A duplicated marker cannot be resolved. Picking one row could
1234
- // select an older version and drive a destructive reset over a
1235
- // newer replica.
1236
- if (rows.length > 1) throw new Error('invalid schema marker');
1237
- const row = rows[0];
1285
+ const rows =
1286
+ meta.type === 'table'
1287
+ ? this.#db.query(
1288
+ 'SELECT value FROM _syncular_meta WHERE key = ?',
1289
+ [LOCAL_SCHEMA_VERSION_KEY],
1290
+ )
1291
+ : undefined;
1292
+ const value = rows?.[0]?.value;
1293
+ const version = Number(value);
1294
+ // The catch below turns each refusal into `sync.local_corrupt`.
1238
1295
  if (
1239
- row === undefined &&
1240
- this.#db.query(
1241
- "SELECT 1 FROM _syncular_meta WHERE key = 'localSchemaDescriptor' LIMIT 1",
1242
- ).length > 0
1243
- ) {
1244
- throw new Error('missing paired schema marker');
1245
- }
1246
- if (row !== undefined) {
1247
- const value = row.value;
1248
- const version = Number(value);
1249
- if (
1250
- typeof value !== 'string' ||
1251
- !Number.isInteger(version) ||
1252
- version < 1 ||
1253
- version > 2147483647 ||
1254
- String(version) !== value
1255
- ) {
1256
- throw new Error('invalid schema marker');
1257
- }
1258
- marker = version;
1259
- }
1296
+ rows === undefined ||
1297
+ // A duplicated marker cannot be resolved. Picking one row could
1298
+ // select an older version and drive a destructive reset over a
1299
+ // newer replica.
1300
+ rows.length > 1 ||
1301
+ (value === undefined
1302
+ ? // A descriptor without its paired marker.
1303
+ this.#db.query(
1304
+ "SELECT 1 FROM _syncular_meta WHERE key = 'localSchemaDescriptor' LIMIT 1",
1305
+ ).length > 0
1306
+ : typeof value !== 'string' ||
1307
+ !Number.isInteger(version) ||
1308
+ version < 1 ||
1309
+ version > 2147483647 ||
1310
+ String(version) !== value)
1311
+ )
1312
+ throw new Error('invalid schema marker');
1313
+ if (value !== undefined) marker = version;
1260
1314
  }
1261
1315
  } catch (error) {
1262
1316
  // A recognized SQLite storage failure (including BUSY/LOCKED
@@ -1264,8 +1318,7 @@ export class SyncClient {
1264
1318
  // or otherwise unreadable marker is `sync.local_corrupt`.
1265
1319
  const failure = classifySqliteFailure(error);
1266
1320
  if (failure.code !== undefined) throw failure.error;
1267
- throw new ClientSyncError(
1268
- 'sync.local_corrupt',
1321
+ throw localStateCorrupt(
1269
1322
  'persisted local schema marker is unreadable or invalid',
1270
1323
  );
1271
1324
  }
@@ -1348,7 +1401,6 @@ export class SyncClient {
1348
1401
  if (this.#securityLifecycle === 'active' && this.#hasStartupWork()) {
1349
1402
  this.#needsPull = true;
1350
1403
  this.#emitSyncNeeded('startup');
1351
- this.#emitSyncIntent({ kind: 'interactive' });
1352
1404
  }
1353
1405
  // Console introspection is a no-op outside a dev page.
1354
1406
  this.#devtoolsUnregister = this.#config.devtools?.({
@@ -1376,32 +1428,23 @@ export class SyncClient {
1376
1428
  * marker, so the shape chosen here commits under that snapshot.
1377
1429
  */
1378
1430
  #detectAndResetSchema(marker: number | undefined): void {
1379
- if (marker === undefined) {
1380
- // Fresh install: the tables just created match the running code.
1381
- this.#db.transaction(() => {
1382
- ensureLocalSyncedSchema(this.#db, this.#schema);
1431
+ if (marker !== undefined && marker !== this.#schema.version)
1432
+ return this.#runSchemaReset();
1433
+ // A fresh install's tables just created match the running code. Same-version
1434
+ // opens remain self-healing for absent tables/indexes, and RFC 0005 D1
1435
+ // backfills the descriptor for a database first opened by 0.22.0 or
1436
+ // earlier WITHOUT a schema bump.
1437
+ this.#db.transaction(() => {
1438
+ ensureLocalSyncedSchema(this.#db, this.#schema);
1439
+ if (marker === undefined)
1383
1440
  setMeta(
1384
1441
  this.#db,
1385
1442
  LOCAL_SCHEMA_VERSION_KEY,
1386
1443
  String(this.#schema.version),
1387
1444
  );
1388
- setLocalSchemaDescriptor(this.#db, this.#schema);
1389
- saveUnitScopeSchema(this.#db, this.#schema);
1390
- });
1391
- return;
1392
- }
1393
- if (marker === this.#schema.version) {
1394
- // Same-version opens remain self-healing for absent tables/indexes, and
1395
- // RFC 0005 D1 backfills the descriptor for a database first opened by
1396
- // 0.22.0 or earlier WITHOUT a schema bump.
1397
- this.#db.transaction(() => {
1398
- ensureLocalSyncedSchema(this.#db, this.#schema);
1399
- setLocalSchemaDescriptor(this.#db, this.#schema);
1400
- saveUnitScopeSchema(this.#db, this.#schema);
1401
- });
1402
- return;
1403
- }
1404
- this.#runSchemaReset();
1445
+ setLocalSchemaDescriptor(this.#db, this.#schema);
1446
+ saveUnitScopeSchema(this.#db, this.#schema);
1447
+ });
1405
1448
  }
1406
1449
 
1407
1450
  /**
@@ -1532,9 +1575,7 @@ export class SyncClient {
1532
1575
  #runLogEpochReset(logEpoch: string): string[] {
1533
1576
  if (getMeta(this.#db, LOG_EPOCH_META_KEY) === undefined) {
1534
1577
  this.#applyBatch(() => setMeta(this.#db, LOG_EPOCH_META_KEY, logEpoch));
1535
- this.#setSyncNeeded(true);
1536
1578
  this.#emitSyncNeeded('startup');
1537
- this.#emitSyncIntent({ kind: 'interactive' });
1538
1579
  return [];
1539
1580
  }
1540
1581
  const units = loadUnits(this.#db);
@@ -1568,9 +1609,7 @@ export class SyncClient {
1568
1609
  },
1569
1610
  );
1570
1611
  this.#localResetEpoch += 1;
1571
- this.#setSyncNeeded(true);
1572
1612
  this.#emitSyncNeeded('startup');
1573
- this.#emitSyncIntent({ kind: 'interactive' });
1574
1613
  return units.map((unit) => unit.id);
1575
1614
  }
1576
1615
 
@@ -1614,32 +1653,32 @@ export class SyncClient {
1614
1653
  this.#syncIntentListeners.clear();
1615
1654
  }
1616
1655
 
1656
+ /** Mark a pull as needed and tell the host; a startup wake also asks for
1657
+ * an interactive round. */
1617
1658
  #emitSyncNeeded(reason: 'startup' | 'hello' | WakeReason): void {
1659
+ this.#setSyncNeeded(true);
1618
1660
  if (!this.#transportEnabled) return;
1619
- try {
1620
- this.#config.onSyncNeeded?.(reason);
1621
- } catch {
1622
- // An observer cannot alter sync correctness.
1623
- }
1624
- for (const listener of this.#syncNeededListeners) {
1661
+ for (const listener of [
1662
+ this.#config.onSyncNeeded,
1663
+ ...this.#syncNeededListeners,
1664
+ ]) {
1625
1665
  try {
1626
- listener(reason);
1666
+ listener?.(reason);
1627
1667
  } catch {
1628
1668
  // An observer cannot alter sync correctness.
1629
1669
  }
1630
1670
  }
1671
+ if (reason === 'startup') this.#emitSyncIntent({ kind: 'interactive' });
1631
1672
  }
1632
1673
 
1633
1674
  #emitSyncIntent(intent: SyncIntent): void {
1634
1675
  if (!this.#transportEnabled && intent.kind !== 'none') return;
1635
- try {
1636
- this.#config.onSyncIntent?.(intent);
1637
- } catch {
1638
- // An observer cannot alter sync correctness.
1639
- }
1640
- for (const listener of this.#syncIntentListeners) {
1676
+ for (const listener of [
1677
+ this.#config.onSyncIntent,
1678
+ ...this.#syncIntentListeners,
1679
+ ]) {
1641
1680
  try {
1642
- listener(intent);
1681
+ listener?.(intent);
1643
1682
  } catch {
1644
1683
  // An observer cannot alter sync correctness.
1645
1684
  }
@@ -1696,16 +1735,11 @@ export class SyncClient {
1696
1735
  this.#syncOutstanding = false;
1697
1736
  })();
1698
1737
  this.#preflightBarrier = barrier;
1699
- void barrier.then(
1700
- () => {
1701
- if (this.#preflightBarrier === barrier)
1702
- this.#preflightBarrier = undefined;
1703
- },
1704
- () => {
1705
- if (this.#preflightBarrier === barrier)
1706
- this.#preflightBarrier = undefined;
1707
- },
1708
- );
1738
+ const release = () => {
1739
+ if (this.#preflightBarrier === barrier)
1740
+ this.#preflightBarrier = undefined;
1741
+ };
1742
+ void barrier.then(release, release);
1709
1743
  return barrier;
1710
1744
  }
1711
1745
 
@@ -1731,9 +1765,7 @@ export class SyncClient {
1731
1765
  });
1732
1766
  await this.#serialize(() => this.#revealSealed());
1733
1767
  if (this.#hasStartupWork()) {
1734
- this.#setSyncNeeded(true);
1735
1768
  this.#emitSyncNeeded('startup');
1736
- this.#emitSyncIntent({ kind: 'interactive' });
1737
1769
  }
1738
1770
  }
1739
1771
 
@@ -1882,11 +1914,7 @@ export class SyncClient {
1882
1914
  const unit = getUnit(this.#db, id);
1883
1915
  if (unit === undefined) return { state: 'unknown', id };
1884
1916
  const cursor = unit.cursor ?? replicaCursor(this.#db);
1885
- if (!Number.isSafeInteger(cursor))
1886
- throw new ClientSyncError(
1887
- 'sync.local_corrupt',
1888
- 'persisted unit state is invalid',
1889
- );
1917
+ if (!Number.isSafeInteger(cursor)) throw unitStateCorrupt();
1890
1918
  const active = unit.status === 'active';
1891
1919
  const pending = bootstrapping(unit);
1892
1920
  return definedObject({
@@ -2002,45 +2030,32 @@ export class SyncClient {
2002
2030
  return this.#previousVersionUnavailable(currentVersion, 'not-configured');
2003
2031
  }
2004
2032
  const record = this.#readPreviousVersionRecord();
2005
- const nowMs = this.#now();
2006
- if (this.#previousVersionLeaseInactive(nowMs)) {
2007
- this.#discardPreviousVersion();
2008
- return this.#previousVersionUnavailable(currentVersion, 'lease-inactive');
2009
- }
2010
- if (loadUnits(this.#db).some((unit) => unit.status === 'revoked')) {
2011
- this.#discardPreviousVersion();
2012
- return this.#previousVersionUnavailable(currentVersion, 'scope-revoked');
2013
- }
2014
2033
  // Coverage completion is a live predicate: the container is normally
2015
2034
  // dropped by the sync path first, so a read can be the first observer.
2016
- if (this.#previousVersionCoverageComplete()) {
2035
+ const nowMs = this.#now();
2036
+ const ended = this.#previousVersionLeaseInactive(nowMs)
2037
+ ? 'lease-inactive'
2038
+ : loadUnits(this.#db).some((unit) => unit.status === 'revoked')
2039
+ ? 'scope-revoked'
2040
+ : this.#previousVersionCoverageComplete()
2041
+ ? 'coverage-complete'
2042
+ : record === undefined
2043
+ ? undefined
2044
+ : record.currentVersion !== currentVersion
2045
+ ? 'no-previous-descriptor'
2046
+ : this.#previousVersionExpired(record, nowMs)
2047
+ ? 'expired'
2048
+ : undefined;
2049
+ if (ended !== undefined) {
2017
2050
  this.#discardPreviousVersion();
2018
- return this.#previousVersionUnavailable(
2019
- currentVersion,
2020
- 'coverage-complete',
2021
- );
2051
+ return this.#previousVersionUnavailable(currentVersion, ended);
2022
2052
  }
2023
- if (record === undefined) {
2024
- const refusal = storedPreviousVersionRefusal(this.#db);
2053
+ if (record === undefined)
2025
2054
  return this.#previousVersionUnavailable(
2026
2055
  currentVersion,
2027
- refusal?.reason ?? 'no-previous-descriptor',
2028
- );
2029
- }
2030
- if (record.currentVersion !== currentVersion) {
2031
- this.#discardPreviousVersion();
2032
- return this.#previousVersionUnavailable(
2033
- currentVersion,
2034
- 'no-previous-descriptor',
2056
+ storedPreviousVersionRefusal(this.#db)?.reason ??
2057
+ 'no-previous-descriptor',
2035
2058
  );
2036
- }
2037
- if (
2038
- nowMs - record.createdAtMs >
2039
- previousVersionMaxAgeMs(this.#config.previousVersionContext)
2040
- ) {
2041
- this.#discardPreviousVersion();
2042
- return this.#previousVersionUnavailable(currentVersion, 'expired');
2043
- }
2044
2059
  const table = record.tables.find((entry) => entry.name === spec.table);
2045
2060
  if (table === undefined) {
2046
2061
  throw invalidRequest(
@@ -2172,21 +2187,24 @@ export class SyncClient {
2172
2187
  return;
2173
2188
  }
2174
2189
  const record = this.#readPreviousVersionRecord();
2175
- if (record === undefined) return;
2176
- if (loadUnits(this.#db).some((unit) => unit.status === 'revoked')) {
2177
- this.#discardPreviousVersion();
2178
- return;
2179
- }
2180
2190
  if (
2191
+ record !== undefined &&
2192
+ (loadUnits(this.#db).some((unit) => unit.status === 'revoked') ||
2193
+ this.#previousVersionExpired(record, nowMs) ||
2194
+ this.#previousVersionCoverageComplete())
2195
+ )
2196
+ this.#discardPreviousVersion();
2197
+ }
2198
+
2199
+ /** RFC 0005 D7: the container outlived `previousVersionContext.maxAgeMs`. */
2200
+ #previousVersionExpired(
2201
+ record: PreviousVersionRecord,
2202
+ nowMs = this.#now(),
2203
+ ): boolean {
2204
+ return (
2181
2205
  nowMs - record.createdAtMs >
2182
2206
  previousVersionMaxAgeMs(this.#config.previousVersionContext)
2183
- ) {
2184
- this.#discardPreviousVersion();
2185
- return;
2186
- }
2187
- if (this.#previousVersionCoverageComplete()) {
2188
- this.#discardPreviousVersion();
2189
- }
2207
+ );
2190
2208
  }
2191
2209
 
2192
2210
  /**
@@ -2197,18 +2215,13 @@ export class SyncClient {
2197
2215
  #reconcilePreviousVersionAtBoot(): void {
2198
2216
  if (!this.#previousVersionExists()) return;
2199
2217
  const record = this.#readPreviousVersionRecord();
2200
- let discard =
2201
- record === undefined || record.currentVersion !== this.#schema.version;
2202
2218
  if (
2203
- !discard &&
2204
- record !== undefined &&
2205
- this.#previousVersion !== undefined &&
2206
- this.#now() - record.createdAtMs >
2207
- previousVersionMaxAgeMs(this.#config.previousVersionContext)
2208
- ) {
2209
- discard = true;
2210
- }
2211
- if (discard) this.#dropPreviousVersion();
2219
+ record === undefined ||
2220
+ record.currentVersion !== this.#schema.version ||
2221
+ (this.#previousVersion !== undefined &&
2222
+ this.#previousVersionExpired(record))
2223
+ )
2224
+ this.#dropPreviousVersion();
2212
2225
  }
2213
2226
 
2214
2227
  // -- live-query invalidation ----------------------------------------------
@@ -2386,13 +2399,14 @@ export class SyncClient {
2386
2399
  : 0;
2387
2400
  const pressure =
2388
2401
  blobBytes > (this.#config.limits?.blobCacheMaxBytes ?? Infinity);
2402
+ const size = (value: unknown) => Math.max(0, Number(value ?? 0));
2389
2403
  return {
2390
2404
  status: pressure ? 'pressure' : 'healthy',
2391
2405
  databaseBytesApprox: Math.max(0, pageCount * pageSize),
2392
- pendingOutboxBytesApprox: Math.max(0, Number(sums?.outbox ?? 0)),
2393
- retainedOutcomeBytesApprox: Math.max(0, Number(sums?.bytes ?? 0)),
2394
- retainedOutcomeEntries: Math.max(0, Number(sums?.entries ?? 0)),
2395
- blobCacheBytesApprox: Math.max(0, blobBytes),
2406
+ pendingOutboxBytesApprox: size(sums?.outbox),
2407
+ retainedOutcomeBytesApprox: size(sums?.bytes),
2408
+ retainedOutcomeEntries: size(sums?.entries),
2409
+ blobCacheBytesApprox: size(blobBytes),
2396
2410
  ...(pressure
2397
2411
  ? { pressureReasonCode: 'client.blob_cache_over_limit' as const }
2398
2412
  : {}),
@@ -2699,8 +2713,7 @@ export class SyncClient {
2699
2713
  cached.byteLength !== cached.bytes.byteLength ||
2700
2714
  (await computeBlobId(cached.bytes)) !== pending.blobId
2701
2715
  ) {
2702
- throw new ClientSyncError(
2703
- 'sync.local_corrupt',
2716
+ throw localStateCorrupt(
2704
2717
  'Pending blob upload body is missing or corrupt',
2705
2718
  );
2706
2719
  }
@@ -2821,67 +2834,68 @@ export class SyncClient {
2821
2834
  ): Promise<CurrentBaseProof> {
2822
2835
  this.#requireActive();
2823
2836
  requireRoundBudget(maxRounds);
2824
- const { clientCommitId, sequence } = outcome;
2825
- const provable = (
2826
- candidate: CommitOutcome | undefined,
2827
- ): candidate is CommitOutcome & {
2828
- readonly retainedRows: readonly RetainedCommitRow[];
2829
- } =>
2830
- candidate !== undefined &&
2831
- candidate.sequence === sequence &&
2832
- candidate.resolution === 'active' &&
2833
- (candidate.status === 'conflict' || candidate.status === 'rejected') &&
2834
- candidate.operations !== undefined &&
2835
- candidate.retainedRows !== undefined &&
2836
- candidate.operations.length === candidate.retainedRows.length &&
2837
- candidate.retainedRows.length > 0;
2838
2837
  let initial: CommitOutcome | undefined;
2839
2838
  try {
2840
- initial = readCommitOutcome(this.#db, clientCommitId);
2839
+ initial = readCommitOutcome(this.#db, outcome.clientCommitId);
2841
2840
  } catch {
2842
- return { proven: false, reason: 'snapshot_failed' };
2841
+ return unproven('snapshot_failed');
2843
2842
  }
2844
- if (!provable(initial))
2845
- return { proven: false, reason: 'outcome_unavailable' };
2846
- if (!this.#transportEnabled) return { proven: false, reason: 'offline' };
2843
+ if (!provable(initial, outcome.sequence))
2844
+ return unproven('outcome_unavailable');
2845
+ if (!this.#transportEnabled) return unproven('offline');
2847
2846
  await this.#opChain;
2848
- if (!this.#transportEnabled) return { proven: false, reason: 'offline' };
2849
- const epoch = this.#transportEpoch;
2850
- const registrationEpoch = this.#registrationEpoch;
2851
- const securityEpoch = this.#securityEpoch;
2852
- let before: UnitRecord[];
2847
+ if (!this.#transportEnabled) return unproven('offline');
2848
+ let start: DriveStart;
2853
2849
  try {
2854
- before = loadUnits(this.#db);
2850
+ start = this.#driveStart();
2855
2851
  } catch {
2856
- return { proven: false, reason: 'snapshot_failed' };
2852
+ return unproven('snapshot_failed');
2857
2853
  }
2858
2854
  let report: SyncIdleResult;
2859
2855
  try {
2860
2856
  report = await this.syncUntilIdle(maxRounds);
2861
2857
  } catch {
2862
- return {
2863
- proven: false,
2864
- reason:
2865
- !this.#transportEnabled || epoch !== this.#transportEpoch
2866
- ? 'offline'
2867
- : registrationEpoch !== this.#registrationEpoch
2868
- ? 'missing_coverage'
2869
- : 'sync_failed',
2870
- };
2858
+ return unproven(
2859
+ !this.#transportEnabled || start.epoch !== this.#transportEpoch
2860
+ ? 'offline'
2861
+ : start.registrationEpoch !== this.#registrationEpoch
2862
+ ? 'missing_coverage'
2863
+ : 'sync_failed',
2864
+ );
2871
2865
  }
2866
+ return this.#provenBase(outcome, start, report);
2867
+ }
2868
+
2869
+ /** The drive state a §7.2.1 proof compares against after the drive. */
2870
+ #driveStart(): DriveStart {
2871
+ return {
2872
+ before: loadUnits(this.#db),
2873
+ epoch: this.#transportEpoch,
2874
+ registrationEpoch: this.#registrationEpoch,
2875
+ securityEpoch: this.#securityEpoch,
2876
+ };
2877
+ }
2878
+
2879
+ /** §7.2.1: the proof after a completed drive that began at `start`. */
2880
+ #provenBase(
2881
+ {
2882
+ clientCommitId,
2883
+ sequence,
2884
+ }: Pick<CommitOutcome, 'clientCommitId' | 'sequence'>,
2885
+ { before, epoch, registrationEpoch, securityEpoch }: DriveStart,
2886
+ report: SyncIdleResult,
2887
+ ): CurrentBaseProof {
2872
2888
  if (!this.#transportEnabled || epoch !== this.#transportEpoch)
2873
- return { proven: false, reason: 'offline' };
2889
+ return unproven('offline');
2874
2890
  if (registrationEpoch !== this.#registrationEpoch)
2875
- return { proven: false, reason: 'missing_coverage' };
2891
+ return unproven('missing_coverage');
2876
2892
  if (
2877
2893
  this.#securityLifecycle !== 'active' ||
2878
2894
  securityEpoch !== this.#securityEpoch
2879
2895
  )
2880
- return { proven: false, reason: 'sync_failed' };
2881
- if (report.schemaFloor !== undefined)
2882
- return { proven: false, reason: 'schema_floor' };
2883
- if (report.budgetExhausted)
2884
- return { proven: false, reason: 'budget_exhausted' };
2896
+ return unproven('sync_failed');
2897
+ if (report.schemaFloor !== undefined) return unproven('schema_floor');
2898
+ if (report.budgetExhausted) return unproven('budget_exhausted');
2885
2899
  try {
2886
2900
  return this.#db.transaction(() => {
2887
2901
  const snapshot = this.#readSnapshot({
@@ -2891,12 +2905,10 @@ export class SyncClient {
2891
2905
  });
2892
2906
  const delivery = snapshot.deliveries[0];
2893
2907
  const current = readCommitOutcome(this.#db, clientCommitId);
2894
- if (delivery?.status !== 'known' || !provable(current))
2895
- return {
2896
- proven: false,
2897
- reason:
2898
- report.revoked.length > 0 ? 'revoked' : 'outcome_unavailable',
2899
- };
2908
+ if (delivery?.status !== 'known' || !provable(current, sequence))
2909
+ return unproven(
2910
+ report.revoked.length > 0 ? 'revoked' : 'outcome_unavailable',
2911
+ );
2900
2912
  const after = new Map(
2901
2913
  loadUnits(this.#db).map((unit) => [unit.id, unit]),
2902
2914
  );
@@ -2951,17 +2963,15 @@ export class SyncClient {
2951
2963
  (conflict) => !covered(row.table, conflict.serverRow),
2952
2964
  )
2953
2965
  ) {
2954
- return {
2955
- proven: false,
2956
- reason:
2957
- report.revoked.length > 0 ? 'revoked' : 'missing_coverage',
2958
- };
2966
+ return unproven(
2967
+ report.revoked.length > 0 ? 'revoked' : 'missing_coverage',
2968
+ );
2959
2969
  }
2960
2970
  }
2961
2971
  return { proven: true, rows: current.retainedRows };
2962
2972
  });
2963
2973
  } catch {
2964
- return { proven: false, reason: 'snapshot_failed' };
2974
+ return unproven('snapshot_failed');
2965
2975
  }
2966
2976
  }
2967
2977
 
@@ -2984,6 +2994,8 @@ export class SyncClient {
2984
2994
  throw outcomeNotFound();
2985
2995
  }
2986
2996
  if (current.resolution !== 'active') return current;
2997
+ if (current.replacementClientCommitId !== undefined)
2998
+ throw replacementPending();
2987
2999
  const replacement = input.replacementClientCommitId;
2988
3000
  if (input.resolution === 'superseded') {
2989
3001
  if (
@@ -3012,11 +3024,157 @@ export class SyncClient {
3012
3024
  );
3013
3025
  }
3014
3026
 
3027
+ return this.#resolveOutcome(input, current);
3028
+ }
3029
+
3030
+ /**
3031
+ * §7.2.2: record a decision against an active failure as a held
3032
+ * replacement commit, written once a later drive proves its base.
3033
+ */
3034
+ replaceCommitOutcome(input: ReplaceCommitOutcomeInput): string {
3035
+ this.#requireActive();
3036
+ const current = readCommitOutcome(this.#db, input.clientCommitId);
3037
+ if (current === undefined) throw outcomeNotFound();
3038
+ if (
3039
+ current.resolution === 'active' &&
3040
+ current.replacementClientCommitId !== undefined
3041
+ )
3042
+ throw replacementPending();
3043
+ if (!provable(current, input.sequence))
3044
+ throw invalidRequest('the outcome holds no complete retained aggregate');
3045
+ // Envelope operation i belongs to retained row i, so keep mine finds
3046
+ // every operation's row; a payload names no version for one.
3047
+ const operations = (
3048
+ input.replacement === undefined
3049
+ ? current.operations
3050
+ : this.#outboxOperations(input.replacement)
3051
+ ).map((operation) => {
3052
+ const row = current.retainedRows.find(
3053
+ (candidate) =>
3054
+ candidate.table === operation.table &&
3055
+ candidate.rowId === operation.rowId,
3056
+ );
3057
+ if (row === undefined) return operation;
3058
+ if (
3059
+ input.replacement !== undefined &&
3060
+ operation.baseVersion !== undefined
3061
+ )
3062
+ throw invalidRequest(
3063
+ 'a replacement takes the base version of a retained row',
3064
+ );
3065
+ return { ...operation, baseVersion: row.serverVersion ?? 0 };
3066
+ });
3067
+ const clientCommitId = crypto.randomUUID();
3068
+ this.#appendCommit(clientCommitId, operations, (batch) => {
3069
+ this.#db.exec(
3070
+ `UPDATE ${OUTCOMES_TABLE} SET replacement_client_commit_id=? WHERE client_commit_id=? AND resolution='active'`,
3071
+ [clientCommitId, input.clientCommitId],
3072
+ );
3073
+ batch.outcomes();
3074
+ });
3075
+ return clientCommitId;
3076
+ }
3077
+
3078
+ /**
3079
+ * §7.2.2: at the idle point of a drive, write or refuse each decision that
3080
+ * was pending when the drive began. True when a replacement was written.
3081
+ */
3082
+ #settleDecisions(
3083
+ decisions: readonly PendingDecision[],
3084
+ start: DriveStart,
3085
+ report: SyncIdleResult,
3086
+ ): boolean {
3087
+ // A registration change during the drive says nothing about the base;
3088
+ // the decisions wait for the next drive.
3089
+ if (start.registrationEpoch !== this.#registrationEpoch) return false;
3090
+ let written = false;
3091
+ for (const decision of decisions) {
3092
+ const current = readCommitOutcome(this.#db, decision.clientCommitId);
3093
+ if (
3094
+ current?.resolution !== 'active' ||
3095
+ current.replacementClientCommitId !== decision.replacementClientCommitId
3096
+ )
3097
+ continue;
3098
+ // A replacement that already left the outbox has its own outcome.
3099
+ const commit = listOutbox(this.#db).find(
3100
+ (candidate) =>
3101
+ candidate.clientCommitId === decision.replacementClientCommitId,
3102
+ );
3103
+ const proof = commit && this.#provenBase(decision, start, report);
3104
+ const reason = !proof
3105
+ ? undefined
3106
+ : !proof.proven
3107
+ ? proof.reason
3108
+ : commit.operations.every((operation) => {
3109
+ const row = proof.rows.find(
3110
+ (candidate) =>
3111
+ candidate.table === operation.table &&
3112
+ candidate.rowId === operation.rowId,
3113
+ );
3114
+ return (
3115
+ row === undefined ||
3116
+ operation.baseVersion === (row.serverVersion ?? 0)
3117
+ );
3118
+ })
3119
+ ? undefined
3120
+ : 'base_moved';
3121
+ // These proof failures say nothing about the base; the next drive retries.
3122
+ if (
3123
+ /^(offline|sync_failed|budget_exhausted|snapshot_failed)$/.test(reason!)
3124
+ )
3125
+ continue;
3126
+ written ||= reason === undefined && commit !== undefined;
3127
+ this.#resolveOutcome(
3128
+ {
3129
+ clientCommitId: decision.clientCommitId,
3130
+ resolution: 'superseded',
3131
+ replacementClientCommitId: decision.replacementClientCommitId,
3132
+ },
3133
+ current,
3134
+ () =>
3135
+ reason !== undefined &&
3136
+ this.#dropIncompatibleCommit(
3137
+ commit!,
3138
+ 'the replacement could not be written on a proven base',
3139
+ REPLACEMENT_REFUSED_CODE,
3140
+ true,
3141
+ reason,
3142
+ ),
3143
+ );
3144
+ }
3145
+ return written;
3146
+ }
3147
+
3148
+ #resolveOutcome(
3149
+ input: ResolveCommitOutcomeInput,
3150
+ current: CommitOutcome,
3151
+ within?: () => void,
3152
+ ): CommitOutcome {
3015
3153
  const priorConflicts = this.#conflicts;
3016
3154
  const priorRejections = this.#rejections;
3017
3155
  return this.#applyBatch(
3018
3156
  (batch) => {
3019
- restoreFailedBases(this.#db, this.#schema);
3157
+ // Restore the server base under the retained rows, then replay what
3158
+ // stays and re-take later commits' before-images over that base, so
3159
+ // a later rollback cannot bring the released intent back.
3160
+ const scope = [
3161
+ ...new Set(
3162
+ this.#db
3163
+ .query(`SELECT tbl,id FROM ${RETAINED_ROWS} WHERE commit_id=?`, [
3164
+ input.clientCommitId,
3165
+ ])
3166
+ .flatMap((row) => {
3167
+ const table = this.#schema.tables.get(String(row.tbl));
3168
+ return [
3169
+ ...(table !== undefined && hasUniqueIndex(table)
3170
+ ? [JSON.stringify([row.tbl])]
3171
+ : []),
3172
+ JSON.stringify([row.tbl, row.id]),
3173
+ ];
3174
+ }),
3175
+ ),
3176
+ ];
3177
+ restoreFailedBases(this.#db, this.#schema, scope);
3020
3178
  this.#db.exec(`DELETE FROM ${RETAINED_ROWS} WHERE commit_id=?`, [
3021
3179
  input.clientCommitId,
3022
3180
  ]);
@@ -3035,12 +3193,13 @@ export class SyncClient {
3035
3193
  (record) => record.clientCommitId !== input.clientCommitId,
3036
3194
  );
3037
3195
  pruneCommitOutcomes(this.#db, this.#outcomeRetentionMaxEntries);
3038
- this.#replayOutbox();
3196
+ this.#replayOutbox(scope, false);
3039
3197
  for (const operation of current.operations ?? [])
3040
3198
  batch.table(operation.table);
3041
3199
  batch.outcomes();
3042
3200
  if (current.status === 'conflict') batch.conflicts();
3043
3201
  if (current.status === 'rejected') batch.rejections();
3202
+ within?.();
3044
3203
  return resolved;
3045
3204
  },
3046
3205
  undefined,
@@ -3177,9 +3336,7 @@ export class SyncClient {
3177
3336
  );
3178
3337
  if (registered) {
3179
3338
  this.#registrationEpoch += 1;
3180
- this.#setSyncNeeded(true);
3181
- this.#emitSyncIntent({ kind: 'interactive' });
3182
- this.#emitDiagnostics();
3339
+ this.#registrationChanged();
3183
3340
  }
3184
3341
  return ids;
3185
3342
  }
@@ -3198,7 +3355,11 @@ export class SyncClient {
3198
3355
  }
3199
3356
  deleteUnit(this.#db, id);
3200
3357
  this.#registrationEpoch += 1;
3201
- if (unit.status !== 'active') return;
3358
+ if (unit.status === 'active') this.#registrationChanged();
3359
+ }
3360
+
3361
+ /** A registration change owes an interactive pull. */
3362
+ #registrationChanged(): void {
3202
3363
  this.#setSyncNeeded(true);
3203
3364
  this.#emitSyncIntent({ kind: 'interactive' });
3204
3365
  this.#emitDiagnostics();
@@ -3477,6 +3638,12 @@ export class SyncClient {
3477
3638
  { clientCommitId: supplied },
3478
3639
  );
3479
3640
  const clientCommitId = supplied ?? crypto.randomUUID();
3641
+ this.#appendCommit(clientCommitId, this.#outboxOperations(mutations));
3642
+ return clientCommitId;
3643
+ }
3644
+
3645
+ /** §7.1: validate local mutations into their stored outbox operations. */
3646
+ #outboxOperations(mutations: readonly MutationInput[]): OutboxOperation[] {
3480
3647
  // §7.1: a patch reads the row as the commit's earlier operations leave
3481
3648
  // it. Keyed by `table rowId` (a table name holds no space): the JSON
3482
3649
  // values an earlier upsert wrote, or null after an earlier delete. A
@@ -3586,14 +3753,9 @@ export class SyncClient {
3586
3753
  if (refusal !== undefined)
3587
3754
  // §7.5: the same structured shape the native authoring APIs return — a
3588
3755
  // static message, and the dynamic cause in `details.legacyCause`.
3589
- throw new ClientSyncError(
3590
- 'sync.invalid_request',
3591
- 'the authoring request is invalid',
3592
- false,
3593
- {
3594
- legacyCause: `sync.invalid_request: table ${table.name}: ${refusal}`,
3595
- },
3596
- );
3756
+ throw invalidRequest('the authoring request is invalid', false, {
3757
+ legacyCause: `sync.invalid_request: table ${table.name}: ${refusal}`,
3758
+ });
3597
3759
  // §7.1 insert intent: a full-row write of a row the replica does not
3598
3760
  // show replays and encodes as a full row under every later schema.
3599
3761
  if (mutation.op !== 'patch') staged.set(`${table.name} ${pkValue}`, json);
@@ -3608,6 +3770,18 @@ export class SyncClient {
3608
3770
  insert: insert ? true : undefined,
3609
3771
  });
3610
3772
  });
3773
+ return operations;
3774
+ }
3775
+
3776
+ /**
3777
+ * Append one local commit and apply it optimistically; `within` adds its
3778
+ * own writes to the same transaction and change batch.
3779
+ */
3780
+ #appendCommit(
3781
+ clientCommitId: string,
3782
+ operations: readonly OutboxOperation[],
3783
+ within?: (batch: ChangeAccumulator) => void,
3784
+ ): void {
3611
3785
  // §5.11: a sealed row is read-only; a write could send NULL over
3612
3786
  // ciphertext this device cannot see.
3613
3787
  for (const operation of operations) {
@@ -3673,12 +3847,12 @@ export class SyncClient {
3673
3847
  }
3674
3848
  throw error;
3675
3849
  }
3850
+ within?.(batch);
3676
3851
  batch.status();
3677
3852
  });
3678
3853
  this.#needsPull = true;
3679
3854
  });
3680
3855
  this.#emitSyncIntent({ kind: 'interactive' });
3681
- return clientCommitId;
3682
3856
  }
3683
3857
 
3684
3858
  /** Host-facing mutation result with explicit network work intent (§7.5). */
@@ -3686,12 +3860,7 @@ export class SyncClient {
3686
3860
  mutations: readonly MutationInput[],
3687
3861
  options?: { readonly clientCommitId?: string },
3688
3862
  ): CommandResult<string> {
3689
- return {
3690
- value: this.mutate(mutations, options),
3691
- effects: {
3692
- sync: { kind: this.#transportEnabled ? 'interactive' : 'none' },
3693
- },
3694
- };
3863
+ return this.#commandResult(this.mutate(mutations, options));
3695
3864
  }
3696
3865
 
3697
3866
  /**
@@ -3775,7 +3944,15 @@ export class SyncClient {
3775
3944
  let result: LocalDataPurgeResult;
3776
3945
  try {
3777
3946
  result = this.#applyBatch((batch) => {
3778
- const targetsByTable = this.#localPurgeTargetsByTable(purge);
3947
+ const targetsByTable = new Map<
3948
+ string,
3949
+ CompiledLocalDataPurgeTarget[]
3950
+ >();
3951
+ for (const target of purge.targets)
3952
+ targetsByTable.set(target.table.name, [
3953
+ ...(targetsByTable.get(target.table.name) ?? []),
3954
+ target,
3955
+ ]);
3779
3956
  restoreFailedBases(this.#db, this.#schema);
3780
3957
  this.#dropRetainedRows(batch, (table, values) =>
3781
3958
  (targetsByTable.get(table) ?? []).some((target) =>
@@ -3866,36 +4043,21 @@ export class SyncClient {
3866
4043
  )
3867
4044
  batch.outcomes();
3868
4045
 
3869
- if (doomed.length > 0) {
3870
- // §5.11 purge erasure: the journal keeps a dropped commit's identity and codes,
3871
- // never its operations, so no purged value survives in it.
3872
- for (const commit of doomed) {
3873
- const results: CommitOperationOutcome[] = commit.operations.map(
3874
- (_operation, opIndex) => {
3875
- const rejection: RejectionRecord = {
3876
- clientCommitId: commit.clientCommitId,
3877
- opIndex,
3878
- code: 'client.local_data_purged',
3879
- message:
3880
- 'the commit was dropped by an application-authorized local data purge',
3881
- retryable: false,
3882
- };
3883
- this.#rejections.push(rejection);
3884
- return { status: 'error', rejection };
3885
- },
3886
- );
3887
- recordCommitOutcome(this.#db, {
3888
- clientCommitId: commit.clientCommitId,
3889
- status: 'rejected',
3890
- recordedAtMs: this.#now(),
3891
- results,
3892
- });
3893
- }
3894
- pruneCommitOutcomes(this.#db, this.#outcomeRetentionMaxEntries);
3895
- batch.status();
3896
- batch.rejections();
3897
- batch.outcomes();
3898
- }
4046
+ // §5.11 purge erasure: the journal keeps a dropped commit's identity and codes,
4047
+ // never its operations, so no purged value survives in it.
4048
+ for (const { clientCommitId, operations } of doomed)
4049
+ this.#journalDrop(
4050
+ batch,
4051
+ clientCommitId,
4052
+ operations.map((_operation, opIndex) => ({
4053
+ clientCommitId,
4054
+ opIndex,
4055
+ code: 'client.local_data_purged',
4056
+ message:
4057
+ 'the commit was dropped by an application-authorized local data purge',
4058
+ retryable: false,
4059
+ })),
4060
+ );
3899
4061
  this.#replayOutbox();
3900
4062
  this.#deleteUnreferencedBlobs();
3901
4063
  setMeta(this.#db, metaKey, purge.canonicalPlan);
@@ -3995,7 +4157,6 @@ export class SyncClient {
3995
4157
 
3996
4158
  if (!priorUpgrading) this.#config.onUpgrading?.(true);
3997
4159
  this.#emitSyncNeeded('startup');
3998
- this.#emitSyncIntent({ kind: 'interactive' });
3999
4160
  return {
4000
4161
  alreadyApplied: false,
4001
4162
  retainedCommits: pending.length,
@@ -4003,18 +4164,6 @@ export class SyncClient {
4003
4164
  };
4004
4165
  }
4005
4166
 
4006
- #localPurgeTargetsByTable(
4007
- purge: CompiledLocalDataPurge,
4008
- ): Map<string, CompiledLocalDataPurgeTarget[]> {
4009
- const byTable = new Map<string, CompiledLocalDataPurgeTarget[]>();
4010
- for (const target of purge.targets) {
4011
- const targets = byTable.get(target.table.name) ?? [];
4012
- targets.push(target);
4013
- byTable.set(target.table.name, targets);
4014
- }
4015
- return byTable;
4016
- }
4017
-
4018
4167
  #localPurgeRowIds(purge: CompiledLocalDataPurge): Map<string, Set<string>> {
4019
4168
  const byTable = new Map<string, Set<string>>();
4020
4169
  for (const target of purge.targets) {
@@ -4045,8 +4194,13 @@ export class SyncClient {
4045
4194
  partial: Readonly<Record<string, unknown>>,
4046
4195
  options?: { readonly baseVersion?: number },
4047
4196
  ): CommandResult<string> {
4197
+ return this.#commandResult(this.patch(table, rowId, partial, options));
4198
+ }
4199
+
4200
+ /** A local write's result; an open transport gate owes interactive sync. */
4201
+ #commandResult<T>(value: T): CommandResult<T> {
4048
4202
  return {
4049
- value: this.patch(table, rowId, partial, options),
4203
+ value,
4050
4204
  effects: {
4051
4205
  sync: { kind: this.#transportEnabled ? 'interactive' : 'none' },
4052
4206
  },
@@ -4113,7 +4267,14 @@ export class SyncClient {
4113
4267
  let ops = 0;
4114
4268
  let bytes = 0;
4115
4269
  let processed = 0;
4270
+ // §7.2.2: a pending replacement holds itself and every later commit.
4271
+ const held = new Set(
4272
+ pendingDecisions(this.#db).map(
4273
+ (decision) => decision.replacementClientCommitId,
4274
+ ),
4275
+ );
4116
4276
  for (const commit of iterateOutbox(this.#db, throughSeq)) {
4277
+ if (held.has(commit.clientCommitId)) break;
4117
4278
  // §6.1/§7.1: the commit-count and operation caps are hard. A first
4118
4279
  // commit that alone exceeds the operation cap is a typed capacity error
4119
4280
  // and stays queued; a later one defers with the complete suffix.
@@ -4261,7 +4422,11 @@ export class SyncClient {
4261
4422
  const priorRejections = [...this.#rejections];
4262
4423
  this.#applyBatch(
4263
4424
  (batch) => {
4264
- if (this.#retainFailedCommits && code === 'client.encrypt_failed')
4425
+ if (
4426
+ this.#retainFailedCommits &&
4427
+ (code === 'client.encrypt_failed' ||
4428
+ code === REPLACEMENT_REFUSED_CODE)
4429
+ )
4265
4430
  retainFailedRows(
4266
4431
  this.#db,
4267
4432
  commit,
@@ -4274,27 +4439,22 @@ export class SyncClient {
4274
4439
  // the journal cannot carry keeps its durable commitId, code and a bounded
4275
4440
  // `details.reason` instead of an opaque rewritten value.
4276
4441
  const representable = commit.operations.every(isStoredOperation);
4277
- const rejection: RejectionRecord = definedObject({
4278
- clientCommitId: commit.clientCommitId,
4279
- opIndex: 0,
4280
- code,
4281
- message,
4282
- retryable: false,
4283
- ...(representable ? { operation: commit.operations[0] } : {}),
4284
- ...(reason === undefined ? {} : { details: { reason } }),
4285
- });
4286
- this.#rejections.push(rejection);
4287
- recordCommitOutcome(this.#db, {
4288
- clientCommitId: commit.clientCommitId,
4289
- status: 'rejected',
4290
- recordedAtMs: this.#now(),
4291
- results: [{ status: 'error', rejection }],
4292
- ...(representable ? { operations: commit.operations } : {}),
4293
- });
4294
- pruneCommitOutcomes(this.#db, this.#outcomeRetentionMaxEntries);
4295
- batch.status();
4296
- batch.rejections();
4297
- batch.outcomes();
4442
+ this.#journalDrop(
4443
+ batch,
4444
+ commit.clientCommitId,
4445
+ [
4446
+ definedObject({
4447
+ clientCommitId: commit.clientCommitId,
4448
+ opIndex: 0,
4449
+ code,
4450
+ message,
4451
+ retryable: false,
4452
+ operation: representable ? commit.operations[0] : undefined,
4453
+ details: reason === undefined ? undefined : { reason },
4454
+ }),
4455
+ ],
4456
+ representable ? commit.operations : undefined,
4457
+ );
4298
4458
  },
4299
4459
  undefined,
4300
4460
  (error) => {
@@ -4306,6 +4466,33 @@ export class SyncClient {
4306
4466
  );
4307
4467
  }
4308
4468
 
4469
+ /** §7.2: journal a dropped commit as rejected with these rejections. */
4470
+ #journalDrop(
4471
+ batch: ChangeAccumulator,
4472
+ clientCommitId: string,
4473
+ rejections: readonly RejectionRecord[],
4474
+ operations?: readonly OutboxOperation[],
4475
+ ): void {
4476
+ this.#rejections.push(...rejections);
4477
+ recordCommitOutcome(
4478
+ this.#db,
4479
+ definedObject({
4480
+ clientCommitId,
4481
+ status: 'rejected',
4482
+ recordedAtMs: this.#now(),
4483
+ results: rejections.map((rejection) => ({
4484
+ status: 'error' as const,
4485
+ rejection,
4486
+ })),
4487
+ operations,
4488
+ }),
4489
+ );
4490
+ pruneCommitOutcomes(this.#db, this.#outcomeRetentionMaxEntries);
4491
+ batch.status();
4492
+ batch.rejections();
4493
+ batch.outcomes();
4494
+ }
4495
+
4309
4496
  // -- sync -------------------------------------------------------------------
4310
4497
 
4311
4498
  /**
@@ -4411,39 +4598,25 @@ export class SyncClient {
4411
4598
  typeof code === 'string'
4412
4599
  ? this.#diagnosticCode(code)
4413
4600
  : 'client.unknown_failure';
4414
- const details =
4415
- typeof error === 'object' && error !== null && 'details' in error
4416
- ? error.details
4417
- : undefined;
4418
- const rawCause =
4419
- typeof details === 'object' &&
4420
- details !== null &&
4421
- 'causeKind' in details
4422
- ? details.causeKind
4423
- : undefined;
4424
- let causeKind: TransportCauseKind | undefined;
4425
- switch (rawCause) {
4426
- case 'network':
4427
- case 'connect':
4428
- case 'tls':
4429
- case 'io':
4430
- case 'request':
4431
- case 'protocol':
4432
- case 'timeout':
4433
- case 'round_deadline':
4434
- case 'aborted':
4435
- case 'body':
4436
- case 'status':
4437
- case 'redirect':
4438
- case 'unknown':
4439
- causeKind = rawCause;
4440
- }
4441
- const rawStatus =
4442
- typeof details === 'object' &&
4443
- details !== null &&
4444
- 'httpStatus' in details
4445
- ? details.httpStatus
4446
- : undefined;
4601
+ const rawCause = errorDetail(error, 'causeKind');
4602
+ const causeKind = (
4603
+ [
4604
+ 'network',
4605
+ 'connect',
4606
+ 'tls',
4607
+ 'io',
4608
+ 'request',
4609
+ 'protocol',
4610
+ 'timeout',
4611
+ 'round_deadline',
4612
+ 'aborted',
4613
+ 'body',
4614
+ 'status',
4615
+ 'redirect',
4616
+ 'unknown',
4617
+ ] as const
4618
+ ).find((kind) => kind === rawCause);
4619
+ const rawStatus = errorDetail(error, 'httpStatus');
4447
4620
  const httpStatus =
4448
4621
  (causeKind === 'status' ||
4449
4622
  causeKind === 'body' ||
@@ -4618,6 +4791,9 @@ export class SyncClient {
4618
4791
  cursor: unit.cursor,
4619
4792
  bootstrapState: unit.bootstrapState,
4620
4793
  }),
4794
+ ...(unit.restrict === undefined
4795
+ ? []
4796
+ : [{ type: 'RESTRICT' as const, ...unit.restrict }]),
4621
4797
  ],
4622
4798
  ),
4623
4799
  ];
@@ -4716,18 +4892,7 @@ export class SyncClient {
4716
4892
  // transport, `network` from a browser fetch) is not a round worth
4717
4893
  // backing off for. Stop without scheduling an intent or growing the
4718
4894
  // delay; the host's own connectivity signal re-arms the drive.
4719
- const details =
4720
- error instanceof ClientSyncError
4721
- ? error.details
4722
- : typeof error === 'object' && error !== null && 'details' in error
4723
- ? error.details
4724
- : undefined;
4725
- const causeKind =
4726
- typeof details === 'object' &&
4727
- details !== null &&
4728
- 'causeKind' in details
4729
- ? details.causeKind
4730
- : undefined;
4895
+ const causeKind = errorDetail(error, 'causeKind');
4731
4896
  const unreachable = causeKind === 'connect' || causeKind === 'network';
4732
4897
  // The round's work is still owed; the host's connectivity resume runs it.
4733
4898
  if (unreachable) this.#setSyncNeeded(true);
@@ -4853,6 +5018,9 @@ export class SyncClient {
4853
5018
  this.#setSyncNeeded(false);
4854
5019
  return result(false);
4855
5020
  }
5021
+ // §7.2.2: decisions pending when the drive began are settled at its end.
5022
+ const decisions = pendingDecisions(this.#db);
5023
+ const start = decisions.length > 0 ? this.#driveStart() : undefined;
4856
5024
  const states = () =>
4857
5025
  JSON.stringify(
4858
5026
  loadUnits(this.#db).map((unit) => [unit.id, unit.bootstrapState]),
@@ -4922,8 +5090,11 @@ export class SyncClient {
4922
5090
  aggregate.deferredCommits = last.deferredCommits ?? 0;
4923
5091
  aggregate.schemaFloor = last.schemaFloor;
4924
5092
  // A disabled transport or a schema floor ends the loop, not the budget.
4925
- if (!this.#transportEnabled || aggregate.schemaFloor)
5093
+ if (!this.#transportEnabled || aggregate.schemaFloor) {
5094
+ if (start !== undefined)
5095
+ this.#settleDecisions(decisions, start, result(false));
4926
5096
  return result(false);
5097
+ }
4927
5098
  if (
4928
5099
  maxRounds === undefined &&
4929
5100
  last.segmentRowsApplied > 0 &&
@@ -4939,6 +5110,11 @@ export class SyncClient {
4939
5110
  !aggregate.deferredCommits &&
4940
5111
  !this.#needsPull
4941
5112
  ) {
5113
+ if (
5114
+ start !== undefined &&
5115
+ this.#settleDecisions(decisions, start, result(false))
5116
+ )
5117
+ continue;
4942
5118
  return result(false);
4943
5119
  }
4944
5120
  }
@@ -5143,7 +5319,7 @@ export class SyncClient {
5143
5319
  // A superseded attempt leaves the successor's (or the deliberate
5144
5320
  // disconnect's) state alone.
5145
5321
  if (generation === this.#realtimeGeneration) {
5146
- this.#setRealtimeState('refused', realtimeErrorCode(error));
5322
+ this.#setRealtimeState('refused', thrownCode(error));
5147
5323
  }
5148
5324
  throw error;
5149
5325
  }
@@ -5266,14 +5442,12 @@ export class SyncClient {
5266
5442
  const event = parsed.event;
5267
5443
  if (event.event === 'hello') {
5268
5444
  if (event.data.requiresSync) {
5269
- this.#setSyncNeeded(true);
5270
5445
  this.#emitSyncNeeded('hello');
5271
5446
  }
5272
5447
  return;
5273
5448
  }
5274
5449
  if (event.event === 'sync') {
5275
5450
  // §8.3: any wake-up means "run a pull soon", never data.
5276
- this.#setSyncNeeded(true);
5277
5451
  this.#emitSyncNeeded(event.data.reason);
5278
5452
  return;
5279
5453
  }
@@ -5334,7 +5508,6 @@ export class SyncClient {
5334
5508
  )
5335
5509
  return;
5336
5510
  if (resetEpoch !== this.#localResetEpoch) {
5337
- this.#setSyncNeeded(true);
5338
5511
  this.#emitSyncNeeded('catchup-required');
5339
5512
  return;
5340
5513
  }
@@ -5344,7 +5517,6 @@ export class SyncClient {
5344
5517
  await this.#processResponse(message, [], undefined, 'delta');
5345
5518
  } catch {
5346
5519
  // A delta that cannot be applied is recovered by a pull (§8.3).
5347
- this.#setSyncNeeded(true);
5348
5520
  this.#emitSyncNeeded('catchup-required');
5349
5521
  }
5350
5522
  });
@@ -5683,13 +5855,7 @@ export class SyncClient {
5683
5855
  // catching up with its cursor unpersisted, and the next
5684
5856
  // round's SUB_START settles it (revoked or a new bootstrap).
5685
5857
  // A host downloader may throw any error carrying the code.
5686
- if (
5687
- typeof error !== 'object' ||
5688
- error === null ||
5689
- !('code' in error) ||
5690
- error.code !== 'sync.forbidden'
5691
- )
5692
- throw error;
5858
+ if (thrownCode(error) !== 'sync.forbidden') throw error;
5693
5859
  section.skip = true;
5694
5860
  break;
5695
5861
  }
@@ -5940,7 +6106,6 @@ export class SyncClient {
5940
6106
  if (deltaCursor >= 0) this.#sendAck(deltaCursor);
5941
6107
  // §8.2: an unapplied delta is a drop; a pull repairs it.
5942
6108
  if (deltaDropped) {
5943
- this.#setSyncNeeded(true);
5944
6109
  this.#emitSyncNeeded('catchup-required');
5945
6110
  }
5946
6111
  } else {
@@ -6022,13 +6187,7 @@ export class SyncClient {
6022
6187
  return true;
6023
6188
  }
6024
6189
  // rejected
6025
- const cacheMiss = frame.results.some(
6026
- (result) =>
6027
- result.status === 'error' &&
6028
- result.code === 'sync.idempotency_cache_miss' &&
6029
- result.retryable,
6030
- );
6031
- if (cacheMiss) {
6190
+ if (!isFinalPushResult(frame)) {
6032
6191
  // §6.3: a serving failure, not the commit's outcome — keep the
6033
6192
  // commit queued and retry the identical push later.
6034
6193
  summary.retryable.push(frame.clientCommitId);
@@ -6038,6 +6197,10 @@ export class SyncClient {
6038
6197
  for (const result of frame.results) {
6039
6198
  const operation = commit.operations[result.opIndex];
6040
6199
  if (result.status === 'conflict') {
6200
+ const columns =
6201
+ this.#schema.tables.get(operation?.table ?? '')?.columns ?? [];
6202
+ const values =
6203
+ columns.length === 0 ? [] : decodeRow(columns, result.serverRow);
6041
6204
  const conflict: ConflictRecord = definedObject({
6042
6205
  clientCommitId: frame.clientCommitId,
6043
6206
  opIndex: result.opIndex,
@@ -6046,11 +6209,21 @@ export class SyncClient {
6046
6209
  code: result.code,
6047
6210
  message: result.message,
6048
6211
  serverVersion: result.serverVersion,
6049
- serverRow: this.#decodeServerRow(operation?.table, result.serverRow),
6050
- conflictColumns: this.#decodeConflictColumns(
6051
- operation?.table,
6052
- result.conflictColumns,
6212
+ serverRow: Object.fromEntries(
6213
+ columns.map((column, index) => [
6214
+ column.name,
6215
+ values[index] ?? null,
6216
+ ]),
6053
6217
  ),
6218
+ // §6.3: the presence-layout bitmap names the present columns whose
6219
+ // `column_version` exceeded `baseVersion`; a custom merge
6220
+ // recomputes exactly these (§6.5).
6221
+ conflictColumns: columns
6222
+ .filter(
6223
+ (_, index) =>
6224
+ ((result.conflictColumns[index >> 3] ?? 0) >> (index & 7)) & 1,
6225
+ )
6226
+ .map((column) => column.name),
6054
6227
  operation: operation,
6055
6228
  });
6056
6229
  this.#conflicts.push(conflict);
@@ -6129,41 +6302,6 @@ export class SyncClient {
6129
6302
  );
6130
6303
  }
6131
6304
 
6132
- #decodeServerRow(
6133
- tableName: string | undefined,
6134
- payload: Uint8Array,
6135
- ): Record<string, RowValue> {
6136
- if (tableName === undefined) return {};
6137
- const table = this.#schema.tables.get(tableName);
6138
- if (table === undefined) return {};
6139
- const values = decodeRow(table.columns, payload);
6140
- const record: Record<string, RowValue> = {};
6141
- table.columns.forEach((column, index) => {
6142
- record[column.name] = values[index] ?? null;
6143
- });
6144
- return record;
6145
- }
6146
-
6147
- /**
6148
- * §6.3 `conflictColumns`: decode the presence-layout bitmap into the names
6149
- * of the present columns whose `column_version` exceeded `baseVersion`. A
6150
- * custom merge recomputes exactly these columns (§6.5).
6151
- */
6152
- #decodeConflictColumns(
6153
- tableName: string | undefined,
6154
- bitmap: Uint8Array,
6155
- ): readonly string[] {
6156
- if (tableName === undefined) return [];
6157
- const table = this.#schema.tables.get(tableName);
6158
- if (table === undefined) return [];
6159
- const names: string[] = [];
6160
- table.columns.forEach((column, index) => {
6161
- const byte = bitmap[index >> 3] ?? 0;
6162
- if (((byte >> (index & 7)) & 1) === 1) names.push(column.name);
6163
- });
6164
- return names;
6165
- }
6166
-
6167
6305
  async #applyCommit(
6168
6306
  frame: CommitFrame,
6169
6307
  summary: MutableSummary,
@@ -6331,10 +6469,17 @@ export class SyncClient {
6331
6469
  // §3.3 owners matter only for rows the clear would reach, so a pair
6332
6470
  // with no matching local or retained row never reads the unit list.
6333
6471
  let owners: readonly ScopeMap[] | undefined;
6472
+ const clearFirst = !section.seeded.has(tableName);
6473
+ // §5.6: a first page outside the restriction is a whole bootstrap from a
6474
+ // server that predates RESTRICT; the restriction ends before the clear.
6475
+ if (clearFirst && unit.restrict?.tables.includes(tableName) === false)
6476
+ this.#db.exec(`UPDATE ${UNITS_TABLE} SET restriction=NULL WHERE id=?`, [
6477
+ unit.id,
6478
+ ]);
6334
6479
  try {
6335
6480
  summary.segmentRowsApplied += await apply(
6336
6481
  table,
6337
- !section.seeded.has(tableName),
6482
+ clearFirst,
6338
6483
  effective,
6339
6484
  () =>
6340
6485
  (owners ??=
@@ -6360,6 +6505,7 @@ export class SyncClient {
6360
6505
  ...current,
6361
6506
  status: 'failed',
6362
6507
  reasonCode: 'sync.scope_revoked',
6508
+ restrict: undefined,
6363
6509
  });
6364
6510
  for (const ref of windowRefs(this.#db, unit.id))
6365
6511
  batch.window(ref.baseKey, ref.value);
@@ -6433,8 +6579,7 @@ export class SyncClient {
6433
6579
  throw invalidRequest('segment exceeds its byteLength', true);
6434
6580
  }
6435
6581
  onProgress(bytes.byteLength);
6436
- const hash = await sha256Hex(bytes);
6437
- if (`sha256:${hash}` !== frame.segmentId) {
6582
+ if ((await computeBlobId(bytes)) !== frame.segmentId) {
6438
6583
  throw invalidRequest(
6439
6584
  'segment failed content-address verification (§5.1)',
6440
6585
  true,
@@ -6468,9 +6613,7 @@ export class SyncClient {
6468
6613
  saveUnit(this.#db, {
6469
6614
  ...unit,
6470
6615
  reasonCode: start.reasonCode,
6471
- cursor: -1,
6472
- bootstrapState: undefined,
6473
- seeded: [],
6616
+ ...UNIT_RESTART,
6474
6617
  });
6475
6618
  summary.resets.push(unit.id);
6476
6619
  return;
@@ -6506,10 +6649,8 @@ export class SyncClient {
6506
6649
  ...unit,
6507
6650
  status: failed ? 'failed' : 'revoked',
6508
6651
  reasonCode: failed ? 'sync.scope_revoked' : start.reasonCode,
6509
- cursor: -1,
6510
- bootstrapState: undefined,
6511
- seeded: [],
6512
6652
  echo: undefined,
6653
+ ...UNIT_RESTART,
6513
6654
  });
6514
6655
  if (revoked) summary.revoked.push(unit.id);
6515
6656
  if (failed) summary.failed.push(unit.id);
@@ -6521,14 +6662,18 @@ export class SyncClient {
6521
6662
  ...unit,
6522
6663
  reasonCode: undefined,
6523
6664
  echo: start.fenced,
6665
+ // §7.4.3: a rearm and a completed bootstrap end the restriction.
6524
6666
  ...(rearmed
6525
- ? { cursor: -1, bootstrapState: undefined, seeded: [] }
6667
+ ? UNIT_RESTART
6526
6668
  : start.bootstrap
6527
6669
  ? {
6528
6670
  cursor: end.nextCursor,
6529
6671
  bootstrapState: end.bootstrapState,
6530
6672
  seeded:
6531
6673
  end.bootstrapState === undefined ? [] : [...section.seeded],
6674
+ ...(end.bootstrapState === undefined
6675
+ ? { restrict: undefined }
6676
+ : {}),
6532
6677
  }
6533
6678
  : {}),
6534
6679
  });
@@ -6602,37 +6747,22 @@ export class SyncClient {
6602
6747
  ownsLocalRow(table, lastEffective, owners, op.values),
6603
6748
  ),
6604
6749
  );
6605
- for (const commit of doomed) {
6606
- const { clientCommitId } = commit;
6750
+ for (const { clientCommitId, operations } of doomed) {
6607
6751
  deleteOutboxCommit(this.#db, clientCommitId);
6608
- const results: CommitOperationOutcome[] = commit.operations.map(
6609
- (operation, opIndex) => {
6610
- const rejection: RejectionRecord = {
6611
- clientCommitId,
6612
- opIndex,
6613
- code: 'sync.scope_revoked',
6614
- message:
6615
- 'the commit was dropped because its effective scope was revoked',
6616
- retryable: false,
6617
- operation,
6618
- };
6619
- this.#rejections.push(rejection);
6620
- return { status: 'error', rejection };
6621
- },
6622
- );
6623
- recordCommitOutcome(this.#db, {
6752
+ this.#journalDrop(
6753
+ batch,
6624
6754
  clientCommitId,
6625
- status: 'rejected',
6626
- recordedAtMs: this.#now(),
6627
- results,
6628
- operations: commit.operations,
6629
- });
6630
- }
6631
- if (doomed.length > 0) {
6632
- pruneCommitOutcomes(this.#db, this.#outcomeRetentionMaxEntries);
6633
- batch.status();
6634
- batch.rejections();
6635
- batch.outcomes();
6755
+ operations.map((operation, opIndex) => ({
6756
+ clientCommitId,
6757
+ opIndex,
6758
+ code: 'sync.scope_revoked',
6759
+ message:
6760
+ 'the commit was dropped because its effective scope was revoked',
6761
+ retryable: false,
6762
+ operation,
6763
+ })),
6764
+ operations,
6765
+ );
6636
6766
  }
6637
6767
  this.#replayOutbox(scope);
6638
6768
  this.#deleteUnreferencedBlobs();
@@ -6669,8 +6799,7 @@ export class SyncClient {
6669
6799
  }
6670
6800
  const syncVersion = row[SYNC_VERSION_COLUMN];
6671
6801
  if (typeof syncVersion !== 'number') {
6672
- throw new ClientSyncError(
6673
- 'sync.local_corrupt',
6802
+ throw localStateCorrupt(
6674
6803
  `local row ${operation.table}/${operation.rowId} has no sync version`,
6675
6804
  );
6676
6805
  }
@@ -6683,8 +6812,7 @@ export class SyncClient {
6683
6812
  onlyKeys?: ReadonlySet<string>,
6684
6813
  ): OutboxBeforeImage[] {
6685
6814
  return operations.flatMap((operation, opIndex) =>
6686
- onlyKeys &&
6687
- !onlyKeys.has(JSON.stringify([operation.table, operation.rowId]))
6815
+ onlyKeys && !onlyKeys.has(rowKey(operation))
6688
6816
  ? []
6689
6817
  : [this.#captureBeforeImage(operation, opIndex)],
6690
6818
  );
@@ -6703,8 +6831,7 @@ export class SyncClient {
6703
6831
  return;
6704
6832
  }
6705
6833
  if (image.values === undefined || image.syncVersion === undefined) {
6706
- throw new ClientSyncError(
6707
- 'sync.local_corrupt',
6834
+ throw localStateCorrupt(
6708
6835
  `rollback image for ${operation.table}/${operation.rowId} is incomplete`,
6709
6836
  );
6710
6837
  }
@@ -6744,19 +6871,14 @@ export class SyncClient {
6744
6871
  const complete = commit.operations.every((_, index) =>
6745
6872
  imageByIndex.has(index),
6746
6873
  );
6747
- const affectedKeys = new Set(
6748
- commit.operations.map((operation) =>
6749
- JSON.stringify([operation.table, operation.rowId]),
6750
- ),
6751
- );
6874
+ const affectedKeys = new Set(commit.operations.map(rowKey));
6752
6875
  if (complete) {
6753
- const restored = new Set<string>();
6876
+ // The first operation on a row holds its pre-commit image.
6877
+ const unrestored = new Set(affectedKeys);
6754
6878
  commit.operations.forEach((operation, index) => {
6755
- const key = JSON.stringify([operation.table, operation.rowId]);
6756
- if (restored.has(key)) return;
6757
6879
  const image = imageByIndex.get(index);
6758
- if (image) this.#restoreBeforeImage(operation, image, batch);
6759
- restored.add(key);
6880
+ if (unrestored.delete(rowKey(operation)) && image)
6881
+ this.#restoreBeforeImage(operation, image, batch);
6760
6882
  });
6761
6883
  } else {
6762
6884
  // Pending commits written by older clients have no before-images.
@@ -6769,7 +6891,7 @@ export class SyncClient {
6769
6891
  for (const later of listOutbox(this.#db, [...affectedKeys])) {
6770
6892
  if (later.seq <= commit.seq) continue;
6771
6893
  const affectedOperations = later.operations.filter((operation) =>
6772
- affectedKeys.has(JSON.stringify([operation.table, operation.rowId])),
6894
+ affectedKeys.has(rowKey(operation)),
6773
6895
  );
6774
6896
  if (affectedOperations.length === 0) continue;
6775
6897
  replaceOutboxBeforeImages(
@@ -6803,14 +6925,8 @@ export class SyncClient {
6803
6925
  : this.#table(op.table);
6804
6926
  if (table === undefined) continue;
6805
6927
  let precise =
6806
- batch === undefined
6807
- ? false
6808
- : this.#recordStoredRowScopes(batch, table, op.rowId);
6809
- if (op.op === 'delete') {
6810
- if (batch !== undefined && !precise) batch.table(op.table);
6811
- deleteLocalRow(this.#db, table, op.rowId, false);
6812
- continue;
6813
- }
6928
+ batch !== undefined &&
6929
+ this.#recordStoredRowScopes(batch, table, op.rowId);
6814
6930
  // §7.1 overlay: apply the operation's PRESENT columns over the current
6815
6931
  // local row. A partial operation over an absent local row leaves it
6816
6932
  // absent — the server answers it with sync.row_deleted or
@@ -6820,20 +6936,21 @@ export class SyncClient {
6820
6936
  const full =
6821
6937
  op.insert === true ||
6822
6938
  table.columns.every((column) => column.name in opValues);
6939
+ const local =
6940
+ op.op === 'delete' ? undefined : this.#rowById(table, op.rowId);
6823
6941
  // An insert lacking a non-nullable column cannot encode (§7.4.4); it
6824
6942
  // stays hidden until the send-time drop classifies it.
6825
6943
  if (
6826
- op.insert === true &&
6827
- table.columns.some(
6828
- (column) => !column.nullable && opValues[column.name] === undefined,
6829
- )
6944
+ op.op === 'delete' ||
6945
+ (op.insert === true &&
6946
+ table.columns.some(
6947
+ (column) => !column.nullable && opValues[column.name] === undefined,
6948
+ )) ||
6949
+ (local === undefined && !full)
6830
6950
  ) {
6831
6951
  if (batch !== undefined && !precise) batch.table(op.table);
6832
- continue;
6833
- }
6834
- const local = this.#rowById(table, op.rowId);
6835
- if (local === undefined && !full) {
6836
- if (batch !== undefined && !precise) batch.table(op.table);
6952
+ if (op.op === 'delete')
6953
+ deleteLocalRow(this.#db, table, op.rowId, false);
6837
6954
  continue;
6838
6955
  }
6839
6956
  const values = table.columns.map((column) => {
@@ -6861,10 +6978,7 @@ export class SyncClient {
6861
6978
  values,
6862
6979
  );
6863
6980
  } catch {
6864
- throw new ClientSyncError(
6865
- 'sync.local_corrupt',
6866
- 'persisted optimistic row value is invalid',
6867
- );
6981
+ throw localStateCorrupt('persisted optimistic row value is invalid');
6868
6982
  }
6869
6983
  }
6870
6984
  // Record the row's scope keys from its scope columns (I2 refinement).
@@ -6924,7 +7038,7 @@ export class SyncClient {
6924
7038
  );
6925
7039
  for (const op of commit.operations) {
6926
7040
  batch.table(op.table);
6927
- scope.push(JSON.stringify([op.table, op.rowId]));
7041
+ scope.push(rowKey(op));
6928
7042
  }
6929
7043
  }
6930
7044
  return scope;
@@ -7058,7 +7172,7 @@ export class SyncClient {
7058
7172
  commit.operations.filter(
7059
7173
  (op) =>
7060
7174
  scope === undefined ||
7061
- scope.includes(JSON.stringify([op.table, op.rowId])) ||
7175
+ scope.includes(rowKey(op)) ||
7062
7176
  scope.includes(JSON.stringify([op.table])),
7063
7177
  ),
7064
7178
  batch,