node-app-replica 7.7.29

Change-only replication for Node app backends: a per-collection ledger (epoch, version, tombstones) that answers a device's pull with nothing new, the changes, or a full copy
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
//! The ledger's rules (Phase 3 spec, sections 4.2, 4.6, 4.7 and 5.1), written
//! against [`LedgerTx`] and nothing else.

use std::collections::{BTreeMap, BTreeSet};

use crate::digest::digest_and_value_len;
use crate::store::{CollectionRecord, LedgerEntry, LedgerTx};
use crate::wire::{
    encoded_delete_bytes, encoded_row_bytes, is_epoch, validate_key, value_within_depth, PullReply,
    PullRequest, Row, MAX_PART_BYTES, MAX_REPLY_ROW_BYTES, MAX_SAFE_INTEGER, MAX_VALUE_BYTES,
    VALUE_TOO_DEEP,
};
use crate::{Environment, ReplicaError};

/// How long, and how many, tombstones are kept (section 4.7).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Horizon {
    /// A tombstone older than this (unix ms since its delete) is pruned.
    pub max_age_ms: u64,
    /// At most this many tombstones are kept per collection; the oldest go first.
    pub max_count: u64,
}

/// 30 days.
pub const TOMBSTONE_MAX_AGE_MS: u64 = 30 * 24 * 60 * 60 * 1000;
/// Per collection.
pub const TOMBSTONE_MAX_COUNT: u64 = 5_000;
/// A rotation the app asks for (`reset()`, or the pruning guard) within this
/// long of the last one is owed, not done at once (section 4.6): a burst of
/// requests becomes one rotation, so the devices take one full copy, not one per
/// request. An owed rotation is never dropped. A rotation for evidence that the
/// database went back in time is never held back.
pub const ROTATION_MIN_INTERVAL_MS: u64 = 60_000;

impl Horizon {
    /// 30 days and 5,000 tombstones per collection.
    pub const DEFAULT: Horizon = Horizon {
        max_age_ms: TOMBSTONE_MAX_AGE_MS,
        max_count: TOMBSTONE_MAX_COUNT,
    };
}

/// What the ledger logic needs to know about one collection.
pub(crate) struct Spec<'a> {
    pub name: &'a str,
    pub schemas: &'a [u32],
    pub env: &'a dyn Environment,
    pub horizon: Horizon,
}

/// The head a pull or an announce reports: `(epoch, version)`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Head {
    /// The collection's current epoch.
    pub epoch: String,
    /// The version of its latest change; 0 means nothing yet.
    pub version: u64,
}

impl From<&CollectionRecord> for Head {
    fn from(record: &CollectionRecord) -> Self {
        Head {
            epoch: record.epoch.clone(),
            version: record.version,
        }
    }
}

/// Checks a row against the contract's limits and returns its digest.
pub(crate) fn check_row(row: &Row) -> Result<String, ReplicaError> {
    let invalid = |reason: String| ReplicaError::InvalidRow {
        key: row.key.chars().take(64).collect(),
        reason,
    };
    validate_key(&row.key).map_err(invalid)?;
    if !value_within_depth(&row.value) {
        return Err(invalid(VALUE_TOO_DEEP.to_string()));
    }
    let (digest, value_bytes) = digest_and_value_len(row);
    if value_bytes > MAX_VALUE_BYTES {
        return Err(invalid(format!(
            "value is {value_bytes} bytes encoded; at most {MAX_VALUE_BYTES} are allowed"
        )));
    }
    if row.ord.unsigned_abs() > MAX_SAFE_INTEGER {
        return Err(invalid("ord must be within ±(2^53 - 1)".to_string()));
    }
    if row.part.len() > MAX_PART_BYTES {
        return Err(invalid(format!(
            "part is {} bytes; at most {MAX_PART_BYTES} are allowed",
            row.part.len()
        )));
    }
    Ok(digest)
}

