@opendatalabs/personal-server-ts-core 1.44.0 → 1.44.2

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 (58) 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/log-apply.d.ts +13 -1
  6. package/dist/localdb/log-apply.d.ts.map +1 -1
  7. package/dist/localdb/log-apply.js +128 -21
  8. package/dist/localdb/log-apply.js.map +1 -1
  9. package/dist/localdb/log-changed-keys.d.ts +33 -0
  10. package/dist/localdb/log-changed-keys.d.ts.map +1 -0
  11. package/dist/localdb/log-changed-keys.js +92 -0
  12. package/dist/localdb/log-changed-keys.js.map +1 -0
  13. package/dist/localdb/log-compact.d.ts +27 -10
  14. package/dist/localdb/log-compact.d.ts.map +1 -1
  15. package/dist/localdb/log-compact.js +81 -30
  16. package/dist/localdb/log-compact.js.map +1 -1
  17. package/dist/localdb/log-fold-workspace.d.ts +22 -0
  18. package/dist/localdb/log-fold-workspace.d.ts.map +1 -0
  19. package/dist/localdb/log-fold-workspace.js +246 -0
  20. package/dist/localdb/log-fold-workspace.js.map +1 -0
  21. package/dist/localdb/log-keyed.d.ts.map +1 -1
  22. package/dist/localdb/log-keyed.js +2 -0
  23. package/dist/localdb/log-keyed.js.map +1 -1
  24. package/dist/localdb/log-publish.d.ts +7 -1
  25. package/dist/localdb/log-publish.d.ts.map +1 -1
  26. package/dist/localdb/log-publish.js +548 -396
  27. package/dist/localdb/log-publish.js.map +1 -1
  28. package/dist/localdb/log-rebase.d.ts.map +1 -1
  29. package/dist/localdb/log-rebase.js +56 -31
  30. package/dist/localdb/log-rebase.js.map +1 -1
  31. package/dist/localdb/log-scratch.d.ts +16 -0
  32. package/dist/localdb/log-scratch.d.ts.map +1 -0
  33. package/dist/localdb/log-scratch.js +95 -0
  34. package/dist/localdb/log-scratch.js.map +1 -0
  35. package/dist/localdb/log-seed.d.ts +5 -5
  36. package/dist/localdb/log-seed.d.ts.map +1 -1
  37. package/dist/localdb/log-seed.js +4 -4
  38. package/dist/localdb/log-seed.js.map +1 -1
  39. package/dist/localdb/log-spool.d.ts +33 -0
  40. package/dist/localdb/log-spool.d.ts.map +1 -0
  41. package/dist/localdb/log-spool.js +112 -0
  42. package/dist/localdb/log-spool.js.map +1 -0
  43. package/dist/localdb/open.d.ts +4 -2
  44. package/dist/localdb/open.d.ts.map +1 -1
  45. package/dist/localdb/open.js +9 -2
  46. package/dist/localdb/open.js.map +1 -1
  47. package/dist/localdb/purge.d.ts.map +1 -1
  48. package/dist/localdb/purge.js +4 -0
  49. package/dist/localdb/purge.js.map +1 -1
  50. package/dist/localdb/schema.d.ts.map +1 -1
  51. package/dist/localdb/schema.js +10 -0
  52. package/dist/localdb/schema.js.map +1 -1
  53. package/dist/localdb/write-batches.d.ts +16 -0
  54. package/dist/localdb/write-batches.d.ts.map +1 -0
  55. package/dist/localdb/write-batches.js +114 -0
  56. package/dist/localdb/write-batches.js.map +1 -0
  57. package/dist-test/tsconfig.tsbuildinfo +1 -1
  58. 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, SpooledObjectGoneError, } 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]);
@@ -321,6 +324,13 @@ async function invalidateExpiredCandidate(held, id, entry) {
321
324
  (await hasDeleteIntent(held, entry.candidate.connector)))
322
325
  transition(entry, "invalidated");
323
326
  }
327
+ /** Whether the candidate's lifetime ended, judged under the connection queue. */
328
+ async function expiredUnderQueue(deps, connectionId, entry) {
329
+ return deps.queue.run(connectionId, "publish", async () => {
330
+ await invalidateExpiredCandidate(insideQueue(deps, connectionId), connectionId, entry);
331
+ return isInvalidated(entry);
332
+ });
333
+ }
324
334
  async function publishRounds(deps, connectionId, clock) {
325
335
  const record = (list) => recordBlocked(deps, connectionId, list);
326
336
  let attempts = 0;
@@ -344,7 +354,7 @@ async function publishRounds(deps, connectionId, clock) {
344
354
  if (entry.state.kind === "invalidated" ||
345
355
  entry.state.kind === "committed" ||
346
356
  entry.state.kind === "refused") {
347
- releaseCandidate(pending, connectionId, entry);
357
+ await releaseCandidate(pending, connectionId, entry);
348
358
  retained = undefined;
349
359
  }
350
360
  }
@@ -389,7 +399,7 @@ async function publishRounds(deps, connectionId, clock) {
389
399
  ? clock.time("attachments", () => uploadBlobs(deps, candidate.attachments))
390
400
  : undefined,
391
401
  clock.time("segment-put", () => allTransferred([
392
- ...candidate.objects.map((object) => putIfMissing(deps, `${scope}/${object.name}`, object.cipher, retained !== undefined || attempts > 0)),
402
+ putSpooled(deps, scope, candidate.objects, retained !== undefined || attempts > 0),
393
403
  putIfMissing(deps, `${scope}/${candidate.blobName}`, candidate.cipher, retained !== undefined || attempts > 0),
394
404
  ])),
395
405
  ]);
