@syncular/client 0.49.2 → 0.51.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
@@ -79,6 +79,11 @@ SPEC §8.4); the supported page-level realtime supervisor owns reconnect and
79
79
  resume policy. The main thread gets `onSyncNeeded` / `onConflict` / `onSynced`
80
80
  events for rendering.
81
81
 
82
+ For a reviewed recovery from a retained conflict or rejection, call
83
+ `await client.proveCurrentBase(outcome)`. The result contains bases for every
84
+ retained row only after a completed covering pull, or a typed failure reason
85
+ without row data. Use the returned versions in the replacement commit.
86
+
82
87
  A direct `SyncClient` used by a long-running service exposes
83
88
  `onSyncNeeded()` and `onSyncIntent()`. Install the shared single-flight loop
84
89
  instead of maintaining host timers:
package/dist/client.d.ts CHANGED
@@ -19,7 +19,7 @@ import { type LeaderLock } from './leader-lock.js';
19
19
  import { type LocalDataPurgeInput, type LocalDataPurgeResult } from './local-purge.js';
20
20
  import { type LocalDataRebootstrapInput, type LocalDataRebootstrapResult } from './local-rebootstrap.js';
21
21
  import { type OutboxCommit } from './outbox.js';
22
- import { type CommitOutcome, type CommitOutcomeQuery, type ConflictRecord, type RejectionRecord, type ResolveCommitOutcomeInput } from './outcomes.js';
22
+ import { type CommitOutcome, type CommitOutcomeQuery, type ConflictRecord, type RejectionRecord, type RetainedCommitRow, type ResolveCommitOutcomeInput } from './outcomes.js';
23
23
  import { type PreviousVersionAudit, type PreviousVersionReadSpec, type PreviousVersionSnapshot } from './previous-version.js';
24
24
  import { type ClientSchema } from './schema.js';
25
25
  import { type SubscriptionRecord } from './state.js';
@@ -105,6 +105,13 @@ export interface SyncIdleOptions {
105
105
  */
106
106
  readonly timeoutMs?: number;
107
107
  }