fn new_epoch(spec: &Spec<'_>, previous: Option<&str>) -> Result<String, ReplicaError> {
    for _ in 0..4 {
        let epoch = spec.env.new_epoch();
        if !is_epoch(&epoch) {
            return Err(ReplicaError::Store(
                "the environment produced an epoch outside [a-z0-9]{1,16}".to_string(),
            ));
        }
        if previous != Some(epoch.as_str()) {
            return Ok(epoch);
        }
    }
    Err(ReplicaError::Store(
        "the environment keeps producing the current epoch".to_string(),
    ))
}

/// The next version, for a change about to be recorded. An owed rotation happens
/// first, whatever the rate limit says: the versions above this ledger's head
/// may already be on devices with other data (the database went back in time),
/// and a version must never name two different lists.
fn assign_version(
    tx: &mut dyn LedgerTx,
    spec: &Spec<'_>,
    record: &mut CollectionRecord,
) -> Result<u64, ReplicaError> {
    if record.rotate_owed {
        rotate_now(tx, spec, record)?;
    }
    if record.version >= MAX_SAFE_INTEGER {
        return Err(ReplicaError::Store(format!(
            "version of {} would pass 2^53 - 1",
            record.epoch
        )));
    }
    record.version += 1;
    Ok(record.version)
}

/// The collection's record, created (new epoch, version 0, dirty) when the ledger
/// has none: a new ledger has not seen the app's rows yet.
pub(crate) fn open(
    tx: &mut dyn LedgerTx,
    spec: &Spec<'_>,
) -> Result<CollectionRecord, ReplicaError> {
    if let Some(record) = tx.record(spec.name)? {
        return Ok(record);
    }
    let record = CollectionRecord {
        epoch: new_epoch(spec, None)?,
        version: 0,
        floor: 0,
        dirty: true,
        rotated_at: spec.env.now_ms(),
        reconciled_at: 0,
        rotate_owed: false,
    };
    tx.put_record(spec.name, &record)?;
    Ok(record)
}

/// Whether the rate limit lets a rotation happen now. A clock that stepped back
/// never holds a rotation off.
fn rotation_allowed(spec: &Spec<'_>, record: &CollectionRecord) -> bool {
    let since = spec.env.now_ms().checked_sub(record.rotated_at);
    record.rotated_at == 0 || since.map_or(true, |since| since >= ROTATION_MIN_INTERVAL_MS)
}

/// A rotation the app asks for (`reset()`, the pruning guard): done now when the
/// rate limit allows, else owed (it then happens before the next version is
/// assigned, or at the first ledger operation after the minute). Returns
/// whether it rotated now. Holding it back is safe because the ledger still
/// knows every version it handed out; only the cost of the copies is at stake.
pub(crate) fn request_rotation(
    tx: &mut dyn LedgerTx,
    spec: &Spec<'_>,
    record: &mut CollectionRecord,
) -> Result<bool, ReplicaError> {
    if rotation_allowed(spec, record) {
        rotate_now(tx, spec, record)?;
        return Ok(true);
    }
    record.rotate_owed = true;
    Ok(false)
}

/// Run at the start of every ledger write, before its own work. `went_back`:
/// this process has handed out a higher version of the ledger's epoch than the
/// ledger now holds, so the database went back in time; that rotates at once
/// (see [`rotate_now`]). Otherwise an owed rotation whose minute has passed
/// happens now. Returns whether it rotated.
pub(crate) fn begin(
    tx: &mut dyn LedgerTx,
    spec: &Spec<'_>,
    record: &mut CollectionRecord,
    went_back: bool,
) -> Result<bool, ReplicaError> {
    if went_back || (record.rotate_owed && rotation_allowed(spec, record)) {
        rotate_now(tx, spec, record)?;
        return Ok(true);
    }
    Ok(false)
}

/// Whether a read of `record` can stand for the write `begin` would do: no
/// owed rotation is due.
pub(crate) fn nothing_due(spec: &Spec<'_>, record: &CollectionRecord) -> bool {
    !(record.rotate_owed && rotation_allowed(spec, record))
}