@@ -400,6 +410,12 @@ async function publishRounds(deps, connectionId, clock) {
400
410
  // Storage kept refusing past its retry budget. Nothing is wrong with the
401
411
  // data: nothing was committed, so the changes stay queued and the next
402
412
  // cycle sends them again.
413
+ // A purge deletes the spool while uploads are blocked: the next read
414
+ // finds nothing. If the candidate's lifetime ended, it is stale and the
415
+ // next turn releases it; a spool missing under a live lifetime is a fault.
416
+ if (error instanceof SpooledObjectGoneError &&
417
+ (await expiredUnderQueue(deps, connectionId, transfer)))
418
+ continue;
403
419
  if (!(error instanceof StorageDeferredError))
404
420
  throw error;
405
421
  deps.logger.info({ connectionId, error: error.message }, "stream sync: storage unavailable, publish left in the queue");
@@ -416,11 +432,11 @@ async function publishRounds(deps, connectionId, clock) {
416
432
  transfer.state.kind === "uploaded" &&
417
433
  !hasAmbiguousCommit(transfer)) {
418
434
  transition(transfer, "refused");
419
- releaseCandidate(pending, connectionId, transfer);
435
+ await releaseCandidate(pending, connectionId, transfer);
420
436
  }
421
437
  throw error;
422
438
  }
