@syncular/server 0.94.0 → 0.96.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/src/pull.ts CHANGED
@@ -26,7 +26,12 @@ import {
26
26
  import { computeEffective, type ResolvedScopes, scopeDigest } from './scopes';
27
27
  import type { SegmentRecord, SegmentStore } from './segment-store';
28
28
  import { issueSegmentUrl } from './signed-url';
29
- import type { ServerStorage, StoredCommit, StoredRow } from './storage';
29
+ import type {
30
+ PartitionHorizons,
31
+ ServerStorage,
32
+ StoredCommit,
33
+ StoredRow,
34
+ } from './storage';
30
35
  import { projectRowPayload, projectRowValues } from './schema-window';
31
36
 
32
37
  // One artifact build per owning storage pair and complete immutable identity.
@@ -433,9 +438,9 @@ async function readTableStart(
433
438
  return { firstPage: await scan };
434
439
  }
435
440
  // §4.7: a sqlite-lane table pins at the newest commit carrying all of the
436
- // unit's values (never below the horizon, never above maxCommitSeq), so a
437
- // stored image stays the reuse key's match until this scope changes
438
- // (§5.3). The server computes the pin; a client token never supplies it.
441
+ // unit's values (never below the table's horizon, never above
442
+ // maxCommitSeq), so a stored image stays the reuse key's match until this
443
+ // scope changes (§5.3). The server computes the pin; a client token never supplies it.
439
444
  const [firstPage, latest] = await Promise.all([
440
445
  scan,
441
446
  ctx.storage.latestScopedChangeSeq(ctx.partition, {
@@ -617,6 +622,14 @@ async function* sqliteImageSegment(
617
622
  return record;
618
623
  }
619
624
 
625
+ /**
626
+ * A section frame: a response frame, or a rows segment's `SEGMENT_REF`
627
+ * whose put is in flight. The consumer emits `ref` in its frame order.
628
+ */
629
+ type SectionFrame =
630
+ | ResponseFrame
631
+ | { readonly type: 'PENDING_REF'; readonly ref: Promise<ResponseFrame> };
632
+
620
633
  /**
621
634
  * One table's segments within the page budget: range images while the table
622
635
  * is on the image lane, then rows pages. Returns the pages it used, the row
@@ -635,7 +648,7 @@ async function* tableSegments(
635
648
  trace: PullSectionTrace | undefined,
636
649
  logEpoch: string,
637
650
  ): AsyncGenerator<
638
- ResponseFrame,
651
+ SectionFrame,
639
652
  { pages: number; rows: number; rowCursor: string | null; image: boolean }
640
653
  > {
641
654
  const { storage, segments, partition } = ctx;
@@ -725,34 +738,40 @@ async function* tableSegments(
725
738
  });
726
739
  yield { type: 'SEGMENT_INLINE', payload: bytes };
727
740
  } else {
728
- const record = await segments.put(
729
- {
730
- partition,
731
- logEpoch,
732
- table: pair.table.name,
733
- schemaVersion: schema.version,
734
- mediaType: 'rows',
735
- scopeDigest: digest,
736
- asOfCommitSeq: pin,
737
- rowCount: pageRows.length,
738
- rowCursor,
739
- nextRowCursor,
740
- },
741
- bytes,
742
- now,
743
- );
741
+ // The page's put runs while the next page is scanned; the caller keeps
742
+ // six puts in flight and emits the frames in order.
744
743
  trace?.segments.push({
745
744
  mediaType: 'rows',
746
745
  delivery: 'ref',
747
746
  origin: 'built',
748
- bytes: record.byteLength,
749
- rows: record.rowCount,
747
+ bytes: bytes.length,
748
+ rows: pageRows.length,
750
749
  });
751
- yield segmentRefFrame(
752
- record,
753
- digest,
754
- await signedUrlFields(ctx, limits, record.segmentId, digest, now),
755
- );
750
+ const ref = segments
751
+ .put(
752
+ {
753
+ partition,
754
+ logEpoch,
755
+ table: pair.table.name,
756
+ schemaVersion: schema.version,
757
+ mediaType: 'rows',
758
+ scopeDigest: digest,
759
+ asOfCommitSeq: pin,
760
+ rowCount: pageRows.length,
761
+ rowCursor,
762
+ nextRowCursor,
763
+ },
764
+ bytes,
765
+ now,
766
+ )
767
+ .then(async (record) =>
768
+ segmentRefFrame(
769
+ record,
770
+ digest,
771
+ await signedUrlFields(ctx, limits, record.segmentId, digest, now),
772
+ ),
773
+ );
774
+ yield { type: 'PENDING_REF', ref };
756
775
  }
757
776
  if (!hasMore)
758
777
  return { pages: page + 1, rows, rowCursor: null, image: false };
@@ -792,17 +811,22 @@ export function planBootstrap(
792
811
  unit: UnitPlan,
793
812
  bootstrapState: string | undefined,
794
813
  maxSeq: number,
795
- horizonSeq: number,
814
+ horizon: PartitionHorizons,
796
815
  logEpoch: string,
797
816
  keptCursor = 0,
798
817
  ): BootstrapPlan {
799
818
  // §4.7: resume at the token's pin unless the token is unusable, or the pin
800
- // fell behind the horizon or a restricted bootstrap's kept cursor; then
801
- // restart from a fresh pin.
819
+ // fell behind the horizon, the table horizon of a bootstrap table, or a
820
+ // restricted bootstrap's kept cursor; then restart from a fresh pin.
802
821
  const token = parseBootstrapToken(bootstrapState, unit.tables, maxSeq);
803
822
  const resume =
804
823
  token !== undefined &&
805
- token.asOfCommitSeq >= Math.max(horizonSeq, keptCursor)
824
+ token.asOfCommitSeq >=
825
+ Math.max(
826
+ horizon.seq,
827
+ keptCursor,
828
+ ...unit.tables.map((table) => horizon.tables.get(table.name) ?? -1),
829
+ )
806
830
  ? token
807
831
  : undefined;
808
832
  const tableIndex = resume?.tableIndex ?? 0;
@@ -826,7 +850,7 @@ export function planBootstrap(
826
850
  index === tableIndex ? rowCursor : null,
827
851
  index === tableIndex && image,
828
852
  maxSeq,
829
- horizonSeq,
853
+ Math.max(horizon.seq, horizon.tables.get(table.name) ?? -1),
830
854
  logEpoch,
831
855
  );
832
856
  // A section that stops early never awaits the later starts.
@@ -876,7 +900,7 @@ export async function* bootstrapSegments(
876
900
  plan: BootstrapPlan,
877
901
  trace: PullSectionTrace | undefined,
878
902
  logEpoch: string,
879
- ): AsyncGenerator<ResponseFrame, string | undefined> {
903
+ ): AsyncGenerator<SectionFrame, string | undefined> {
880
904
  const { unit, pin } = plan;
881
905
  let { tableIndex, rowCursor, image } = plan;
882
906
  let pages = 0;
@@ -1007,7 +1031,7 @@ export async function publishSqliteImage(
1007
1031
  accept: ACCEPT_SQLITE,
1008
1032
  };
1009
1033
  const maxSeq = await config.storage.getMaxCommitSeq(partition);
1010
- const horizonSeq = await config.storage.getHorizonSeq(partition);
1034
+ const horizons = await config.storage.getHorizons(partition);
1011
1035
  const trace: PullSectionTrace = { segments: [] };
1012
1036
  const plan = planBootstrap(
1013
1037
  ctx,
@@ -1016,7 +1040,7 @@ export async function publishSqliteImage(
1016
1040
  unit,
1017
1041
  undefined,
1018
1042
  maxSeq,
1019
- horizonSeq,
1043
+ horizons,
1020
1044
  logEpoch,
1021
1045
  );
1022
1046
  const refs: SegmentRefFrame[] = [];
@@ -1028,7 +1052,8 @@ export async function publishSqliteImage(
1028
1052
  trace,
1029
1053
  logEpoch,
1030
1054
  )) {
1031
- if (frame.type === 'SEGMENT_REF' && frame.mediaType === 'sqlite') {
1055
+ if (frame.type === 'PENDING_REF') await frame.ref;
1056
+ else if (frame.type === 'SEGMENT_REF' && frame.mediaType === 'sqlite') {
1032
1057
  refs.push(frame);
1033
1058
  }
1034
1059
  }
package/src/push.ts CHANGED
@@ -71,7 +71,6 @@ import type {
71
71
  CommitValidationRow,
72
72
  CommitValidator,
73
73
  ValidateCommitOperation,
74
- ServerColumnsRegistry,
75
74
  ValidateOpKind,
76
75
  ValidatorRegistry,
77
76
  } from './validate';
@@ -222,31 +221,36 @@ async function resolveBlobPresence(
222
221
  }
223
222
 
224
223
  /**
225
- * §6.7: run the table's write-validation hook, if configured, on the row
226
- * that WILL persist (post scope-strip, post CRDT-merge — the values the
227
- * store receives). Returns a terminating outcome iff the validator rejects
228
- * (its `ValidationRejection` code, or `sync.constraint_violation` for a
229
- * non-`ValidationRejection` throw), else `undefined` (accept / no hook).
230
- * A no-op for tables with no validator — the `undefined` short-circuit
231
- * keeps the feature zero-cost when off.
224
+ * §6.7: run the table's row hook, if configured, on the row that will persist
225
+ * (post scope-strip, post CRDT-merge). With `present` (an accepted insert or
226
+ * update of a pushed commit or a registered command) the hook's returned
227
+ * values for server-owned columns land in `values` and are marked present, so
228
+ * their column versions advance; elsewhere (a delete, a rescope, a §6.11
229
+ * cascade) the server ignores them. Returns a terminating outcome iff the
230
+ * hook fails: a `ValidationRejection` keeps its host code, and any other
231
+ * throw, a returned column that is not server-owned, a value the column's
232
+ * type refuses or a changed scope column on an update is
233
+ * `sync.constraint_violation`.
232
234
  */
233
235
  async function runValidator(
234
236
  validators: ValidatorRegistry | undefined,
237
+ tx: StorageTransaction,
238
+ schema: CompiledSchema,
235
239
  table: CompiledTable,
236
240
  op: ValidateOpKind,
237
241
  rowId: string,
238
- values: readonly RowValue[] | undefined,
242
+ values: RowValue[] | undefined,
239
243
  storedValues: readonly RowValue[] | undefined,
240
244
  opIndex: number,
241
- tx: StorageTransaction,
242
245
  partition: string,
243
246
  actorId: string,
244
247
  context: string | undefined,
248
+ present?: boolean[],
245
249
  ): Promise<TerminatingOutcome | undefined> {
246
250
  const validator = validators?.[table.name];
247
251
  if (validator === undefined) return undefined;
248
252
  try {
249
- await validator(
253
+ const output = await validator(
250
254
  {
251
255
  op,
252
256
  table: table.name,
@@ -260,69 +264,6 @@ async function runValidator(
260
264
  ? toValidateRow(table.columns, storedValues)
261
265
  : undefined,
262
266
  },
263
- {
264
- actorId,
265
- partition,
266
- ...(context !== undefined ? { context } : {}),
267
- queryAuthoritative: (query) => transactionQuery(tx, query),
268
- },
269
- );
270
- } catch (error) {
271
- if (error instanceof ValidationRejection) {
272
- return errorRecord(
273
- opIndex,
274
- error.code,
275
- error.message,
276
- false,
277
- error.details,
278
- );
279
- }
280
- // §6.7: a non-ValidationRejection throw is still a rejection, mapped to
281
- // the generic server-side constraint code (§10.2) — the validator's
282
- // failure never crashes the request or leaks its message as a code.
283
- return errorRecord(
284
- opIndex,
285
- 'sync.constraint_violation',
286
- 'write validator failed',
287
- );
288
- }
289
- return undefined;
290
- }
291
-
292
- /**
293
- * §6.12: complete an accepted upsert with the table's server column hook.
294
- * The returned values land in `values` and are marked present, so their
295
- * column versions advance. A `ValidationRejection` keeps its host code; any
296
- * other failure (an undeclared key, a value the column's type refuses, a
297
- * changed scope column on an update) is `sync.constraint_violation`.
298
- */
299
- async function runServerColumns(
300
- hooks: ServerColumnsRegistry | undefined,
301
- tx: StorageTransaction,
302
- schema: CompiledSchema,
303
- table: CompiledTable,
304
- rowId: string,
305
- values: RowValue[],
306
- storedValues: readonly RowValue[] | undefined,
307
- present: boolean[],
308
- opIndex: number,
309
- partition: string,
310
- actorId: string,
311
- context: string | undefined,
312
- ): Promise<TerminatingOutcome | undefined> {
313
- const hook = hooks?.[table.name];
314
- if (hook === undefined) return undefined;
315
- try {
316
- const output = await hook(
317
- {
318
- table: table.name,
319
- rowId,
320
- row: toValidateRow(table.columns, values),
321
- stored:
322
- storedValues !== undefined
323
- ? toValidateRow(table.columns, storedValues)
324
- : undefined,
325
- },
326
267
  {
327
268
  actorId,
328
269
  partition,
@@ -330,6 +271,8 @@ async function runServerColumns(
330
271
  read: commitValidationReader(tx, schema),
331
272
  },
332
273
  );
274
+ if (output === undefined || present === undefined || values === undefined)
275
+ return undefined;
333
276
  for (const [name, value] of Object.entries(output)) {
334
277
  const index = table.columnIndex.get(name);
335
278
  if (
@@ -337,7 +280,7 @@ async function runServerColumns(
337
280
  !table.serverOwnedColumnIndices.includes(index)
338
281
  ) {
339
282
  throw new Error(
340
- 'server column hook returned a column that is not server-owned',
283
+ 'write validator returned a column that is not server-owned',
341
284
  );
342
285
  }
343
286
  // The column's own codec refuses a value of the wrong type.
@@ -347,7 +290,7 @@ async function runServerColumns(
347
290
  table.scopePatterns.some((pattern) => pattern.columnIndex === index) &&
348
291
  value !== (storedValues[index] ?? null)
349
292
  ) {
350
- throw new Error('server column hook changed a scope column on update');
293
+ throw new Error('write validator changed a scope column on update');
351
294
  }
352
295
  values[index] = value;
353
296
  present[index] = true;
@@ -362,10 +305,13 @@ async function runServerColumns(
362
305
  error.details,
363
306
  );
364
307
  }
308
+ // §6.7: any other failure is still a rejection, mapped to the generic
309
+ // server-side constraint code (§10.2); the hook's failure never crashes
310
+ // the request or leaks its message.
365
311
  return errorRecord(
366
312
  opIndex,
367
313
  'sync.constraint_violation',
368
- 'server column hook failed',
314
+ 'write validator failed',
369
315
  );
370
316
  }
371
317
  return undefined;
@@ -435,7 +381,6 @@ async function applyOperation(
435
381
  blobCtx: BlobApplyContext,
436
382
  crdtMergers: CrdtMergerRegistry | undefined,
437
383
  validators: ValidatorRegistry | undefined,
438
- serverColumns: ServerColumnsRegistry | undefined,
439
384
  partition: string,
440
385
  actorId: string,
441
386
  context: string | undefined,
@@ -558,13 +503,14 @@ async function applyOperation(
558
503
  }
559
504
  const deleteReject = await runValidator(
560
505
  validators,
506
+ tx,
507
+ schema,
561
508
  table,
562
509
  'delete',
563
510
  op.rowId,
564
511
  undefined,
565
512
  storedValues,
566
513
  opIndex,
567
- tx,
568
514
  partition,
569
515
  actorId,
570
516
  context,
@@ -572,13 +518,14 @@ async function applyOperation(
572
518
  if (deleteReject !== undefined) return deleteReject;
573
519
  const upsertReject = await runValidator(
574
520
  validators,
521
+ tx,
522
+ schema,
575
523
  table,
576
524
  'upsert',
577
525
  op.rowId,
578
526
  values,
579
527
  storedValues,
580
528
  opIndex,
581
- tx,
582
529
  partition,
583
530
  actorId,
584
531
  context,
@@ -715,13 +662,14 @@ async function applyOperation(
715
662
  const storedValues = decodeRow(table.columns, stored.payload);
716
663
  const deleteReject = await runValidator(
717
664
  validators,
665
+ tx,
666
+ schema,
718
667
  table,
719
668
  'delete',
720
669
  op.rowId,
721
670
  undefined,
722
671
  storedValues,
723
672
  opIndex,
724
- tx,
725
673
  partition,
726
674
  actorId,
727
675
  context,
@@ -783,7 +731,7 @@ async function applyOperation(
783
731
  `row payload failed row-codec decode (§1.7): ${error instanceof Error ? error.message : String(error)}`,
784
732
  );
785
733
  }
786
- // §6.12: the server discards a pushed value of a server-owned column, so an
734
+ // §6.7: the server discards a pushed value of a server-owned column, so an
787
735
  // older client that still writes one stays valid.
788
736
  for (const index of table.serverOwnedColumnIndices) {
789
737
  sparse[index] = stored === undefined ? null : undefined;
@@ -897,21 +845,24 @@ async function applyOperation(
897
845
  crdtMergers,
898
846
  );
899
847
  if ('kind' in mergeOutcome) return mergeOutcome;
900
- const serverReject = await runServerColumns(
901
- serverColumns,
848
+ // §6.7: validate the merged row that will persist (for a crdt column the
849
+ // MERGED value, §5.10.3) and take its server-owned values.
850
+ const updateReject = await runValidator(
851
+ validators,
902
852
  tx,
903
853
  schema,
904
854
  table,
855
+ 'upsert',
905
856
  op.rowId,
906
857
  values,
907
858
  storedValues,
908
- present,
909
859
  opIndex,
910
860
  partition,
911
861
  actorId,
912
862
  context,
863
+ present,
913
864
  );
914
- if (serverReject !== undefined) return serverReject;
865
+ if (updateReject !== undefined) return updateReject;
915
866
  const newVersion = stored.serverVersion + 1;
916
867
  const nextVersions = new Map<number, number>();
917
868
  for (let i = 0; i < table.columns.length; i++) {
@@ -936,23 +887,6 @@ async function applyOperation(
936
887
  blobCtx,
937
888
  );
938
889
  if (blobCheck !== undefined) return blobCheck;
939
- // §6.7: validate the merged row that will persist — for a crdt column
940
- // the validator sees the MERGED value (§5.10.3), the state the store
941
- // holds, not the raw pushed update.
942
- const updateReject = await runValidator(
943
- validators,
944
- table,
945
- 'upsert',
946
- op.rowId,
947
- values,
948
- storedValues,
949
- opIndex,
950
- tx,
951
- partition,
952
- actorId,
953
- context,
954
- );
955
- if (updateReject !== undefined) return updateReject;
956
890
  const columnVersions = encodeColumnVersions(nextVersions);
957
891
  const newRow = {
958
892
  rowId: op.rowId,
@@ -1078,29 +1012,33 @@ async function applyOperation(
1078
1012
  crdtMergers,
1079
1013
  );
1080
1014
  if ('kind' in insertMerge) return insertMerge;
1081
- const serverReject = await runServerColumns(
1082
- serverColumns,
1015
+ // §6.7: validate the insert row (stored = undefined, so a validator can
1016
+ // distinguish create from update; crdt columns are already merged against
1017
+ // the empty document) and take its server-owned values.
1018
+ const insertReject = await runValidator(
1019
+ validators,
1083
1020
  tx,
1084
1021
  schema,
1085
1022
  table,
1023
+ 'upsert',
1086
1024
  op.rowId,
1087
1025
  values,
1088
1026
  undefined,
1089
- present,
1090
1027
  opIndex,
1091
1028
  partition,
1092
1029
  actorId,
1093
1030
  context,
1031
+ present,
1094
1032
  );
1095
- if (serverReject !== undefined) return serverReject;
1096
- // §6.12: the stored scopes and the change-scope index take the hook's
1033
+ if (insertReject !== undefined) return insertReject;
1034
+ // §6.7: the stored scopes and the change-scope index take the validator's
1097
1035
  // values, so the row reaches a server-set scope's units in this commit.
1098
1036
  const scoped = storedScopesForRow(table, values);
1099
1037
  if ('missing' in scoped) {
1100
1038
  return errorRecord(
1101
1039
  opIndex,
1102
1040
  'sync.constraint_violation',
1103
- 'server column hook failed',
1041
+ 'write validator failed',
1104
1042
  );
1105
1043
  }
1106
1044
  // The stored payload is the full-row codec (§2.4); every column is
@@ -1116,23 +1054,6 @@ async function applyOperation(
1116
1054
  blobCtx,
1117
1055
  );
1118
1056
  if (blobCheck !== undefined) return blobCheck;
1119
- // §6.7: validate the insert row (stored = undefined, so a validator can
1120
- // distinguish create from update); crdt columns are already merged
1121
- // against the empty document.
1122
- const insertReject = await runValidator(
1123
- validators,
1124
- table,
1125
- 'upsert',
1126
- op.rowId,
1127
- values,
1128
- undefined,
1129
- opIndex,
1130
- tx,
1131
- partition,
1132
- actorId,
1133
- context,
1134
- );
1135
- if (insertReject !== undefined) return insertReject;
1136
1057
  // §2.2, §6.2: every insert starts one above the delete floor, over a
1137
1058
  // tombstone or not; without a column-versions blob every column sits at
1138
1059
  // that version.
@@ -1701,13 +1622,14 @@ async function enforceReferences(
1701
1622
  if (reference.onDelete === 'CASCADE') {
1702
1623
  const reject = await runValidator(
1703
1624
  validators,
1625
+ tx,
1626
+ schema,
1704
1627
  child,
1705
1628
  'delete',
1706
1629
  childRow.rowId,
1707
1630
  undefined,
1708
1631
  storedValues,
1709
1632
  item.originOpIndex,
1710
- tx,
1711
1633
  partition,
1712
1634
  actorId,
1713
1635
  context,
@@ -1737,13 +1659,14 @@ async function enforceReferences(
1737
1659
  values[reference.columnIndex] = null;
1738
1660
  const reject = await runValidator(
1739
1661
  validators,
1662
+ tx,
1663
+ schema,
1740
1664
  child,
1741
1665
  'upsert',
1742
1666
  childRow.rowId,
1743
1667
  values,
1744
1668
  storedValues,
1745
1669
  item.originOpIndex,
1746
- tx,
1747
1670
  partition,
1748
1671
  actorId,
1749
1672
  context,
@@ -2243,7 +2166,6 @@ async function applyPushCommits(
2243
2166
  blobCtx,
2244
2167
  crdtMergers,
2245
2168
  validators,
2246
- ctx.serverColumns,
2247
2169
  partition,
2248
2170
  ctx.actorId,
2249
2171
  ctx.context,
package/src/realtime.ts CHANGED
@@ -734,8 +734,8 @@ export class RealtimeSession {
734
734
  try {
735
735
  step = await iterator.next();
736
736
  } catch (error) {
737
- // The generator builds the whole response (and runs the read-verify
738
- // refusal) on its first `next()`, before any chunk is yielded.
737
+ // The first `next()` waits until the response is built (and the
738
+ // read-verify refusal ran) or its first KEEPALIVE is due (§1.6).
739
739
  // Nothing has escaped, so a failure there is delivered as the same
740
740
  // §8.4 ERROR frame HTTP returns rather than a silent close; a
741
741
  // non-catalog exception is reported and answers
@@ -1563,9 +1563,11 @@ export class RealtimeHub {
1563
1563
 
1564
1564
  /**
1565
1565
  * Host-initiated, fail-closed registration refresh (§8.7). A host calls this
1566
- * after it changes an actor's membership or connection state, so the
1567
- * partition's connected sessions stop using grants the host already revoked
1568
- * without waiting for the client to happen to run a round.
1566
+ * after it changes an actor's grants, whether they shrank or grew. Each
1567
+ * matching session re-resolves its registrations, so it stops using grants
1568
+ * the host already revoked without waiting for its client to run a round,
1569
+ * and then receives one `scopes` event, so its client's app runs its
1570
+ * discovery and registers units it did not know.
1569
1571
  *
1570
1572
  * This differs deliberately from the round-end refresh
1571
1573
  * (`RealtimeSession.refreshRegistrations`), which keeps the previous
@@ -1578,24 +1580,10 @@ export class RealtimeHub {
1578
1580
  for (const session of [...this.#sessions]) {
1579
1581
  if (session.partition !== partition) continue;
1580
1582
  if (actorId !== undefined && session.actorId !== actorId) continue;
1581
- // Fail closed (see the doc above): an unreadable client record drops
1582
- // every grant on the connection. The session's generation guard keeps
1583
- // this revocation from being overwritten by a slower round-end reload.
1583
+ // The session's generation guard keeps this revocation from being
1584
+ // overwritten by a slower round-end reload.
1584
1585
  await session.refreshRegistrations(true);
1585
- }
1586
- }
1587
-
1588
- /**
1589
- * Host announcement (§8.7): tell the connected sessions of `actorIds` on
1590
- * the partition that their grant widened, so each client's app runs its
1591
- * discovery and registers the units it did not know. Sends one `scopes`
1592
- * event per session and changes no registration; a narrowed grant needs
1593
- * `refreshScopes`.
1594
- */
1595
- announceScopes(partition: string, actorIds: readonly string[]): void {
1596
- for (const session of this.#sessions) {
1597
- if (session.partition !== partition) continue;
1598
- if (actorIds.includes(session.actorId)) session.sendScopes();
1586
+ session.sendScopes();
1599
1587
  }
1600
1588
  }
1601
1589
 
@@ -1010,8 +1010,10 @@ export function assertStoredScopePatterns(
1010
1010
 
1011
1011
  /**
1012
1012
  * §3.1 re-key, before the row walk: drop the re-keyed tables' row scope index
1013
- * entries and tombstones, and raise every partition's horizon past the
1014
- * changes logged under the previous patterns. Empty when nothing re-keys.
1013
+ * entries and tombstones. The re-key takes a commit sequence number of its
1014
+ * own in every partition and records it as each re-keyed table's horizon
1015
+ * (§4.6), past the changes logged under the previous patterns. Empty when
1016
+ * nothing re-keys.
1015
1017
  */
1016
1018
  export function rekeyCleanupSql(tables: readonly string[]): string[] {
1017
1019
  if (tables.length === 0) return [];
@@ -1019,7 +1021,12 @@ export function rekeyCleanupSql(tables: readonly string[]): string[] {
1019
1021
  return [
1020
1022
  `DELETE FROM sync_row_scopes WHERE tbl IN (${names.join(',')})`,
1021
1023
  `DELETE FROM sync_tombstones WHERE tbl IN (${names.join(',')})`,
1022
- 'UPDATE sync_partitions SET horizon_seq=max_commit_seq WHERE horizon_seq<max_commit_seq',
1024
+ 'UPDATE sync_partitions SET max_commit_seq=max_commit_seq+1',
1025
+ ...names.map(
1026
+ (name) => `INSERT INTO sync_table_horizons(partition, tbl, commit_seq)
1027
+ SELECT partition, ${name}, max_commit_seq FROM sync_partitions WHERE true
1028
+ ON CONFLICT(partition, tbl) DO UPDATE SET commit_seq=excluded.commit_seq`,
1029
+ ),
1023
1030
  ];
1024
1031
  }
1025
1032
 
@@ -31,7 +31,7 @@ export function schemaWindowOf(
31
31
  if (
32
32
  next === undefined ||
33
33
  table.columns.length > next.columns.length ||
34
- // §6.12: a version may mark an existing column server-owned; the flag
34
+ // §6.7: a version may mark an existing column server-owned; the flag
35
35
  // never reaches the wire.
36
36
  table.columns.some(
37
37
  (column, i) =>
@@ -42,7 +42,7 @@ export function schemaWindowOf(
42
42
  .slice(table.columns.length)
43
43
  .some((column) => !column.nullable) ||
44
44
  table.primaryKeyIndex !== next.primaryKeyIndex ||
45
- // §6.12: a pattern over an appended server-owned column is new to the
45
+ // §6.7: a pattern over an appended server-owned column is new to the
46
46
  // current version; an older client neither holds nor writes it.
47
47
  JSON.stringify(table.scopePatterns) !==
48
48
  JSON.stringify(