@syncular/client 0.82.2 → 0.83.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.
package/README.md CHANGED
@@ -409,7 +409,9 @@ stop, pending outbox, offline transport, and storage pressure/unreadability.
409
409
  Failed progress and `lastRound` diagnostics expose an optional bounded
410
410
  `causeKind` and HTTP status. Worker leaders and followers receive the same
411
411
  evidence. A new progress attempt clears its failure fields; a successful round
412
- replaces the failed last round. `host.connectivity` describes the latest
412
+ replaces the failed last round. `lastRound.epoch` and `lastRound.attempt`
413
+ identify the round and match its progress events; count rounds by that pair
414
+ instead of `completedAtMs`. `host.connectivity` describes the latest
413
415
  endpoint observation and does not prove the device's network state.
414
416
  `queryFailures` retains at most 256 failed owned snapshot reads until each query
415
417
  reads successfully. An entry contains only its stable PHI-free owner id,
@@ -836,9 +838,11 @@ const stop = client.onProgress((progress) => {
836
838
  stop();
837
839
  ```
838
840
 
839
- Each snapshot identifies the round with `attempt`, and the current payload with
841
+ Each snapshot identifies the round with `epoch` and `attempt`, and the current payload with
840
842
  `unitId`, `table`, and optional `segmentId`. Counters reset for each
841
- payload; `syncUntilIdle` starts a new attempt for each round. `phase` is `request`,
843
+ payload; `syncUntilIdle` starts a new attempt for each round. `epoch` is random per
844
+ client core; a new core (a Worker handover, a reload) counts attempts from 1
845
+ under a new `epoch`. `phase` is `request`,
842
846
  `download`, or `import`; `state` is `running`, `complete`, or `failed`. Unknown
843
847
  totals remain absent. A new attempt clears prior errors and counters.
844
848
 
package/dist/client.js CHANGED
@@ -201,6 +201,8 @@ export class SyncClient {
201
201
  /** §7.8: restarts the running drive's round bound when rows apply. */
202
202
  #roundProgressed;
203
203
  #progressAttempt = 0;
204
+ /** §7.6: scopes `#progressAttempt`; a new core gets a new epoch. */
205
+ #epoch = crypto.randomUUID();
204
206
  /**
205
207
  * True from the synchronous entry of `sync()` until its serialized round
206
208
  * settles — the "one loop owns the database" guard that rejects a
@@ -2261,12 +2263,19 @@ export class SyncClient {
2261
2263
  readCommitOutcome(this.#db, supplied)))
2262
2264
  throw new ClientSyncError('client.commit_id_reused', 'clientCommitId is held', false, { clientCommitId: supplied });
2263
2265
  const clientCommitId = supplied ?? crypto.randomUUID();
2266
+ // §7.1: a patch reads the row as the commit's earlier operations leave
2267
+ // it. Keyed by `table rowId` (a table name holds no space): the JSON
2268
+ // values an earlier upsert wrote, or null after an earlier delete. A
2269
+ // patch changes neither presence nor a scope column, so it records
2270
+ // nothing.
2271
+ const staged = new Map();
2264
2272
  const operations = mutations.map((mutation) => {
2265
2273
  const table = this.#table(mutation.table);
2266
2274
  if (mutation.op === 'delete') {
2267
2275
  // §2.4: the server rejects a rowId holding U+0000.
2268
2276
  if (mutation.rowId.includes('\u0000'))
2269
2277
  throw invalidRequest('rowId holds U+0000');
2278
+ staged.set(`${table.name} ${mutation.rowId}`, null);
2270
2279
  return definedObject({
2271
2280
  table: mutation.table,
2272
2281
  rowId: mutation.rowId,
@@ -2284,8 +2293,13 @@ export class SyncClient {
2284
2293
  const scopeColumns = new Set(table.scopeColumnByVariable.values());
2285
2294
  const pkColumn = table.columns[table.primaryKeyIndex];
2286
2295
  const pkValue = requireRowId(normalized.get(pkColumn.name));
2287
- const local = this.#db.query(`SELECT * FROM ${quoteIdent(table.name)} WHERE ${quoteIdent(table.primaryKey)}=?`, [pkSqlValue(table, pkValue)])[0];
2288
- if (!local)
2296
+ // The base: an earlier operation's JSON values, else the stored row.
2297
+ const key = `${table.name} ${pkValue}`;
2298
+ const base = staged.get(key);
2299
+ const stored = staged.has(key)
2300
+ ? undefined
2301
+ : this.#rowById(table, pkValue);
2302
+ if (!base && !stored)
2289
2303
  throw new ClientSyncError('sync.row_missing', 'a sparse patch requires a local row');
2290
2304
  for (const column of table.columns) {
2291
2305
  if (!normalized.has(column.name))
@@ -2294,7 +2308,8 @@ export class SyncClient {
2294
2308
  // §3.4 rule 5 / §6.2: scope columns are immutable on update. The
2295
2309
  // server accepts a present scope column whose value equals the
2296
2310
  // stored row and applies it as a no-op, so a decoded envelope
2297
- // round-trips. The local row is the only value the client can
2311
+ // round-trips. The local row, as the commit's earlier operations
2312
+ // leave it, is the only value the client can
2298
2313
  // prove equality against; when the row is absent locally the
2299
2314
  // client cannot prove equality against the server's stored row
2300
2315
  // and fails closed. A primary key that is also a scope column
@@ -2302,7 +2317,9 @@ export class SyncClient {
2302
2317
  // by construction the row id being patched (§6.1), so its value is
2303
2318
  // proven equal already.
2304
2319
  if (scopeColumns.has(column.name) && column.name !== pkColumn.name) {
2305
- if (!Object.is(rowValueToJson(fromSqlValue(column, local[column.name] ?? null)), rowValueToJson(coerceSqlRepresentation(column, normalized.get(column.name))))) {
2320
+ if (!Object.is(stored
2321
+ ? rowValueToJson(fromSqlValue(column, stored[column.name] ?? null))
2322
+ : base?.[column.name], rowValueToJson(coerceSqlRepresentation(column, normalized.get(column.name))))) {
2306
2323
  throw invalidRequest('patch cannot write a scope column (§3.4)', false, at);
2307
2324
  }
2308
2325
  continue;
@@ -2337,8 +2354,9 @@ export class SyncClient {
2337
2354
  });
2338
2355
  // §7.1 insert intent: a full-row write of a row the replica does not
2339
2356
  // show replays and encodes as a full row under every later schema.
2340
- const insert = mutation.op !== 'patch' &&
2341
- this.#db.query(`SELECT 1 FROM ${quoteIdent(table.name)} WHERE ${quoteIdent(table.primaryKey)}=? LIMIT 1`, [pkSqlValue(table, pkValue)]).length === 0;
2357
+ if (mutation.op !== 'patch')
2358
+ staged.set(`${table.name} ${pkValue}`, json);
2359
+ const insert = mutation.op !== 'patch' && !this.#rowById(table, pkValue, '1');
2342
2360
  return definedObject({
2343
2361
  table: mutation.table,
2344
2362
  rowId: pkValue,
@@ -2354,7 +2372,7 @@ export class SyncClient {
2354
2372
  const table = this.#table(operation.table);
2355
2373
  if (!table.hasEncryptedColumns)
2356
2374
  continue;
2357
- const keyId = this.#db.query(`SELECT ${quoteIdent(SEALED_KEY_COLUMN)} AS k FROM ${quoteIdent(table.name)} WHERE ${quoteIdent(table.primaryKey)}=?`, [pkSqlValue(table, operation.rowId)])[0]?.k;
2375
+ const keyId = this.#rowById(table, operation.rowId, `${quoteIdent(SEALED_KEY_COLUMN)} AS k`)?.k;
2358
2376
  if (typeof keyId === 'string')
2359
2377
  throw new ClientSyncError('client.encryption_key_missing', 'the row is sealed under a key this device does not hold', false, { table: table.name, keyId });
2360
2378
  }
@@ -2781,7 +2799,7 @@ export class SyncClient {
2781
2799
  const selector = this.#encryption?.keyIdColumns?.[table.name];
2782
2800
  if (selector === undefined)
2783
2801
  return undefined;
2784
- const row = this.#db.query(`SELECT ${quoteIdent(selector)} AS value FROM ${quoteIdent(table.name)} WHERE ${quoteIdent(table.primaryKey)}=?`, [pkSqlValue(table, rowId)])[0];
2802
+ const row = this.#rowById(table, rowId, `${quoteIdent(selector)} AS value`);
2785
2803
  const value = row?.value;
2786
2804
  return typeof value === 'string' && value.length > 0
2787
2805
  ? value
@@ -2955,22 +2973,36 @@ export class SyncClient {
2955
2973
  this.#syncOutstanding = true;
2956
2974
  this.#beginDiagnosticsDeferral();
2957
2975
  const startedAtMs = this.#now();
2958
- return this.#serialize(() => this.#runSync(signal))
2959
- .then((summary) => {
2976
+ // `#syncOutstanding` keeps this the attempt `#runSync` starts (§7.6).
2977
+ const attempt = this.#progressAttempt + 1;
2978
+ const round = () => {
2960
2979
  const completedAtMs = this.#now();
2961
- this.#lastRound = {
2962
- status: 'succeeded',
2980
+ return {
2981
+ epoch: this.#epoch,
2982
+ attempt,
2963
2983
  startedAtMs,
2964
2984
  completedAtMs,
2965
2985
  durationMs: Math.max(0, completedAtMs - startedAtMs),
2986
+ };
2987
+ };
2988
+ return this.#serialize(() => this.#runSync(signal))
2989
+ .then((summary) => {
2990
+ this.#lastRound = {
2991
+ status: 'succeeded',
2992
+ ...round(),
2966
2993
  counters: this.#diagnosticRoundCounters(summary),
2967
2994
  };
2968
2995
  this.#emitDiagnostics();
2969
2996
  return summary;
2970
2997
  }, (caught) => {
2971
2998
  const error = classifySqliteFailure(caught).error;
2972
- const completedAtMs = this.#now();
2999
+ // A gate refusal starts no attempt and records no round.
3000
+ if (this.#progressAttempt !== attempt)
3001
+ throw error;
2973
3002
  const code = error.code;
3003
+ const errorCode = typeof code === 'string'
3004
+ ? this.#diagnosticCode(code)
3005
+ : 'client.unknown_failure';
2974
3006
  const details = typeof error === 'object' && error !== null && 'details' in error
2975
3007
  ? error.details
2976
3008
  : undefined;
@@ -3012,24 +3044,18 @@ export class SyncClient {
3012
3044
  : undefined;
3013
3045
  this.#progress.update(definedObject({
3014
3046
  state: 'failed',
3015
- errorCode: typeof code === 'string'
3016
- ? this.#diagnosticCode(code)
3017
- : 'client.unknown_failure',
3047
+ errorCode,
3018
3048
  retryDelayMs: this.#roundRetryDelayMs,
3019
3049
  causeKind,
3020
3050
  httpStatus,
3021
3051
  }));
3022
- this.#lastRound = {
3052
+ this.#lastRound = definedObject({
3023
3053
  status: 'failed',
3024
- startedAtMs,
3025
- completedAtMs,
3026
- durationMs: Math.max(0, completedAtMs - startedAtMs),
3027
- errorCode: typeof code === 'string'
3028
- ? this.#diagnosticCode(code)
3029
- : 'client.unknown_failure',
3030
- ...(causeKind !== undefined ? { causeKind } : {}),
3031
- ...(httpStatus !== undefined ? { httpStatus } : {}),
3032
- };
3054
+ ...round(),
3055
+ errorCode,
3056
+ causeKind,
3057
+ httpStatus,
3058
+ });
3033
3059
  this.#emitDiagnostics();
3034
3060
  throw error;
3035
3061
  })
@@ -3063,6 +3089,7 @@ export class SyncClient {
3063
3089
  this.#requireTransport();
3064
3090
  this.#roundRetryDelayMs = undefined;
3065
3091
  this.#progress.emit({
3092
+ epoch: this.#epoch,
3066
3093
  attempt: ++this.#progressAttempt,
3067
3094
  state: 'running',
3068
3095
  phase: 'request',
@@ -4489,7 +4516,7 @@ export class SyncClient {
4489
4516
  const mappings = [...table.scopeColumnByVariable].filter(([variable]) => table.scopePrefixByVariable.has(variable));
4490
4517
  if (mappings.length === 0)
4491
4518
  return false;
4492
- const row = this.#db.query(`SELECT ${mappings.map(([, column]) => quoteIdent(column)).join(', ')} FROM ${quoteIdent(table.name)} WHERE ${quoteIdent(table.primaryKey)}=?`, [pkSqlValue(table, rowId)])[0];
4519
+ const row = this.#rowById(table, rowId, mappings.map(([, column]) => quoteIdent(column)).join());
4493
4520
  if (row === undefined)
4494
4521
  return false;
4495
4522
  let recorded = false;
@@ -4819,7 +4846,7 @@ export class SyncClient {
4819
4846
  ...table.columns.map((column) => quoteIdent(column.name)),
4820
4847
  quoteIdent(SYNC_VERSION_COLUMN),
4821
4848
  ];
4822
- const row = this.#db.query(`SELECT ${columns.join(', ')} FROM ${quoteIdent(table.name)} WHERE ${quoteIdent(table.primaryKey)}=?`, [pkSqlValue(table, operation.rowId)])[0];
4849
+ const row = this.#rowById(table, operation.rowId, columns.join());
4823
4850
  if (row === undefined)
4824
4851
  return { opIndex, existed: false };
4825
4852
  const values = {};
@@ -4861,7 +4888,7 @@ export class SyncClient {
4861
4888
  const table = this.#schema.tables.get(operation.table);
4862
4889
  if (table === undefined)
4863
4890
  continue;
4864
- const row = this.#db.query(`SELECT ${quoteIdent(SYNC_VERSION_COLUMN)} AS v FROM ${quoteIdent(table.name)} WHERE ${quoteIdent(table.primaryKey)}=?`, [pkSqlValue(table, operation.rowId)])[0];
4891
+ const row = this.#rowById(table, operation.rowId, `${quoteIdent(SYNC_VERSION_COLUMN)} AS v`);
4865
4892
  if (row !== undefined && row.v === OPTIMISTIC_VERSION) {
4866
4893
  batch.table(table.name);
4867
4894
  deleteLocalRow(this.#db, table, operation.rowId);
@@ -4947,7 +4974,7 @@ export class SyncClient {
4947
4974
  batch.table(op.table);
4948
4975
  continue;
4949
4976
  }
4950
- const local = this.#db.query(`SELECT * FROM ${quoteIdent(table.name)} WHERE ${quoteIdent(table.primaryKey)}=?`, [pkSqlValue(table, op.rowId)])[0];
4977
+ const local = this.#rowById(table, op.rowId);
4951
4978
  if (local === undefined && !full) {
4952
4979
  if (batch !== undefined && !precise)
4953
4980
  batch.table(op.table);
@@ -5148,6 +5175,10 @@ export class SyncClient {
5148
5175
  deleteUnreferencedCachedBlobs(this.#db, this.#schema);
5149
5176
  }
5150
5177
  // -- helpers -----------------------------------------------------------------
5178
+ /** The local row `rowId` of `table`, selecting `columns`. */
5179
+ #rowById(table, rowId, columns = '*') {
5180
+ return this.#db.query(`SELECT ${columns} FROM ${quoteIdent(table.name)} WHERE ${quoteIdent(table.primaryKey)}=?`, [pkSqlValue(table, rowId)])[0];
5181
+ }
5151
5182
  #table(name) {
5152
5183
  const table = this.#schema.tables.get(name);
5153
5184
  if (table === undefined) {
@@ -56,14 +56,19 @@ export interface DiagnosticRoundCounters {
56
56
  readonly failed: number;
57
57
  readonly deferredCommits: number;
58
58
  }
59
+ /** One completed sync round. `(epoch, attempt)` identifies it (SPEC §7.6). */
59
60
  export type DiagnosticLastRound = {
60
61
  readonly status: 'succeeded';
62
+ readonly epoch: string;
63
+ readonly attempt: number;
61
64
  readonly startedAtMs: number;
62
65
  readonly completedAtMs: number;
63
66
  readonly durationMs: number;
64
67
  readonly counters: DiagnosticRoundCounters;
65
68
  } | {
66
69
  readonly status: 'failed';
70
+ readonly epoch: string;
71
+ readonly attempt: number;
67
72
  readonly startedAtMs: number;
68
73
  readonly completedAtMs: number;
69
74
  readonly durationMs: number;
@@ -1,6 +1,8 @@
1
1
  import type { TransportCauseKind } from './diagnostics.js';
2
2
  /** Ephemeral sync work, independent of committed change notifications (SPEC §7.7). */
3
3
  export interface SyncProgress {
4
+ /** Random per client core; `(epoch, attempt)` identifies the attempt (SPEC §7.6). */
5
+ readonly epoch: string;
4
6
  readonly attempt: number;
5
7
  readonly state: 'running' | 'complete' | 'failed';
6
8
  readonly phase: 'request' | 'download' | 'import';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@syncular/client",
3
- "version": "0.82.2",
3
+ "version": "0.83.0",
4
4
  "description": "Syncular TypeScript client core — offline-first sync over SQLite (WASM/OPFS, Bun, Node)",
5
5
  "license": "Apache-2.0",
6
6
  "author": "Benjamin Kniffler",
@@ -121,11 +121,11 @@
121
121
  },
122
122
  "dependencies": {
123
123
  "@sqlite.org/sqlite-wasm": "^3.53.0-build1",
124
- "@syncular/core": "0.82.2"
124
+ "@syncular/core": "0.83.0"
125
125
  },
126
126
  "devDependencies": {
127
127
  "@electric-sql/pglite": "^0.5.4",
128
- "@syncular/server": "0.82.2",
128
+ "@syncular/server": "0.83.0",
129
129
  "playwright": "1.63.0",
130
130
  "vite": "8.3.4"
131
131
  }
package/src/client.ts CHANGED
@@ -989,6 +989,8 @@ export class SyncClient {
989
989
  /** §7.8: restarts the running drive's round bound when rows apply. */
990
990
  #roundProgressed: (() => void) | undefined;
991
991
  #progressAttempt = 0;
992
+ /** §7.6: scopes `#progressAttempt`; a new core gets a new epoch. */
993
+ readonly #epoch = crypto.randomUUID();
992
994
  /**
993
995
  * True from the synchronous entry of `sync()` until its serialized round
994
996
  * settles — the "one loop owns the database" guard that rejects a
@@ -3463,12 +3465,19 @@ export class SyncClient {
3463
3465
  { clientCommitId: supplied },
3464
3466
  );
3465
3467
  const clientCommitId = supplied ?? crypto.randomUUID();
3468
+ // §7.1: a patch reads the row as the commit's earlier operations leave
3469
+ // it. Keyed by `table rowId` (a table name holds no space): the JSON
3470
+ // values an earlier upsert wrote, or null after an earlier delete. A
3471
+ // patch changes neither presence nor a scope column, so it records
3472
+ // nothing.
3473
+ const staged = new Map<string, Record<string, JsonRowValue> | null>();
3466
3474
  const operations: OutboxOperation[] = mutations.map((mutation) => {
3467
3475
  const table = this.#table(mutation.table);
3468
3476
  if (mutation.op === 'delete') {
3469
3477
  // §2.4: the server rejects a rowId holding U+0000.
3470
3478
  if (mutation.rowId.includes('\u0000'))
3471
3479
  throw invalidRequest('rowId holds U+0000');
3480
+ staged.set(`${table.name} ${mutation.rowId}`, null);
3472
3481
  return definedObject({
3473
3482
  table: mutation.table,
3474
3483
  rowId: mutation.rowId,
@@ -3486,11 +3495,13 @@ export class SyncClient {
3486
3495
  const scopeColumns = new Set(table.scopeColumnByVariable.values());
3487
3496
  const pkColumn = table.columns[table.primaryKeyIndex] as RowColumn;
3488
3497
  const pkValue = requireRowId(normalized.get(pkColumn.name));
3489
- const local = this.#db.query(
3490
- `SELECT * FROM ${quoteIdent(table.name)} WHERE ${quoteIdent(table.primaryKey)}=?`,
3491
- [pkSqlValue(table, pkValue)],
3492
- )[0];
3493
- if (!local)
3498
+ // The base: an earlier operation's JSON values, else the stored row.
3499
+ const key = `${table.name} ${pkValue}`;
3500
+ const base = staged.get(key);
3501
+ const stored = staged.has(key)
3502
+ ? undefined
3503
+ : this.#rowById(table, pkValue);
3504
+ if (!base && !stored)
3494
3505
  throw new ClientSyncError(
3495
3506
  'sync.row_missing',
3496
3507
  'a sparse patch requires a local row',
@@ -3501,7 +3512,8 @@ export class SyncClient {
3501
3512
  // §3.4 rule 5 / §6.2: scope columns are immutable on update. The
3502
3513
  // server accepts a present scope column whose value equals the
3503
3514
  // stored row and applies it as a no-op, so a decoded envelope
3504
- // round-trips. The local row is the only value the client can
3515
+ // round-trips. The local row, as the commit's earlier operations
3516
+ // leave it, is the only value the client can
3505
3517
  // prove equality against; when the row is absent locally the
3506
3518
  // client cannot prove equality against the server's stored row
3507
3519
  // and fails closed. A primary key that is also a scope column
@@ -3511,9 +3523,11 @@ export class SyncClient {
3511
3523
  if (scopeColumns.has(column.name) && column.name !== pkColumn.name) {
3512
3524
  if (
3513
3525
  !Object.is(
3514
- rowValueToJson(
3515
- fromSqlValue(column, local[column.name] ?? null),
3516
- ),
3526
+ stored
3527
+ ? rowValueToJson(
3528
+ fromSqlValue(column, stored[column.name] ?? null),
3529
+ )
3530
+ : base?.[column.name],
3517
3531
  rowValueToJson(
3518
3532
  coerceSqlRepresentation(
3519
3533
  column,
@@ -3570,12 +3584,9 @@ export class SyncClient {
3570
3584
  );
3571
3585
  // §7.1 insert intent: a full-row write of a row the replica does not
3572
3586
  // show replays and encodes as a full row under every later schema.
3587
+ if (mutation.op !== 'patch') staged.set(`${table.name} ${pkValue}`, json);
3573
3588
  const insert =
3574
- mutation.op !== 'patch' &&
3575
- this.#db.query(
3576
- `SELECT 1 FROM ${quoteIdent(table.name)} WHERE ${quoteIdent(table.primaryKey)}=? LIMIT 1`,
3577
- [pkSqlValue(table, pkValue)],
3578
- ).length === 0;
3589
+ mutation.op !== 'patch' && !this.#rowById(table, pkValue, '1');
3579
3590
  return definedObject({
3580
3591
  table: mutation.table,
3581
3592
  rowId: pkValue,
@@ -3590,10 +3601,11 @@ export class SyncClient {
3590
3601
  for (const operation of operations) {
3591
3602
  const table = this.#table(operation.table);
3592
3603
  if (!table.hasEncryptedColumns) continue;
3593
- const keyId = this.#db.query(
3594
- `SELECT ${quoteIdent(SEALED_KEY_COLUMN)} AS k FROM ${quoteIdent(table.name)} WHERE ${quoteIdent(table.primaryKey)}=?`,
3595
- [pkSqlValue(table, operation.rowId)],
3596
- )[0]?.k;
3604
+ const keyId = this.#rowById(
3605
+ table,
3606
+ operation.rowId,
3607
+ `${quoteIdent(SEALED_KEY_COLUMN)} AS k`,
3608
+ )?.k;
3597
3609
  if (typeof keyId === 'string')
3598
3610
  throw new ClientSyncError(
3599
3611
  'client.encryption_key_missing',
@@ -4127,10 +4139,11 @@ export class SyncClient {
4127
4139
  (table, rowId) => {
4128
4140
  const selector = this.#encryption?.keyIdColumns?.[table.name];
4129
4141
  if (selector === undefined) return undefined;
4130
- const row = this.#db.query(
4131
- `SELECT ${quoteIdent(selector)} AS value FROM ${quoteIdent(table.name)} WHERE ${quoteIdent(table.primaryKey)}=?`,
4132
- [pkSqlValue(table, rowId)],
4133
- )[0];
4142
+ const row = this.#rowById(
4143
+ table,
4144
+ rowId,
4145
+ `${quoteIdent(selector)} AS value`,
4146
+ );
4134
4147
  const value = row?.value;
4135
4148
  return typeof value === 'string' && value.length > 0
4136
4149
  ? value
@@ -4364,15 +4377,24 @@ export class SyncClient {
4364
4377
  this.#syncOutstanding = true;
4365
4378
  this.#beginDiagnosticsDeferral();
4366
4379
  const startedAtMs = this.#now();
4380
+ // `#syncOutstanding` keeps this the attempt `#runSync` starts (§7.6).
4381
+ const attempt = this.#progressAttempt + 1;
4382
+ const round = () => {
4383
+ const completedAtMs = this.#now();
4384
+ return {
4385
+ epoch: this.#epoch,
4386
+ attempt,
4387
+ startedAtMs,
4388
+ completedAtMs,
4389
+ durationMs: Math.max(0, completedAtMs - startedAtMs),
4390
+ };
4391
+ };
4367
4392
  return this.#serialize(() => this.#runSync(signal))
4368
4393
  .then(
4369
4394
  (summary) => {
4370
- const completedAtMs = this.#now();
4371
4395
  this.#lastRound = {
4372
4396
  status: 'succeeded',
4373
- startedAtMs,
4374
- completedAtMs,
4375
- durationMs: Math.max(0, completedAtMs - startedAtMs),
4397
+ ...round(),
4376
4398
  counters: this.#diagnosticRoundCounters(summary),
4377
4399
  };
4378
4400
  this.#emitDiagnostics();
@@ -4380,8 +4402,13 @@ export class SyncClient {
4380
4402
  },
4381
4403
  (caught: unknown) => {
4382
4404
  const error = classifySqliteFailure(caught).error;
4383
- const completedAtMs = this.#now();
4405
+ // A gate refusal starts no attempt and records no round.
4406
+ if (this.#progressAttempt !== attempt) throw error;
4384
4407
  const code = (error as { code?: unknown }).code;
4408
+ const errorCode =
4409
+ typeof code === 'string'
4410
+ ? this.#diagnosticCode(code)
4411
+ : 'client.unknown_failure';
4385
4412
  const details =
4386
4413
  typeof error === 'object' && error !== null && 'details' in error
4387
4414
  ? error.details
@@ -4428,27 +4455,19 @@ export class SyncClient {
4428
4455
  this.#progress.update(
4429
4456
  definedObject({
4430
4457
  state: 'failed',
4431
- errorCode:
4432
- typeof code === 'string'
4433
- ? this.#diagnosticCode(code)
4434
- : 'client.unknown_failure',
4458
+ errorCode,
4435
4459
  retryDelayMs: this.#roundRetryDelayMs,
4436
4460
  causeKind,
4437
4461
  httpStatus,
4438
4462
  }),
4439
4463
  );
4440
- this.#lastRound = {
4464
+ this.#lastRound = definedObject({
4441
4465
  status: 'failed',
4442
- startedAtMs,
4443
- completedAtMs,
4444
- durationMs: Math.max(0, completedAtMs - startedAtMs),
4445
- errorCode:
4446
- typeof code === 'string'
4447
- ? this.#diagnosticCode(code)
4448
- : 'client.unknown_failure',
4449
- ...(causeKind !== undefined ? { causeKind } : {}),
4450
- ...(httpStatus !== undefined ? { httpStatus } : {}),
4451
- };
4466
+ ...round(),
4467
+ errorCode,
4468
+ causeKind,
4469
+ httpStatus,
4470
+ });
4452
4471
  this.#emitDiagnostics();
4453
4472
  throw error;
4454
4473
  },
@@ -4485,6 +4504,7 @@ export class SyncClient {
4485
4504
  this.#requireTransport();
4486
4505
  this.#roundRetryDelayMs = undefined;
4487
4506
  this.#progress.emit({
4507
+ epoch: this.#epoch,
4488
4508
  attempt: ++this.#progressAttempt,
4489
4509
  state: 'running',
4490
4510
  phase: 'request',
@@ -6176,10 +6196,11 @@ export class SyncClient {
6176
6196
  table.scopePrefixByVariable.has(variable),
6177
6197
  );
6178
6198
  if (mappings.length === 0) return false;
6179
- const row = this.#db.query(
6180
- `SELECT ${mappings.map(([, column]) => quoteIdent(column)).join(', ')} FROM ${quoteIdent(table.name)} WHERE ${quoteIdent(table.primaryKey)}=?`,
6181
- [pkSqlValue(table, rowId)],
6182
- )[0];
6199
+ const row = this.#rowById(
6200
+ table,
6201
+ rowId,
6202
+ mappings.map(([, column]) => quoteIdent(column)).join(),
6203
+ );
6183
6204
  if (row === undefined) return false;
6184
6205
  let recorded = false;
6185
6206
  for (const [variable, column] of mappings) {
@@ -6613,10 +6634,7 @@ export class SyncClient {
6613
6634
  ...table.columns.map((column) => quoteIdent(column.name)),
6614
6635
  quoteIdent(SYNC_VERSION_COLUMN),
6615
6636
  ];
6616
- const row = this.#db.query(
6617
- `SELECT ${columns.join(', ')} FROM ${quoteIdent(table.name)} WHERE ${quoteIdent(table.primaryKey)}=?`,
6618
- [pkSqlValue(table, operation.rowId)],
6619
- )[0];
6637
+ const row = this.#rowById(table, operation.rowId, columns.join());
6620
6638
  if (row === undefined) return { opIndex, existed: false };
6621
6639
  const values: Record<string, ReturnType<typeof rowValueToJson>> = {};
6622
6640
  for (const column of table.columns) {
@@ -6679,10 +6697,11 @@ export class SyncClient {
6679
6697
  if (operation.op !== 'upsert') continue;
6680
6698
  const table = this.#schema.tables.get(operation.table);
6681
6699
  if (table === undefined) continue;
6682
- const row = this.#db.query(
6683
- `SELECT ${quoteIdent(SYNC_VERSION_COLUMN)} AS v FROM ${quoteIdent(table.name)} WHERE ${quoteIdent(table.primaryKey)}=?`,
6684
- [pkSqlValue(table, operation.rowId)],
6685
- )[0];
6700
+ const row = this.#rowById(
6701
+ table,
6702
+ operation.rowId,
6703
+ `${quoteIdent(SYNC_VERSION_COLUMN)} AS v`,
6704
+ );
6686
6705
  if (row !== undefined && row.v === OPTIMISTIC_VERSION) {
6687
6706
  batch.table(table.name);
6688
6707
  deleteLocalRow(this.#db, table, operation.rowId);
@@ -6787,10 +6806,7 @@ export class SyncClient {
6787
6806
  if (batch !== undefined && !precise) batch.table(op.table);
6788
6807
  continue;
6789
6808
  }
6790
- const local = this.#db.query(
6791
- `SELECT * FROM ${quoteIdent(table.name)} WHERE ${quoteIdent(table.primaryKey)}=?`,
6792
- [pkSqlValue(table, op.rowId)],
6793
- )[0];
6809
+ const local = this.#rowById(table, op.rowId);
6794
6810
  if (local === undefined && !full) {
6795
6811
  if (batch !== undefined && !precise) batch.table(op.table);
6796
6812
  continue;
@@ -7045,6 +7061,18 @@ export class SyncClient {
7045
7061
 
7046
7062
  // -- helpers -----------------------------------------------------------------
7047
7063
 
7064
+ /** The local row `rowId` of `table`, selecting `columns`. */
7065
+ #rowById(
7066
+ table: CompiledClientTable,
7067
+ rowId: string,
7068
+ columns = '*',
7069
+ ): SqlRow | undefined {
7070
+ return this.#db.query(
7071
+ `SELECT ${columns} FROM ${quoteIdent(table.name)} WHERE ${quoteIdent(table.primaryKey)}=?`,
7072
+ [pkSqlValue(table, rowId)],
7073
+ )[0];
7074
+ }
7075
+
7048
7076
  #table(name: string): CompiledClientTable {
7049
7077
  const table = this.#schema.tables.get(name);
7050
7078
  if (table === undefined) {
@@ -91,9 +91,12 @@ export interface DiagnosticRoundCounters {
91
91
  readonly deferredCommits: number;
92
92
  }
93
93
 
94
+ /** One completed sync round. `(epoch, attempt)` identifies it (SPEC §7.6). */
94
95
  export type DiagnosticLastRound =
95
96
  | {
96
97
  readonly status: 'succeeded';
98
+ readonly epoch: string;
99
+ readonly attempt: number;
97
100
  readonly startedAtMs: number;
98
101
  readonly completedAtMs: number;
99
102
  readonly durationMs: number;
@@ -101,6 +104,8 @@ export type DiagnosticLastRound =
101
104
  }
102
105
  | {
103
106
  readonly status: 'failed';
107
+ readonly epoch: string;
108
+ readonly attempt: number;
104
109
  readonly startedAtMs: number;
105
110
  readonly completedAtMs: number;
106
111
  readonly durationMs: number;
package/src/progress.ts CHANGED
@@ -2,6 +2,8 @@ import type { TransportCauseKind } from './diagnostics';
2
2
 
3
3
  /** Ephemeral sync work, independent of committed change notifications (SPEC §7.7). */
4
4
  export interface SyncProgress {
5
+ /** Random per client core; `(epoch, attempt)` identifies the attempt (SPEC §7.6). */
6
+ readonly epoch: string;
5
7
  readonly attempt: number;
6
8
  readonly state: 'running' | 'complete' | 'failed';
7
9
  readonly phase: 'request' | 'download' | 'import';