423
- releaseCandidate(pending, connectionId, transfer);
439
+ await releaseCandidate(pending, connectionId, transfer);
424
440
  if (committed.kind === "retry") {
425
441
  if (++attempts >= MAX_ATTEMPTS) {
426
442
  await record(await backoff(deps, connectionId));
@@ -442,6 +458,33 @@ async function putIfMissing(deps, key, bytes, checkExisting) {
442
458
  if (!checkExisting || !(await deps.blobs.exists(key)))
443
459
  await deps.blobs.put(key, bytes);
444
460
  }
461
+ /**
462
+ * Put the spooled objects, `PARTS_IN_FLIGHT` at a time. An object is read from
463
+ * the spool when its put starts and is not held after it ends, so the memory
464
+ * of the transfer is the pool's, whatever the size of the log. After a
465
+ * failure no put starts, and the ones in flight end before this returns.
466
+ */
467
+ async function putSpooled(deps, scope, objects, checkExisting) {
468
+ let next = 0;
469
+ let failure;
470
+ const worker = async () => {
471
+ while (!failure && next < objects.length) {
472
+ const object = objects[next++];
473
+ try {
474
+ const key = `${scope}/${object.name}`;
475
+ if (checkExisting && (await deps.blobs.exists(key)))
476
+ continue;
477
+ await deps.blobs.put(key, await object.read());
478
+ }
479
+ catch (reason) {
480
+ failure ??= { reason };
481
+ }
482
+ }
483
+ };
484
+ await Promise.all(Array.from({ length: Math.min(PARTS_IN_FLIGHT, objects.length) }, worker));
485
+ if (failure)
486
+ throw failure.reason;
487
+ }
445
488
  // A failed transfer must not leave another PUT running into the next retry.
446
489
  async function allTransferred(transfers) {
447
490
  const results = await Promise.allSettled(transfers);
@@ -539,366 +582,427 @@ async function snapshotRound(held, connectionId, clock) {
539
582
  : new Set();
540
583
  const planned = [];
541
584
  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,
585
+ const scope = logScope(connection.connector, connection.ns);
586
+ // The sealed objects this round uploads wait on disk, not in the candidate:
587
+ // the pieces of a body larger than the part target are sealed into the spool
588
+ // as the planner selects the record, and the round keeps its reference. A
589
+ // process that ended mid-round left rows nothing refers to; they are gone
590
+ // when the file opens (`log-scratch.ts`).
591
+ const spool = openSpool(held.db, connectionId);
592
+ let handedOver = false;
593
+ try {
594
+ let budget = 0;
595
+ let first = true;
596
+ /**
597
+ * The operation as the segment will carry it. An upsert whose body is larger
598
+ * than the part target goes out of line at once (`log-bodies.ts`): its pieces
599
+ * are sealed into the spool, and the round holds the reference, not the body.
600
+ * Its size was counted before (`opSize`), so the round's budget is unchanged.
601
+ */
602
+ const spill = async (op) => {
603
+ if (op.kind !== "upsert" || JSON.stringify(op.value).length <= target)
604
+ return op;
605
+ const out = await putBodiesOutOfLine(held, scope, [op], target);
606
+ for (const piece of out.pieces)
607
+ await spool.add(piece.name, piece.cipher);
608
+ return out.ops[0];
587
609
  };
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`);
610
+ // Streams this pass holds back, and streams it did not examine for it.
611
+ const heldNow = new Set();
612
+ const unexamined = new Set();
613
+ eachStream: for (const row of streams) {
614
+ const { stream } = row;
615
+ if (await discardFencedRuns(held, connectionId, stream)) {
616
+ await applyConnection(held, connectionId);
617
+ return { kind: "retry" };
674
618
  }
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);
619
+ if (connection.generation !== 1)
620
+ await excludeSeedsIfAny(held, connectionId, stream);
621
+ // The plan's base is what the log last said, not what the run's end wrote.
622
+ const published = asPublished(row);
623
+ const plan = await planStream(held, connectionId, connection, stream, published, null, row.head_version, row.head_data_hash);
624
+ if (plan.refused) {
625
+ await unwriteRefusedRun(held, {
626
+ connectionId,
627
+ stream,
628
+ runId: plan.refused.runId,
629
+ reason: plan.refused.reason,
630
+ });
631
+ await applyConnection(held, connectionId);
632
+ return { kind: "retry" };
633
+ }
634
+ const [wRow] = await held.db.query("SELECT MAX(seq) AS w FROM record_changes WHERE connection_id = ? AND stream = ?", [connectionId, stream]);
635
+ const watermark = wRow?.w ?? row.publish_watermark;
636
+ const base = {
637
+ stream,
638
+ local: row,
639
+ plan,
640
+ watermark,
641
+ ack: watermark,
642
+ included: false,
643
+ rest: false,
644
+ operations: [],
645
+ meta: null,
646
+ runIds: plan.steps.map((step) => step.runId),
647
+ replace: null,
648
+ replacing: null,
649
+ omitting: null,
650
+ omitted: [],
651
+ bytes: 0,
652
+ cursor: null,
653
+ };
654
+ if (plan.deferred) {
655
+ unexamined.add(stream);
656
+ planned.push({ ...base, ack: row.publish_watermark });
657
+ continue;
658
+ }
659
+ // The stream's local head stands for the log's last segment that touched
660
+ // it (see `applySegmentOperations`): a replacing run applies only if no
661
+ // segment touched the stream since the run began.
662
+ const replace = plan.replaceBelow ?? null;
663
+ const omitted = replace
664
+ ? await omittedBy(held, connectionId, stream, plan.finalHead?.primaryKey ?? JSON.parse(row.primary_key), replace)
665
+ : [];
666
+ const hasChanges = await hasChangedKeys(held.db, connectionId, stream, row.publish_watermark, watermark);
667
+ // The changed keys are read a page at a time, in the order they changed:
668
+ // a round takes a segment's worth and stops.
669
+ const pages = () => changedKeyPages(held.db, connectionId, stream, row.publish_watermark, watermark);
670
+ // A stream with no head yet (a first collection that publishes while it
671
+ // collects) is described by its local state.
672
+ const head = plan.finalHead ??
673
+ (hasChanges
674
+ ? {
675
+ generation: row.head_generation ?? connection.generation,
676
+ primaryKey: JSON.parse(row.primary_key),
677
+ profile: {
678
+ key: row.profile_key ?? connection.connector,
679
+ version: row.profile_version ?? row.floor_version ?? "0",
680
+ },
681
+ // A seeded stream is what this device holds, head and all: its
682
+ // completeness is its own. Other changes with no run to describe
683
+ // them belong to a first collection that is still filling.
684
+ complete: seeded.has(stream) && row.complete === 1,
685
+ }
686
+ : null);
687
+ const metaChanged = head !== null &&
688
+ (row.head_version === 0 ||
689
+ !sameHead(head, {
690
+ generation: row.head_generation ?? head.generation,
691
+ primaryKey: JSON.parse(published.primary_key),
692
+ profile: {
693
+ key: published.profile_key ?? connection.connector,
694
+ version: published.profile_version ?? "0",
695
+ },
696
+ complete: published.complete === 1,
697
+ }));
698
+ const metaPublishes = metaChanged && plan.steps.some((s) => s.decision.kind === "publish");
699
+ const hasWork = hasChanges || replace !== null || metaPublishes;
700
+ if (!hasWork || head === null) {
701
+ planned.push({ ...base, runIds: base.runIds });
685
702
  continue;
686
703
  }
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 });
704
+ // Changes go in the order they were made, until the segment reaches the
705
+ // part target, measured on the operations themselves. The first thing in
706
+ // a segment always goes, however large, so a round always progresses.
707
+ //
708
+ // A replacing stream whose rows and completion fit one segment goes whole
709
+ // (a reader sees the replace at once), or waits for the next round if
710
+ // this segment is full. One larger than a segment goes like any other
711
+ // changes, over as many rounds as it needs. Its completion (the keys it
712
+ // dropped) goes in the round that takes its last rows, or alone in the
713
+ // next. A completion larger than what is left of the segment goes in
714
+ // pieces over as many rounds as it needs: each is a completion at the
715
+ // run's cutoff for the next keys in hash order, an omission per key like
716
+ // any other. Only the round with the last piece says the stream is
717
+ // complete: an earlier round says it is not, so a reader never takes a
718
+ // replace that is half published for a complete stream. Every operation
719
+ // merges per key by stamp, so rounds from other writers in between
720
+ // interleave as they would with any other changes.
721
+ const room = (size) => first || budget + size <= target;
722
+ const sizeOf = (op) => opSize(op, target);
723
+ // What the round takes: how many keys, the last one's change, and their operations.
724
+ let selectedCount = 0;
725
+ let lastSelectedSeq = 0;
726
+ const taken = [];
727
+ let bytes = 100;
728
+ let rest = false;
729
+ let whole = false;
730
+ // A stream with a change the log cannot say stops here: nothing of it is
731
+ // published or acknowledged this round (`plan.deferred`, as for a stream
732
+ // that waits on its runs), so no change is lost without a trace.
733
+ const wasFirst = first;
734
+ const stop = (untyped) => {
735
+ first = wasFirst;
736
+ heldNow.add(stream);
737
+ // One warning per held state, not per pass: a cycle publishes more than
738
+ // once and a held stream is met again on every poll until its keys are
739
+ // known. The state is the set of changes held; a different set warns.
740
+ const state = [...untyped].sort().join(",");
741
+ const warned = warnedHolds(held.db, connectionId);
742
+ if (warned.get(stream) !== state) {
743
+ warned.set(stream, state);
744
+ 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`);
745
+ }
746
+ planned.push({
747
+ ...base,
748
+ plan: { ...plan, deferred: true },
749
+ ack: row.publish_watermark,
750
+ });
751
+ };
752
+ if (replace !== null) {
753
+ // The whole stream is looked at for deletes the log cannot say before
754
+ // any row goes, with no bodies read. Then bodies are read a batch at a
755
+ // time until they no longer fit one segment: a replace of a stream
756
+ // larger than the segment never has more than a segment in memory.
757
+ const untypedKeys = [];
758
+ for await (const page of untypedDeletePages(held.db, connectionId, stream, row.publish_watermark, watermark))
759
+ for (const d of page)
760
+ if ((await declaredKey(held, connectionId, stream, {
761
+ pk_hash: d.pk,
762
+ record_key: d.recordKey,
763
+ })) === null)
764
+ untypedKeys.push(d.pk);
765
+ if (untypedKeys.length > 0) {
766
+ stop(untypedKeys);
693
767
  continue;
694
768
  }
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;
769
+ let size = bytes + 100 + omittedSize(omitted);
770
+ const found = new Map();
771
+ let count = 0;
772
+ probe: for await (const page of pages()) {
773
+ for (const batch of await bodyBatches(held, connectionId, stream, page)) {
774
+ if (size > target)
775
+ break probe;
776
+ const read = await operationsFor(held, connectionId, stream, batch.map((g) => g.pk), row.publish_watermark, watermark);
777
+ for (const [pk, op] of read.ops) {
778
+ size += sizeOf(op);
779
+ found.set(pk, await spill(op));
780
+ }
781
+ count += batch.length;
782
+ }
711
783
  }
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;
784
+ if (size > target)
785
+ found.clear();
786
+ if (size <= target) {
787
+ if (!room(size)) {
788
+ planned.push({ ...base, ack: row.publish_watermark, rest: true });
789
+ continue;
718
790
  }
719
- selected.push(group);
720
- if (op)
791
+ selectedCount = count;
792
+ for (const op of found.values())
721
793
  taken.push(op);
722
- bytes += size;
723
- first = false;
794
+ bytes = size;
795
+ whole = true;
724
796
  }
725
797
  }
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);
798
+ if (!whole)
799
+ scan: for await (const page of pages()) {
800
+ for (const batch of await bodyBatches(held, connectionId, stream, page)) {
801
+ const { ops: found, untyped } = await operationsFor(held, connectionId, stream, batch.map((g) => g.pk), row.publish_watermark, watermark);
802
+ if (untyped.length > 0) {
803
+ stop(untyped);
804
+ continue eachStream;
805
+ }
806
+ for (const group of batch) {
807
+ const op = found.get(group.pk);
808
+ const size = op ? sizeOf(op) : 0;
809
+ if (!room(bytes + size)) {
810
+ rest = true;
811
+ break scan;
812
+ }
813
+ selectedCount += 1;
814
+ lastSelectedSeq = group.seq;
815
+ if (op)
816
+ taken.push(await spill(op));
817
+ bytes += size;
818
+ first = false;
819
+ }
820
+ }
821
+ }
822
+ if (selectedCount === 0 && hasChanges) {
823
+ planned.push({ ...base, ack: row.publish_watermark, rest: true });
824
+ continue;
741
825
  }
742
- else {
743
- rest = true;
744
- piece = omitted.slice(0, take);
745
- if (piece.length > 0)
746
- bytes += 100 + omittedSize(piece);
826
+ // Rows of the stream wait for a later round; its completion waits with them.
827
+ const rowsRest = rest;
828
+ let completes = whole;
829
+ let piece = [];
830
+ if (replace !== null && !whole && !rowsRest) {
831
+ // An empty segment takes at least one key, so a round always progresses.
832
+ const fit = omissionsThatFit(omitted, target - budget - bytes - 100);
833
+ const take = fit === 0 && first ? 1 : fit;
834
+ if (take >= omitted.length) {
835
+ completes = true;
836
+ bytes += 100 + omittedSize(omitted);
837
+ }
838
+ else {
839
+ rest = true;
840
+ piece = omitted.slice(0, take);
841
+ if (piece.length > 0)
842
+ bytes += 100 + omittedSize(piece);
843
+ }
747
844
  }
845
+ // A replace whose completion waits, with no rows or piece of its
846
+ // completion in this round, waits whole.
847
+ if (replace !== null &&
848
+ !completes &&
849
+ taken.length === 0 &&
850
+ piece.length === 0) {
851
+ planned.push({ ...base, ack: row.publish_watermark, rest: true });
852
+ continue;
853
+ }
854
+ // Changes that carry no operation are nothing to publish: the rows a
855
+ // replacing run dropped are deleted locally in the commit that publishes
856
+ // its completion, and those deletions are changes above that commit's
857
+ // watermark. Counted as work they would cost a segment that says nothing.
858
+ if (!completes && !rest && taken.length === 0 && !metaPublishes) {
859
+ planned.push({ ...base });
860
+ continue;
861
+ }
862
+ budget += bytes;
863
+ first = false;
864
+ const ack = rowsRest ? lastSelectedSeq : watermark;
865
+ planned.push({
866
+ ...base,
867
+ included: true,
868
+ rest,
869
+ ack,
870
+ operations: [
871
+ ...orderedOperations(taken),
872
+ ...(replace && (completes || piece.length > 0)
873
+ ? [
874
+ {
875
+ kind: "complete",
876
+ stream,
877
+ cutoff: { o: replace.o, r: replace.r },
878
+ omitted: completes ? omitted : piece,
879
+ },
880
+ ]
881
+ : []),
882
+ ],
883
+ meta: {
884
+ stream,
885
+ primaryKey: head.primaryKey,
886
+ profile: head.profile,
887
+ complete: replace !== null && !completes ? false : head.complete,
888
+ },
889
+ replace: completes ? replace : null,
890
+ replacing: replace !== null && !completes ? replace : null,
891
+ omitting: piece.length > 0
892
+ ? { from: piece[0].pkHash, to: piece.at(-1).pkHash }
893
+ : null,
894
+ omitted: completes ? omitted : piece,
895
+ bytes,
896
+ });
748
897
  }
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;
898
+ await carryCursors(held, connectionId, connection.connector, streams, planned);
899
+ // A stream that is no longer held warns again if it is held again.
900
+ const warned = warnedHolds(held.db, connectionId);
901
+ for (const stream of [...warned.keys()])
902
+ if (!heldNow.has(stream) && !unexamined.has(stream))
903
+ warned.delete(stream);
904
+ const included = planned.filter((p) => p.included);
905
+ const settle = (outcomeFor) => planned.map((p) => ({
906
+ stream: p.stream,
907
+ outcome: outcomeFor(p),
908
+ watermark: p.watermark,
909
+ }));
910
+ // Attachments named by any stream's records, published or not yet: bytes can
911
+ // arrive after the records that name them were published.
912
+ clock.record("plan", planStart);
913
+ const attachments = [];
914
+ for (const p of planned)
915
+ if (!p.plan.deferred)
916
+ attachments.push(...(await listStreamBlobs(held, {
917
+ connectionId,
918
+ stream: p.stream,
919
+ scope: streamScope(connection.connector, connection.ns, p.stream),
920
+ generation: connection.generation,
921
+ })));
922
+ if (included.length === 0) {
923
+ // Nothing to publish. A new connection's control row is still created, as
924
+ // a request of its own. Record that every covered run was already saved
925
+ // by what the log holds, move the watermarks, and compact.
926
+ if (createControl) {
927
+ const created = await clock.time("control", () => commitControl(held, connectionId, connection, hashes));
928
+ if (created === "retry")
929
+ return { kind: "retry" };
930
+ if (created !== "active")
931
+ return all(created);
932
+ }
933
+ await commitIdle(held, connectionId, planned, log);
934
+ return {
935
+ kind: "done",
936
+ results: settle((p) => (p.plan.deferred ? "deferred" : "noop")),
937
+ attachments,
938
+ };
765
939
  }
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);
940
+ // What the round did not select stays out of the spool: a replace read
941
+ // that did not fit one segment spilled the bodies it had read, and the
942
+ // scan selects them again.
943
+ await spool.keepOnly(new Set(included.flatMap((p) => p.operations.flatMap((op) => op.kind === "upsert-ref"
944
+ ? op.body.pieces.map((hash) => bodyPieceBlobName(hash))
945
+ : []))));
946
+ // The log is folded into a snapshot when that is cheaper than replaying it
947
+ // (or it is at the head's bound), and this segment carries the result.
948
+ const compaction = await planCompaction(held, {
949
+ connectionId,
950
+ connector: connection.connector,
951
+ ns: connection.ns,
952
+ generation: connection.generation,
953
+ keyCheck,
954
+ scope,
955
+ log,
956
+ }, spool);
957
+ const base = compaction ? log.position : log.base;
958
+ const refs = compaction ? [] : log.refs;
959
+ const snapshot = compaction ? compaction.snapshot : log.snapshot;
960
+ if (compactionRequired(refs.length, snapshot?.parts.length ?? 0)) {
961
+ held.logger.warn({ connectionId, refs: refs.length, parts: snapshot?.parts.length ?? 0 }, "stream sync: the log head is full even after compaction");
962
+ return all("deferred");
836
963
  }