/// Starts a new epoch: every live row is renumbered 1…n in key order, every
/// tombstone is dropped (a device holding the old epoch takes a full copy), the
/// floor returns to 0, and an owed rotation is settled.
///
/// Evidence that the database went back in time (a device ahead of the head,
/// the node's `rotate`, this process having handed out more) rotates through
/// here at once, whatever the rate limit says. Held back, the ledger would go on
/// answering in an epoch whose versions above its head are already on devices
/// with other data: a device whose version names exactly the head would be told
/// "nothing new" while holding rows the ledger never had (a device that finished
/// a paged copy holds rows newer than the copy's version until its follow-up
/// pull), and the next write would hand a version out twice.
pub(crate) fn rotate_now(
    tx: &mut dyn LedgerTx,
    spec: &Spec<'_>,
    record: &mut CollectionRecord,
) -> Result<(), ReplicaError> {
    let now = spec.env.now_ms();
    let mut version = 0;
    for mut entry in tx.entries(spec.name)? {
        if entry.deleted {
            tx.delete_entry(spec.name, &entry.key)?;
            continue;
        }
        version += 1;
        entry.version = version;
        entry.changed_at = now;
        tx.put_entry(spec.name, &entry)?;
    }
    record.epoch = new_epoch(spec, Some(&record.epoch))?;
    record.version = version;
    record.floor = 0;
    record.rotated_at = now;
    record.rotate_owed = false;
    Ok(())
}

/// Records one row; returns whether the ledger changed.
fn record_row(
    tx: &mut dyn LedgerTx,
    spec: &Spec<'_>,
    record: &mut CollectionRecord,
    row: &Row,
    digest: String,
    now: u64,
) -> Result<bool, ReplicaError> {
    if let Some(entry) = tx.entry(spec.name, &row.key)? {
        if !entry.deleted && entry.digest == digest {
            return Ok(false);
        }
    }
    let version = assign_version(tx, spec, record)?;
    tx.put_entry(
        spec.name,
        &LedgerEntry {
            key: row.key.clone(),
            digest,
            version,
            deleted: false,
            changed_at: now,
        },
    )?;
    Ok(true)
}

/// Records one delete; returns whether the ledger changed.
fn record_delete(
    tx: &mut dyn LedgerTx,
    spec: &Spec<'_>,
    record: &mut CollectionRecord,
    key: &str,
    now: u64,
) -> Result<bool, ReplicaError> {
    let Some(entry) = tx.entry(spec.name, key)? else {
        return Ok(false);
    };
    if entry.deleted {
        return Ok(false);
    }
    let version = assign_version(tx, spec, record)?;
    tx.put_entry(
        spec.name,
        &LedgerEntry {
            key: key.to_string(),
            digest: entry.digest,
            version,
            deleted: true,
            changed_at: now,
        },
    )?;
    Ok(true)
}

/// Prunes tombstones past the horizon and raises the floor to the highest
/// version pruned. When pruning could not keep the count (a store that did not
/// prune), the epoch rotates, which drops every tombstone.
fn prune(
    tx: &mut dyn LedgerTx,
    spec: &Spec<'_>,
    record: &mut CollectionRecord,
    now: u64,
) -> Result<(), ReplicaError> {
    let pruned = tx.prune_tombstones(
        spec.name,
        now.saturating_sub(spec.horizon.max_age_ms),
        spec.horizon.max_count,
    )?;
    if let Some(highest) = pruned.highest {
        record.floor = record.floor.max(highest);
    }
    if pruned.over_keep {
        request_rotation(tx, spec, record)?;
    }
    Ok(())
}

