@opendatalabs/personal-server-ts-core 1.43.3 → 1.44.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (88) hide show
  1. package/dist/localdb/byte-pages.d.ts +46 -0
  2. package/dist/localdb/byte-pages.d.ts.map +1 -0
  3. package/dist/localdb/byte-pages.js +84 -0
  4. package/dist/localdb/byte-pages.js.map +1 -0
  5. package/dist/localdb/import-readback.d.ts.map +1 -1
  6. package/dist/localdb/import-readback.js +6 -4
  7. package/dist/localdb/import-readback.js.map +1 -1
  8. package/dist/localdb/import-snapshot.d.ts +33 -3
  9. package/dist/localdb/import-snapshot.d.ts.map +1 -1
  10. package/dist/localdb/import-snapshot.js +98 -17
  11. package/dist/localdb/import-snapshot.js.map +1 -1
  12. package/dist/localdb/index.d.ts +3 -0
  13. package/dist/localdb/index.d.ts.map +1 -1
  14. package/dist/localdb/index.js +3 -0
  15. package/dist/localdb/index.js.map +1 -1
  16. package/dist/localdb/legacy-fold.d.ts +68 -0
  17. package/dist/localdb/legacy-fold.d.ts.map +1 -0
  18. package/dist/localdb/legacy-fold.js +225 -0
  19. package/dist/localdb/legacy-fold.js.map +1 -0
  20. package/dist/localdb/legacy-import-types.d.ts +11 -2
  21. package/dist/localdb/legacy-import-types.d.ts.map +1 -1
  22. package/dist/localdb/legacy-import.d.ts +13 -0
  23. package/dist/localdb/legacy-import.d.ts.map +1 -1
  24. package/dist/localdb/legacy-import.js +130 -20
  25. package/dist/localdb/legacy-import.js.map +1 -1
  26. package/dist/localdb/legacy-quarantine.d.ts +67 -0
  27. package/dist/localdb/legacy-quarantine.d.ts.map +1 -0
  28. package/dist/localdb/legacy-quarantine.js +108 -0
  29. package/dist/localdb/legacy-quarantine.js.map +1 -0
  30. package/dist/localdb/legacy-seed-producer.d.ts +71 -0
  31. package/dist/localdb/legacy-seed-producer.d.ts.map +1 -0
  32. package/dist/localdb/legacy-seed-producer.js +217 -0
  33. package/dist/localdb/legacy-seed-producer.js.map +1 -0
  34. package/dist/localdb/log-apply.d.ts +13 -1
  35. package/dist/localdb/log-apply.d.ts.map +1 -1
  36. package/dist/localdb/log-apply.js +60 -20
  37. package/dist/localdb/log-apply.js.map +1 -1
  38. package/dist/localdb/log-changed-keys.d.ts +33 -0
  39. package/dist/localdb/log-changed-keys.d.ts.map +1 -0
  40. package/dist/localdb/log-changed-keys.js +92 -0
  41. package/dist/localdb/log-changed-keys.js.map +1 -0
  42. package/dist/localdb/log-compact.d.ts +27 -10
  43. package/dist/localdb/log-compact.d.ts.map +1 -1
  44. package/dist/localdb/log-compact.js +81 -30
  45. package/dist/localdb/log-compact.js.map +1 -1
  46. package/dist/localdb/log-fold-workspace.d.ts +22 -0
  47. package/dist/localdb/log-fold-workspace.d.ts.map +1 -0
  48. package/dist/localdb/log-fold-workspace.js +246 -0
  49. package/dist/localdb/log-fold-workspace.js.map +1 -0
  50. package/dist/localdb/log-keyed.d.ts +1 -1
  51. package/dist/localdb/log-keyed.d.ts.map +1 -1
  52. package/dist/localdb/log-keyed.js +9 -2
  53. package/dist/localdb/log-keyed.js.map +1 -1
  54. package/dist/localdb/log-publish.d.ts +7 -1
  55. package/dist/localdb/log-publish.d.ts.map +1 -1
  56. package/dist/localdb/log-publish.js +535 -396
  57. package/dist/localdb/log-publish.js.map +1 -1
  58. package/dist/localdb/log-rebase.d.ts.map +1 -1
  59. package/dist/localdb/log-rebase.js +56 -31
  60. package/dist/localdb/log-rebase.js.map +1 -1
  61. package/dist/localdb/log-scratch.d.ts +16 -0
  62. package/dist/localdb/log-scratch.d.ts.map +1 -0
  63. package/dist/localdb/log-scratch.js +95 -0
  64. package/dist/localdb/log-scratch.js.map +1 -0
  65. package/dist/localdb/log-seed.d.ts +5 -5
  66. package/dist/localdb/log-seed.d.ts.map +1 -1
  67. package/dist/localdb/log-seed.js +4 -4
  68. package/dist/localdb/log-seed.js.map +1 -1
  69. package/dist/localdb/log-spool.d.ts +22 -0
  70. package/dist/localdb/log-spool.d.ts.map +1 -0
  71. package/dist/localdb/log-spool.js +92 -0
  72. package/dist/localdb/log-spool.js.map +1 -0
  73. package/dist/localdb/open.d.ts +4 -2
  74. package/dist/localdb/open.d.ts.map +1 -1
  75. package/dist/localdb/open.js +9 -2
  76. package/dist/localdb/open.js.map +1 -1
  77. package/dist/localdb/purge.d.ts.map +1 -1
  78. package/dist/localdb/purge.js +4 -0
  79. package/dist/localdb/purge.js.map +1 -1
  80. package/dist/localdb/schema.d.ts.map +1 -1
  81. package/dist/localdb/schema.js +19 -0
  82. package/dist/localdb/schema.js.map +1 -1
  83. package/dist/localdb/write-batches.d.ts +16 -0
  84. package/dist/localdb/write-batches.d.ts.map +1 -0
  85. package/dist/localdb/write-batches.js +114 -0
  86. package/dist/localdb/write-batches.js.map +1 -0
  87. package/dist-test/tsconfig.tsbuildinfo +1 -1
  88. package/package.json +2 -2
@@ -41,9 +41,10 @@
41
41
  // or the head's bound says so, the segment carries a snapshot pointer, a new
42
42
  // `base`, and no refs at or below it.
43
43
  import { sha256 } from "@noble/hashes/sha2";
44
- import { LOG_FORMAT, DEFAULT_PART_TARGET_BYTES, classifyControl, compactionRequired, controlHashes, controlScope, deriveKeyCheck, digestSegment, encodeSegment, segmentRemoves, deletionKeyMatchesHash, firstDeletionKeyMismatch, keyFromRecordKey, logScope, primaryKeyValues, streamScope, verifySegment, } from "@opendatalabs/personal-server-ts-stream-sync";
44
+ import { bytesToHex } from "@noble/hashes/utils";
45
+ import { LOG_FORMAT, DEFAULT_PART_TARGET_BYTES, classifyControl, compactionRequired, controlHashes, controlScope, deriveKeyCheck, digestSegment, encodeSegment, segmentRemoves, deletionKeyMatchesHash, firstDeletionKeyMismatch, keyFromRecordKey, logScope, primaryKeyValues, streamScope, bodyPieceBlobName, verifySegment, } from "@opendatalabs/personal-server-ts-stream-sync";
45
46
  import { RegistryBatchRouteMissingError, RegistryRefusedError, } from "../stream-sync/ports.js";
46
- import { StorageDeferredError } from "../stream-sync/storage-retry.js";
47
+ import { PARTS_IN_FLIGHT, StorageDeferredError, } from "../stream-sync/storage-retry.js";
47
48
  import { sameHead } from "../stream-sync/publish-plan.js";
48
49
  import { keccakOf } from "../stream-sync/crypto-port.js";
49
50
  import { putBodiesOutOfLine } from "./log-bodies.js";