837
- await commitIdle(held, connectionId, planned, log);
838
- return {
839
- kind: "done",
840
- results: settle((p) => (p.plan.deferred ? "deferred" : "noop")),
841
- attachments,
964
+ const position = log.position + 1;
965
+ const observedAt = Math.max(...included.map((p) => p.plan.newestRunObservedAt ?? 0), 0);
966
+ const segment = {
967
+ format: LOG_FORMAT,
968
+ connector: connection.connector,
969
+ ns: connection.ns,
970
+ generation: connection.generation,
971
+ keyCheck,
972
+ position,
973
+ observedAt: observedAt || held.now(),
974
+ base,
975
+ snapshot,
976
+ refs,
977
+ streams: included.map((p) => p.meta),
978
+ operations: included.flatMap((p) => p.operations),
842
979
  };
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: {
980
+ // A deletion's key is the one its hash covers, or the segment is not written.
981
+ const mismatch = await firstDeletionKeyMismatch(async (bytes) => sha256(bytes), segment.streams, segment.operations);
982
+ if (mismatch)
983
+ throw new Error(`publish: a deletion's key does not match its hash (${mismatch.stream}/${mismatch.pkHash})`);
984
+ const encodeStart = clock.now();
985
+ // A body larger than one object goes out of line (stream-sync `log.ts`).
986
+ const outOfLine = await putBodiesOutOfLine(held, scope, segment.operations, target);
987
+ const clear = encodeSegment({ ...segment, operations: outOfLine.ops });
988
+ const { dataHash, blobName } = await digestSegment(keccakOf(held.streamCrypto), clear);
989
+ // A segment that would not verify is never uploaded or posted.
990
+ const verified = await verifySegment(keccakOf(held.streamCrypto), clear, {
991
+ dataHash,
992
+ connector: connection.connector,
993
+ ns: connection.ns,
994
+ keyCheck,
995
+ position,
996
+ });
997
+ if (verified.kind !== "ok")
998
+ throw new Error(`publish: the log segment failed verification: ${verified.kind}`);
999
+ const cipher = await held.keys.encrypt(scope, clear);
1000
+ clock.record("encode", encodeStart);
1001
+ for (const piece of outOfLine.pieces)
1002
+ await spool.add(piece.name, piece.cipher);
1003
+ // Everything that can fail is done before the spool changes hands: a
1004
+ // candidate that is never returned would leave its rows with no owner.
1005
+ const candidate = {
902
1006
  lifetime: connectionLifetime(held.db, connectionId),
903
1007
  connector: connection.connector,
904
1008
  ns: connection.ns,
@@ -907,7 +1011,8 @@ async function snapshotRound(held, connectionId, clock) {
907
1011
  base,
908
1012
  refs,
909
1013
  snapshot,
910
- objects: [...(compaction?.objects ?? []), ...outOfLine.pieces],
1014
+ objects: spool.objects(),
1015
+ spool,
911
1016
  position,
912
1017
  generation: connection.generation,
913
1018
  dataHash,
@@ -921,8 +1026,14 @@ async function snapshotRound(held, connectionId, clock) {
921
1026
  controlDataHash,
922
1027
  createControl,
923
1028
  prevHash: log.refs.at(-1)?.dataHash ?? null,
924
- },
925
- };
1029
+ };
1030
+ handedOver = true;
1031
+ return { kind: "candidate", candidate };
1032
+ }
1033
+ finally {
1034
+ if (!handedOver)
1035
+ await spool.discard();
1036
+ }
926
1037
  }