/// Whole-list mode: `rows` is every current row. A new key or a changed digest
/// gets the next version; a ledger key missing from `rows` becomes a tombstone
/// at the next version. All rows are checked before anything is written.
pub(crate) fn reconcile(
    tx: &mut dyn LedgerTx,
    spec: &Spec<'_>,
    record: &mut CollectionRecord,
    rows: &[Row],
) -> Result<(), ReplicaError> {
    let now = spec.env.now_ms();
    let mut current: Vec<(&Row, String)> = rows
        .iter()
        .map(|row| check_row(row).map(|digest| (row, digest)))
        .collect::<Result<_, _>>()?;
    current.sort_unstable_by(|a, b| a.0.key.cmp(&b.0.key));
    if let Some(pair) = current
        .windows(2)
        .find(|pair| pair[0].0.key == pair[1].0.key)
    {
        return Err(ReplicaError::InvalidRow {
            key: pair[0].0.key.chars().take(64).collect(),
            reason: "the key appears twice in the list".to_string(),
        });
    }
    // Both lists are in key order: one merge finds what changed.
    let ledger = tx.entries(spec.name)?;
    let mut upserts: Vec<(&Row, &String)> = Vec::new();
    let mut deletes: Vec<&LedgerEntry> = Vec::new();
    let mut held = ledger.iter().peekable();
    for (row, digest) in &current {
        while let Some(entry) = held.next_if(|entry| entry.key < row.key) {
            if !entry.deleted {
                deletes.push(entry);
            }
        }
        let unchanged = held
            .next_if(|entry| entry.key == row.key)
            .is_some_and(|entry| !entry.deleted && &entry.digest == digest);
        if !unchanged {
            upserts.push((row, digest));
        }
    }
    deletes.extend(held.filter(|entry| !entry.deleted));
    for (row, digest) in upserts {
        let version = assign_version(tx, spec, record)?;
        tx.put_entry(
            spec.name,
            &LedgerEntry {
                key: row.key.clone(),
                digest: digest.clone(),
                version,
                deleted: false,
                changed_at: now,
            },
        )?;
    }
    for entry in deletes {
        let version = assign_version(tx, spec, record)?;
        tx.put_entry(
            spec.name,
            &LedgerEntry {
                key: entry.key.clone(),
                digest: entry.digest.clone(),
                version,
                deleted: true,
                changed_at: now,
            },
        )?;
    }
    prune(tx, spec, record, now)?;
    record.dirty = false;
    record.reconciled_at = now;
    Ok(())
}

pub(crate) fn touch(
    tx: &mut dyn LedgerTx,
    spec: &Spec<'_>,
    record: &mut CollectionRecord,
    row: &Row,
) -> Result<(), ReplicaError> {
    let digest = check_row(row)?;
    let now = spec.env.now_ms();
    record_row(tx, spec, record, row, digest, now)?;
    prune(tx, spec, record, now)
}

pub(crate) fn remove(
    tx: &mut dyn LedgerTx,
    spec: &Spec<'_>,
    record: &mut CollectionRecord,
    key: &str,
) -> Result<(), ReplicaError> {
    validate_key(key).map_err(|reason| ReplicaError::InvalidRow {
        key: key.chars().take(64).collect(),
        reason,
    })?;
    let now = spec.env.now_ms();
    record_delete(tx, spec, record, key, now)?;
    prune(tx, spec, record, now)
}

/// Loads the app's current rows: all of them for `None`, else those of the
/// given keys (a key with no row is simply absent from the result).
pub(crate) type Load<'l> = dyn FnMut(Option<&[String]>) -> Result<Vec<Row>, ReplicaError> + 'l;

/// Which answer a request gets, before any row is loaded.
enum Plan {
    NothingNew,
    Changes(Vec<LedgerEntry>),
    FullCopy {
        version: u64,
        entries: Vec<LedgerEntry>,
    },
}

fn full_copy(
    tx: &mut dyn LedgerTx,
    spec: &Spec<'_>,
    after: Option<&str>,
    version: u64,
    fetch: usize,
) -> Result<Plan, ReplicaError> {
    Ok(Plan::FullCopy {
        version,
        entries: tx.live_after(spec.name, after, fetch)?,
    })
}