@@ -52,7 +53,10 @@ import { applyConnection } from "./apply.js";
52
53
  import { listStreamBlobs, uploadBlobs } from "./blobs.js";
53
54
  import { batchBounds, checkBatchRoom, settleRequirementFailure, settleRow, } from "./batch-commit.js";
54
55
  import { tombstoneOmissions } from "./admit.js";
56
+ import { blobIfFits, PAGE_BYTES, readChunked, replyBytes, rowsWithin, SIZE_ROWS, textOf, } from "./byte-pages.js";
57
+ import { changedKeyPages, hasChangedKeys, untypedDeletePages, } from "./log-changed-keys.js";
55
58
  import { planCompaction } from "./log-compact.js";
59
+ import { openSpool } from "./log-spool.js";
56
60
  import { logPublishPhases, openPhases, } from "./log-publish-phases.js";
57
61
  import { readLogState, writeLogState } from "./log-apply.js";
58
62
  import { appendAll, prepareOperations, rowsPerStatement, tombstoneStatements, } from "./log-batch.js";
@@ -67,11 +71,9 @@ import { unwriteRefusedRun } from "./unwrite.js";
67
71
  /**
68
72
  * A transfer page holds at most `PAGE_BYTES` of bodies when two or more rows
69
73
  * fit; a row larger than that is a page of its own (a body is encoded whole).
70
- * Row sizes are read `META_ROWS` at a time and cut into pages; a page also
71
- * holds at most `META_ROWS` rows.
74
+ * Every read of bodies is cut by the rows' real sizes (`byte-pages.ts`).
72
75
  */
73
- const META_ROWS = 2048;
74
- export const PAGE_BYTES = 2 * 1024 * 1024;
76
+ export { PAGE_BYTES };
75
77
  const MAX_ATTEMPTS = 5;
76
78
  /** Keys a query binds: the delete lookup binds a connection, a stream and two positions beside them. */
77
79
  const KEYS_PER_QUERY = rowsPerStatement(1, 4);
@@ -300,12 +302,13 @@ function transition(entry, event) {
300
302
  throw new Error(`publish: invalid candidate transition ${state.kind} -> ${event}`);
301
303
  }
302
304
  }
303
- function releaseCandidate(pending, id, entry) {
305
+ async function releaseCandidate(pending, id, entry) {
304
306
  if (hasAmbiguousCommit(entry) ||
305
307
  entry.state.kind === "uploading" ||
306
308
  entry.state.kind === "uploaded")
307
309
  throw new Error("publish: cannot release an unsettled candidate");
308
310
  pending.delete(id);
311
+ await entry.candidate.spool.discard();
309
312
  }
310
313
  async function invalidateExpiredCandidate(held, id, entry) {
311
314
  const [row] = await held.db.query("SELECT generation, control_state FROM connections WHERE connection_id = ?", [id]);
@@ -344,7 +347,7 @@ async function publishRounds(deps, connectionId, clock) {
344
347
  if (entry.state.kind === "invalidated" ||
345
348
  entry.state.kind === "committed" ||
346
349
  entry.state.kind === "refused") {
347
- releaseCandidate(pending, connectionId, entry);
350
+ await releaseCandidate(pending, connectionId, entry);
348
351
  retained = undefined;
349
352
  }
350
353
  }
@@ -389,7 +392,7 @@ async function publishRounds(deps, connectionId, clock) {
389
392
  ? clock.time("attachments", () => uploadBlobs(deps, candidate.attachments))
390
393
  : undefined,
391
394
  clock.time("segment-put", () => allTransferred([
392
- ...candidate.objects.map((object) => putIfMissing(deps, `${scope}/${object.name}`, object.cipher, retained !== undefined || attempts > 0)),
395
+ putSpooled(deps, scope, candidate.objects, retained !== undefined || attempts > 0),
393
396
  putIfMissing(deps, `${scope}/${candidate.blobName}`, candidate.cipher, retained !== undefined || attempts > 0),
394
397
  ])),
395
398
  ]);
@@ -416,11 +419,11 @@ async function publishRounds(deps, connectionId, clock) {
416
419
  transfer.state.kind === "uploaded" &&
417
420
  !hasAmbiguousCommit(transfer)) {
418
421
  transition(transfer, "refused");
419
- releaseCandidate(pending, connectionId, transfer);
422
+ await releaseCandidate(pending, connectionId, transfer);
420
423
  }
421
424
  throw error;
422
425
  }