927
1038
  /**
928
1039
  * A stream's unpublished cursor rides this round only when no row it covers
@@ -1134,13 +1245,29 @@ async function commitControl(held, connectionId, connection, hashes) {
1134
1245
  await held.db.batch([markControlActive(connectionId, connection)]);
1135
1246
  return state;
1136
1247
  }
1248
+ /** The stored size of a held record's body, in bytes: the size column, or its length where the column is empty. */
1249
+ const BODY_SIZE = `COALESCE(body_bytes, ${BODY_BYTES})`;
1250
+ /**
1251
+ * The text of a held record's body: the blob that came with the row, or, for a
1252
+ * body too large for a reply beside other rows, the body read in chunks (a body
1253
+ * larger than the frame still crosses it).
1254
+ */
1255
+ async function bodyText(deps, connectionId, stream, row) {
1256
+ if (row.body)
1257
+ return textOf(row.body);
1258
+ return textOf(await readChunked(deps.db, Number(row.n), (offset, length) => ({
1259
+ sql: `SELECT substr(CAST(body AS BLOB), ?, ?) AS c FROM records
1260
+ WHERE connection_id = ? AND stream = ? AND pk_hash = ?`,
1261
+ params: [offset, length, connectionId, stream, row.pk_hash],
1262
+ })));
1263
+ }
1137
1264
  /**
1138
1265
  * The keys a replacing run dropped: held rows last observed before it. Each
1139
1266
  * names its typed primary-key values from the row it drops, which is held until
1140
1267
  * the run deletes it: the row's data holds them with their types, and a
1141
1268
  * deletion's key is exactly what its hash was computed from.
1142
1269
  *
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
1270
+ * 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
1271
  * time): the shared SQL cannot return just the key fields of a body (a phone's
1145
1272
  * SQLite 3.22 has no JSON1), and a pass that drops many large records must not
1146
1273
  * hold them all at once. Only the small keys are kept.
@@ -1155,50 +1282,73 @@ async function omittedBy(deps, connectionId, stream, primaryKey, replace) {
1155
1282
  const omitted = [];
1156
1283
  let after;
1157
1284
  for (;;) {
1158
- const meta = await deps.db.query(`SELECT pk_hash, COALESCE(body_bytes, ${BODY_BYTES}) AS n FROM records
1285
+ const meta = await deps.db.query(`SELECT pk_hash, ${BODY_SIZE} AS n FROM records
1159
1286
  WHERE ${scope}${after === undefined ? "" : " AND pk_hash > ?"}
1160
- ORDER BY pk_hash LIMIT ${META_ROWS}`, after === undefined ? scopeParams : [...scopeParams, after]);
1287
+ ORDER BY pk_hash LIMIT ${SIZE_ROWS}`, after === undefined ? scopeParams : [...scopeParams, after]);
1161
1288
  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
1289
+ const take = rowsWithin(meta.slice(at).map((row) => replyBytes(Number(row.n))));
1290
+ const page = await deps.db.query(`SELECT pk_hash, ${BODY_SIZE} AS n, ${blobIfFits("body", BODY_SIZE)} AS body FROM records
1170
1291
  WHERE ${scope} AND pk_hash >= ? AND pk_hash <= ? ORDER BY pk_hash`, [...scopeParams, meta[at].pk_hash, meta[at + take - 1].pk_hash]);
1171
1292
  for (const row of page)
1172
1293
  omitted.push({
1173
1294
  pkHash: row.pk_hash,
1174
- key: primaryKeyValues(JSON.parse(row.body), primaryKey),
1295
+ key: primaryKeyValues(JSON.parse(await bodyText(deps, connectionId, stream, row)), primaryKey),
1175
1296
  });
1176
1297
  at += take;
1177
1298
  }
1178
- if (meta.length < META_ROWS)
1299
+ if (meta.length < SIZE_ROWS)
1179
1300
  return omitted;
1180
1301
  after = meta[meta.length - 1].pk_hash;
1181
1302
  }
1182
1303
  }
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);
1304
+ /**
1305
+ * A digest of the hashes `omittedBy` names, for a comparison that needs no
1306
+ * key: read a page at a time, so what a stream omits is not held to be
1307
+ * compared.
1308
+ */
1309
+ async function omittedDigest(deps, connectionId, stream, replace, keys) {
1310
+ const hash = sha256.create();
1311
+ const encoder = new TextEncoder();
1312
+ let after;
1313
+ let count = 0;
1314
+ for (;;) {
1315
+ const rows = await deps.db.query(`SELECT pk_hash FROM records WHERE connection_id = ? AND stream = ?
1316
+ AND ${SEEN_BEFORE}${keys ? " AND pk_hash >= ? AND pk_hash <= ?" : ""}${after === undefined ? "" : " AND pk_hash > ?"}
1317
+ ORDER BY pk_hash LIMIT ${DIGEST_PAGE}`, [
1318
+ connectionId,
1319
+ stream,
1320
+ ...seenBeforeParams(replace.o, replace.r),
1321
+ ...(keys ? [keys.from, keys.to] : []),
1322
+ ...(after === undefined ? [] : [after]),
1323
+ ]);
1324
+ for (const row of rows)
1325
+ hash.update(encoder.encode(`${row.pk_hash}\n`));
1326
+ count += rows.length;
1327
+ if (rows.length < DIGEST_PAGE)
1328
+ return `${count}:${bytesToHex(hash.digest())}`;
1329
+ after = rows[rows.length - 1].pk_hash;
1330
+ }
1194
1331
  }
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 }));
1332
+ const DIGEST_PAGE = 4096;
1333
+ /**
1334
+ * The groups of a page cut into batches whose bodies hold about `PAGE_BYTES`
1335
+ * (a group alone if its body is larger), by the sizes the rows keep: a batch is
1336
+ * read whole, so the keys of a query are not the bound on what it holds.
1337
+ * Groups with no row (a delete) weigh nothing.
1338
+ */
1339
+ async function bodyBatches(deps, connectionId, stream, groups) {
1340
+ const sizes = await deps.db.query(`SELECT pk_hash, ${BODY_SIZE} AS n FROM records
1341
+ WHERE connection_id = ? AND stream = ?
1342
+ AND pk_hash IN (${groups.map(() => "?").join(",")})`, [connectionId, stream, ...groups.map((g) => g.pk)]);
1343
+ const bytesOf = new Map(sizes.map((r) => [r.pk_hash, Number(r.n)]));
1344
+ const weights = groups.map((g) => replyBytes(bytesOf.get(g.pk) ?? 0));
1345
+ const batches = [];
1346
+ for (let at = 0; at < groups.length;) {
1347
+ const take = rowsWithin(weights.slice(at));
1348
+ batches.push(groups.slice(at, at + take));
1349
+ at += take;
1350
+ }
1351
+ return batches;
1202
1352
  }
