Skip to main content

node_app_replica/
ledger.rs

1//! The ledger's rules (Phase 3 spec, sections 4.2, 4.6, 4.7 and 5.1), written
2//! against [`LedgerTx`] and nothing else.
3
4use std::collections::{BTreeMap, BTreeSet};
5
6use crate::digest::digest_and_value_len;
7use crate::store::{CollectionRecord, LedgerEntry, LedgerTx};
8use crate::wire::{
9    encoded_delete_bytes, encoded_row_bytes, is_epoch, validate_key, value_within_depth, PullReply,
10    PullRequest, Row, MAX_PART_BYTES, MAX_REPLY_ROW_BYTES, MAX_SAFE_INTEGER, MAX_VALUE_BYTES,
11    VALUE_TOO_DEEP,
12};
13use crate::{Environment, ReplicaError};
14
15/// How long, and how many, tombstones are kept (section 4.7).
16#[derive(Debug, Clone, Copy, PartialEq, Eq)]
17pub struct Horizon {
18    /// A tombstone older than this (unix ms since its delete) is pruned.
19    pub max_age_ms: u64,
20    /// At most this many tombstones are kept per collection; the oldest go first.
21    pub max_count: u64,
22}
23
24/// 30 days.
25pub const TOMBSTONE_MAX_AGE_MS: u64 = 30 * 24 * 60 * 60 * 1000;
26/// Per collection.
27pub const TOMBSTONE_MAX_COUNT: u64 = 5_000;
28/// A rotation the app asks for (`reset()`, or the pruning guard) within this
29/// long of the last one is owed, not done at once (section 4.6): a burst of
30/// requests becomes one rotation, so the devices take one full copy, not one per
31/// request. An owed rotation is never dropped. A rotation for evidence that the
32/// database went back in time is never held back.
33pub const ROTATION_MIN_INTERVAL_MS: u64 = 60_000;
34
35impl Horizon {
36    /// 30 days and 5,000 tombstones per collection.
37    pub const DEFAULT: Horizon = Horizon {
38        max_age_ms: TOMBSTONE_MAX_AGE_MS,
39        max_count: TOMBSTONE_MAX_COUNT,
40    };
41}
42
43/// What the ledger logic needs to know about one collection.
44pub(crate) struct Spec<'a> {
45    pub name: &'a str,
46    pub schemas: &'a [u32],
47    pub env: &'a dyn Environment,
48    pub horizon: Horizon,
49}
50
51/// The head a pull or an announce reports: `(epoch, version)`.
52#[derive(Debug, Clone, PartialEq, Eq)]
53pub struct Head {
54    /// The collection's current epoch.
55    pub epoch: String,
56    /// The version of its latest change; 0 means nothing yet.
57    pub version: u64,
58}
59
60impl From<&CollectionRecord> for Head {
61    fn from(record: &CollectionRecord) -> Self {
62        Head {
63            epoch: record.epoch.clone(),
64            version: record.version,
65        }
66    }
67}
68
69/// Checks a row against the contract's limits and returns its digest.
70pub(crate) fn check_row(row: &Row) -> Result<String, ReplicaError> {
71    let invalid = |reason: String| ReplicaError::InvalidRow {
72        key: row.key.chars().take(64).collect(),
73        reason,
74    };
75    validate_key(&row.key).map_err(invalid)?;
76    if !value_within_depth(&row.value) {
77        return Err(invalid(VALUE_TOO_DEEP.to_string()));
78    }
79    let (digest, value_bytes) = digest_and_value_len(row);
80    if value_bytes > MAX_VALUE_BYTES {
81        return Err(invalid(format!(
82            "value is {value_bytes} bytes encoded; at most {MAX_VALUE_BYTES} are allowed"
83        )));
84    }
85    if row.ord.unsigned_abs() > MAX_SAFE_INTEGER {
86        return Err(invalid("ord must be within ±(2^53 - 1)".to_string()));
87    }
88    if row.part.len() > MAX_PART_BYTES {
89        return Err(invalid(format!(
90            "part is {} bytes; at most {MAX_PART_BYTES} are allowed",
91            row.part.len()
92        )));
93    }
94    Ok(digest)
95}
96
97fn new_epoch(spec: &Spec<'_>, previous: Option<&str>) -> Result<String, ReplicaError> {
98    for _ in 0..4 {
99        let epoch = spec.env.new_epoch();
100        if !is_epoch(&epoch) {
101            return Err(ReplicaError::Store(
102                "the environment produced an epoch outside [a-z0-9]{1,16}".to_string(),
103            ));
104        }
105        if previous != Some(epoch.as_str()) {
106            return Ok(epoch);
107        }
108    }
109    Err(ReplicaError::Store(
110        "the environment keeps producing the current epoch".to_string(),
111    ))
112}
113
114/// The next version, for a change about to be recorded. An owed rotation happens
115/// first, whatever the rate limit says: the versions above this ledger's head
116/// may already be on devices with other data (the database went back in time),
117/// and a version must never name two different lists.
118fn assign_version(
119    tx: &mut dyn LedgerTx,
120    spec: &Spec<'_>,
121    record: &mut CollectionRecord,
122) -> Result<u64, ReplicaError> {
123    if record.rotate_owed {
124        rotate_now(tx, spec, record)?;
125    }
126    if record.version >= MAX_SAFE_INTEGER {
127        return Err(ReplicaError::Store(format!(
128            "version of {} would pass 2^53 - 1",
129            record.epoch
130        )));
131    }
132    record.version += 1;
133    Ok(record.version)
134}
135
136/// The collection's record, created (new epoch, version 0, dirty) when the ledger
137/// has none: a new ledger has not seen the app's rows yet.
138pub(crate) fn open(
139    tx: &mut dyn LedgerTx,
140    spec: &Spec<'_>,
141) -> Result<CollectionRecord, ReplicaError> {
142    if let Some(record) = tx.record(spec.name)? {
143        return Ok(record);
144    }
145    let record = CollectionRecord {
146        epoch: new_epoch(spec, None)?,
147        version: 0,
148        floor: 0,
149        dirty: true,
150        rotated_at: spec.env.now_ms(),
151        reconciled_at: 0,
152        rotate_owed: false,
153    };
154    tx.put_record(spec.name, &record)?;
155    Ok(record)
156}
157
158/// Whether the rate limit lets a rotation happen now. A clock that stepped back
159/// never holds a rotation off.
160fn rotation_allowed(spec: &Spec<'_>, record: &CollectionRecord) -> bool {
161    let since = spec.env.now_ms().checked_sub(record.rotated_at);
162    record.rotated_at == 0 || since.map_or(true, |since| since >= ROTATION_MIN_INTERVAL_MS)
163}
164
165/// A rotation the app asks for (`reset()`, the pruning guard): done now when the
166/// rate limit allows, else owed (it then happens before the next version is
167/// assigned, or at the first ledger operation after the minute). Returns
168/// whether it rotated now. Holding it back is safe because the ledger still
169/// knows every version it handed out; only the cost of the copies is at stake.
170pub(crate) fn request_rotation(
171    tx: &mut dyn LedgerTx,
172    spec: &Spec<'_>,
173    record: &mut CollectionRecord,
174) -> Result<bool, ReplicaError> {
175    if rotation_allowed(spec, record) {
176        rotate_now(tx, spec, record)?;
177        return Ok(true);
178    }
179    record.rotate_owed = true;
180    Ok(false)
181}
182
183/// Run at the start of every ledger write, before its own work. `went_back`:
184/// this process has handed out a higher version of the ledger's epoch than the
185/// ledger now holds, so the database went back in time; that rotates at once
186/// (see [`rotate_now`]). Otherwise an owed rotation whose minute has passed
187/// happens now. Returns whether it rotated.
188pub(crate) fn begin(
189    tx: &mut dyn LedgerTx,
190    spec: &Spec<'_>,
191    record: &mut CollectionRecord,
192    went_back: bool,
193) -> Result<bool, ReplicaError> {
194    if went_back || (record.rotate_owed && rotation_allowed(spec, record)) {
195        rotate_now(tx, spec, record)?;
196        return Ok(true);
197    }
198    Ok(false)
199}
200
201/// Whether a read of `record` can stand for the write `begin` would do: no
202/// owed rotation is due.
203pub(crate) fn nothing_due(spec: &Spec<'_>, record: &CollectionRecord) -> bool {
204    !(record.rotate_owed && rotation_allowed(spec, record))
205}
206
207/// Starts a new epoch: every live row is renumbered 1…n in key order, every
208/// tombstone is dropped (a device holding the old epoch takes a full copy), the
209/// floor returns to 0, and an owed rotation is settled.
210///
211/// Evidence that the database went back in time (a device ahead of the head,
212/// the node's `rotate`, this process having handed out more) rotates through
213/// here at once, whatever the rate limit says. Held back, the ledger would go on
214/// answering in an epoch whose versions above its head are already on devices
215/// with other data: a device whose version names exactly the head would be told
216/// "nothing new" while holding rows the ledger never had (a device that finished
217/// a paged copy holds rows newer than the copy's version until its follow-up
218/// pull), and the next write would hand a version out twice.
219pub(crate) fn rotate_now(
220    tx: &mut dyn LedgerTx,
221    spec: &Spec<'_>,
222    record: &mut CollectionRecord,
223) -> Result<(), ReplicaError> {
224    let now = spec.env.now_ms();
225    let mut version = 0;
226    for mut entry in tx.entries(spec.name)? {
227        if entry.deleted {
228            tx.delete_entry(spec.name, &entry.key)?;
229            continue;
230        }
231        version += 1;
232        entry.version = version;
233        entry.changed_at = now;
234        tx.put_entry(spec.name, &entry)?;
235    }
236    record.epoch = new_epoch(spec, Some(&record.epoch))?;
237    record.version = version;
238    record.floor = 0;
239    record.rotated_at = now;
240    record.rotate_owed = false;
241    Ok(())
242}
243
244/// Records one row; returns whether the ledger changed.
245fn record_row(
246    tx: &mut dyn LedgerTx,
247    spec: &Spec<'_>,
248    record: &mut CollectionRecord,
249    row: &Row,
250    digest: String,
251    now: u64,
252) -> Result<bool, ReplicaError> {
253    if let Some(entry) = tx.entry(spec.name, &row.key)? {
254        if !entry.deleted && entry.digest == digest {
255            return Ok(false);
256        }
257    }
258    let version = assign_version(tx, spec, record)?;
259    tx.put_entry(
260        spec.name,
261        &LedgerEntry {
262            key: row.key.clone(),
263            digest,
264            version,
265            deleted: false,
266            changed_at: now,
267        },
268    )?;
269    Ok(true)
270}
271
272/// Records one delete; returns whether the ledger changed.
273fn record_delete(
274    tx: &mut dyn LedgerTx,
275    spec: &Spec<'_>,
276    record: &mut CollectionRecord,
277    key: &str,
278    now: u64,
279) -> Result<bool, ReplicaError> {
280    let Some(entry) = tx.entry(spec.name, key)? else {
281        return Ok(false);
282    };
283    if entry.deleted {
284        return Ok(false);
285    }
286    let version = assign_version(tx, spec, record)?;
287    tx.put_entry(
288        spec.name,
289        &LedgerEntry {
290            key: key.to_string(),
291            digest: entry.digest,
292            version,
293            deleted: true,
294            changed_at: now,
295        },
296    )?;
297    Ok(true)
298}
299
300/// Prunes tombstones past the horizon and raises the floor to the highest
301/// version pruned. When pruning could not keep the count (a store that did not
302/// prune), the epoch rotates, which drops every tombstone.
303fn prune(
304    tx: &mut dyn LedgerTx,
305    spec: &Spec<'_>,
306    record: &mut CollectionRecord,
307    now: u64,
308) -> Result<(), ReplicaError> {
309    let pruned = tx.prune_tombstones(
310        spec.name,
311        now.saturating_sub(spec.horizon.max_age_ms),
312        spec.horizon.max_count,
313    )?;
314    if let Some(highest) = pruned.highest {
315        record.floor = record.floor.max(highest);
316    }
317    if pruned.over_keep {
318        request_rotation(tx, spec, record)?;
319    }
320    Ok(())
321}
322
323/// Whole-list mode: `rows` is every current row. A new key or a changed digest
324/// gets the next version; a ledger key missing from `rows` becomes a tombstone
325/// at the next version. All rows are checked before anything is written.
326///
327/// A pass that changes nothing writes nothing: `reconciled_at` moves only
328/// together with another change to the record, so it never causes a write alone.
329pub(crate) fn reconcile(
330    tx: &mut dyn LedgerTx,
331    spec: &Spec<'_>,
332    record: &mut CollectionRecord,
333    rows: &[Row],
334) -> Result<(), ReplicaError> {
335    let now = spec.env.now_ms();
336    let start = record.clone();
337    let mut current: Vec<(&Row, String)> = rows
338        .iter()
339        .map(|row| check_row(row).map(|digest| (row, digest)))
340        .collect::<Result<_, _>>()?;
341    current.sort_unstable_by(|a, b| a.0.key.cmp(&b.0.key));
342    if let Some(pair) = current
343        .windows(2)
344        .find(|pair| pair[0].0.key == pair[1].0.key)
345    {
346        return Err(ReplicaError::InvalidRow {
347            key: pair[0].0.key.chars().take(64).collect(),
348            reason: "the key appears twice in the list".to_string(),
349        });
350    }
351    // Both lists are in key order: one merge finds what changed.
352    let ledger = tx.entries(spec.name)?;
353    let mut upserts: Vec<(&Row, &String)> = Vec::new();
354    let mut deletes: Vec<&LedgerEntry> = Vec::new();
355    let mut held = ledger.iter().peekable();
356    for (row, digest) in &current {
357        while let Some(entry) = held.next_if(|entry| entry.key < row.key) {
358            if !entry.deleted {
359                deletes.push(entry);
360            }
361        }
362        let unchanged = held
363            .next_if(|entry| entry.key == row.key)
364            .is_some_and(|entry| !entry.deleted && &entry.digest == digest);
365        if !unchanged {
366            upserts.push((row, digest));
367        }
368    }
369    deletes.extend(held.filter(|entry| !entry.deleted));
370    for (row, digest) in upserts {
371        let version = assign_version(tx, spec, record)?;
372        tx.put_entry(
373            spec.name,
374            &LedgerEntry {
375                key: row.key.clone(),
376                digest: digest.clone(),
377                version,
378                deleted: false,
379                changed_at: now,
380            },
381        )?;
382    }
383    for entry in deletes {
384        let version = assign_version(tx, spec, record)?;
385        tx.put_entry(
386            spec.name,
387            &LedgerEntry {
388                key: entry.key.clone(),
389                digest: entry.digest.clone(),
390                version,
391                deleted: true,
392                changed_at: now,
393            },
394        )?;
395    }
396    prune(tx, spec, record, now)?;
397    record.dirty = false;
398    // Every entry written above moved the version, so the record tells it all.
399    if *record != start {
400        record.reconciled_at = now;
401    }
402    Ok(())
403}
404
405pub(crate) fn touch(
406    tx: &mut dyn LedgerTx,
407    spec: &Spec<'_>,
408    record: &mut CollectionRecord,
409    row: &Row,
410) -> Result<(), ReplicaError> {
411    let digest = check_row(row)?;
412    let now = spec.env.now_ms();
413    record_row(tx, spec, record, row, digest, now)?;
414    prune(tx, spec, record, now)
415}
416
417pub(crate) fn remove(
418    tx: &mut dyn LedgerTx,
419    spec: &Spec<'_>,
420    record: &mut CollectionRecord,
421    key: &str,
422) -> Result<(), ReplicaError> {
423    validate_key(key).map_err(|reason| ReplicaError::InvalidRow {
424        key: key.chars().take(64).collect(),
425        reason,
426    })?;
427    let now = spec.env.now_ms();
428    record_delete(tx, spec, record, key, now)?;
429    prune(tx, spec, record, now)
430}
431
432/// Loads the app's current rows: all of them for `None`, else those of the
433/// given keys (a key with no row is simply absent from the result).
434pub(crate) type Load<'l> = dyn FnMut(Option<&[String]>) -> Result<Vec<Row>, ReplicaError> + 'l;
435
436/// Which answer a request gets, before any row is loaded.
437enum Plan {
438    NothingNew,
439    Changes(Vec<LedgerEntry>),
440    FullCopy {
441        version: u64,
442        entries: Vec<LedgerEntry>,
443    },
444}
445
446fn full_copy(
447    tx: &mut dyn LedgerTx,
448    spec: &Spec<'_>,
449    after: Option<&str>,
450    version: u64,
451    fetch: usize,
452) -> Result<Plan, ReplicaError> {
453    Ok(Plan::FullCopy {
454        version,
455        entries: tx.live_after(spec.name, after, fetch)?,
456    })
457}
458
459fn plan(
460    tx: &mut dyn LedgerTx,
461    spec: &Spec<'_>,
462    record: &mut CollectionRecord,
463    request: &PullRequest,
464) -> Result<Plan, ReplicaError> {
465    // One more than the limit tells whether more remain.
466    let fetch = request.effective_limit() + 1;
467    if request.epoch != record.epoch {
468        // Rule 2: another lineage, or nothing held.
469        return full_copy(tx, spec, None, record.version, fetch);
470    }
471    if request.version > record.version {
472        // Rule 3: the caller has seen a future this ledger does not contain (the
473        // database was restored or replaced). That is evidence: rotate at once.
474        rotate_now(tx, spec, record)?;
475        return full_copy(tx, spec, None, record.version, fetch);
476    }
477    if let Some(resume) = &request.resume {
478        // A later page of a full copy is "as of page one's version V": it carries
479        // the rows after the resume key as they are now and keeps V, and once the
480        // last page is in the caller asks for the changes since V, which brings
481        // every row changed after V (whatever page it was on) and every delete
482        // after V. So a copy always ends after as many pages as the list has,
483        // however busy the list is. Only when deletes after V were forgotten
484        // (V below the floor) would those changes come back as another full copy,
485        // so the copy starts over at the head now (its version is above V, so the
486        // caller sees a new page one).
487        if request.version >= record.floor {
488            return full_copy(tx, spec, Some(resume), request.version, fetch);
489        }
490        return full_copy(tx, spec, None, record.version, fetch);
491    }
492    if request.version < record.floor {
493        // Rule 2: deletes the caller has not seen were forgotten.
494        return full_copy(tx, spec, None, record.version, fetch);
495    }
496    if request.version == record.version {
497        return Ok(Plan::NothingNew);
498    }
499    Ok(Plan::Changes(tx.changes_after(
500        spec.name,
501        request.version,
502        fetch,
503    )?))
504}
505
506/// Re-records the rows whose loaded value no longer matches the ledger (a write
507/// the app made without telling the helper), and the live keys the app no
508/// longer has. Returns whether the ledger changed.
509fn heal(
510    tx: &mut dyn LedgerTx,
511    spec: &Spec<'_>,
512    record: &mut CollectionRecord,
513    wanted: &[LedgerEntry],
514    loaded: &BTreeMap<String, Row>,
515) -> Result<bool, ReplicaError> {
516    let now = spec.env.now_ms();
517    let mut changed = false;
518    for entry in wanted.iter().filter(|entry| !entry.deleted) {
519        match loaded.get(&entry.key) {
520            None => changed |= record_delete(tx, spec, record, &entry.key, now)?,
521            Some(row) => {
522                let digest = check_row(row)?;
523                if digest != entry.digest {
524                    changed |= record_row(tx, spec, record, row, digest, now)?;
525                }
526            }
527        }
528    }
529    Ok(changed)
530}
531
532/// Refuses a request for a schema this collection does not serve, or outside
533/// the contract.
534pub(crate) fn check_request(spec: &Spec<'_>, request: &PullRequest) -> Result<(), ReplicaError> {
535    if !spec.schemas.contains(&request.schema) {
536        return Err(ReplicaError::SchemaUnsupported {
537            capability: spec.name.to_string(),
538            schema: request.schema,
539        });
540    }
541    request.validate().map_err(ReplicaError::InvalidRequest)
542}
543
544/// Answers one pull (section 4.2). `record` is the collection's current record;
545/// the caller writes it back.
546pub(crate) fn answer(
547    tx: &mut dyn LedgerTx,
548    spec: &Spec<'_>,
549    record: &mut CollectionRecord,
550    request: &PullRequest,
551    load: &mut Load<'_>,
552) -> Result<PullReply, ReplicaError> {
553    check_request(spec, request)?;
554    if record.dirty {
555        // Rule 1: a pull reflects every write the app has acknowledged.
556        let rows = load(None)?;
557        reconcile(tx, spec, record, &rows)?;
558    }
559    let limit = request.effective_limit();
560    let mut whole_copy = false;
561    let mut heals = 0;
562    loop {
563        let plan = if whole_copy {
564            full_copy(tx, spec, None, record.version, limit + 1)?
565        } else {
566            plan(tx, spec, record, request)?
567        };
568        let wanted = match &plan {
569            Plan::NothingNew => {
570                return Ok(PullReply::NothingNew {
571                    epoch: record.epoch.clone(),
572                    version: record.version,
573                })
574            }
575            Plan::Changes(entries) | Plan::FullCopy { entries, .. } => entries,
576        };
577        let window = &wanted[..wanted.len().min(limit)];
578        let keys: Vec<String> = window
579            .iter()
580            .filter(|entry| !entry.deleted)
581            .map(|entry| entry.key.clone())
582            .collect();
583        let loaded: BTreeMap<String, Row> = if keys.is_empty() {
584            BTreeMap::new()
585        } else {
586            let wanted_keys: BTreeSet<&str> = keys.iter().map(String::as_str).collect();
587            load(Some(&keys))?
588                .into_iter()
589                .filter(|row| wanted_keys.contains(row.key.as_str()))
590                .map(|row| (row.key.clone(), row))
591                .collect()
592        };
593        // The rows are read after the ledger is; a mismatch found while reading
594        // is recorded and the answer computed again, at most twice.
595        if heals < 2 && heal(tx, spec, record, window, &loaded)? {
596            heals += 1;
597            continue;
598        }
599        match build(record, request, plan, limit, &loaded) {
600            Some(reply) => return Ok(reply),
601            None if !whole_copy => whole_copy = true,
602            None => {
603                return Err(ReplicaError::Store(
604                    "a full copy could not be built".to_string(),
605                ))
606            }
607        }
608    }
609}
610
611/// The reply for a plan and the rows read for it; `None` when a change list must
612/// be cut and no exact version to cut at exists (the caller then takes a full
613/// copy).
614fn build(
615    record: &CollectionRecord,
616    request: &PullRequest,
617    plan: Plan,
618    limit: usize,
619    loaded: &BTreeMap<String, Row>,
620) -> Option<PullReply> {
621    match plan {
622        Plan::NothingNew => Some(PullReply::NothingNew {
623            epoch: record.epoch.clone(),
624            version: record.version,
625        }),
626        Plan::Changes(entries) => {
627            let mut taken: Vec<&LedgerEntry> = Vec::new();
628            let mut bytes = 0;
629            let mut more = false;
630            for entry in &entries {
631                if taken.len() == limit {
632                    more = true;
633                    break;
634                }
635                let size = match (entry.deleted, loaded.get(&entry.key)) {
636                    (true, _) => encoded_delete_bytes(&entry.key),
637                    (false, Some(row)) => encoded_row_bytes(row),
638                    // A row that vanished while it was read: its delete is in the
639                    // ledger at a later version.
640                    (false, None) => 0,
641                };
642                if !taken.is_empty() && bytes + size > MAX_REPLY_ROW_BYTES {
643                    more = true;
644                    break;
645                }
646                bytes += size;
647                taken.push(entry);
648            }
649            let version = if more {
650                // A cut list is labelled with the version of its last change, and
651                // the caller then believes it holds the list as it was at that
652                // version. That is true only up to the first superseded change: a
653                // version missing from the run (v+1, v+2, …) belongs to a row that
654                // changed again later, whose value at the cut the ledger no longer
655                // knows. So the cut is made before the first gap; when the very
656                // first version is missing there is nothing exact to send.
657                let exact = taken
658                    .iter()
659                    .zip(request.version + 1..)
660                    .take_while(|(entry, expected)| entry.version == *expected)
661                    .count();
662                if exact == 0 {
663                    return None;
664                }
665                taken.truncate(exact);
666                request.version + exact as u64
667            } else {
668                // Untruncated, every change above the caller's version is in: the
669                // caller is at the head.
670                record.version
671            };
672            let mut upserts = Vec::new();
673            let mut deletes = Vec::new();
674            for entry in taken {
675                match (entry.deleted, loaded.get(&entry.key)) {
676                    (true, _) => deletes.push(entry.key.clone()),
677                    (false, Some(row)) => upserts.push(row.clone()),
678                    (false, None) => {}
679                }
680            }
681            Some(PullReply::Changes {
682                epoch: record.epoch.clone(),
683                version,
684                upserts,
685                deletes,
686                more,
687            })
688        }
689        Plan::FullCopy { version, entries } => {
690            let mut rows = Vec::new();
691            let mut bytes = 0;
692            let mut last_key: Option<&str> = None;
693            let mut more = false;
694            for (index, entry) in entries.iter().enumerate() {
695                if index == limit {
696                    more = true;
697                    break;
698                }
699                let Some(row) = loaded.get(&entry.key) else {
700                    last_key = Some(&entry.key);
701                    continue;
702                };
703                let size = encoded_row_bytes(row);
704                if index > 0 && bytes + size > MAX_REPLY_ROW_BYTES {
705                    more = true;
706                    break;
707                }
708                rows.push(row.clone());
709                bytes += size;
710                last_key = Some(&entry.key);
711            }
712            Some(PullReply::FullCopy {
713                epoch: record.epoch.clone(),
714                version,
715                rows,
716                next: if more {
717                    last_key.map(str::to_string)
718                } else {
719                    None
720                },
721                // A later page carries rows as they are now, which can be newer
722                // than the copy's version; the node marks the head it was read at.
723                head: (record.version > version).then_some(record.version),
724            })
725        }
726    }
727}