108
+ export type CurrentBaseProof = {
109
+ readonly proven: true;
110
+ readonly rows: readonly RetainedCommitRow[];
111
+ } | {
112
+ readonly proven: false;
113
+ readonly reason: 'offline' | 'sync_failed' | 'schema_floor' | 'budget_exhausted' | 'snapshot_failed' | 'missing_coverage' | 'revoked' | 'outcome_unavailable';
114
+ };
108
115
  export interface SyncClientLimits {
109
116
  readonly limitCommits?: number;
110
117
  readonly limitSnapshotRows?: number;
@@ -530,6 +537,8 @@ export declare class SyncClient {
530
537
  rejections(): readonly RejectionRecord[];
531
538
  /** One durable final outcome by the originating client commit id. */
532
539
  commitOutcome(clientCommitId: string): CommitOutcome | undefined;
540
+ /** Prove all retained bases against a completed post-rejection pull (§7.2.1). */
541
+ proveCurrentBase(outcome: Pick<CommitOutcome, 'clientCommitId' | 'sequence'>, maxRounds?: number): Promise<CurrentBaseProof>;
533
542
  /** Newest-first durable outcome journal. */
534
543
  commitOutcomes(query?: CommitOutcomeQuery): readonly CommitOutcome[];
535
544
  /**
package/dist/client.js CHANGED
@@ -145,7 +145,10 @@ export class SyncClient {
145
145
  /** RFC 0005 resolved capture budgets; undefined ⇒ feature off. */
146
146
  #previousVersion;
147
147
  #securityLifecycle;
148
+ #securityEpoch = 0;
148
149
  #transportEnabled;
150
+ #transportEpoch = 0;
151
+ #subscriptionEpoch = 0;
149
152
  #now;
150
153
  #outcomeRetentionMaxEntries;
151
154
  #retainFailedCommits;
@@ -716,6 +719,7 @@ export class SyncClient {
716
719
  if (this.#transportEnabled === enabled)
717
720
  return;
718
721
  this.#transportEnabled = enabled;
722
+ this.#transportEpoch += 1;
719
723
  if (!enabled && !this.#syncOutstanding)
720
724
  this.disconnectRealtime();
721
725
  this.#emitSyncIntent(enabled && this.#securityLifecycle === 'active'
@@ -741,6 +745,7 @@ export class SyncClient {
741
745
  if (this.#preflightBarrier !== undefined)
742
746
  return this.#preflightBarrier;
743
747
  this.#securityLifecycle = 'preflight';
748
+ this.#securityEpoch += 1;
744
749
  this.disconnectRealtime();
745
750
  const barrier = (async () => {
746
751
  await Promise.allSettled([this.#opChain, ...this.#protectedAsync]);
@@ -1701,6 +1706,143 @@ export class SyncClient {
1701
1706
  this.#requireActive();
1702
1707
  return readCommitOutcome(this.#db, clientCommitId);
1703
1708
  }
1709
+ /** Prove all retained bases against a completed post-rejection pull (§7.2.1). */
1710
+ async proveCurrentBase(outcome, maxRounds) {
1711
+ this.#requireActive();
1712
+ if (maxRounds !== undefined &&
1713
+ (!Number.isInteger(maxRounds) || maxRounds < 1 || maxRounds > 0xffffffff))
1714
+ throw invalidRequest('maxRounds must be a positive integer');
1715
+ const { clientCommitId, sequence } = outcome;
1716
+ let initial;
1717
+ try {
1718
+ initial = readCommitOutcome(this.#db, clientCommitId);
1719
+ }
1720
+ catch {
1721
+ return { proven: false, reason: 'snapshot_failed' };
1722
+ }
1723
+ if (initial === undefined ||
1724
+ initial.sequence !== sequence ||
1725
+ initial.resolution !== 'active' ||
1726
+ (initial.status !== 'conflict' && initial.status !== 'rejected') ||
1727
+ initial.operations === undefined ||
1728
+ initial.retainedRows === undefined ||
1729
+ initial.operations.length !== initial.retainedRows.length ||
1730
+ initial.retainedRows.length === 0)
1731
+ return { proven: false, reason: 'outcome_unavailable' };
1732
+ if (!this.#transportEnabled)
1733
+ return { proven: false, reason: 'offline' };
1734
+ await this.#opChain;
1735
+ if (!this.#transportEnabled)
1736
+ return { proven: false, reason: 'offline' };
1737
+ const epoch = this.#transportEpoch;
1738
+ const subscriptionEpoch = this.#subscriptionEpoch;
1739
+ const securityEpoch = this.#securityEpoch;
1740
+ let before;
1741
+ try {
1742
+ before = loadSubscriptions(this.#db);
1743
+ }
1744
+ catch {
1745
+ return { proven: false, reason: 'snapshot_failed' };
1746
+ }
1747
+ let report;
1748
+ try {
1749
+ report = await this.syncUntilIdle(maxRounds);
1750
+ }
1751
+ catch {
1752
+ return {
1753
+ proven: false,
1754
+ reason: !this.#transportEnabled || epoch !== this.#transportEpoch
1755
+ ? 'offline'
1756
+ : subscriptionEpoch !== this.#subscriptionEpoch
1757
+ ? 'missing_coverage'
1758
+ : 'sync_failed',
1759
+ };
1760
+ }
1761
+ if (!this.#transportEnabled || epoch !== this.#transportEpoch)
1762
+ return { proven: false, reason: 'offline' };
1763
+ if (subscriptionEpoch !== this.#subscriptionEpoch)
1764
+ return { proven: false, reason: 'missing_coverage' };
1765
+ if (this.#securityLifecycle !== 'active' ||
1766
+ securityEpoch !== this.#securityEpoch)
1767
+ return { proven: false, reason: 'sync_failed' };
1768
+ if (report.schemaFloor !== undefined)
1769
+ return { proven: false, reason: 'schema_floor' };
1770
+ if (report.budgetExhausted)
1771
+ return { proven: false, reason: 'budget_exhausted' };
1772
+ try {
1773
+ return this.#db.transaction(() => {
1774
+ const snapshot = this.#readSnapshot({
1775
+ statements: [],
1776
+ subscriptions: before.map((sub) => sub.id),
1777
+ commitIds: [clientCommitId],
1778
+ });
1779
+ const delivery = snapshot.deliveries[0];
1780
+ const current = readCommitOutcome(this.#db, clientCommitId);
1781
+ if (delivery?.status !== 'known' ||
1782
+ current === undefined ||
1783
+ current.sequence !== sequence ||
1784
+ current.resolution !== 'active' ||
1785
+ (current.status !== 'conflict' && current.status !== 'rejected') ||
1786
+ current.operations === undefined ||
1787
+ current.retainedRows === undefined ||
1788
+ current.operations.length !== current.retainedRows.length ||
1789
+ current.retainedRows.length === 0)
1790
+ return {
1791
+ proven: false,
1792
+ reason: report.revoked.length > 0 ? 'revoked' : 'outcome_unavailable',
1793
+ };
1794
+ const after = new Map(loadSubscriptions(this.#db).map((sub) => [sub.id, sub]));
1795
+ const states = new Map(snapshot.subscriptions.map((sub) => [sub.id, sub]));
1796
+ const candidates = before.flatMap((previous) => {
1797
+ const sub = after.get(previous.id);
1798
+ const state = states.get(previous.id);
1799
+ return sub !== undefined &&
1800
+ sub.table === previous.table &&
1801
+ sub.params === previous.params &&
1802
+ canonicalScopeJson(sub.scopes) ===
1803
+ canonicalScopeJson(previous.scopes) &&
1804
+ sub.effectiveScopes !== undefined &&
1805
+ state?.state === 'known' &&
1806
+ state.bootstrapComplete
1807
+ ? [{ table: sub.table, scopes: sub.effectiveScopes }]
1808
+ : [];
1809
+ });
1810
+ const covered = (tableName, row) => {
1811
+ const table = this.#schema.tables.get(tableName);
1812
+ if (table === undefined || row === null)
1813
+ return false;
1814
+ const values = Object.fromEntries(Object.entries(row).map(([key, value]) => [
1815
+ key,
1816
+ rowValueToJson(value),
1817
+ ]));
1818
+ return candidates.some((candidate) => {
1819
+ return (candidate.table === tableName &&
1820
+ Object.keys(candidate.scopes).every((variable) => {
1821
+ const column = table.scopeColumnByVariable.get(variable);
1822
+ const value = column === undefined ? undefined : row[column];
1823
+ return ((typeof value === 'string' && value.length > 0) ||
1824
+ typeof value === 'number' ||
1825
+ typeof value === 'boolean');
1826
+ }) &&
1827
+ matchesLocalScopes(table, candidate.scopes, values));
1828
+ });
1829
+ };
1830
+ for (const row of current.retainedRows) {
1831
+ if (!covered(row.table, row.serverRow ?? row.localRow) ||
1832
+ row.uniqueConflicts?.some((conflict) => !covered(row.table, conflict.serverRow))) {
1833
+ return {
1834
+ proven: false,
1835
+ reason: report.revoked.length > 0 ? 'revoked' : 'missing_coverage',
1836
+ };
1837
+ }
1838
+ }
1839
+ return { proven: true, rows: current.retainedRows };
1840
+ });
1841
+ }
1842
+ catch {
1843
+ return { proven: false, reason: 'snapshot_failed' };
1844
+ }
1845
+ }
1704
1846
  /** Newest-first durable outcome journal. */
1705
1847
  commitOutcomes(query = {}) {
1706
1848
  this.#requireActive();
@@ -1894,6 +2036,7 @@ export class SyncClient {
1894
2036
  });
1895
2037
  if (!registered)
1896
2038
  return;
2039
+ this.#subscriptionEpoch += 1;
1897
2040
  this.#setSyncNeeded(true);
1898
2041
  this.#emitSyncIntent({ kind: 'interactive' });
1899
2042
  this.#emitDiagnostics();
@@ -1903,6 +2046,7 @@ export class SyncClient {
1903
2046
  if (getSubscription(this.#db, id) === undefined)
1904
2047
  return;
1905
2048
  deleteSubscription(this.#db, id);
2049
+ this.#subscriptionEpoch += 1;
1906
2050
  this.#setSyncNeeded(true);
1907
2051
  this.#emitSyncIntent({ kind: 'interactive' });
1908
2052
  this.#emitDiagnostics();
@@ -1966,6 +2110,7 @@ export class SyncClient {
1966
2110
  });
1967
2111
  changed = true;
1968
2112
  widened = true;
2113
+ this.#subscriptionEpoch += 1;
1969
2114
  }
1970
2115
  // Shrink: units live but not wanted → unsubscribe fused with eviction.
1971
2116
  for (const { unit, subId } of live) {
@@ -1973,6 +2118,7 @@ export class SyncClient {
1973
2118
  continue;
1974
2119
  await this.#evictUnit(baseKey, base, unit, subId);
1975
2120
  changed = true;
2121
+ this.#subscriptionEpoch += 1;
1976
2122
  }
1977
2123
  });
1978
2124
  const effects = {
@@ -3581,6 +3727,7 @@ export class SyncClient {
3581
3727
  let section;
3582
3728
  let errorFrame;
3583
3729
  let deltaCursor = -1;
3730
+ const incompleteSubscriptions = new Set(mode === 'pull' ? subsById.keys() : []);
3584
3731
  // §5.4/§5.5: issue every segment download of this response before the
3585
3732
  // apply loop reaches the first one, so a paged bootstrap overlaps its page
3586
3733
  // fetches instead of paying one blocking round trip per page. Eligibility
@@ -3845,6 +3992,11 @@ export class SyncClient {
3845
3992
  break;
3846
3993
  }
3847
3994
  case 'SUB_END': {
3995
+ if (section?.sub !== undefined &&
3996
+ !section.skip &&
3997
+ this.#localResetEpoch === resetEpoch) {
3998
+ incompleteSubscriptions.delete(section.sub.id);
3999
+ }
3848
4000
  if (section !== undefined &&
3849
4001
  !section.skip &&
3850
4002
  section.sub !== undefined &&
@@ -3894,6 +4046,10 @@ export class SyncClient {
3894
4046
  }
3895
4047
  if (errorFrame !== undefined)
3896
4048
  throw errorFrame;
4049
+ if (incompleteSubscriptions.size > 0) {
4050
+ this.#setSyncNeeded(true);
4051
+ this.#emitSyncIntent({ kind: 'interactive' });
4052
+ }
3897
4053
  if (mode === 'delta') {
3898
4054
  if (deltaCursor >= 0)
3899
4055
  this.#sendAck(deltaCursor);
@@ -64,7 +64,7 @@ export interface RetainedCommitRow {
64
64
  readonly rowId: string;
65
65
  /** Complete intended row, or null for a local deletion. */
66
66
  readonly localRow: Readonly<Record<string, RowValue>> | null;
67
- /** Latest authorized server base, or null for an absent server row. */
67
+ /** Latest delivered authorized base; a new rejection can precede its pull. */
68
68
  readonly serverRow: Readonly<Record<string, RowValue>> | null;
69
69
  readonly serverVersion: number | null;
70
70
  }
@@ -436,6 +436,10 @@ export function startSyncWorker(overrides = {}) {
436
436
  const running = requireClient();
437
437
  return serializedSync(() => running.syncUntilIdle(options));
438
438
  },
439
+ proveCurrentBase: (outcome, options) => {
440
+ const running = requireClient();
441
+ return serializedSync(() => running.proveCurrentBase(outcome, options));
442
+ },
439
443
  resetClientId: () => requireClient().resetClientId(),
440
444
  localRevision: () => requireClient().localRevision,
441
445
  diagnosticsSnapshot: (request) => {
@@ -25,7 +25,7 @@ import type { PromiseMethods } from './client.js';
25
25
  */
26
26
  import type { WakeReason } from '@syncular/core';
27
27
  import type { BlobRef, CachedBlob } from './blob.js';
28
- import type { ConflictRecord, MutationInput, PresencePeer, QueryReadSpec, QuerySnapshot, RejectionRecord, SecurityLifecycle, SnapshotRead, SnapshotReadRequest, SubscribeInput, SyncClientConfig, SyncClientLimits, SyncSummary, SyncIdleOptions, SyncIdleResult, WindowState } from './client.js';
28
+ import type { ConflictRecord, CurrentBaseProof, MutationInput, PresencePeer, QueryReadSpec, QuerySnapshot, RejectionRecord, SecurityLifecycle, SnapshotRead, SnapshotReadRequest, SubscribeInput, SyncClientConfig, SyncClientLimits, SyncSummary, SyncIdleOptions, SyncIdleResult, WindowState } from './client.js';
29
29
  import type { SqlRow, SqlValue } from './database.js';
30
30
  import { ClientDiagnosticsEmitter, type ClientDiagnosticsListener, type ClientDiagnosticsRequest, type ClientDiagnosticsSnapshot, type RealtimePolicy } from './diagnostics.js';
31
31
  import type { EncryptionKeyringConfig } from './encryption.js';
@@ -255,6 +255,7 @@ export declare class SyncClientHandle implements PromiseMethods<WorkerApi> {
255
255
  }>;
256
256
  sync(): Promise<SyncSummary>;
257
257
  syncUntilIdle(options?: number | SyncIdleOptions): Promise<SyncIdleResult>;
258
+ proveCurrentBase(outcome: Pick<CommitOutcome, 'clientCommitId' | 'sequence'>, maxRounds?: number): Promise<CurrentBaseProof>;
258
259
  /**
259
260
  * Rotate the client id (§1.5) after a `sync.invalid_client_id` refusal.
260
261
  * The worker's next round carries the new id; the replica and outbox stay
@@ -316,6 +316,12 @@ export class SyncClientHandle {
316
316
  syncUntilIdle(options) {
317
317
  return this.#call('syncUntilIdle', [options]);
318
318
  }
319
+ proveCurrentBase(outcome, maxRounds) {
320
+ return this.#call('proveCurrentBase', [
321
+ { clientCommitId: outcome.clientCommitId, sequence: outcome.sequence },
322
+ maxRounds,
323
+ ]);
324
+ }
319
325
  /**
320
326
  * Rotate the client id (§1.5) after a `sync.invalid_client_id` refusal.
321
327
  * The worker's next round carries the new id; the replica and outbox stay
@@ -19,7 +19,7 @@ import type { SyncProgress } from './progress.js';
19
19
  */
20
20
  import type { WakeReason } from '@syncular/core';
21
21
  import type { BlobRef, CachedBlob } from './blob.js';
22
- import type { ConflictRecord, ClientSnapshotMethods, MutationInput, PresencePeer, QueryReadSpec, QuerySnapshot, SecurityLifecycle, SubscribeInput, SyncClientConfig, SyncClientLimits, SyncSummary, SyncIdleOptions, SyncIdleResult, WindowState } from './client.js';
22
+ import type { ConflictRecord, CurrentBaseProof, ClientSnapshotMethods, MutationInput, PresencePeer, QueryReadSpec, QuerySnapshot, SecurityLifecycle, SubscribeInput, SyncClientConfig, SyncClientLimits, SyncSummary, SyncIdleOptions, SyncIdleResult, WindowState } from './client.js';
23
23
  import type { SqlRow, SqlValue } from './database.js';
24
24
  import type { ClientDiagnosticsSnapshot, RealtimePolicy } from './diagnostics.js';
25
25
  import type { EncryptionKeyringConfig } from './encryption.js';
@@ -27,6 +27,7 @@ import type { ClientChangeBatch, LocalRevision } from './invalidation.js';
27
27
  import type { LocalDataPurgeInput, LocalDataPurgeResult } from './local-purge.js';
28
28
  import type { LocalDataRebootstrapInput, LocalDataRebootstrapResult } from './local-rebootstrap.js';
29
29
  import type { OutboxCommit } from './outbox.js';
30
+ import type { CommitOutcome } from './outcomes.js';
30
31
  import type { PreviousVersionAudit, PreviousVersionReadSpec, PreviousVersionSnapshot } from './previous-version.js';
31
32
  import type { ClientSchema } from './schema.js';
32
33
  import type { SubscriptionRecord } from './state.js';
@@ -155,6 +156,7 @@ export interface WorkerApi extends Omit<ClientSnapshotMethods, 'querySnapshot'>
155
156
  };
156
157
  sync(): Promise<SyncSummary>;
157
158
  syncUntilIdle(options?: number | SyncIdleOptions): Promise<SyncIdleResult>;
159
+ proveCurrentBase(outcome: Pick<CommitOutcome, 'clientCommitId' | 'sequence'>, maxRounds?: number): Promise<CurrentBaseProof>;
158
160
  resetClientId(): string;
159
161
  query(sql: string, params?: readonly SqlValue[]): SqlRow[];
160
162
  authoritySnapshot(): import('./authority.js').AuthoritySnapshot;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@syncular/client",
3
- "version": "0.49.2",
3
+ "version": "0.51.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",
@@ -97,10 +97,10 @@
97
97
  },
98
98
  "dependencies": {
99
99
  "@sqlite.org/sqlite-wasm": "^3.53.0-build1",
100
- "@syncular/core": "0.49.2"
100
+ "@syncular/core": "0.51.0"
101
101
  },
102
102
  "devDependencies": {
103
- "@syncular/server": "0.49.2",
103
+ "@syncular/server": "0.51.0",
104
104
  "playwright": "1.63.0",
105
105
  "@electric-sql/pglite": "^0.5.4"
106
106
  }
package/src/client.ts CHANGED
@@ -177,6 +177,7 @@ import {
177
177
  persistedCommitOutcome,
178
178
  pruneCommitOutcomes,
179
179
  type RejectionRecord,
180
+ type RetainedCommitRow,
180
181
  type ResolveCommitOutcomeInput,
181
182
  commitOutcome as readCommitOutcome,
182
183
  recordCommitOutcome,
@@ -365,6 +366,21 @@ export interface SyncIdleOptions {
365
366
  readonly timeoutMs?: number;
366
367
  }
367
368
 
369
+ export type CurrentBaseProof =
370
+ | { readonly proven: true; readonly rows: readonly RetainedCommitRow[] }
371
+ | {
372
+ readonly proven: false;
373
+ readonly reason:
374
+ | 'offline'
375
+ | 'sync_failed'
376
+ | 'schema_floor'
377
+ | 'budget_exhausted'
378
+ | 'snapshot_failed'
379
+ | 'missing_coverage'
380
+ | 'revoked'
381
+ | 'outcome_unavailable';
382
+ };
383
+
368
384
  export interface SyncClientLimits {
369
385
  readonly limitCommits?: number;
370
386
  readonly limitSnapshotRows?: number;
@@ -874,7 +890,10 @@ export class SyncClient {
874
890
  /** RFC 0005 resolved capture budgets; undefined ⇒ feature off. */
875
891
  readonly #previousVersion: PreviousVersionCaptureConfig | undefined;
876
892
  #securityLifecycle: SecurityLifecycle;
893
+ #securityEpoch = 0;
877
894
  #transportEnabled: boolean;
895
+ #transportEpoch = 0;
896
+ #subscriptionEpoch = 0;
878
897
  readonly #now: () => number;
879
898
  readonly #outcomeRetentionMaxEntries: number;
880
899
  readonly #retainFailedCommits: boolean;
@@ -1543,6 +1562,7 @@ export class SyncClient {
1543
1562
  throw invalidRequest('transportEnabled must be a boolean');
1544
1563
  if (this.#transportEnabled === enabled) return;
1545
1564
  this.#transportEnabled = enabled;
1565
+ this.#transportEpoch += 1;
1546
1566
  if (!enabled && !this.#syncOutstanding) this.disconnectRealtime();
1547
1567
  this.#emitSyncIntent(
1548
1568
  enabled && this.#securityLifecycle === 'active'
@@ -1571,6 +1591,7 @@ export class SyncClient {
1571
1591
  this.#requireStarted();
1572
1592
  if (this.#preflightBarrier !== undefined) return this.#preflightBarrier;
1573
1593
  this.#securityLifecycle = 'preflight';
1594
+ this.#securityEpoch += 1;
1574
1595
  this.disconnectRealtime();
1575
1596
  const barrier = (async () => {
1576
1597
  await Promise.allSettled([this.#opChain, ...this.#protectedAsync]);
@@ -2743,6 +2764,168 @@ export class SyncClient {
2743
2764
  return readCommitOutcome(this.#db, clientCommitId);
2744
2765
  }
2745
2766
 
2767
+ /** Prove all retained bases against a completed post-rejection pull (§7.2.1). */
2768
+ async proveCurrentBase(
2769
+ outcome: Pick<CommitOutcome, 'clientCommitId' | 'sequence'>,
2770
+ maxRounds?: number,
2771
+ ): Promise<CurrentBaseProof> {
2772
+ this.#requireActive();
2773
+ if (
2774
+ maxRounds !== undefined &&
2775
+ (!Number.isInteger(maxRounds) || maxRounds < 1 || maxRounds > 0xffffffff)
2776
+ )
2777
+ throw invalidRequest('maxRounds must be a positive integer');
2778
+ const { clientCommitId, sequence } = outcome;
2779
+ let initial: CommitOutcome | undefined;
2780
+ try {
2781
+ initial = readCommitOutcome(this.#db, clientCommitId);
2782
+ } catch {
2783
+ return { proven: false, reason: 'snapshot_failed' };
2784
+ }
2785
+ if (
2786
+ initial === undefined ||
2787
+ initial.sequence !== sequence ||
2788
+ initial.resolution !== 'active' ||
2789
+ (initial.status !== 'conflict' && initial.status !== 'rejected') ||
2790
+ initial.operations === undefined ||
2791
+ initial.retainedRows === undefined ||
2792
+ initial.operations.length !== initial.retainedRows.length ||
2793
+ initial.retainedRows.length === 0
2794
+ )
2795
+ return { proven: false, reason: 'outcome_unavailable' };
2796
+ if (!this.#transportEnabled) return { proven: false, reason: 'offline' };
2797
+ await this.#opChain;
2798
+ if (!this.#transportEnabled) return { proven: false, reason: 'offline' };
2799
+ const epoch = this.#transportEpoch;
2800
+ const subscriptionEpoch = this.#subscriptionEpoch;
2801
+ const securityEpoch = this.#securityEpoch;
2802
+ let before: SubscriptionRecord[];
2803
+ try {
2804
+ before = loadSubscriptions(this.#db);
2805
+ } catch {
2806
+ return { proven: false, reason: 'snapshot_failed' };
2807
+ }
2808
+ let report: SyncIdleResult;
2809
+ try {
2810
+ report = await this.syncUntilIdle(maxRounds);
2811
+ } catch {
2812
+ return {
2813
+ proven: false,
2814
+ reason:
2815
+ !this.#transportEnabled || epoch !== this.#transportEpoch
2816
+ ? 'offline'
2817
+ : subscriptionEpoch !== this.#subscriptionEpoch
2818
+ ? 'missing_coverage'
2819
+ : 'sync_failed',
2820
+ };
2821
+ }
2822
+ if (!this.#transportEnabled || epoch !== this.#transportEpoch)
2823
+ return { proven: false, reason: 'offline' };
2824
+ if (subscriptionEpoch !== this.#subscriptionEpoch)
2825
+ return { proven: false, reason: 'missing_coverage' };
2826
+ if (
2827
+ this.#securityLifecycle !== 'active' ||
2828
+ securityEpoch !== this.#securityEpoch
2829
+ )
2830
+ return { proven: false, reason: 'sync_failed' };
2831
+ if (report.schemaFloor !== undefined)
2832
+ return { proven: false, reason: 'schema_floor' };
2833
+ if (report.budgetExhausted)
2834
+ return { proven: false, reason: 'budget_exhausted' };
2835
+ try {
2836
+ return this.#db.transaction(() => {
2837
+ const snapshot = this.#readSnapshot({
2838
+ statements: [],
2839
+ subscriptions: before.map((sub) => sub.id),
2840
+ commitIds: [clientCommitId],
2841
+ });
2842
+ const delivery = snapshot.deliveries[0];
2843
+ const current = readCommitOutcome(this.#db, clientCommitId);
2844
+ if (
2845
+ delivery?.status !== 'known' ||
2846
+ current === undefined ||
2847
+ current.sequence !== sequence ||
2848
+ current.resolution !== 'active' ||
2849
+ (current.status !== 'conflict' && current.status !== 'rejected') ||
2850
+ current.operations === undefined ||
2851
+ current.retainedRows === undefined ||
2852
+ current.operations.length !== current.retainedRows.length ||
2853
+ current.retainedRows.length === 0
2854
+ )
2855
+ return {
2856
+ proven: false,
2857
+ reason:
2858
+ report.revoked.length > 0 ? 'revoked' : 'outcome_unavailable',
2859
+ };
2860
+ const after = new Map(
2861
+ loadSubscriptions(this.#db).map((sub) => [sub.id, sub]),
2862
+ );
2863
+ const states = new Map(
2864
+ snapshot.subscriptions.map((sub) => [sub.id, sub]),
2865
+ );
2866
+ const candidates = before.flatMap((previous) => {
2867
+ const sub = after.get(previous.id);
2868
+ const state = states.get(previous.id);
2869
+ return sub !== undefined &&
2870
+ sub.table === previous.table &&
2871
+ sub.params === previous.params &&
2872
+ canonicalScopeJson(sub.scopes) ===
2873
+ canonicalScopeJson(previous.scopes) &&
2874
+ sub.effectiveScopes !== undefined &&
2875
+ state?.state === 'known' &&
2876
+ state.bootstrapComplete
2877
+ ? [{ table: sub.table, scopes: sub.effectiveScopes }]
2878
+ : [];
2879
+ });
2880
+ const covered = (
2881
+ tableName: string,
2882
+ row: Readonly<Record<string, RowValue>> | null,
2883
+ ): boolean => {
2884
+ const table = this.#schema.tables.get(tableName);
2885
+ if (table === undefined || row === null) return false;
2886
+ const values = Object.fromEntries(
2887
+ Object.entries(row).map(([key, value]) => [
2888
+ key,
2889
+ rowValueToJson(value),
2890
+ ]),
2891
+ );
2892
+ return candidates.some((candidate) => {
2893
+ return (
2894
+ candidate.table === tableName &&
2895
+ Object.keys(candidate.scopes).every((variable) => {
2896
+ const column = table.scopeColumnByVariable.get(variable);
2897
+ const value = column === undefined ? undefined : row[column];
2898
+ return (
2899
+ (typeof value === 'string' && value.length > 0) ||
2900
+ typeof value === 'number' ||
2901
+ typeof value === 'boolean'
2902
+ );
2903
+ }) &&
2904
+ matchesLocalScopes(table, candidate.scopes, values)
2905
+ );
2906
+ });
2907
+ };
2908
+ for (const row of current.retainedRows) {
2909
+ if (
2910
+ !covered(row.table, row.serverRow ?? row.localRow) ||
2911
+ row.uniqueConflicts?.some(
2912
+ (conflict) => !covered(row.table, conflict.serverRow),
2913
+ )
2914
+ ) {
2915
+ return {
2916
+ proven: false,
2917
+ reason:
2918
+ report.revoked.length > 0 ? 'revoked' : 'missing_coverage',
2919
+ };
2920
+ }
2921
+ }
2922
+ return { proven: true, rows: current.retainedRows };
2923
+ });
2924
+ } catch {
2925
+ return { proven: false, reason: 'snapshot_failed' };
2926
+ }
2927
+ }
2928
+
2746
2929
  /** Newest-first durable outcome journal. */
2747
2930
  commitOutcomes(query: CommitOutcomeQuery = {}): readonly CommitOutcome[] {
2748
2931
  this.#requireActive();
@@ -2985,6 +3168,7 @@ export class SyncClient {
2985
3168
  }
2986
3169
  });
2987
3170
  if (!registered) return;
3171
+ this.#subscriptionEpoch += 1;
2988
3172
  this.#setSyncNeeded(true);
2989
3173
  this.#emitSyncIntent({ kind: 'interactive' });
2990
3174
  this.#emitDiagnostics();
@@ -2994,6 +3178,7 @@ export class SyncClient {
2994
3178
  this.#requireActive();
2995
3179
  if (getSubscription(this.#db, id) === undefined) return;
2996
3180
  deleteSubscription(this.#db, id);
3181
+ this.#subscriptionEpoch += 1;
2997
3182
  this.#setSyncNeeded(true);
2998
3183
  this.#emitSyncIntent({ kind: 'interactive' });
2999
3184
  this.#emitDiagnostics();
@@ -3068,6 +3253,7 @@ export class SyncClient {
3068
3253
  });
3069
3254
  changed = true;
3070
3255
  widened = true;
3256
+ this.#subscriptionEpoch += 1;
3071
3257
  }
3072
3258
 
3073
3259
  // Shrink: units live but not wanted → unsubscribe fused with eviction.
@@ -3075,6 +3261,7 @@ export class SyncClient {
3075
3261
  if (wanted.has(unit)) continue;
3076
3262
  await this.#evictUnit(baseKey, base, unit, subId);
3077
3263
  changed = true;
3264
+ this.#subscriptionEpoch += 1;
3078
3265
  }
3079
3266
  });
3080
3267
  const effects: CommandEffects = {
@@ -5008,6 +5195,9 @@ export class SyncClient {
5008
5195
  let section: OpenSection | undefined;
5009
5196
  let errorFrame: ClientSyncError | undefined;
5010
5197
  let deltaCursor = -1;
5198
+ const incompleteSubscriptions = new Set(
5199
+ mode === 'pull' ? subsById.keys() : [],
5200
+ );
5011
5201
 
5012
5202
  // §5.4/§5.5: issue every segment download of this response before the
5013
5203
  // apply loop reaches the first one, so a paged bootstrap overlaps its page
@@ -5352,6 +5542,13 @@ export class SyncClient {
5352
5542
  break;
5353
5543
  }
5354
5544
  case 'SUB_END': {
5545
+ if (
5546
+ section?.sub !== undefined &&
5547
+ !section.skip &&
5548
+ this.#localResetEpoch === resetEpoch
5549
+ ) {
5550
+ incompleteSubscriptions.delete(section.sub.id);
5551
+ }
5355
5552
  if (
5356
5553
  section !== undefined &&
5357
5554
  !section.skip &&
@@ -5415,6 +5612,11 @@ export class SyncClient {
5415
5612
 
5416
5613
  if (errorFrame !== undefined) throw errorFrame;
5417
5614
 
5615
+ if (incompleteSubscriptions.size > 0) {
5616
+ this.#setSyncNeeded(true);
5617
+ this.#emitSyncIntent({ kind: 'interactive' });
5618
+ }
5619
+
5418
5620
  if (mode === 'delta') {
5419
5621
  if (deltaCursor >= 0) this.#sendAck(deltaCursor);
5420
5622
  } else {
package/src/outcomes.ts CHANGED
@@ -95,7 +95,7 @@ export interface RetainedCommitRow {
95
95
  readonly rowId: string;
96
96
  /** Complete intended row, or null for a local deletion. */
97
97
  readonly localRow: Readonly<Record<string, RowValue>> | null;
98
- /** Latest authorized server base, or null for an absent server row. */
98
+ /** Latest delivered authorized base; a new rejection can precede its pull. */
99
99
  readonly serverRow: Readonly<Record<string, RowValue>> | null;
100
100
  readonly serverVersion: number | null;
101
101
  }
@@ -605,6 +605,10 @@ export function startSyncWorker(overrides: SyncWorkerOverrides = {}): void {
605
605
  const running = requireClient();
606
606
  return serializedSync(() => running.syncUntilIdle(options));
607
607
  },
608
+ proveCurrentBase: (outcome, options) => {
609
+ const running = requireClient();
610
+ return serializedSync(() => running.proveCurrentBase(outcome, options));
611
+ },
608
612
  resetClientId: () => requireClient().resetClientId(),
609
613
  localRevision: () => requireClient().localRevision,
610
614
  diagnosticsSnapshot: (request) => {
@@ -31,6 +31,7 @@ import type { WakeReason } from '@syncular/core';
31
31
  import type { BlobRef, CachedBlob } from './blob';
32
32
  import type {
33
33
  ConflictRecord,
34
+ CurrentBaseProof,
34
35
  MutationInput,
35
36
  PresencePeer,
36
37
  QueryReadSpec,
@@ -655,6 +656,16 @@ export class SyncClientHandle implements PromiseMethods<WorkerApi> {
655
656
  return this.#call('syncUntilIdle', [options]);
656
657
  }
657
658
 
659
+ proveCurrentBase(
660
+ outcome: Pick<CommitOutcome, 'clientCommitId' | 'sequence'>,
661
+ maxRounds?: number,
662
+ ): Promise<CurrentBaseProof> {
663
+ return this.#call('proveCurrentBase', [
664
+ { clientCommitId: outcome.clientCommitId, sequence: outcome.sequence },
665
+ maxRounds,
666
+ ]);
667
+ }
668
+
658
669
  /**
659
670
  * Rotate the client id (§1.5) after a `sync.invalid_client_id` refusal.
660
671
  * The worker's next round carries the new id; the replica and outbox stay
@@ -21,6 +21,7 @@ import type { WakeReason } from '@syncular/core';
21
21
  import type { BlobRef, CachedBlob } from './blob';
22
22
  import type {
23
23
  ConflictRecord,
24
+ CurrentBaseProof,
24
25
  ClientSnapshotMethods,
25
26
  MutationInput,
26
27
  PresencePeer,
@@ -45,6 +46,7 @@ import type {
45
46
  LocalDataRebootstrapResult,
46
47
  } from './local-rebootstrap';
47
48
  import type { OutboxCommit } from './outbox';
49
+ import type { CommitOutcome } from './outcomes';
48
50
  import type {
49
51
  PreviousVersionAudit,
50
52
  PreviousVersionReadSpec,
@@ -207,6 +209,10 @@ export interface WorkerApi extends Omit<
207
209
  previousVersionDiscard(): { present: boolean; discarded: boolean };
208
210
  sync(): Promise<SyncSummary>;
209
211
  syncUntilIdle(options?: number | SyncIdleOptions): Promise<SyncIdleResult>;
212
+ proveCurrentBase(
213
+ outcome: Pick<CommitOutcome, 'clientCommitId' | 'sequence'>,
214
+ maxRounds?: number,
215
+ ): Promise<CurrentBaseProof>;
210
216
  resetClientId(): string;
211
217
  query(sql: string, params?: readonly SqlValue[]): SqlRow[];
212
218
  authoritySnapshot(): import('./authority').AuthoritySnapshot;