423
- releaseCandidate(pending, connectionId, transfer);
426
+ await releaseCandidate(pending, connectionId, transfer);
424
427
  if (committed.kind === "retry") {
425
428
  if (++attempts >= MAX_ATTEMPTS) {
426
429
  await record(await backoff(deps, connectionId));
@@ -442,6 +445,33 @@ async function putIfMissing(deps, key, bytes, checkExisting) {
442
445
  if (!checkExisting || !(await deps.blobs.exists(key)))
443
446
  await deps.blobs.put(key, bytes);
444
447
  }
448
+ /**
449
+ * Put the spooled objects, `PARTS_IN_FLIGHT` at a time. An object is read from
450
+ * the spool when its put starts and is not held after it ends, so the memory
451
+ * of the transfer is the pool's, whatever the size of the log. After a
452
+ * failure no put starts, and the ones in flight end before this returns.
453
+ */
454
+ async function putSpooled(deps, scope, objects, checkExisting) {
455
+ let next = 0;
456
+ let failure;
457
+ const worker = async () => {
458
+ while (!failure && next < objects.length) {
459
+ const object = objects[next++];
460
+ try {
461
+ const key = `${scope}/${object.name}`;
462
+ if (checkExisting && (await deps.blobs.exists(key)))
463
+ continue;
464
+ await deps.blobs.put(key, await object.read());
465
+ }
466
+ catch (reason) {
467
+ failure ??= { reason };
468
+ }
469
+ }
470
+ };
471
+ await Promise.all(Array.from({ length: Math.min(PARTS_IN_FLIGHT, objects.length) }, worker));
472
+ if (failure)
473
+ throw failure.reason;
474
+ }
445
475
  // A failed transfer must not leave another PUT running into the next retry.
446
476
  async function allTransferred(transfers) {
447
477
  const results = await Promise.allSettled(transfers);
@@ -539,366 +569,427 @@ async function snapshotRound(held, connectionId, clock) {
539
569
  : new Set();
540
570
  const planned = [];
541
571
  const target = held.partTargetBytes ?? DEFAULT_PART_TARGET_BYTES;
542
- let budget = 0;
543
- let first = true;
544
- // Streams this pass holds back, and streams it did not examine for it.
545
- const heldNow = new Set();
546
- const unexamined = new Set();
547
- eachStream: for (const row of streams) {
548
- const { stream } = row;
549
- if (await discardFencedRuns(held, connectionId, stream)) {
550
- await applyConnection(held, connectionId);
551
- return { kind: "retry" };
552
- }
553
- if (connection.generation !== 1)
554
- await excludeSeedsIfAny(held, connectionId, stream);
555
- // The plan's base is what the log last said, not what the run's end wrote.
556
- const published = asPublished(row);
557
- const plan = await planStream(held, connectionId, connection, stream, published, null, row.head_version, row.head_data_hash);
558
- if (plan.refused) {
559
- await unwriteRefusedRun(held, {
560
- connectionId,
561
- stream,
562
- runId: plan.refused.runId,
563
- reason: plan.refused.reason,
564
- });
565
- await applyConnection(held, connectionId);
566
- return { kind: "retry" };
567
- }
568
- const [wRow] = await held.db.query("SELECT MAX(seq) AS w FROM record_changes WHERE connection_id = ? AND stream = ?", [connectionId, stream]);
569
- const watermark = wRow?.w ?? row.publish_watermark;
570
- const base = {
571
- stream,
572
- local: row,
573
- plan,
574
- watermark,
575
- ack: watermark,
576
- included: false,
577
- rest: false,
578
- operations: [],
579
- meta: null,
580
- runIds: plan.steps.map((step) => step.runId),
581
- replace: null,
582
- replacing: null,
583
- omitting: null,
584
- omitted: [],
585
- bytes: 0,
586
- cursor: null,
572
+ const scope = logScope(connection.connector, connection.ns);
573
+ // The sealed objects this round uploads wait on disk, not in the candidate:
574
+ // the pieces of a body larger than the part target are sealed into the spool
575
+ // as the planner selects the record, and the round keeps its reference. A
576
+ // process that ended mid-round left rows nothing refers to; they are gone
577
+ // when the file opens (`log-scratch.ts`).
578
+ const spool = openSpool(held.db, connectionId);
579
+ let handedOver = false;
580
+ try {
581
+ let budget = 0;
582
+ let first = true;
583
+ /**
584
+ * The operation as the segment will carry it. An upsert whose body is larger
585
+ * than the part target goes out of line at once (`log-bodies.ts`): its pieces
586
+ * are sealed into the spool, and the round holds the reference, not the body.
587
+ * Its size was counted before (`opSize`), so the round's budget is unchanged.
588
+ */
589
+ const spill = async (op) => {
590
+ if (op.kind !== "upsert" || JSON.stringify(op.value).length <= target)
591
+ return op;
592
+ const out = await putBodiesOutOfLine(held, scope, [op], target);
593
+ for (const piece of out.pieces)
594
+ await spool.add(piece.name, piece.cipher);
595
+ return out.ops[0];
587
596
  };
588
- if (plan.deferred) {
589
- unexamined.add(stream);
590
- planned.push({ ...base, ack: row.publish_watermark });
591
- continue;
592
- }
593
- // The stream's local head stands for the log's last segment that touched
594
- // it (see `applySegmentOperations`): a replacing run applies only if no
595
- // segment touched the stream since the run began.
596
- const replace = plan.replaceBelow ?? null;
597
- const omitted = replace
598
- ? await omittedBy(held, connectionId, stream, plan.finalHead?.primaryKey ?? JSON.parse(row.primary_key), replace)
599
- : [];
600
- const groups = await changedKeys(held, connectionId, stream, row.publish_watermark, watermark);
601
- // A stream with no head yet (a first collection that publishes while it
602
- // collects) is described by its local state.
603
- const head = plan.finalHead ??
604
- (groups.length > 0
605
- ? {
606
- generation: row.head_generation ?? connection.generation,
607
- primaryKey: JSON.parse(row.primary_key),
608
- profile: {
609
- key: row.profile_key ?? connection.connector,
610
- version: row.profile_version ?? row.floor_version ?? "0",
611
- },
612
- // A seeded stream is what this device holds, head and all: its
613
- // completeness is its own. Other changes with no run to describe
614
- // them belong to a first collection that is still filling.
615
- complete: seeded.has(stream) && row.complete === 1,
616
- }
617
- : null);
618
- const metaChanged = head !== null &&
619
- (row.head_version === 0 ||
620
- !sameHead(head, {
621
- generation: row.head_generation ?? head.generation,
622
- primaryKey: JSON.parse(published.primary_key),
623
- profile: {
624
- key: published.profile_key ?? connection.connector,
625
- version: published.profile_version ?? "0",
626
- },
627
- complete: published.complete === 1,
628
- }));
629
- const metaPublishes = metaChanged && plan.steps.some((s) => s.decision.kind === "publish");
630
- const hasWork = groups.length > 0 || replace !== null || metaPublishes;
631
- if (!hasWork || head === null) {
632
- planned.push({ ...base, runIds: base.runIds });
633
- continue;
634
- }
635
- // Changes go in the order they were made, until the segment reaches the
636
- // part target, measured on the operations themselves. The first thing in
637
- // a segment always goes, however large, so a round always progresses.
638
- //
639
- // A replacing stream whose rows and completion fit one segment goes whole
640
- // (a reader sees the replace at once), or waits for the next round if
641
- // this segment is full. One larger than a segment goes like any other
642
- // changes, over as many rounds as it needs. Its completion (the keys it
643
- // dropped) goes in the round that takes its last rows, or alone in the
644
- // next. A completion larger than what is left of the segment goes in
645
- // pieces over as many rounds as it needs: each is a completion at the
646
- // run's cutoff for the next keys in hash order, an omission per key like
647
- // any other. Only the round with the last piece says the stream is
648
- // complete: an earlier round says it is not, so a reader never takes a
649
- // replace that is half published for a complete stream. Every operation
650
- // merges per key by stamp, so rounds from other writers in between
651
- // interleave as they would with any other changes.
652
- const room = (size) => first || budget + size <= target;
653
- const sizeOf = (op) => opSize(op, target);
654
- const selected = [];
655
- const taken = [];
656
- let bytes = 100;
657
- let rest = false;
658
- let whole = false;
659
- // A stream with a change the log cannot say stops here: nothing of it is
660
- // published or acknowledged this round (`plan.deferred`, as for a stream
661
- // that waits on its runs), so no change is lost without a trace.
662
- const wasFirst = first;
663
- const stop = (untyped) => {
664
- first = wasFirst;
665
- heldNow.add(stream);
666
- // One warning per held state, not per pass: a cycle publishes more than
667
- // once and a held stream is met again on every poll until its keys are
668
- // known. The state is the set of changes held; a different set warns.
669
- const state = [...untyped].sort().join(",");
670
- const warned = warnedHolds(held.db, connectionId);
671
- if (warned.get(stream) !== state) {
672
- warned.set(stream, state);
673
- held.logger.warn({ connectionId, stream, pkHashes: untyped.slice(0, 5) }, `stream sync: the log holds back stream "${stream}": an explicit delete made before typed keys were kept cannot be written to it, and the stream's declared key types do not give its key back`);
597
+ // Streams this pass holds back, and streams it did not examine for it.
598
+ const heldNow = new Set();
599
+ const unexamined = new Set();
600
+ eachStream: for (const row of streams) {
601
+ const { stream } = row;
602
+ if (await discardFencedRuns(held, connectionId, stream)) {
603
+ await applyConnection(held, connectionId);
604
+ return { kind: "retry" };
674
605
  }
675
- planned.push({
676
- ...base,
677
- plan: { ...plan, deferred: true },
678
- ack: row.publish_watermark,
679
- });
680
- };
681
- if (replace !== null) {
682
- const { ops: found, untyped } = await operationsFor(held, connectionId, stream, groups.map((g) => g.pk), row.publish_watermark, watermark);
683
- if (untyped.length > 0) {
684
- stop(untyped);
606
+ if (connection.generation !== 1)
607
+ await excludeSeedsIfAny(held, connectionId, stream);
608
+ // The plan's base is what the log last said, not what the run's end wrote.
609
+ const published = asPublished(row);
610
+ const plan = await planStream(held, connectionId, connection, stream, published, null, row.head_version, row.head_data_hash);
611
+ if (plan.refused) {
612
+ await unwriteRefusedRun(held, {
613
+ connectionId,
614
+ stream,
615
+ runId: plan.refused.runId,
616
+ reason: plan.refused.reason,
617
+ });
618
+ await applyConnection(held, connectionId);
619
+ return { kind: "retry" };
620
+ }
621
+ const [wRow] = await held.db.query("SELECT MAX(seq) AS w FROM record_changes WHERE connection_id = ? AND stream = ?", [connectionId, stream]);
622
+ const watermark = wRow?.w ?? row.publish_watermark;
623
+ const base = {
624
+ stream,
625
+ local: row,
626
+ plan,
627
+ watermark,
628
+ ack: watermark,
629
+ included: false,
630
+ rest: false,
631
+ operations: [],
632
+ meta: null,
633
+ runIds: plan.steps.map((step) => step.runId),
634
+ replace: null,
635
+ replacing: null,
636
+ omitting: null,
637
+ omitted: [],
638
+ bytes: 0,
639
+ cursor: null,
640
+ };
641
+ if (plan.deferred) {
642
+ unexamined.add(stream);
643
+ planned.push({ ...base, ack: row.publish_watermark });
685
644
  continue;
686
645
  }
687
- let size = bytes + 100 + omittedSize(omitted);
688
- for (const op of found.values())
689
- size += sizeOf(op);
690
- if (size <= target) {
691
- if (!room(size)) {
692
- planned.push({ ...base, ack: row.publish_watermark, rest: true });
646
+ // The stream's local head stands for the log's last segment that touched
647
+ // it (see `applySegmentOperations`): a replacing run applies only if no
648
+ // segment touched the stream since the run began.
649
+ const replace = plan.replaceBelow ?? null;
650
+ const omitted = replace
651
+ ? await omittedBy(held, connectionId, stream, plan.finalHead?.primaryKey ?? JSON.parse(row.primary_key), replace)
652
+ : [];
653
+ const hasChanges = await hasChangedKeys(held.db, connectionId, stream, row.publish_watermark, watermark);
654
+ // The changed keys are read a page at a time, in the order they changed:
655
+ // a round takes a segment's worth and stops.
656
+ const pages = () => changedKeyPages(held.db, connectionId, stream, row.publish_watermark, watermark);
657
+ // A stream with no head yet (a first collection that publishes while it
658
+ // collects) is described by its local state.
659
+ const head = plan.finalHead ??
660
+ (hasChanges
661
+ ? {
662
+ generation: row.head_generation ?? connection.generation,
663
+ primaryKey: JSON.parse(row.primary_key),
664
+ profile: {
665
+ key: row.profile_key ?? connection.connector,
666
+ version: row.profile_version ?? row.floor_version ?? "0",
667
+ },
668
+ // A seeded stream is what this device holds, head and all: its
669
+ // completeness is its own. Other changes with no run to describe
670
+ // them belong to a first collection that is still filling.
671
+ complete: seeded.has(stream) && row.complete === 1,
672
+ }
673
+ : null);
674
+ const metaChanged = head !== null &&
675
+ (row.head_version === 0 ||
676
+ !sameHead(head, {
677
+ generation: row.head_generation ?? head.generation,
678
+ primaryKey: JSON.parse(published.primary_key),
679
+ profile: {
680
+ key: published.profile_key ?? connection.connector,
681
+ version: published.profile_version ?? "0",
682
+ },
683
+ complete: published.complete === 1,
684
+ }));
685
+ const metaPublishes = metaChanged && plan.steps.some((s) => s.decision.kind === "publish");
686
+ const hasWork = hasChanges || replace !== null || metaPublishes;
687
+ if (!hasWork || head === null) {
688
+ planned.push({ ...base, runIds: base.runIds });
689
+ continue;
690
+ }
691
+ // Changes go in the order they were made, until the segment reaches the
692
+ // part target, measured on the operations themselves. The first thing in
693
+ // a segment always goes, however large, so a round always progresses.
694
+ //
695
+ // A replacing stream whose rows and completion fit one segment goes whole
696
+ // (a reader sees the replace at once), or waits for the next round if
697
+ // this segment is full. One larger than a segment goes like any other
698
+ // changes, over as many rounds as it needs. Its completion (the keys it
699
+ // dropped) goes in the round that takes its last rows, or alone in the
700
+ // next. A completion larger than what is left of the segment goes in
701
+ // pieces over as many rounds as it needs: each is a completion at the
702
+ // run's cutoff for the next keys in hash order, an omission per key like
703
+ // any other. Only the round with the last piece says the stream is
704
+ // complete: an earlier round says it is not, so a reader never takes a
705
+ // replace that is half published for a complete stream. Every operation
706
+ // merges per key by stamp, so rounds from other writers in between
707
+ // interleave as they would with any other changes.
708
+ const room = (size) => first || budget + size <= target;
709
+ const sizeOf = (op) => opSize(op, target);
710
+ // What the round takes: how many keys, the last one's change, and their operations.
711
+ let selectedCount = 0;
712
+ let lastSelectedSeq = 0;
713
+ const taken = [];
714
+ let bytes = 100;
715
+ let rest = false;
716
+ let whole = false;
717
+ // A stream with a change the log cannot say stops here: nothing of it is
718
+ // published or acknowledged this round (`plan.deferred`, as for a stream
719
+ // that waits on its runs), so no change is lost without a trace.
720
+ const wasFirst = first;
721
+ const stop = (untyped) => {
722
+ first = wasFirst;
723
+ heldNow.add(stream);
724
+ // One warning per held state, not per pass: a cycle publishes more than
725
+ // once and a held stream is met again on every poll until its keys are
726
+ // known. The state is the set of changes held; a different set warns.
727
+ const state = [...untyped].sort().join(",");
728
+ const warned = warnedHolds(held.db, connectionId);
729
+ if (warned.get(stream) !== state) {
730
+ warned.set(stream, state);
731
+ held.logger.warn({ connectionId, stream, pkHashes: untyped.slice(0, 5) }, `stream sync: the log holds back stream "${stream}": an explicit delete made before typed keys were kept cannot be written to it, and the stream's declared key types do not give its key back`);
732
+ }
733
+ planned.push({
734
+ ...base,
735
+ plan: { ...plan, deferred: true },
736
+ ack: row.publish_watermark,
737
+ });
738
+ };
739
+ if (replace !== null) {
740
+ // The whole stream is looked at for deletes the log cannot say before
741
+ // any row goes, with no bodies read. Then bodies are read a batch at a
742
+ // time until they no longer fit one segment: a replace of a stream
743
+ // larger than the segment never has more than a segment in memory.
744
+ const untypedKeys = [];
745
+ for await (const page of untypedDeletePages(held.db, connectionId, stream, row.publish_watermark, watermark))
746
+ for (const d of page)
747
+ if ((await declaredKey(held, connectionId, stream, {
748
+ pk_hash: d.pk,
749
+ record_key: d.recordKey,
750
+ })) === null)
751
+ untypedKeys.push(d.pk);
752
+ if (untypedKeys.length > 0) {
753
+ stop(untypedKeys);
693
754
  continue;
694
755
  }
695
- // A stream can hold more keys than a call takes as arguments (a
696
- // spread of ~125k overflows the stack), so these go one by one.
697
- for (const group of groups)
698
- selected.push(group);
699
- for (const op of found.values())
700
- taken.push(op);
701
- bytes = size;
702
- whole = true;
703
- }
704
- }
705
- if (!whole)
706
- scan: for (const batch of chunked(groups, KEYS_PER_QUERY)) {
707
- const { ops: found, untyped } = await operationsFor(held, connectionId, stream, batch.map((g) => g.pk), row.publish_watermark, watermark);
708
- if (untyped.length > 0) {
709
- stop(untyped);
710
- continue eachStream;
756
+ let size = bytes + 100 + omittedSize(omitted);
757
+ const found = new Map();
758
+ let count = 0;
759
+ probe: for await (const page of pages()) {
760
+ for (const batch of await bodyBatches(held, connectionId, stream, page)) {
761
+ if (size > target)
762
+ break probe;
763
+ const read = await operationsFor(held, connectionId, stream, batch.map((g) => g.pk), row.publish_watermark, watermark);
764
+ for (const [pk, op] of read.ops) {
765
+ size += sizeOf(op);
766
+ found.set(pk, await spill(op));
767
+ }
768
+ count += batch.length;
769
+ }
711
770
  }
712
- for (const group of batch) {
713
- const op = found.get(group.pk);
714
- const size = op ? sizeOf(op) : 0;
715
- if (!room(bytes + size)) {
716
- rest = true;
717
- break scan;
771
+ if (size > target)
772
+ found.clear();
773
+ if (size <= target) {
774
+ if (!room(size)) {
775
+ planned.push({ ...base, ack: row.publish_watermark, rest: true });
776
+ continue;
718
777
  }
719
- selected.push(group);
720
- if (op)
778
+ selectedCount = count;
779
+ for (const op of found.values())
721
780
  taken.push(op);
722
- bytes += size;
723
- first = false;
781
+ bytes = size;
782
+ whole = true;
724
783
  }
725
784
  }
726
- if (selected.length === 0 && groups.length > 0) {
727
- planned.push({ ...base, ack: row.publish_watermark, rest: true });
728
- continue;
729
- }
730
- // Rows of the stream wait for a later round; its completion waits with them.
731
- const rowsRest = rest;
732
- let completes = whole;
733
- let piece = [];
734
- if (replace !== null && !whole && !rowsRest) {
735
- // An empty segment takes at least one key, so a round always progresses.
736
- const fit = omissionsThatFit(omitted, target - budget - bytes - 100);
737
- const take = fit === 0 && first ? 1 : fit;
738
- if (take >= omitted.length) {
739
- completes = true;
740
- bytes += 100 + omittedSize(omitted);
785
+ if (!whole)
786
+ scan: for await (const page of pages()) {
787
+ for (const batch of await bodyBatches(held, connectionId, stream, page)) {
788
+ const { ops: found, untyped } = await operationsFor(held, connectionId, stream, batch.map((g) => g.pk), row.publish_watermark, watermark);
789
+ if (untyped.length > 0) {
790
+ stop(untyped);
791
+ continue eachStream;
792
+ }
793
+ for (const group of batch) {
794
+ const op = found.get(group.pk);
795
+ const size = op ? sizeOf(op) : 0;
796
+ if (!room(bytes + size)) {
797
+ rest = true;
798
+ break scan;
799
+ }
800
+ selectedCount += 1;
801
+ lastSelectedSeq = group.seq;
802
+ if (op)
803
+ taken.push(await spill(op));
804
+ bytes += size;
805
+ first = false;
806
+ }
807
+ }
808
+ }
809
+ if (selectedCount === 0 && hasChanges) {
810
+ planned.push({ ...base, ack: row.publish_watermark, rest: true });
811
+ continue;
741
812
  }
742
- else {
743
- rest = true;
744
- piece = omitted.slice(0, take);
745
- if (piece.length > 0)
746
- bytes += 100 + omittedSize(piece);
813
+ // Rows of the stream wait for a later round; its completion waits with them.
814
+ const rowsRest = rest;
815
+ let completes = whole;
816
+ let piece = [];
817
+ if (replace !== null && !whole && !rowsRest) {
818
+ // An empty segment takes at least one key, so a round always progresses.
819
+ const fit = omissionsThatFit(omitted, target - budget - bytes - 100);
820
+ const take = fit === 0 && first ? 1 : fit;
821
+ if (take >= omitted.length) {
822
+ completes = true;
823
+ bytes += 100 + omittedSize(omitted);
824
+ }
825
+ else {
826
+ rest = true;
827
+ piece = omitted.slice(0, take);
828
+ if (piece.length > 0)
829
+ bytes += 100 + omittedSize(piece);
830
+ }
747
831
  }
832
+ // A replace whose completion waits, with no rows or piece of its
833
+ // completion in this round, waits whole.
834
+ if (replace !== null &&
835
+ !completes &&
836
+ taken.length === 0 &&
837
+ piece.length === 0) {
838
+ planned.push({ ...base, ack: row.publish_watermark, rest: true });
839
+ continue;
840
+ }
841
+ // Changes that carry no operation are nothing to publish: the rows a
842
+ // replacing run dropped are deleted locally in the commit that publishes
843
+ // its completion, and those deletions are changes above that commit's
844
+ // watermark. Counted as work they would cost a segment that says nothing.
845
+ if (!completes && !rest && taken.length === 0 && !metaPublishes) {
846
+ planned.push({ ...base });
847
+ continue;
848
+ }
849
+ budget += bytes;
850
+ first = false;
851
+ const ack = rowsRest ? lastSelectedSeq : watermark;
852
+ planned.push({
853
+ ...base,
854
+ included: true,
855
+ rest,
856
+ ack,
857
+ operations: [
858
+ ...orderedOperations(taken),
859
+ ...(replace && (completes || piece.length > 0)
860
+ ? [
861
+ {
862
+ kind: "complete",
863
+ stream,
864
+ cutoff: { o: replace.o, r: replace.r },
865
+ omitted: completes ? omitted : piece,
866
+ },
867
+ ]
868
+ : []),
869
+ ],
870
+ meta: {
871
+ stream,
872
+ primaryKey: head.primaryKey,
873
+ profile: head.profile,
874
+ complete: replace !== null && !completes ? false : head.complete,
875
+ },
876
+ replace: completes ? replace : null,
877
+ replacing: replace !== null && !completes ? replace : null,
878
+ omitting: piece.length > 0
879
+ ? { from: piece[0].pkHash, to: piece.at(-1).pkHash }
880
+ : null,
881
+ omitted: completes ? omitted : piece,
882
+ bytes,
883
+ });
748
884
  }
749
- // A replace whose completion waits, with no rows or piece of its
750
- // completion in this round, waits whole.
751
- if (replace !== null &&
752
- !completes &&
753
- taken.length === 0 &&
754
- piece.length === 0) {
755
- planned.push({ ...base, ack: row.publish_watermark, rest: true });
756
- continue;
757
- }
758
- // Changes that carry no operation are nothing to publish: the rows a
759
- // replacing run dropped are deleted locally in the commit that publishes
760
- // its completion, and those deletions are changes above that commit's
761
- // watermark. Counted as work they would cost a segment that says nothing.
762
- if (!completes && !rest && taken.length === 0 && !metaPublishes) {
763
- planned.push({ ...base });
764
- continue;
885
+ await carryCursors(held, connectionId, connection.connector, streams, planned);
886
+ // A stream that is no longer held warns again if it is held again.
887
+ const warned = warnedHolds(held.db, connectionId);
888
+ for (const stream of [...warned.keys()])
889
+ if (!heldNow.has(stream) && !unexamined.has(stream))
890
+ warned.delete(stream);
891
+ const included = planned.filter((p) => p.included);
892
+ const settle = (outcomeFor) => planned.map((p) => ({
893
+ stream: p.stream,
894
+ outcome: outcomeFor(p),
895
+ watermark: p.watermark,
896
+ }));
897
+ // Attachments named by any stream's records, published or not yet: bytes can
898
+ // arrive after the records that name them were published.
899
+ clock.record("plan", planStart);
900
+ const attachments = [];
901
+ for (const p of planned)
902
+ if (!p.plan.deferred)
903
+ attachments.push(...(await listStreamBlobs(held, {
904
+ connectionId,
905
+ stream: p.stream,
906
+ scope: streamScope(connection.connector, connection.ns, p.stream),
907
+ generation: connection.generation,
908
+ })));
909
+ if (included.length === 0) {
910
+ // Nothing to publish. A new connection's control row is still created, as
911
+ // a request of its own. Record that every covered run was already saved
912
+ // by what the log holds, move the watermarks, and compact.
913
+ if (createControl) {
914
+ const created = await clock.time("control", () => commitControl(held, connectionId, connection, hashes));
915
+ if (created === "retry")
916
+ return { kind: "retry" };
917
+ if (created !== "active")
918
+ return all(created);
919
+ }
920
+ await commitIdle(held, connectionId, planned, log);
921
+ return {
922
+ kind: "done",
923
+ results: settle((p) => (p.plan.deferred ? "deferred" : "noop")),
924
+ attachments,
925
+ };
765
926
  }
766
- budget += bytes;
767
- first = false;
768
- const ack = rowsRest ? selected.at(-1).seq : watermark;
769
- planned.push({
770
- ...base,
771
- included: true,
772
- rest,
773
- ack,
774
- operations: [
775
- ...orderedOperations(taken),
776
- ...(replace && (completes || piece.length > 0)
777
- ? [
778
- {
779
- kind: "complete",
780
- stream,
781
- cutoff: { o: replace.o, r: replace.r },
782
- omitted: completes ? omitted : piece,
783
- },
784
- ]
785
- : []),
786
- ],
787
- meta: {
788
- stream,
789
- primaryKey: head.primaryKey,
790
- profile: head.profile,
791
- complete: replace !== null && !completes ? false : head.complete,
792
- },
793
- replace: completes ? replace : null,
794
- replacing: replace !== null && !completes ? replace : null,
795
- omitting: piece.length > 0
796
- ? { from: piece[0].pkHash, to: piece.at(-1).pkHash }
797
- : null,
798
- omitted: completes ? omitted : piece,
799
- bytes,
800
- });
801
- }
802
- await carryCursors(held, connectionId, connection.connector, streams, planned);
803
- // A stream that is no longer held warns again if it is held again.
804
- const warned = warnedHolds(held.db, connectionId);
805
- for (const stream of [...warned.keys()])
806
- if (!heldNow.has(stream) && !unexamined.has(stream))
807
- warned.delete(stream);
808
- const included = planned.filter((p) => p.included);
809
- const settle = (outcomeFor) => planned.map((p) => ({
810
- stream: p.stream,
811
- outcome: outcomeFor(p),
812
- watermark: p.watermark,
813
- }));
814
- // Attachments named by any stream's records, published or not yet: bytes can
815
- // arrive after the records that name them were published.
816
- clock.record("plan", planStart);
817
- const attachments = [];
818
- for (const p of planned)
819
- if (!p.plan.deferred)
820
- attachments.push(...(await listStreamBlobs(held, {
821
- connectionId,
822
- stream: p.stream,
823
- scope: streamScope(connection.connector, connection.ns, p.stream),
824
- generation: connection.generation,
825
- })));
826
- if (included.length === 0) {
827
- // Nothing to publish. A new connection's control row is still created, as
828
- // a request of its own. Record that every covered run was already saved
829
- // by what the log holds, move the watermarks, and compact.
830
- if (createControl) {
831
- const created = await clock.time("control", () => commitControl(held, connectionId, connection, hashes));
832
- if (created === "retry")
833
- return { kind: "retry" };
834
- if (created !== "active")
835
- return all(created);
927
+ // What the round did not select stays out of the spool: a replace read
928
+ // that did not fit one segment spilled the bodies it had read, and the
929
+ // scan selects them again.
930
+ await spool.keepOnly(new Set(included.flatMap((p) => p.operations.flatMap((op) => op.kind === "upsert-ref"
931
+ ? op.body.pieces.map((hash) => bodyPieceBlobName(hash))
932
+ : []))));
933
+ // The log is folded into a snapshot when that is cheaper than replaying it
934
+ // (or it is at the head's bound), and this segment carries the result.
935
+ const compaction = await planCompaction(held, {
936
+ connectionId,
937
+ connector: connection.connector,
938
+ ns: connection.ns,
939
+ generation: connection.generation,
940
+ keyCheck,
941
+ scope,
942
+ log,
943
+ }, spool);
944
+ const base = compaction ? log.position : log.base;
945
+ const refs = compaction ? [] : log.refs;
946
+ const snapshot = compaction ? compaction.snapshot : log.snapshot;
947
+ if (compactionRequired(refs.length, snapshot?.parts.length ?? 0)) {
948
+ held.logger.warn({ connectionId, refs: refs.length, parts: snapshot?.parts.length ?? 0 }, "stream sync: the log head is full even after compaction");
949
+ return all("deferred");
836
950
  }
837
- await commitIdle(held, connectionId, planned, log);
838
- return {
839
- kind: "done",
840
- results: settle((p) => (p.plan.deferred ? "deferred" : "noop")),
841
- attachments,
951
+ const position = log.position + 1;
952
+ const observedAt = Math.max(...included.map((p) => p.plan.newestRunObservedAt ?? 0), 0);
953
+ const segment = {
954
+ format: LOG_FORMAT,
955
+ connector: connection.connector,
956
+ ns: connection.ns,
957
+ generation: connection.generation,
958
+ keyCheck,
959
+ position,
960
+ observedAt: observedAt || held.now(),
961
+ base,
962
+ snapshot,
963
+ refs,
964
+ streams: included.map((p) => p.meta),
965
+ operations: included.flatMap((p) => p.operations),
842
966
  };
843
- }
844
- const scope = logScope(connection.connector, connection.ns);
845
- // The log is folded into a snapshot when that is cheaper than replaying it
846
- // (or it is at the head's bound), and this segment carries the result.
847
- const compaction = await planCompaction(held, {
848
- connector: connection.connector,
849
- ns: connection.ns,
850
- generation: connection.generation,
851
- keyCheck,
852
- scope,
853
- log,
854
- });
855
- const base = compaction ? log.position : log.base;
856
- const refs = compaction ? [] : log.refs;
857
- const snapshot = compaction ? compaction.snapshot : log.snapshot;
858
- if (compactionRequired(refs.length, snapshot?.parts.length ?? 0)) {
859
- held.logger.warn({ connectionId, refs: refs.length, parts: snapshot?.parts.length ?? 0 }, "stream sync: the log head is full even after compaction");
860
- return all("deferred");
861
- }
862
- const position = log.position + 1;
863
- const observedAt = Math.max(...included.map((p) => p.plan.newestRunObservedAt ?? 0), 0);
864
- const segment = {
865
- format: LOG_FORMAT,
866
- connector: connection.connector,
867
- ns: connection.ns,
868
- generation: connection.generation,
869
- keyCheck,
870
- position,
871
- observedAt: observedAt || held.now(),
872
- base,
873
- snapshot,
874
- refs,
875
- streams: included.map((p) => p.meta),
876
- operations: included.flatMap((p) => p.operations),
877
- };
878
- // A deletion's key is the one its hash covers, or the segment is not written.
879
- const mismatch = await firstDeletionKeyMismatch(async (bytes) => sha256(bytes), segment.streams, segment.operations);
880
- if (mismatch)
881
- throw new Error(`publish: a deletion's key does not match its hash (${mismatch.stream}/${mismatch.pkHash})`);
882
- const encodeStart = clock.now();
883
- // A body larger than one object goes out of line (stream-sync `log.ts`).
884
- const outOfLine = await putBodiesOutOfLine(held, scope, segment.operations, target);
885
- const clear = encodeSegment({ ...segment, operations: outOfLine.ops });
886
- const { dataHash, blobName } = await digestSegment(keccakOf(held.streamCrypto), clear);
887
- // A segment that would not verify is never uploaded or posted.
888
- const verified = await verifySegment(keccakOf(held.streamCrypto), clear, {
889
- dataHash,
890
- connector: connection.connector,
891
- ns: connection.ns,
892
- keyCheck,
893
- position,
894
- });
895
- if (verified.kind !== "ok")
896
- throw new Error(`publish: the log segment failed verification: ${verified.kind}`);
897
- const cipher = await held.keys.encrypt(scope, clear);
898
- clock.record("encode", encodeStart);
899
- return {
900
- kind: "candidate",
901
- candidate: {
967
+ // A deletion's key is the one its hash covers, or the segment is not written.
968
+ const mismatch = await firstDeletionKeyMismatch(async (bytes) => sha256(bytes), segment.streams, segment.operations);
969
+ if (mismatch)
970
+ throw new Error(`publish: a deletion's key does not match its hash (${mismatch.stream}/${mismatch.pkHash})`);
971
+ const encodeStart = clock.now();
972
+ // A body larger than one object goes out of line (stream-sync `log.ts`).
973
+ const outOfLine = await putBodiesOutOfLine(held, scope, segment.operations, target);
974
+ const clear = encodeSegment({ ...segment, operations: outOfLine.ops });
975
+ const { dataHash, blobName } = await digestSegment(keccakOf(held.streamCrypto), clear);
976
+ // A segment that would not verify is never uploaded or posted.
977
+ const verified = await verifySegment(keccakOf(held.streamCrypto), clear, {
978
+ dataHash,
979
+ connector: connection.connector,
980
+ ns: connection.ns,
981
+ keyCheck,
982
+ position,
983
+ });
984
+ if (verified.kind !== "ok")
985
+ throw new Error(`publish: the log segment failed verification: ${verified.kind}`);
986
+ const cipher = await held.keys.encrypt(scope, clear);
987
+ clock.record("encode", encodeStart);
988
+ for (const piece of outOfLine.pieces)
989
+ await spool.add(piece.name, piece.cipher);
990
+ // Everything that can fail is done before the spool changes hands: a
991
+ // candidate that is never returned would leave its rows with no owner.
992
+ const candidate = {
902
993
  lifetime: connectionLifetime(held.db, connectionId),
903
994
  connector: connection.connector,
904
995
  ns: connection.ns,
@@ -907,7 +998,8 @@ async function snapshotRound(held, connectionId, clock) {
907
998
  base,
908
999
  refs,
909
1000
  snapshot,
910
- objects: [...(compaction?.objects ?? []), ...outOfLine.pieces],
1001
+ objects: spool.objects(),
1002
+ spool,
911
1003
  position,
912
1004
  generation: connection.generation,
913
1005
  dataHash,
@@ -921,8 +1013,14 @@ async function snapshotRound(held, connectionId, clock) {
921
1013
  controlDataHash,
922
1014
  createControl,
923
1015
  prevHash: log.refs.at(-1)?.dataHash ?? null,
924
- },
925
- };
1016
+ };
1017
+ handedOver = true;
1018
+ return { kind: "candidate", candidate };
1019
+ }
1020
+ finally {
1021
+ if (!handedOver)
1022
+ await spool.discard();
1023
+ }
926
1024
  }
927
1025
  /**
928
1026
  * A stream's unpublished cursor rides this round only when no row it covers
@@ -1134,13 +1232,29 @@ async function commitControl(held, connectionId, connection, hashes) {
1134
1232
  await held.db.batch([markControlActive(connectionId, connection)]);
1135
1233
  return state;
1136
1234
  }
1235
+ /** The stored size of a held record's body, in bytes: the size column, or its length where the column is empty. */
1236
+ const BODY_SIZE = `COALESCE(body_bytes, ${BODY_BYTES})`;
1237
+ /**
1238
+ * The text of a held record's body: the blob that came with the row, or, for a
1239
+ * body too large for a reply beside other rows, the body read in chunks (a body
1240
+ * larger than the frame still crosses it).
1241
+ */
1242
+ async function bodyText(deps, connectionId, stream, row) {
1243
+ if (row.body)
1244
+ return textOf(row.body);
1245
+ return textOf(await readChunked(deps.db, Number(row.n), (offset, length) => ({
1246
+ sql: `SELECT substr(CAST(body AS BLOB), ?, ?) AS c FROM records
1247
+ WHERE connection_id = ? AND stream = ? AND pk_hash = ?`,
1248
+ params: [offset, length, connectionId, stream, row.pk_hash],
1249
+ })));
1250
+ }
1137
1251
  /**
1138
1252
  * The keys a replacing run dropped: held rows last observed before it. Each
1139
1253
  * names its typed primary-key values from the row it drops, which is held until
1140
1254
  * the run deletes it: the row's data holds them with their types, and a
1141
1255
  * deletion's key is exactly what its hash was computed from.
1142
1256
  *
1143
- * The bodies are read a page at a time (`PAGE_BYTES` of bodies, or one row), after reading the rows' sizes alone (`META_ROWS` at a
1257
+ * The bodies are read a page at a time (`PAGE_BYTES` of bodies, or one row), after reading the rows' sizes alone (`SIZE_ROWS` at a
1144
1258
  * time): the shared SQL cannot return just the key fields of a body (a phone's
1145
1259
  * SQLite 3.22 has no JSON1), and a pass that drops many large records must not
1146
1260
  * hold them all at once. Only the small keys are kept.
@@ -1155,50 +1269,73 @@ async function omittedBy(deps, connectionId, stream, primaryKey, replace) {
1155
1269
  const omitted = [];
1156
1270
  let after;
1157
1271
  for (;;) {
1158
- const meta = await deps.db.query(`SELECT pk_hash, COALESCE(body_bytes, ${BODY_BYTES}) AS n FROM records
1272
+ const meta = await deps.db.query(`SELECT pk_hash, ${BODY_SIZE} AS n FROM records
1159
1273
  WHERE ${scope}${after === undefined ? "" : " AND pk_hash > ?"}
1160
- ORDER BY pk_hash LIMIT ${META_ROWS}`, after === undefined ? scopeParams : [...scopeParams, after]);
1274
+ ORDER BY pk_hash LIMIT ${SIZE_ROWS}`, after === undefined ? scopeParams : [...scopeParams, after]);
1161
1275
  for (let at = 0; at < meta.length;) {
1162
- let take = 0;
1163
- let bytes = 0;
1164
- while (at + take < meta.length &&
1165
- (take === 0 || bytes + Number(meta[at + take].n) <= PAGE_BYTES)) {
1166
- bytes += Number(meta[at + take].n);
1167
- take += 1;
1168
- }
1169
- const page = await deps.db.query(`SELECT pk_hash, body FROM records
1276
+ const take = rowsWithin(meta.slice(at).map((row) => replyBytes(Number(row.n))));
1277
+ const page = await deps.db.query(`SELECT pk_hash, ${BODY_SIZE} AS n, ${blobIfFits("body", BODY_SIZE)} AS body FROM records
1170
1278
  WHERE ${scope} AND pk_hash >= ? AND pk_hash <= ? ORDER BY pk_hash`, [...scopeParams, meta[at].pk_hash, meta[at + take - 1].pk_hash]);
1171
1279
  for (const row of page)
1172
1280
  omitted.push({
1173
1281
  pkHash: row.pk_hash,
1174
- key: primaryKeyValues(JSON.parse(row.body), primaryKey),
1282
+ key: primaryKeyValues(JSON.parse(await bodyText(deps, connectionId, stream, row)), primaryKey),
1175
1283
  });
1176
1284
  at += take;
1177
1285
  }
1178
- if (meta.length < META_ROWS)
1286
+ if (meta.length < SIZE_ROWS)
1179
1287
  return omitted;
1180
1288
  after = meta[meta.length - 1].pk_hash;
1181
1289
  }
1182
1290
  }
1183
- /** The hashes `omittedBy` names, for a comparison that needs no key. */
1184
- async function omittedHashes(deps, connectionId, stream, replace, keys) {
1185
- const rows = await deps.db.query(`SELECT pk_hash FROM records WHERE connection_id = ? AND stream = ?
1186
- AND ${SEEN_BEFORE}${keys ? " AND pk_hash >= ? AND pk_hash <= ?" : ""}
1187
- ORDER BY pk_hash`, [
1188
- connectionId,
1189
- stream,
1190
- ...seenBeforeParams(replace.o, replace.r),
1191
- ...(keys ? [keys.from, keys.to] : []),
1192
- ]);
1193
- return rows.map((row) => row.pk_hash);
1291
+ /**
1292
+ * A digest of the hashes `omittedBy` names, for a comparison that needs no
1293
+ * key: read a page at a time, so what a stream omits is not held to be
1294
+ * compared.
1295
+ */
1296
+ async function omittedDigest(deps, connectionId, stream, replace, keys) {
1297
+ const hash = sha256.create();
1298
+ const encoder = new TextEncoder();
1299
+ let after;
1300
+ let count = 0;
1301
+ for (;;) {
1302
+ const rows = await deps.db.query(`SELECT pk_hash FROM records WHERE connection_id = ? AND stream = ?
1303
+ AND ${SEEN_BEFORE}${keys ? " AND pk_hash >= ? AND pk_hash <= ?" : ""}${after === undefined ? "" : " AND pk_hash > ?"}
1304
+ ORDER BY pk_hash LIMIT ${DIGEST_PAGE}`, [
1305
+ connectionId,
1306
+ stream,
1307
+ ...seenBeforeParams(replace.o, replace.r),
1308
+ ...(keys ? [keys.from, keys.to] : []),
1309
+ ...(after === undefined ? [] : [after]),
1310
+ ]);
1311
+ for (const row of rows)
1312
+ hash.update(encoder.encode(`${row.pk_hash}\n`));
1313
+ count += rows.length;
1314
+ if (rows.length < DIGEST_PAGE)
1315
+ return `${count}:${bytesToHex(hash.digest())}`;
1316
+ after = rows[rows.length - 1].pk_hash;
1317
+ }
1194
1318
  }
1195
- /** Changed keys since the watermark, oldest change first. */
1196
- async function changedKeys(deps, connectionId, stream, from, to) {
1197
- const rows = await deps.db.query(`SELECT pk_hash, MAX(seq) AS seq FROM record_changes
1198
- WHERE connection_id = ? AND stream = ? AND seq > ? AND seq <= ?
1199
- AND ${ELIGIBLE_CHANGE}
1200
- GROUP BY pk_hash ORDER BY MAX(seq)`, [connectionId, stream, from, to]);
1201
- return rows.map((row) => ({ pk: row.pk_hash, seq: row.seq }));
1319
+ const DIGEST_PAGE = 4096;
1320
+ /**
1321
+ * The groups of a page cut into batches whose bodies hold about `PAGE_BYTES`
1322
+ * (a group alone if its body is larger), by the sizes the rows keep: a batch is
1323
+ * read whole, so the keys of a query are not the bound on what it holds.
1324
+ * Groups with no row (a delete) weigh nothing.
1325
+ */
1326
+ async function bodyBatches(deps, connectionId, stream, groups) {
1327
+ const sizes = await deps.db.query(`SELECT pk_hash, ${BODY_SIZE} AS n FROM records
1328
+ WHERE connection_id = ? AND stream = ?
1329
+ AND pk_hash IN (${groups.map(() => "?").join(",")})`, [connectionId, stream, ...groups.map((g) => g.pk)]);
1330
+ const bytesOf = new Map(sizes.map((r) => [r.pk_hash, Number(r.n)]));
1331
+ const weights = groups.map((g) => replyBytes(bytesOf.get(g.pk) ?? 0));
1332
+ const batches = [];
1333
+ for (let at = 0; at < groups.length;) {
1334
+ const take = rowsWithin(weights.slice(at));
1335
+ batches.push(groups.slice(at, at + take));
1336
+ at += take;
1337
+ }
1338
+ return batches;
1202
1339
  }
1203
1340
  /**
1204
1341
  * Local publication debt, independent of publishRounds' aggregate receipt.
@@ -1213,7 +1350,7 @@ export async function hasPendingLogPublication(deps, connectionId) {
1213
1350
  for (const row of streams) {
1214
1351
  if ((await retainedRuns(deps, connectionId, row.stream)).length > 0)
1215
1352
  return true;
1216
- if ((await changedKeys(deps, connectionId, row.stream, row.publish_watermark, last?.seq ?? row.publish_watermark)).length > 0)
1353
+ if (await hasChangedKeys(deps.db, connectionId, row.stream, row.publish_watermark, last?.seq ?? row.publish_watermark))
1217
1354
  return true;
1218
1355
  }
1219
1356
  return false;
@@ -1234,7 +1371,8 @@ async function operationsFor(deps, connectionId, stream, keys, from, to) {
1234
1371
  const untyped = [];
1235
1372
  for (const group of chunked(keys, KEYS_PER_QUERY)) {
1236
1373
  const marks = group.map(() => "?").join(",");
1237
- const rows = await deps.db.query(`SELECT pk_hash, stamp_o, stamp_r, stamp_n, first_o, body FROM records
1374
+ const rows = await deps.db.query(`SELECT pk_hash, stamp_o, stamp_r, stamp_n, first_o, ${BODY_SIZE} AS n,
1375
+ ${blobIfFits("body", BODY_SIZE)} AS body FROM records
1238
1376
  WHERE connection_id = ? AND stream = ? AND pk_hash IN (${marks})`, [connectionId, stream, ...group]);
1239
1377
  const held = new Set(rows.map((row) => row.pk_hash));
1240
1378
  for (const row of rows)
@@ -1246,7 +1384,7 @@ async function operationsFor(deps, connectionId, stream, keys, from, to) {
1246
1384
  // Absent for the run's first batch and for rows from before the column.
1247
1385
  ...(row.stamp_n > 0 ? { ordinal: row.stamp_n } : {}),
1248
1386
  firstSeen: row.first_o,
1249
- value: JSON.parse(row.body),
1387
+ value: JSON.parse(await bodyText(deps, connectionId, stream, row)),
1250
1388
  });
1251
1389
  const gone = group.filter((pk) => !held.has(pk));
1252
1390
  if (gone.length === 0)
@@ -1311,8 +1449,9 @@ async function declaredKey(deps, connectionId, stream, row) {
1311
1449
  }
1312
1450
  /** Upserts, then deletes, each by key: one order for every writer. */
1313
1451
  function orderedOperations(ops) {
1452
+ const isUpsert = (op) => op.kind === "upsert" || op.kind === "upsert-ref";
1314
1453
  const pkOf = (op) => op.kind === "complete" ? (op.omitted[0]?.pkHash ?? "") : op.pkHash;
1315
- return [...ops].sort((a, b) => (a.kind === "upsert" ? 0 : 1) - (b.kind === "upsert" ? 0 : 1) ||
1454
+ return [...ops].sort((a, b) => (isUpsert(a) ? 0 : 1) - (isUpsert(b) ? 0 : 1) ||
1316
1455
  pkOf(a).localeCompare(pkOf(b)));
1317
1456
  }
1318
1457
  /**
@@ -1339,10 +1478,10 @@ async function basisOf(deps, connectionId, planned, log) {
1339
1478
  const covered = await deps.db.query(`SELECT COUNT(*) AS n, MAX(seq) AS newest FROM record_changes
1340
1479
  WHERE connection_id = ? AND stream = ? AND seq > ? AND seq <= ?`, [connectionId, p.stream, p.local.publish_watermark, p.ack]);
1341
1480
  const omitted = p.replace
1342
- ? await omittedHashes(deps, connectionId, p.stream, p.replace)
1481
+ ? await omittedDigest(deps, connectionId, p.stream, p.replace)
1343
1482
  : p.replacing && p.omitting
1344
- ? await omittedHashes(deps, connectionId, p.stream, p.replacing, p.omitting)
1345
- : [];
1483
+ ? await omittedDigest(deps, connectionId, p.stream, p.replacing, p.omitting)
1484
+ : "";
1346
1485
  streams.push([p.stream, state, runs, covered, omitted]);
1347
1486
  }
1348
1487
  return JSON.stringify([connection, log, intents, streams]);
@@ -1640,7 +1779,7 @@ async function candidateAcknowledgements(held, connectionId, candidate, acknowle
1640
1779
  // the same rows through `operationStatements`.
1641
1780
  for (const p of touched)
1642
1781
  if (p.meta)
1643
- appendAll(statements, tombstoneStatements(connectionId, await prepareOperations([p.meta], p.operations.filter((op) => op.kind !== "upsert"))));
1782
+ appendAll(statements, tombstoneStatements(connectionId, await prepareOperations([p.meta], p.operations.filter((op) => op.kind === "delete" || op.kind === "complete"))));
1644
1783
  // A replace still under way read the stream at its basis; the segment this
1645
1784
  // round committed is this device's own, so the basis moves to it (after the
1646
1785
  // head columns above have).