1203
1353
  /**
1204
1354
  * Local publication debt, independent of publishRounds' aggregate receipt.
@@ -1213,7 +1363,7 @@ export async function hasPendingLogPublication(deps, connectionId) {
1213
1363
  for (const row of streams) {
1214
1364
  if ((await retainedRuns(deps, connectionId, row.stream)).length > 0)
1215
1365
  return true;
1216
- if ((await changedKeys(deps, connectionId, row.stream, row.publish_watermark, last?.seq ?? row.publish_watermark)).length > 0)
1366
+ if (await hasChangedKeys(deps.db, connectionId, row.stream, row.publish_watermark, last?.seq ?? row.publish_watermark))
1217
1367
  return true;
1218
1368
  }
1219
1369
  return false;
@@ -1234,7 +1384,8 @@ async function operationsFor(deps, connectionId, stream, keys, from, to) {
1234
1384
  const untyped = [];
1235
1385
  for (const group of chunked(keys, KEYS_PER_QUERY)) {
1236
1386
  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
1387
+ const rows = await deps.db.query(`SELECT pk_hash, stamp_o, stamp_r, stamp_n, first_o, ${BODY_SIZE} AS n,
1388
+ ${blobIfFits("body", BODY_SIZE)} AS body FROM records
1238
1389
  WHERE connection_id = ? AND stream = ? AND pk_hash IN (${marks})`, [connectionId, stream, ...group]);
1239
1390
  const held = new Set(rows.map((row) => row.pk_hash));
1240
1391
  for (const row of rows)
@@ -1246,7 +1397,7 @@ async function operationsFor(deps, connectionId, stream, keys, from, to) {
1246
1397
  // Absent for the run's first batch and for rows from before the column.
1247
1398
  ...(row.stamp_n > 0 ? { ordinal: row.stamp_n } : {}),
1248
1399
  firstSeen: row.first_o,
1249
- value: JSON.parse(row.body),
1400
+ value: JSON.parse(await bodyText(deps, connectionId, stream, row)),
1250
1401
  });
1251
1402
  const gone = group.filter((pk) => !held.has(pk));
1252
1403
  if (gone.length === 0)
@@ -1311,8 +1462,9 @@ async function declaredKey(deps, connectionId, stream, row) {
1311
1462
  }
1312
1463
  /** Upserts, then deletes, each by key: one order for every writer. */
