@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/README.md CHANGED
@@ -195,20 +195,21 @@ fail at construction. Diagnostic prose stays in `message`; apps should map
195
195
  the stable code/details to localized copy instead of displaying that message.
196
196
 
197
197
  Validators are per-operation. A validator must not mutate the row it receives;
198
- a value only the server decides belongs in a server-owned column, which a
199
- `serverColumns` hook sets before the validator runs
198
+ a value only the server decides belongs in a server-owned column, whose value
199
+ the validator returns
200
200
  ([Server-owned columns](https://syncular.dev/guide-server/#server-owned-columns)).
201
201
 
202
202
  A validator that decides from other rows (a membership, a role, a grant) calls
203
- `context.queryAuthoritative` with the request `storage.queryAuthoritative`
203
+ `context.read.queryAuthoritative` with the request `storage.queryAuthoritative`
204
204
  takes, built from a generated query descriptor. The storage binds every
205
205
  relation to the commit's partition and runs the statement on the push
206
206
  transaction's connection, so the read sees the operations staged before this
207
207
  one and needs no second pool connection. Never call
208
208
  `storage.queryAuthoritative` from a validator: on SQLite and PGlite it waits
209
209
  for the push transaction and the push never completes, and on a pool it reads
210
- committed state. The whole-commit reader, the reaction planner reader, and the
211
- remote command context expose the same method. See
210
+ committed state. `context.read` is the whole-commit candidate-state reader;
211
+ the reaction planner reader and the remote command context expose the same
212
+ method. See
212
213
  [Read a generated query inside a push transaction](https://syncular.dev/guide-remote-operations/#read-a-generated-query-inside-a-push-transaction).
213
214
 
214
215
  For a multi-row or multi-table invariant, install `commitValidator`. It runs
package/dist/context.d.ts CHANGED
@@ -16,7 +16,7 @@ import type { SegmentStore } from './segment-store.js';
16
16
  import type { BlobPresignConfig, BlobUploadPresignConfig, SegmentUrlConfig } from './signed-url.js';
17
17
  import type { SqliteImageBuilder } from './sqlite-image.js';
18
18
  import type { CheckpointDeclaration, PartitionTouch, ServerStorage, StoredCommit } from './storage.js';
19
- import type { CommitValidator, ServerColumnsRegistry, ValidatorRegistry } from './validate.js';
19
+ import type { CommitValidator, ValidatorRegistry } from './validate.js';
20
20
  /** SSP2 body content type (§1.1). */
21
21
  export declare const SSP2_CONTENT_TYPE = "application/vnd.syncular.sync.v2";
22
22
  /** Internal idempotency namespace. Ordinary SSP2 client IDs cannot use it. */
@@ -149,19 +149,13 @@ export interface SyncServerConfig {
149
149
  * builds no validator context — zero cost. Present ⇒ each push operation
150
150
  * on a listed table runs its validator after decode + §3.4 scope
151
151
  * authorization, inside the commit transaction; a throw rejects the
152
- * whole commit atomically (§6.4) with the host code (§6.3). Kept a host
152
+ * whole commit atomically (§6.4) with the host code (§6.3). On an insert
153
+ * or update the validator may return values of the table's server-owned
154
+ * columns, which are stored and fanned out in the same commit. Kept a host
153
155
  * callback (like `resolveScopes`) — business rules live in the host
154
156
  * process, never on the wire.
155
157
  */
156
158
  readonly validators?: ValidatorRegistry;
157
- /**
158
- * §6.12 per-table server column hooks (`table` → hook). Each accepted
159
- * upsert on a listed table runs its hook inside the push transaction,
160
- * after §3.4 authorization and before §6.7 validation; the returned values
161
- * of the table's server-owned columns are stored and fanned out in the
162
- * same commit.
163
- */
164
- readonly serverColumns?: ServerColumnsRegistry;
165
159
  /**
166
160
  * §6.8 whole-commit validator. When present, the storage serializes this
167
161
  * partition before operation reads/writes, then invokes the callback once
package/dist/errors.js CHANGED
@@ -226,6 +226,14 @@ export const ERROR_CATALOG = {
226
226
  recommendedAction: 'forceResync',
227
227
  httpStatus: 404,
228
228
  },
229
+ // §1.6: a response still building at the 300 s build deadline. In-band
230
+ // after its header frames, HTTP 503 before them.
231
+ 'sync.segment_build_timeout': {
232
+ category: 'internal',
233
+ retryable: true,
234
+ recommendedAction: 'retryLater',
235
+ httpStatus: 503,
236
+ },
229
237
  'sync.segment_expired': {
230
238
  category: 'not-found',
231
239
  retryable: true,
@@ -53,6 +53,7 @@ function wrapperFor(frame) {
53
53
  switch (frame.type) {
54
54
  case 'RESP_HEADER':
55
55
  return { frames: [frame], index: 0 };
56
+ case 'KEEPALIVE':
56
57
  case 'LEASE':
57
58
  // §7.3.2: LEASE rides immediately after RESP_HEADER.
58
59
  return { frames: [stubHeader(), frame], index: 1 };
package/dist/handler.d.ts CHANGED
@@ -1,9 +1,27 @@
1
1
  import type { SyncRequestContext } from './context.js';
2
+ /**
3
+ * A response's chunks, one per encoded frame (§1.4). `live` turns true when
4
+ * the response goes out before it is built: its header frames and
5
+ * `KEEPALIVE` frames (§1.6) precede the rest, and a later failure is an
6
+ * in-band `ERROR`.
7
+ */
8
+ export interface SyncResponseStream extends AsyncIterable<Uint8Array> {
9
+ readonly live: boolean;
10
+ }
2
11
  /**
3
12
  * Decode and validate the request, then return the streaming response.
4
13
  * Request-validation failures (§1.7) throw `SyncError` here, before any
5
- * bytes are produced; adapters map them to HTTP JSON errors (§1.1).
14
+ * bytes are produced; adapters map them to HTTP JSON errors (§1.1). The
15
+ * first chunk arrives once the response is built or its first `KEEPALIVE`
16
+ * is due (§1.6); a failure before then throws from it, before any byte.
17
+ */
18
+ export declare function createSyncResponseStream(bytes: Uint8Array, ctx: SyncRequestContext): Promise<SyncResponseStream>;
19
+ /**
20
+ * The `POST /sync` body (§1.1): the whole response when it was built before
21
+ * its first `KEEPALIVE` was due, otherwise a stream that carries the header
22
+ * frames and `KEEPALIVE` frames first (§1.6). Adapters compress only the
23
+ * whole response (§1.3).
6
24
  */
7
- export declare function createSyncResponseStream(bytes: Uint8Array, ctx: SyncRequestContext): Promise<AsyncIterable<Uint8Array>>;
25
+ export declare function createSyncResponseBody(bytes: Uint8Array, ctx: SyncRequestContext): Promise<Uint8Array | ReadableStream<Uint8Array>>;
8
26
  /** Byte-concatenating wrapper over the streaming core (§1.4). */
9
27
  export declare function handleSyncRequest(bytes: Uint8Array, ctx: SyncRequestContext): Promise<Uint8Array>;
package/dist/handler.js CHANGED
@@ -11,7 +11,7 @@
11
11
  */
12
12
  import { DecodeError, decodeRequest, echoDigest, registrationDigest, unitId, } from '@syncular/core';
13
13
  import { clockOf, limitsOf, REMOTE_COMMAND_CLIENT_ID_PREFIX, RESOLVER_OUTAGE, touchAuthenticatedPartition, } from './context.js';
14
- import { reportError, SyncError, syncError } from './errors.js';
14
+ import { adapterSyncError, reportError, SyncError, syncError } from './errors.js';
15
15
  import { emitEvent, } from './events.js';
16
16
  import { END_FRAME_BYTES, encodeResponseFrame, responseEnvelopeHeader, } from './frame-bytes.js';
17
17
  import { ACCEPT_EXTERNAL_ROWS, ACCEPT_INLINE_ROWS, bootstrapSegments, clampPullLimits, commitFrame, coveredTables, planBootstrap, planUnit, } from './pull.js';
@@ -558,7 +558,8 @@ async function* streamResponse(plan, ctx, schema, report) {
558
558
  }
559
559
  }
560
560
  else {
561
- const horizonSeq = await ctx.storage.getHorizonSeq(ctx.partition);
561
+ const horizons = await ctx.storage.getHorizons(ctx.partition);
562
+ const { seq: horizonSeq, tables: tableHorizons } = horizons;
562
563
  const R = pull.header.cursor;
563
564
  const echo = echoDigest(units.map(({ plan: unit }) => ({
564
565
  id: unit.id,
@@ -572,14 +573,25 @@ async function* streamResponse(plan, ctx, schema, report) {
572
573
  const liveUnits = units.some((unit) => unit.progress === undefined && unit.plan.status === 'active');
573
574
  // §4.6 replica reset: a live unit with R outside [horizon, max].
574
575
  let liveReset = liveUnits && (R < horizonSeq || R > maxSeq);
575
- const states = units.map(({ plan: unit, progress, restrict }) => {
576
+ // §4.6 unit reset: `cursor` lies below the table horizon of one of
577
+ // the unit's active pairs outside its RESTRICT tables.
578
+ const belowTable = (index, cursor, horizons) => {
579
+ const { plan: unit, restrict } = units[index];
580
+ return [...unit.pairs.keys()].some((table) => cursor < (horizons.get(table) ?? -1) &&
581
+ restrict?.tables.includes(table) !== true);
582
+ };
583
+ const states = units.map(({ plan: unit, progress, restrict }, index) => {
576
584
  if (unit.status === 'revoked')
577
585
  return { kind: 'revoked' };
578
586
  if (progress === undefined)
579
- return { kind: 'live' };
587
+ return !liveReset && belowTable(index, R, tableHorizons)
588
+ ? { kind: 'reset' }
589
+ : { kind: 'live' };
580
590
  // §4.6: a kept cursor outside [horizon, max] cannot join.
581
591
  if (restrict !== undefined)
582
- return restrict.cursor < horizonSeq || restrict.cursor > maxSeq
592
+ return restrict.cursor < horizonSeq ||
593
+ restrict.cursor > maxSeq ||
594
+ belowTable(index, restrict.cursor, tableHorizons)
583
595
  ? { kind: 'reset' }
584
596
  : {
585
597
  kind: 'bootstrap',
@@ -592,7 +604,8 @@ async function* streamResponse(plan, ctx, schema, report) {
592
604
  if (progress.bootstrapState === undefined &&
593
605
  progress.cursor >= 0 &&
594
606
  progress.cursor <= maxSeq) {
595
- return progress.cursor < horizonSeq
607
+ return progress.cursor < horizonSeq ||
608
+ belowTable(index, progress.cursor, tableHorizons)
596
609
  ? { kind: 'reset' }
597
610
  : { kind: 'post', cursor: progress.cursor };
598
611
  }
@@ -615,6 +628,11 @@ async function* streamResponse(plan, ctx, schema, report) {
615
628
  // follows the configured limits, never the unit count.
616
629
  const bootstrapping = states.flatMap((state, index) => state.kind === 'bootstrap' ? [index] : []);
617
630
  const firstPages = Math.max(1, Math.floor(100_000 / (limits.limitSnapshotRows + 1)));
631
+ // The segment puts of every bootstrap section, in frame order. A
632
+ // pull holds the encoded bytes of the puts in flight.
633
+ const puts = [];
634
+ const inFlight = new Set();
635
+ let failed = false;
618
636
  for (let next = 0; next < bootstrapping.length;) {
619
637
  const window = [];
620
638
  let pages = 0;
@@ -639,7 +657,7 @@ async function* streamResponse(plan, ctx, schema, report) {
639
657
  ...unit,
640
658
  tables: unit.tables.filter((table) => only.has(table.name)),
641
659
  pairs: new Map([...unit.pairs].filter(([name]) => only.has(name))),
642
- }, progress?.bootstrapState, maxSeq, horizonSeq, plan.logEpoch, restrict?.cursor),
660
+ }, progress?.bootstrapState, maxSeq, horizons, plan.logEpoch, restrict?.cursor),
643
661
  };
644
662
  });
645
663
  for (const { index, plan: bootstrap } of batch) {
@@ -647,7 +665,32 @@ async function* streamResponse(plan, ctx, schema, report) {
647
665
  const segments = bootstrapSegments(ctx, schema, limits, bootstrap, traces[index], plan.logEpoch);
648
666
  let step = await segments.next();
649
667
  while (!step.done) {
650
- frames.push(step.value);
668
+ const frame = step.value;
669
+ if (frame.type === 'PENDING_REF') {
670
+ // A rows segment's put runs while later pages are scanned;
671
+ // the next page waits while six puts are in flight: a
672
+ // Workers invocation holds six connections open at once and
673
+ // an R2 put uses one, so past six the runtime queues the put.
674
+ const settled = frame.ref.then(() => void inFlight.delete(settled), () => {
675
+ failed = true;
676
+ inFlight.delete(settled);
677
+ });
678
+ inFlight.add(settled);
679
+ puts.push(frame.ref);
680
+ frames.push(frame.ref);
681
+ while (inFlight.size >= 6) {
682
+ await Promise.race(inFlight);
683
+ if (failed)
684
+ break;
685
+ }
686
+ // A failed put ends the pull before it scans another page.
687
+ if (failed)
688
+ for (const put of puts)
689
+ await put;
690
+ }
691
+ else {
692
+ frames.push(frame);
693
+ }
651
694
  step = await segments.next();
652
695
  }
653
696
  const restrict = units[index].restrict;
@@ -660,6 +703,13 @@ async function* streamResponse(plan, ctx, schema, report) {
660
703
  };
661
704
  }
662
705
  }
706
+ // Every put completes before the live read, as in a pull with one put
707
+ // in flight. A failed put fails the pull with the error of the first
708
+ // failed page, and the puts still in flight finish unobserved: each
709
+ // stores its bytes before its record, so no record points at missing
710
+ // bytes.
711
+ for (const put of puts)
712
+ await put;
663
713
  const bound = (state) => state.kind === 'live'
664
714
  ? R
665
715
  : state.kind === 'post'
@@ -673,10 +723,22 @@ async function* streamResponse(plan, ctx, schema, report) {
673
723
  let live;
674
724
  for (;;) {
675
725
  const scanned = units.flatMap(({ plan: unit }, index) => {
676
- const afterSeq = bound(states[index]);
677
- return afterSeq === undefined
678
- ? []
679
- : [{ index, scopes: unit.scopes, afterSeq, tables: unit.pairs }];
726
+ const bounded = bound(states[index]);
727
+ if (bounded === undefined)
728
+ return [];
729
+ // §4.5: a table reaches the unit only above its table horizon,
730
+ // which lies above the bound only for a RESTRICT table.
731
+ const byBound = new Map();
732
+ for (const [table, scopes] of unit.pairs) {
733
+ const afterSeq = Math.max(bounded, tableHorizons.get(table) ?? -1);
734
+ byBound.set(afterSeq, (byBound.get(afterSeq) ?? new Map()).set(table, scopes));
735
+ }
736
+ return [...byBound].map(([afterSeq, tables]) => ({
737
+ index,
738
+ scopes: unit.scopes,
739
+ afterSeq,
740
+ tables,
741
+ }));
680
742
  });
681
743
  if (liveReset || scanned.length === 0)
682
744
  break;
@@ -699,18 +761,24 @@ async function* streamResponse(plan, ctx, schema, report) {
699
761
  live = undefined;
700
762
  continue;
701
763
  }
702
- const recheck = await ctx.storage.getHorizonSeq(ctx.partition);
764
+ const { seq: recheck, tables: recheckTables } = await ctx.storage.getHorizons(ctx.partition);
703
765
  let expired = false;
704
766
  for (const [index, state] of states.entries()) {
705
- // §4.6: a restricted bootstrap's kept cursor is rechecked too.
706
- const afterSeq = bound(state) ??
707
- (state.kind === 'bootstrap' && state.restricted
708
- ? state.pin
709
- : undefined);
710
- if (afterSeq === undefined || afterSeq >= recheck)
767
+ // §4.6: a restricted bootstrap's kept cursor is rechecked too,
768
+ // and a table horizon that rose during the round resets it: its
769
+ // segments were read before the re-key.
770
+ const restricted = state.kind === 'bootstrap' && state.restricted;
771
+ const afterSeq = bound(state) ?? (restricted ? state.pin : undefined);
772
+ if (afterSeq === undefined ||
773
+ (afterSeq >= recheck &&
774
+ !belowTable(index, afterSeq, recheckTables) &&
775
+ !(restricted &&
776
+ [...units[index].plan.pairs.keys()].some((table) => (recheckTables.get(table) ?? -1) >
777
+ (tableHorizons.get(table) ?? -1)))))
711
778
  continue;
712
779
  expired = true;
713
- if (state.kind === 'live')
780
+ // A live unit below a table horizon alone takes a unit reset.
781
+ if (state.kind === 'live' && afterSeq < recheck)
714
782
  liveReset = true;
715
783
  else
716
784
  states[index] = { kind: 'reset' };
@@ -757,7 +825,7 @@ async function* streamResponse(plan, ctx, schema, report) {
757
825
  }, plan.wireVersion);
758
826
  if (state.kind === 'bootstrap') {
759
827
  for (const frame of state.frames) {
760
- yield encodeResponseFrame(frame, plan.wireVersion);
828
+ yield encodeResponseFrame(await frame, plan.wireVersion);
761
829
  }
762
830
  }
763
831
  yield encodeResponseFrame(state.kind === 'bootstrap'
@@ -901,15 +969,7 @@ async function* streamResponse(plan, ctx, schema, report) {
901
969
  report.errorCode = error.code;
902
970
  await recordRoundFailure(ctx, clientId, error);
903
971
  // §1.6: in-band ERROR, then END, nothing else.
904
- yield encodeResponseFrame({
905
- type: 'ERROR',
906
- code: error.code,
907
- message: error.message,
908
- category: error.category,
909
- retryable: error.retryable,
910
- recommendedAction: error.recommendedAction,
911
- ...(error.details !== undefined ? { details: error.details } : {}),
912
- }, plan.wireVersion);
972
+ yield errorFrameBytes(error, plan.wireVersion);
913
973
  yield END_FRAME_BYTES;
914
974
  return;
915
975
  }
@@ -917,10 +977,24 @@ async function* streamResponse(plan, ctx, schema, report) {
917
977
  }
918
978
  yield END_FRAME_BYTES;
919
979
  }
980
+ /** The in-band `ERROR` frame of a failure (§1.6). */
981
+ function errorFrameBytes(error, wireVersion) {
982
+ return encodeResponseFrame({
983
+ type: 'ERROR',
984
+ code: error.code,
985
+ message: error.message,
986
+ category: error.category,
987
+ retryable: error.retryable,
988
+ recommendedAction: error.recommendedAction,
989
+ ...(error.details !== undefined ? { details: error.details } : {}),
990
+ }, wireVersion);
991
+ }
920
992
  /**
921
993
  * Decode and validate the request, then return the streaming response.
922
994
  * Request-validation failures (§1.7) throw `SyncError` here, before any
923
- * bytes are produced; adapters map them to HTTP JSON errors (§1.1).
995
+ * bytes are produced; adapters map them to HTTP JSON errors (§1.1). The
996
+ * first chunk arrives once the response is built or its first `KEEPALIVE`
997
+ * is due (§1.6); a failure before then throws from it, before any byte.
924
998
  */
925
999
  export async function createSyncResponseStream(bytes, ctx) {
926
1000
  const sink = ctx.events;
@@ -1057,19 +1131,24 @@ async function createStreamCore(bytes, ctx, events, startedAtMs = 0) {
1057
1131
  await recordRoundFailureCode(ctx, plan.header.clientId, plan.roundFailure.code);
1058
1132
  }
1059
1133
  const report = { outcome: 'ok' };
1060
- // RFC 0007 read-verify-refuse for the streamed read path: the generator
1061
- // builds the whole response (its data reads) before yielding the first
1062
- // frame, then compares the gate token across those reads. Nothing escapes
1063
- // before the verification, and the buffered size is bounded by the request's
1064
- // pull limits and the server's inline segment cap. Every request verifies,
1134
+ // RFC 0007 read-verify-refuse for the streamed read path: the build
1135
+ // buffers the whole response (its data reads), then compares the gate token
1136
+ // across those reads. No push result or section escapes before the
1137
+ // verification, and the buffered size is bounded by the request's pull
1138
+ // limits and the server's inline segment cap. Every request verifies,
1065
1139
  // including a mixed push+pull: a write that already applied when the token
1066
1140
  // changed is durable and replayable under the same commit id / idempotency
1067
1141
  // key, so refusing the request is safe (proved in the serve-gate lane).
1068
- const verified = async function* () {
1069
- const buffered = [];
1142
+ const buffered = [];
1143
+ // Set at the build deadline: a build that finishes later stops before the
1144
+ // serve-gate read and persists nothing.
1145
+ let abandoned = false;
1146
+ const built = (async () => {
1070
1147
  for await (const chunk of streamResponse(plan, ctx, served, report)) {
1071
1148
  buffered.push(chunk);
1072
1149
  }
1150
+ if (abandoned)
1151
+ return false;
1073
1152
  const after = await ctx.storage.readServeGate(ctx.partition, schema.version);
1074
1153
  const changed = serveGateTokenChanged(gate, after);
1075
1154
  const afterRefusal = serveGateRefusal(after, schema.version, ctx.checkpoints);
@@ -1078,13 +1157,117 @@ async function createStreamCore(bytes, ctx, events, startedAtMs = 0) {
1078
1157
  if (changed !== undefined)
1079
1158
  throw serveNotReadyError(changed);
1080
1159
  await report.persist?.();
1081
- for (const chunk of buffered)
1082
- yield chunk;
1160
+ return true;
1161
+ })();
1162
+ // The races below observe the failure; this keeps an abandoned stream's
1163
+ // failure from surfacing as unhandled.
1164
+ built.catch(() => { });
1165
+ // §1.6 header frames: the envelope header, RESP_HEADER and its LEASE.
1166
+ const headerChunks = plan.leaseToEmit !== undefined ? 3 : 2;
1167
+ let live = false;
1168
+ const verified = async function* () {
1169
+ let timer;
1170
+ let elapsedMs = 0;
1171
+ try {
1172
+ for (;;) {
1173
+ let done;
1174
+ try {
1175
+ done = await Promise.race([
1176
+ built,
1177
+ // §1.6: every 10 s, a third of the native client's 30 s socket
1178
+ // round silence bound (§1.8).
1179
+ new Promise((resolve) => {
1180
+ timer = setTimeout(() => resolve(false), 10_000);
1181
+ }),
1182
+ ]);
1183
+ if (!done)
1184
+ elapsedMs += 10_000;
1185
+ // §1.6 build deadline: 300 s, 2.5 times the slowest cold build
1186
+ // measured in production (119.7 s for 67 segment puts). A build
1187
+ // still running then is abandoned like a failed put.
1188
+ if (elapsedMs === 300_000) {
1189
+ abandoned = true;
1190
+ throw syncError('sync.segment_build_timeout', 'the response was not built within the server build deadline');
1191
+ }
1192
+ }
1193
+ catch (thrown) {
1194
+ if (!live)
1195
+ throw thrown;
1196
+ // The header frames went out: the failure is in-band (§1.6), and
1197
+ // one outside the catalog answers `sync.internal_error`.
1198
+ const error = adapterSyncError(thrown, ctx.onError, 'sync', ctx.mapError);
1199
+ report.outcome = 'error';
1200
+ report.errorCode = error.code;
1201
+ await recordRoundFailure(ctx, plan.header.clientId, error);
1202
+ yield errorFrameBytes(error, plan.wireVersion);
1203
+ yield END_FRAME_BYTES;
1204
+ return;
1205
+ }
1206
+ clearTimeout(timer);
1207
+ if (done)
1208
+ break;
1209
+ if (!live && buffered.length < headerChunks)
1210
+ continue;
1211
+ if (!live) {
1212
+ live = true;
1213
+ yield* buffered.slice(0, headerChunks);
1214
+ }
1215
+ yield encodeResponseFrame({ type: 'KEEPALIVE' }, plan.wireVersion);
1216
+ }
1217
+ }
1218
+ finally {
1219
+ clearTimeout(timer);
1220
+ }
1221
+ yield* buffered.slice(live ? headerChunks : 0);
1222
+ };
1223
+ const stream = recordedStream(events === undefined
1224
+ ? verified()
1225
+ : instrumentedStream(verified(), ctx, events, plan, report, bytes.length, startedAtMs), ctx, plan.header.clientId);
1226
+ return {
1227
+ get live() {
1228
+ return live;
1229
+ },
1230
+ [Symbol.asyncIterator]: () => stream,
1083
1231
  };
1084
- if (events === undefined) {
1085
- return recordedStream(verified(), ctx, plan.header.clientId);
1232
+ }
1233
+ /**
1234
+ * The `POST /sync` body (§1.1): the whole response when it was built before
1235
+ * its first `KEEPALIVE` was due, otherwise a stream that carries the header
1236
+ * frames and `KEEPALIVE` frames first (§1.6). Adapters compress only the
1237
+ * whole response (§1.3).
1238
+ */
1239
+ export async function createSyncResponseBody(bytes, ctx) {
1240
+ const stream = await createSyncResponseStream(bytes, ctx);
1241
+ const iterator = stream[Symbol.asyncIterator]();
1242
+ const first = await iterator.next();
1243
+ if (stream.live) {
1244
+ return new ReadableStream({
1245
+ start(controller) {
1246
+ if (!first.done)
1247
+ controller.enqueue(first.value);
1248
+ },
1249
+ async pull(controller) {
1250
+ const step = await iterator.next();
1251
+ if (step.done)
1252
+ controller.close();
1253
+ else
1254
+ controller.enqueue(step.value);
1255
+ },
1256
+ async cancel() {
1257
+ await iterator.return?.();
1258
+ },
1259
+ });
1260
+ }
1261
+ const chunks = first.done ? [] : [first.value];
1262
+ for (let step = await iterator.next(); !step.done; step = await iterator.next())
1263
+ chunks.push(step.value);
1264
+ const out = new Uint8Array(chunks.reduce((sum, chunk) => sum + chunk.length, 0));
1265
+ let offset = 0;
1266
+ for (const chunk of chunks) {
1267
+ out.set(chunk, offset);
1268
+ offset += chunk.length;
1086
1269
  }
1087
- return recordedStream(instrumentedStream(verified(), ctx, events, plan, report, bytes.length, startedAtMs), ctx, plan.header.clientId);
1270
+ return out;
1088
1271
  }
1089
1272
  /** Counts response bytes and emits `request.handled` when the stream
1090
1273
  * finishes — including a thrown host failure mid-stream (fail loud). */
@@ -1127,18 +1310,8 @@ async function* instrumentedStream(stream, ctx, events, plan, report, bytesIn, s
1127
1310
  }
1128
1311
  /** Byte-concatenating wrapper over the streaming core (§1.4). */
1129
1312
  export async function handleSyncRequest(bytes, ctx) {
1130
- const stream = await createSyncResponseStream(bytes, ctx);
1131
- const chunks = [];
1132
- let total = 0;
1133
- for await (const chunk of stream) {
1134
- chunks.push(chunk);
1135
- total += chunk.length;
1136
- }
1137
- const out = new Uint8Array(total);
1138
- let offset = 0;
1139
- for (const chunk of chunks) {
1140
- out.set(chunk, offset);
1141
- offset += chunk.length;
1142
- }
1143
- return out;
1313
+ const body = await createSyncResponseBody(bytes, ctx);
1314
+ return body instanceof Uint8Array
1315
+ ? body
1316
+ : new Uint8Array(await new Response(body).arrayBuffer());
1144
1317
  }
@@ -1,4 +1,4 @@
1
- import type { CommitPruneQuery, CommitPruneResult } from './storage.js';
1
+ import type { CommitPruneQuery, CommitPruneResult, PartitionHorizons } from './storage.js';
2
2
  /**
3
3
  * Postgres server storage: the production database path.
4
4
  *
@@ -74,7 +74,7 @@ import type { AuthoritativeQueryRequest, AuthoritativeQueryResult, CheckpointDec
74
74
  * set, §5.9.5) as an index range, never a scan. `postgres-explain
75
75
  * .test.ts` asserts an `Index` node here too.
76
76
  */
77
- export declare const POSTGRES_DDL = "\nCREATE TABLE IF NOT EXISTS sync_partitions(\n partition TEXT PRIMARY KEY,\n max_commit_seq BIGINT NOT NULL DEFAULT 0,\n horizon_seq BIGINT NOT NULL DEFAULT 0,\n delete_floor BIGINT NOT NULL DEFAULT 0\n);\nCREATE TABLE IF NOT EXISTS sync_partition_registry(\n partition TEXT PRIMARY KEY,\n log_epoch TEXT NOT NULL,\n epoch_required BOOLEAN NOT NULL DEFAULT FALSE,\n last_authenticated_at_ms BIGINT NOT NULL\n);\nCREATE TABLE IF NOT EXISTS sync_row_scopes(\n partition TEXT NOT NULL, tbl TEXT NOT NULL,\n var TEXT NOT NULL, value TEXT NOT NULL, row_id TEXT NOT NULL,\n PRIMARY KEY(partition, tbl, var, value, row_id)\n);\nCREATE INDEX IF NOT EXISTS sync_row_scopes_by_row\n ON sync_row_scopes(partition, tbl, row_id);\nCREATE TABLE IF NOT EXISTS sync_commits(\n partition TEXT NOT NULL, commit_seq BIGINT NOT NULL,\n client_id TEXT NOT NULL, client_commit_id TEXT NOT NULL,\n actor_id TEXT NOT NULL, created_at_ms BIGINT NOT NULL,\n writer_version BIGINT,\n PRIMARY KEY(partition, commit_seq)\n);\nCREATE INDEX IF NOT EXISTS sync_commits_by_time\n ON sync_commits(partition, created_at_ms);\nCREATE TABLE IF NOT EXISTS sync_changes(\n partition TEXT NOT NULL, commit_seq BIGINT NOT NULL, idx INTEGER NOT NULL,\n tbl TEXT NOT NULL, row_id TEXT NOT NULL, op SMALLINT NOT NULL,\n row_version BIGINT, scopes JSONB NOT NULL, payload BYTEA,\n PRIMARY KEY(partition, commit_seq, idx)\n);\nCREATE INDEX IF NOT EXISTS sync_changes_by_table\n ON sync_changes(partition, commit_seq, tbl, idx);\nCREATE TABLE IF NOT EXISTS sync_change_scopes(\n partition TEXT NOT NULL, tbl TEXT NOT NULL,\n var TEXT NOT NULL, value TEXT NOT NULL, commit_seq BIGINT NOT NULL,\n PRIMARY KEY(partition, tbl, var, value, commit_seq)\n);\nCREATE INDEX IF NOT EXISTS sync_change_scopes_by_key\n ON sync_change_scopes(partition, var, value, commit_seq);\nCREATE TABLE IF NOT EXISTS sync_push_results(\n partition TEXT NOT NULL, client_id TEXT NOT NULL,\n client_commit_id TEXT NOT NULL, result JSONB NOT NULL,\n outbox_id TEXT, client_seq BIGINT,\n PRIMARY KEY(partition, client_id, client_commit_id)\n);\nALTER TABLE sync_push_results ADD COLUMN IF NOT EXISTS outbox_id TEXT;\nALTER TABLE sync_push_results ADD COLUMN IF NOT EXISTS client_seq BIGINT;\nCREATE TABLE IF NOT EXISTS sync_push_watermarks(\n partition TEXT NOT NULL, client_id TEXT NOT NULL, outbox_id TEXT NOT NULL,\n through_seq BIGINT NOT NULL,\n PRIMARY KEY(partition, client_id, outbox_id)\n);\nCREATE TABLE IF NOT EXISTS sync_reactions(\n partition TEXT NOT NULL, idempotency_key TEXT NOT NULL,\n type TEXT NOT NULL, version INTEGER NOT NULL, payload JSONB NOT NULL,\n source_client_id TEXT NOT NULL, source_client_commit_id TEXT NOT NULL,\n source_commit_seq BIGINT NOT NULL, created_at_ms BIGINT NOT NULL,\n available_at_ms BIGINT NOT NULL, status TEXT NOT NULL,\n attempts INTEGER NOT NULL, max_attempts INTEGER NOT NULL,\n lease_owner TEXT, lease_expires_at_ms BIGINT, completed_at_ms BIGINT,\n last_failure JSONB,\n PRIMARY KEY(partition, idempotency_key),\n CHECK(status IN ('pending', 'leased', 'completed', 'dead-letter'))\n);\nCREATE INDEX IF NOT EXISTS sync_reactions_due\n ON sync_reactions(partition, status, available_at_ms, created_at_ms, idempotency_key);\nCREATE INDEX IF NOT EXISTS sync_reactions_lease\n ON sync_reactions(partition, status, lease_expires_at_ms);\nCREATE INDEX IF NOT EXISTS sync_reactions_completed\n ON sync_reactions(partition, status, completed_at_ms, idempotency_key);\nCREATE INDEX IF NOT EXISTS sync_reactions_dead_letter\n ON sync_reactions(partition, status, available_at_ms, idempotency_key);\nCREATE TABLE IF NOT EXISTS sync_clients(\n partition TEXT NOT NULL, client_id TEXT NOT NULL, actor_id TEXT NOT NULL,\n wire_version INTEGER NOT NULL DEFAULT 1,\n cursor BIGINT NOT NULL,\n updated_at_ms BIGINT NOT NULL,\n last_round_at_ms BIGINT, last_error_code TEXT,\n consecutive_failures INTEGER NOT NULL DEFAULT 0,\n schema_version INTEGER, units JSONB, registration_digest BYTEA,\n catching_up JSONB NOT NULL DEFAULT '[]',\n PRIMARY KEY(partition, client_id)\n);\nALTER TABLE sync_clients\n ADD COLUMN IF NOT EXISTS wire_version INTEGER NOT NULL DEFAULT 1;\nALTER TABLE sync_clients ADD COLUMN IF NOT EXISTS last_round_at_ms BIGINT;\nALTER TABLE sync_clients ADD COLUMN IF NOT EXISTS last_error_code TEXT;\nALTER TABLE sync_clients\n ADD COLUMN IF NOT EXISTS consecutive_failures INTEGER NOT NULL DEFAULT 0;\nALTER TABLE sync_clients ADD COLUMN IF NOT EXISTS schema_version INTEGER;\nALTER TABLE sync_clients ADD COLUMN IF NOT EXISTS units JSONB;\nALTER TABLE sync_clients ADD COLUMN IF NOT EXISTS registration_digest BYTEA;\nALTER TABLE sync_clients\n ADD COLUMN IF NOT EXISTS catching_up JSONB NOT NULL DEFAULT '[]';\n-- \u00A79: a database from before wire version 4 (its client records still hold\n-- subscriptions) starts the horizon at its last commit.\nUPDATE sync_partitions SET horizon_seq = max_commit_seq\n WHERE EXISTS (SELECT 1 FROM information_schema.columns\n WHERE table_schema = current_schema()\n AND table_name = 'sync_clients'\n AND column_name = 'subscriptions');\nALTER TABLE sync_clients DROP COLUMN IF EXISTS subscriptions;\nCREATE TABLE IF NOT EXISTS sync_blob_refs(\n partition TEXT NOT NULL, tbl TEXT NOT NULL, row_id TEXT NOT NULL,\n blob_id TEXT NOT NULL,\n PRIMARY KEY(partition, tbl, row_id, blob_id)\n);\nCREATE INDEX IF NOT EXISTS sync_blob_refs_by_blob\n ON sync_blob_refs(partition, blob_id);\nCREATE TABLE IF NOT EXISTS sync_tombstones(\n partition TEXT NOT NULL, tbl TEXT NOT NULL, row_id TEXT NOT NULL,\n commit_seq BIGINT NOT NULL, server_version BIGINT, scopes JSONB,\n PRIMARY KEY(partition, tbl, row_id)\n);\nALTER TABLE sync_tombstones ADD COLUMN IF NOT EXISTS server_version BIGINT;\nALTER TABLE sync_tombstones ADD COLUMN IF NOT EXISTS scopes JSONB;\nALTER TABLE sync_partitions\n ADD COLUMN IF NOT EXISTS delete_floor BIGINT NOT NULL DEFAULT 0;\nUPDATE sync_partitions SET delete_floor = t.version\n FROM (SELECT partition, max(server_version) AS version\n FROM sync_tombstones GROUP BY partition) t\n WHERE t.partition = sync_partitions.partition\n AND t.version > sync_partitions.delete_floor;\nCREATE TABLE IF NOT EXISTS sync_backfill_checkpoints(\n partition TEXT NOT NULL, name TEXT NOT NULL,\n schema_version INTEGER NOT NULL,\n state TEXT NOT NULL CHECK(state IN ('declared','backfilling','activated')),\n watermark BIGINT NOT NULL DEFAULT 0,\n owner_epoch BIGINT NOT NULL DEFAULT 0,\n observed_rows BIGINT NOT NULL DEFAULT 0,\n updated_at_ms BIGINT NOT NULL,\n PRIMARY KEY(partition, name)\n);\nCREATE TABLE IF NOT EXISTS sync_writer_fence(\n partition TEXT PRIMARY KEY,\n required_writer_version INTEGER NOT NULL\n);\n";
77
+ export declare const POSTGRES_DDL = "\nCREATE TABLE IF NOT EXISTS sync_partitions(\n partition TEXT PRIMARY KEY,\n max_commit_seq BIGINT NOT NULL DEFAULT 0,\n horizon_seq BIGINT NOT NULL DEFAULT 0,\n delete_floor BIGINT NOT NULL DEFAULT 0\n);\nCREATE TABLE IF NOT EXISTS sync_partition_registry(\n partition TEXT PRIMARY KEY,\n log_epoch TEXT NOT NULL,\n epoch_required BOOLEAN NOT NULL DEFAULT FALSE,\n last_authenticated_at_ms BIGINT NOT NULL\n);\nCREATE TABLE IF NOT EXISTS sync_table_horizons(\n partition TEXT NOT NULL, tbl TEXT NOT NULL,\n commit_seq BIGINT NOT NULL,\n PRIMARY KEY(partition, tbl)\n);\nCREATE TABLE IF NOT EXISTS sync_row_scopes(\n partition TEXT NOT NULL, tbl TEXT NOT NULL,\n var TEXT NOT NULL, value TEXT NOT NULL, row_id TEXT NOT NULL,\n PRIMARY KEY(partition, tbl, var, value, row_id)\n);\nCREATE INDEX IF NOT EXISTS sync_row_scopes_by_row\n ON sync_row_scopes(partition, tbl, row_id);\nCREATE TABLE IF NOT EXISTS sync_commits(\n partition TEXT NOT NULL, commit_seq BIGINT NOT NULL,\n client_id TEXT NOT NULL, client_commit_id TEXT NOT NULL,\n actor_id TEXT NOT NULL, created_at_ms BIGINT NOT NULL,\n writer_version BIGINT,\n PRIMARY KEY(partition, commit_seq)\n);\nCREATE INDEX IF NOT EXISTS sync_commits_by_time\n ON sync_commits(partition, created_at_ms);\nCREATE TABLE IF NOT EXISTS sync_changes(\n partition TEXT NOT NULL, commit_seq BIGINT NOT NULL, idx INTEGER NOT NULL,\n tbl TEXT NOT NULL, row_id TEXT NOT NULL, op SMALLINT NOT NULL,\n row_version BIGINT, scopes JSONB NOT NULL, payload BYTEA,\n PRIMARY KEY(partition, commit_seq, idx)\n);\nCREATE INDEX IF NOT EXISTS sync_changes_by_table\n ON sync_changes(partition, commit_seq, tbl, idx);\nCREATE TABLE IF NOT EXISTS sync_change_scopes(\n partition TEXT NOT NULL, tbl TEXT NOT NULL,\n var TEXT NOT NULL, value TEXT NOT NULL, commit_seq BIGINT NOT NULL,\n PRIMARY KEY(partition, tbl, var, value, commit_seq)\n);\nCREATE INDEX IF NOT EXISTS sync_change_scopes_by_key\n ON sync_change_scopes(partition, var, value, commit_seq);\nCREATE TABLE IF NOT EXISTS sync_push_results(\n partition TEXT NOT NULL, client_id TEXT NOT NULL,\n client_commit_id TEXT NOT NULL, result JSONB NOT NULL,\n outbox_id TEXT, client_seq BIGINT,\n PRIMARY KEY(partition, client_id, client_commit_id)\n);\nALTER TABLE sync_push_results ADD COLUMN IF NOT EXISTS outbox_id TEXT;\nALTER TABLE sync_push_results ADD COLUMN IF NOT EXISTS client_seq BIGINT;\nCREATE TABLE IF NOT EXISTS sync_push_watermarks(\n partition TEXT NOT NULL, client_id TEXT NOT NULL, outbox_id TEXT NOT NULL,\n through_seq BIGINT NOT NULL,\n PRIMARY KEY(partition, client_id, outbox_id)\n);\nCREATE TABLE IF NOT EXISTS sync_reactions(\n partition TEXT NOT NULL, idempotency_key TEXT NOT NULL,\n type TEXT NOT NULL, version INTEGER NOT NULL, payload JSONB NOT NULL,\n source_client_id TEXT NOT NULL, source_client_commit_id TEXT NOT NULL,\n source_commit_seq BIGINT NOT NULL, created_at_ms BIGINT NOT NULL,\n available_at_ms BIGINT NOT NULL, status TEXT NOT NULL,\n attempts INTEGER NOT NULL, max_attempts INTEGER NOT NULL,\n lease_owner TEXT, lease_expires_at_ms BIGINT, completed_at_ms BIGINT,\n last_failure JSONB,\n PRIMARY KEY(partition, idempotency_key),\n CHECK(status IN ('pending', 'leased', 'completed', 'dead-letter'))\n);\nCREATE INDEX IF NOT EXISTS sync_reactions_due\n ON sync_reactions(partition, status, available_at_ms, created_at_ms, idempotency_key);\nCREATE INDEX IF NOT EXISTS sync_reactions_lease\n ON sync_reactions(partition, status, lease_expires_at_ms);\nCREATE INDEX IF NOT EXISTS sync_reactions_completed\n ON sync_reactions(partition, status, completed_at_ms, idempotency_key);\nCREATE INDEX IF NOT EXISTS sync_reactions_dead_letter\n ON sync_reactions(partition, status, available_at_ms, idempotency_key);\nCREATE TABLE IF NOT EXISTS sync_clients(\n partition TEXT NOT NULL, client_id TEXT NOT NULL, actor_id TEXT NOT NULL,\n wire_version INTEGER NOT NULL DEFAULT 1,\n cursor BIGINT NOT NULL,\n updated_at_ms BIGINT NOT NULL,\n last_round_at_ms BIGINT, last_error_code TEXT,\n consecutive_failures INTEGER NOT NULL DEFAULT 0,\n schema_version INTEGER, units JSONB, registration_digest BYTEA,\n catching_up JSONB NOT NULL DEFAULT '[]',\n PRIMARY KEY(partition, client_id)\n);\nALTER TABLE sync_clients\n ADD COLUMN IF NOT EXISTS wire_version INTEGER NOT NULL DEFAULT 1;\nALTER TABLE sync_clients ADD COLUMN IF NOT EXISTS last_round_at_ms BIGINT;\nALTER TABLE sync_clients ADD COLUMN IF NOT EXISTS last_error_code TEXT;\nALTER TABLE sync_clients\n ADD COLUMN IF NOT EXISTS consecutive_failures INTEGER NOT NULL DEFAULT 0;\nALTER TABLE sync_clients ADD COLUMN IF NOT EXISTS schema_version INTEGER;\nALTER TABLE sync_clients ADD COLUMN IF NOT EXISTS units JSONB;\nALTER TABLE sync_clients ADD COLUMN IF NOT EXISTS registration_digest BYTEA;\nALTER TABLE sync_clients\n ADD COLUMN IF NOT EXISTS catching_up JSONB NOT NULL DEFAULT '[]';\n-- \u00A79: a database from before wire version 4 (its client records still hold\n-- subscriptions) starts the horizon at its last commit.\nUPDATE sync_partitions SET horizon_seq = max_commit_seq\n WHERE EXISTS (SELECT 1 FROM information_schema.columns\n WHERE table_schema = current_schema()\n AND table_name = 'sync_clients'\n AND column_name = 'subscriptions');\nALTER TABLE sync_clients DROP COLUMN IF EXISTS subscriptions;\nCREATE TABLE IF NOT EXISTS sync_blob_refs(\n partition TEXT NOT NULL, tbl TEXT NOT NULL, row_id TEXT NOT NULL,\n blob_id TEXT NOT NULL,\n PRIMARY KEY(partition, tbl, row_id, blob_id)\n);\nCREATE INDEX IF NOT EXISTS sync_blob_refs_by_blob\n ON sync_blob_refs(partition, blob_id);\nCREATE TABLE IF NOT EXISTS sync_tombstones(\n partition TEXT NOT NULL, tbl TEXT NOT NULL, row_id TEXT NOT NULL,\n commit_seq BIGINT NOT NULL, server_version BIGINT, scopes JSONB,\n PRIMARY KEY(partition, tbl, row_id)\n);\nALTER TABLE sync_tombstones ADD COLUMN IF NOT EXISTS server_version BIGINT;\nALTER TABLE sync_tombstones ADD COLUMN IF NOT EXISTS scopes JSONB;\nALTER TABLE sync_partitions\n ADD COLUMN IF NOT EXISTS delete_floor BIGINT NOT NULL DEFAULT 0;\nUPDATE sync_partitions SET delete_floor = t.version\n FROM (SELECT partition, max(server_version) AS version\n FROM sync_tombstones GROUP BY partition) t\n WHERE t.partition = sync_partitions.partition\n AND t.version > sync_partitions.delete_floor;\nCREATE TABLE IF NOT EXISTS sync_backfill_checkpoints(\n partition TEXT NOT NULL, name TEXT NOT NULL,\n schema_version INTEGER NOT NULL,\n state TEXT NOT NULL CHECK(state IN ('declared','backfilling','activated')),\n watermark BIGINT NOT NULL DEFAULT 0,\n owner_epoch BIGINT NOT NULL DEFAULT 0,\n observed_rows BIGINT NOT NULL DEFAULT 0,\n updated_at_ms BIGINT NOT NULL,\n PRIMARY KEY(partition, name)\n);\nCREATE TABLE IF NOT EXISTS sync_writer_fence(\n partition TEXT PRIMARY KEY,\n required_writer_version INTEGER NOT NULL\n);\n";
78
78
  export declare class PostgresServerStorage implements ServerStorage {
79
79
  #private;
80
80
  constructor(exec: PgExecutor);
@@ -105,6 +105,7 @@ export declare class PostgresServerStorage implements ServerStorage {
105
105
  queryAuthoritative(partition: string, query: AuthoritativeQueryRequest, checkpoints?: readonly CheckpointDeclaration[]): Promise<AuthoritativeQueryResult>;
106
106
  getPartitionLogEpoch(partition: string): Promise<string | undefined>;
107
107
  getHorizonSeq(partition: string): Promise<number>;
108
+ getHorizons(partition: string): Promise<PartitionHorizons>;
108
109
  setHorizonSeq(partition: string, seq: number): Promise<void>;
109
110
  pruneCommitsThrough(partition: string, query: CommitPruneQuery): Promise<CommitPruneResult>;
110
111
  getCommitSeqBefore(partition: string, createdBeforeMs: number): Promise<number>;
@@ -94,6 +94,11 @@ CREATE TABLE IF NOT EXISTS sync_partition_registry(
94
94
  epoch_required BOOLEAN NOT NULL DEFAULT FALSE,
95
95
  last_authenticated_at_ms BIGINT NOT NULL
96
96
  );
97
+ CREATE TABLE IF NOT EXISTS sync_table_horizons(
98
+ partition TEXT NOT NULL, tbl TEXT NOT NULL,
99
+ commit_seq BIGINT NOT NULL,
100
+ PRIMARY KEY(partition, tbl)
101
+ );
97
102
  CREATE TABLE IF NOT EXISTS sync_row_scopes(
98
103
  partition TEXT NOT NULL, tbl TEXT NOT NULL,
99
104
  var TEXT NOT NULL, value TEXT NOT NULL, row_id TEXT NOT NULL,
@@ -1930,6 +1935,14 @@ FOR EACH ROW EXECUTE FUNCTION syncular_writer_fence()`,
1930
1935
  const { rows } = await this.#exec.query('SELECT horizon_seq FROM sync_partitions WHERE partition=$1', [partition]);
1931
1936
  return rows[0] === undefined ? 0 : asNumber(rows[0].horizon_seq);
1932
1937
  }
1938
+ async getHorizons(partition) {
1939
+ const { rows } = await this.#exec.query(`SELECT coalesce((SELECT horizon_seq FROM sync_partitions WHERE partition=$1),0) AS seq,
1940
+ coalesce((SELECT jsonb_object_agg(tbl, commit_seq) FROM sync_table_horizons WHERE partition=$1),'{}')::text AS tables`, [partition]);
1941
+ return {
1942
+ seq: asNumber(rows[0]?.seq),
1943
+ tables: new Map(Object.entries(asJson(rows[0]?.tables ?? '{}'))),
1944
+ };
1945
+ }
1933
1946
  async setHorizonSeq(partition, seq) {
1934
1947
  await this.#exec.query(`INSERT INTO sync_partitions(partition, horizon_seq) VALUES ($1,$2)
1935
1948
  ON CONFLICT (partition) DO UPDATE SET horizon_seq=GREATEST(sync_partitions.horizon_seq,EXCLUDED.horizon_seq)`, [partition, seq]);
@@ -1956,8 +1969,11 @@ FOR EACH ROW EXECUTE FUNCTION syncular_writer_fence()`,
1956
1969
  WHERE s.partition=$1 AND s.tbl=k.tbl AND s.var=k.key
1957
1970
  AND s.value=k.value AND s.commit_seq=k.commit_seq`, [partition, horizonSeq]);
1958
1971
  await client.query('DELETE FROM sync_changes WHERE partition=$1 AND commit_seq<=$2', [partition, horizonSeq]);
1959
- // §4.6: tombstones prune in the same pass as the commit log.
1960
- await client.query('DELETE FROM sync_tombstones WHERE partition=$1 AND commit_seq<=$2', [partition, horizonSeq]);
1972
+ // §4.6: tombstones and table horizons prune in the same pass as the
1973
+ // commit log.
1974
+ for (const table of ['sync_tombstones', 'sync_table_horizons']) {
1975
+ await client.query(`DELETE FROM ${table} WHERE partition=$1 AND commit_seq<=$2`, [partition, horizonSeq]);
1976
+ }
1961
1977
  return {
1962
1978
  previousHorizonSeq,
1963
1979
  horizonSeq,