fn plan(
    tx: &mut dyn LedgerTx,
    spec: &Spec<'_>,
    record: &mut CollectionRecord,
    request: &PullRequest,
) -> Result<Plan, ReplicaError> {
    // One more than the limit tells whether more remain.
    let fetch = request.effective_limit() + 1;
    if request.epoch != record.epoch {
        // Rule 2: another lineage, or nothing held.
        return full_copy(tx, spec, None, record.version, fetch);
    }
    if request.version > record.version {
        // Rule 3: the caller has seen a future this ledger does not contain (the
        // database was restored or replaced). That is evidence: rotate at once.
        rotate_now(tx, spec, record)?;
        return full_copy(tx, spec, None, record.version, fetch);
    }
    if let Some(resume) = &request.resume {
        // A later page of a full copy is "as of page one's version V": it carries
        // the rows after the resume key as they are now and keeps V, and once the
        // last page is in the caller asks for the changes since V, which brings
        // every row changed after V (whatever page it was on) and every delete
        // after V. So a copy always ends after as many pages as the list has,
        // however busy the list is. Only when deletes after V were forgotten
        // (V below the floor) would those changes come back as another full copy,
        // so the copy starts over at the head now (its version is above V, so the
        // caller sees a new page one).
        if request.version >= record.floor {
            return full_copy(tx, spec, Some(resume), request.version, fetch);
        }
        return full_copy(tx, spec, None, record.version, fetch);
    }
    if request.version < record.floor {
        // Rule 2: deletes the caller has not seen were forgotten.
        return full_copy(tx, spec, None, record.version, fetch);
    }
    if request.version == record.version {
        return Ok(Plan::NothingNew);
    }
    Ok(Plan::Changes(tx.changes_after(
        spec.name,
        request.version,
        fetch,
    )?))
}

/// Re-records the rows whose loaded value no longer matches the ledger (a write
/// the app made without telling the helper), and the live keys the app no
/// longer has. Returns whether the ledger changed.
fn heal(
    tx: &mut dyn LedgerTx,
    spec: &Spec<'_>,
    record: &mut CollectionRecord,
    wanted: &[LedgerEntry],
    loaded: &BTreeMap<String, Row>,
) -> Result<bool, ReplicaError> {
    let now = spec.env.now_ms();
    let mut changed = false;
    for entry in wanted.iter().filter(|entry| !entry.deleted) {
        match loaded.get(&entry.key) {
            None => changed |= record_delete(tx, spec, record, &entry.key, now)?,
            Some(row) => {
                let digest = check_row(row)?;
                if digest != entry.digest {
                    changed |= record_row(tx, spec, record, row, digest, now)?;
                }
            }
        }
    }
    Ok(changed)
}

/// Refuses a request for a schema this collection does not serve, or outside
/// the contract.
pub(crate) fn check_request(spec: &Spec<'_>, request: &PullRequest) -> Result<(), ReplicaError> {
    if !spec.schemas.contains(&request.schema) {
        return Err(ReplicaError::SchemaUnsupported {
            capability: spec.name.to_string(),
            schema: request.schema,
        });
    }
    request.validate().map_err(ReplicaError::InvalidRequest)
}

/// Answers one pull (section 4.2). `record` is the collection's current record;
/// the caller writes it back.
pub(crate) fn answer(
    tx: &mut dyn LedgerTx,
    spec: &Spec<'_>,
    record: &mut CollectionRecord,
    request: &PullRequest,
    load: &mut Load<'_>,
) -> Result<PullReply, ReplicaError> {
    check_request(spec, request)?;
    if record.dirty {
        // Rule 1: a pull reflects every write the app has acknowledged.
        let rows = load(None)?;
        reconcile(tx, spec, record, &rows)?;
    }
    let limit = request.effective_limit();
    let mut whole_copy = false;
    let mut heals = 0;
    loop {
        let plan = if whole_copy {
            full_copy(tx, spec, None, record.version, limit + 1)?
        } else {
            plan(tx, spec, record, request)?
        };
        let wanted = match &plan {
            Plan::NothingNew => {
                return Ok(PullReply::NothingNew {
                    epoch: record.epoch.clone(),
                    version: record.version,
                })
            }
            Plan::Changes(entries) | Plan::FullCopy { entries, .. } => entries,
        };
        let window = &wanted[..wanted.len().min(limit)];
        let keys: Vec<String> = window
            .iter()
            .filter(|entry| !entry.deleted)
            .map(|entry| entry.key.clone())
            .collect();
        let loaded: BTreeMap<String, Row> = if keys.is_empty() {
            BTreeMap::new()
        } else {
            let wanted_keys: BTreeSet<&str> = keys.iter().map(String::as_str).collect();
            load(Some(&keys))?
                .into_iter()
                .filter(|row| wanted_keys.contains(row.key.as_str()))
                .map(|row| (row.key.clone(), row))
                .collect()
        };
        // The rows are read after the ledger is; a mismatch found while reading
        // is recorded and the answer computed again, at most twice.
        if heals < 2 && heal(tx, spec, record, window, &loaded)? {
            heals += 1;
            continue;
        }
        match build(record, request, plan, limit, &loaded) {
            Some(reply) => return Ok(reply),
            None if !whole_copy => whole_copy = true,
            None => {
                return Err(ReplicaError::Store(
                    "a full copy could not be built".to_string(),
                ))
            }
        }
    }
}