1313
1464
  function orderedOperations(ops) {
1465
+ const isUpsert = (op) => op.kind === "upsert" || op.kind === "upsert-ref";
1314
1466
  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) ||
1467
+ return [...ops].sort((a, b) => (isUpsert(a) ? 0 : 1) - (isUpsert(b) ? 0 : 1) ||
1316
1468
  pkOf(a).localeCompare(pkOf(b)));
1317
1469
  }
1318
1470
  /**
@@ -1339,10 +1491,10 @@ async function basisOf(deps, connectionId, planned, log) {
1339
1491
  const covered = await deps.db.query(`SELECT COUNT(*) AS n, MAX(seq) AS newest FROM record_changes
1340
1492
  WHERE connection_id = ? AND stream = ? AND seq > ? AND seq <= ?`, [connectionId, p.stream, p.local.publish_watermark, p.ack]);
1341
1493
  const omitted = p.replace
1342
- ? await omittedHashes(deps, connectionId, p.stream, p.replace)
1494
+ ? await omittedDigest(deps, connectionId, p.stream, p.replace)
1343
1495
  : p.replacing && p.omitting
1344
- ? await omittedHashes(deps, connectionId, p.stream, p.replacing, p.omitting)
1345
- : [];
1496
+ ? await omittedDigest(deps, connectionId, p.stream, p.replacing, p.omitting)
1497
+ : "";
1346
1498
  streams.push([p.stream, state, runs, covered, omitted]);
1347
1499
  }
1348
1500
  return JSON.stringify([connection, log, intents, streams]);
@@ -1640,7 +1792,7 @@ async function candidateAcknowledgements(held, connectionId, candidate, acknowle
1640
1792
  // the same rows through `operationStatements`.
1641
1793
  for (const p of touched)
1642
1794
  if (p.meta)
1643
- appendAll(statements, tombstoneStatements(connectionId, await prepareOperations([p.meta], p.operations.filter((op) => op.kind !== "upsert"))));
1795
+ appendAll(statements, tombstoneStatements(connectionId, await prepareOperations([p.meta], p.operations.filter((op) => op.kind === "delete" || op.kind === "complete"))));
1644
1796
  // A replace still under way read the stream at its basis; the segment this
1645
1797
  // round committed is this device's own, so the basis moves to it (after the
1646
1798
  // head columns above have).