/// The reply for a plan and the rows read for it; `None` when a change list must
/// be cut and no exact version to cut at exists (the caller then takes a full
/// copy).
fn build(
    record: &CollectionRecord,
    request: &PullRequest,
    plan: Plan,
    limit: usize,
    loaded: &BTreeMap<String, Row>,
) -> Option<PullReply> {
    match plan {
        Plan::NothingNew => Some(PullReply::NothingNew {
            epoch: record.epoch.clone(),
            version: record.version,
        }),
        Plan::Changes(entries) => {
            let mut taken: Vec<&LedgerEntry> = Vec::new();
            let mut bytes = 0;
            let mut more = false;
            for entry in &entries {
                if taken.len() == limit {
                    more = true;
                    break;
                }
                let size = match (entry.deleted, loaded.get(&entry.key)) {
                    (true, _) => encoded_delete_bytes(&entry.key),
                    (false, Some(row)) => encoded_row_bytes(row),
                    // A row that vanished while it was read: its delete is in the
                    // ledger at a later version.
                    (false, None) => 0,
                };
                if !taken.is_empty() && bytes + size > MAX_REPLY_ROW_BYTES {
                    more = true;
                    break;
                }
                bytes += size;
                taken.push(entry);
            }
            let version = if more {
                // A cut list is labelled with the version of its last change, and
                // the caller then believes it holds the list as it was at that
                // version. That is true only up to the first superseded change: a
                // version missing from the run (v+1, v+2, …) belongs to a row that
                // changed again later, whose value at the cut the ledger no longer
                // knows. So the cut is made before the first gap; when the very
                // first version is missing there is nothing exact to send.
                let exact = taken
                    .iter()
                    .zip(request.version + 1..)
                    .take_while(|(entry, expected)| entry.version == *expected)
                    .count();
                if exact == 0 {
                    return None;
                }
                taken.truncate(exact);
                request.version + exact as u64
            } else {
                // Untruncated, every change above the caller's version is in: the
                // caller is at the head.
                record.version
            };
            let mut upserts = Vec::new();
            let mut deletes = Vec::new();
            for entry in taken {
                match (entry.deleted, loaded.get(&entry.key)) {
                    (true, _) => deletes.push(entry.key.clone()),
                    (false, Some(row)) => upserts.push(row.clone()),
                    (false, None) => {}
                }
            }
            Some(PullReply::Changes {
                epoch: record.epoch.clone(),
                version,
                upserts,
                deletes,
                more,
            })
        }
        Plan::FullCopy { version, entries } => {
            let mut rows = Vec::new();
            let mut bytes = 0;
            let mut last_key: Option<&str> = None;
            let mut more = false;
            for (index, entry) in entries.iter().enumerate() {
                if index == limit {
                    more = true;
                    break;
                }
                let Some(row) = loaded.get(&entry.key) else {
                    last_key = Some(&entry.key);
                    continue;
                };
                let size = encoded_row_bytes(row);
                if index > 0 && bytes + size > MAX_REPLY_ROW_BYTES {
                    more = true;
                    break;
                }
                rows.push(row.clone());
                bytes += size;
                last_key = Some(&entry.key);
            }
            Some(PullReply::FullCopy {
                epoch: record.epoch.clone(),
                version,
                rows,
                next: if more {
                    last_key.map(str::to_string)
                } else {
                    None
                },
                // A later page carries rows as they are now, which can be newer
                // than the copy's version; the node marks the head it was read at.
                head: (record.version > version).then_some(record.version),
            })
        }
    }
}