Skip to main content

ic_db/store/maintenance/
copy.rs

1//! Whole-database copy with private target admission and message-atomic checkpoints.
2use super::{Maintenance, SchemaTransition, decode as decode_source};
3use crate::{
4    Batch, Entity, EntitySchema, Error, PrimaryKey, QueryCursor, Schema,
5    codec::{Decoder, Encoder},
6    primary::RowKey,
7    store::Database,
8    store::{
9        EntityState, Map, collect_references, entity_state_key, index_entries, live_manifest,
10        manifest_key, read_entity_state, row_key, validate_index_entry, validate_reference_target,
11    },
12    store_key::StoreKey,
13};
14use ic_storage::{Memory, RuntimeMemory};
15use std::{collections::BTreeSet, ops::Bound};
16
17pub(super) const MAGIC: &[u8; 8] = b"ICDBCP02";
18const MAX_FRAME: usize = 8 + 4 + super::MAX_FRAME + 20 + 2 + 4 + QueryCursor::MAX_ENCODED_BYTES;
19
20#[derive(Clone, Debug, PartialEq, Eq)]
21pub(super) struct Identity {
22    transition: SchemaTransition,
23    source: [u8; 16],
24    target: [u8; 16],
25}
26pub(super) enum Phase {
27    Source,
28    Copying(u8, Option<QueryCursor>),
29    Copied,
30    Cancelling,
31    Cancelled,
32    ValidatingSource(Option<StoreKey>),
33    ValidatingTarget(Option<StoreKey>),
34    Ready,
35    Retired,
36}
37impl Identity {
38    fn encode(&self, phase: &Phase) -> Result<Vec<u8>, Error> {
39        let mut writer = Encoder::new();
40        writer.bytes(&self.transition.freeze(self.source)?)?;
41        writer.bytes(&self.target)?;
42        writer.nat8(match phase {
43            Phase::Source => 0,
44            Phase::Copying(0, _) => 1,
45            Phase::Copying(_, _) => 9,
46            Phase::Copied => 2,
47            Phase::Cancelling => 3,
48            Phase::Cancelled => 4,
49            Phase::ValidatingSource(_) => 5,
50            Phase::ValidatingTarget(_) => 6,
51            Phase::Ready => 7,
52            Phase::Retired => 8,
53        })?;
54        if let Phase::Copying(entity, cursor) = phase {
55            if *entity != 0 {
56                writer.nat8(*entity)?;
57            }
58            writer.bytes(&cursor.as_ref().map_or_else(Vec::new, QueryCursor::to_bytes))?;
59        }
60        if let Phase::ValidatingSource(cursor) | Phase::ValidatingTarget(cursor) = phase {
61            writer.bytes(cursor.as_ref().map_or(&[], |key| &key[..]))?;
62        }
63        let mut bytes = MAGIC.to_vec();
64        bytes.extend(writer.finish());
65        Ok(bytes)
66    }
67}
68
69pub(super) fn decode(bytes: &[u8]) -> Result<(Identity, Phase), Error> {
70    if !bytes.starts_with(MAGIC) || bytes.len() > MAX_FRAME {
71        return Err(Error::InvalidTransition);
72    }
73    let mut reader = Decoder::new(&bytes[8..])?;
74    let (transition, source) = decode_source(reader.blob_ref(super::MAX_FRAME)?)?;
75    let target = reader
76        .blob_ref(16)?
77        .try_into()
78        .map_err(|_| Error::Corrupt)?;
79    if target == [0; 16] || target == source {
80        return Err(Error::Corrupt);
81    }
82    let phase = match reader.nat8()? {
83        0 => Phase::Source,
84        tag @ (1 | 9) => {
85            let entity = if tag == 1 {
86                0
87            } else {
88                let entity = reader.nat8()?;
89                if !(1..32).contains(&entity) {
90                    return Err(Error::Corrupt);
91                }
92                entity
93            };
94            let cursor = reader.blob_ref(QueryCursor::MAX_ENCODED_BYTES)?;
95            Phase::Copying(
96                entity,
97                if cursor.is_empty() {
98                    None
99                } else {
100                    Some(QueryCursor::from_bytes(cursor)?)
101                },
102            )
103        }
104        2 => Phase::Copied,
105        3 => Phase::Cancelling,
106        4 => Phase::Cancelled,
107        tag @ (5 | 6) => {
108            let bytes = reader.blob_ref(crate::MAX_INDEX_KEY_BYTES)?;
109            let cursor = if bytes.is_empty() {
110                None
111            } else {
112                Some(StoreKey::new(bytes.to_vec())?)
113            };
114            if tag == 5 {
115                Phase::ValidatingSource(cursor)
116            } else {
117                Phase::ValidatingTarget(cursor)
118            }
119        }
120        7 => Phase::Ready,
121        8 => Phase::Retired,
122        _ => return Err(Error::IncompatibleSchema),
123    };
124    reader.finish()?;
125    Ok((
126        Identity {
127            transition,
128            source,
129            target,
130        },
131        phase,
132    ))
133}
134
135fn admit(source: &Schema, target: &Schema, transition: &SchemaTransition) -> Result<(), Error> {
136    if source.fingerprint() != transition.source || target.fingerprint() != transition.target {
137        return Err(Error::IncompatibleSchema);
138    }
139    for source in source.entities() {
140        let target = target
141            .entities()
142            .iter()
143            .find(|entity| entity.name == source.name)
144            .ok_or(Error::InvalidTransition)?;
145        if source.primary_key != target.primary_key
146            || source.key_type()? != target.key_type()?
147            || managed_roles(source) != managed_roles(target)
148        {
149            return Err(Error::InvalidTransition);
150        }
151    }
152    Ok(())
153}
154
155fn managed_roles(entity: &EntitySchema) -> [bool; 2] {
156    let mut roles = [false; 2];
157    for policy in entity.fields.iter().filter_map(|field| field.managed) {
158        roles[policy.slot()] = true;
159    }
160    roles
161}
162
163/// A bounded copy result. Completion means all source rows were copied, not
164/// that the target is validated for publication or available for ordinary access.
165#[derive(Debug, PartialEq, Eq)]
166pub struct CopyStep {
167    /// Rows transformed and inserted by this call.
168    pub rows: usize,
169    /// Every entity in the frozen source has been copied.
170    pub complete: bool,
171}
172
173/// Current stage of an admitted schema copy, derived from its saved checkpoint.
174#[derive(Clone, Copy, Debug, PartialEq, Eq)]
175pub enum CopyStatus {
176    /// Copy the next bounded chunk of this source entity.
177    Copying(&'static str),
178    /// All source entities are copied. Start or continue bounded validation.
179    Validating,
180    /// Validation finished. The host may explicitly publish or cancel.
181    ReadyToPublish,
182    /// Continue bounded cancellation until the source reopens.
183    Cancelling,
184    /// Cancellation finished on this handle. The source may reopen after drop.
185    Cancelled,
186}
187
188/// Exclusive source/target custody for a key-preserving whole-database transformation.
189/// Both allocations remain closed to ordinary access. Dropping preserves progress.
190/// Publication requires completed validation. Allocation reuse remains unsupported.
191pub struct SchemaCopy<M: Memory> {
192    source: Maintenance<M>,
193    source_schema: Schema,
194    target: Database<M>,
195    identity: Identity,
196    phase: Phase,
197}
198
199impl<M: Memory> Maintenance<M> {
200    /// Bind a fresh target allocation to this frozen source and initialize copying.
201    /// The host supplies a fresh nonzero target incarnation, distinct from the source.
202    /// Every source entity retains its name, primary key declaration and managed
203    /// timestamp roles. Additional target entities start empty. References validate only after
204    /// all entities are copied, including unchanged entities. All values
205    /// and target indexes use ordinary codecs and shared batch validation.
206    /// # Errors
207    /// Refuses unsupported shapes, wrong schemas/identity or nonempty target memory
208    /// before mutation. Initial supplier growth may also refuse.
209    /// # Panics
210    /// Failures after target initialization trap; never catch and continue.
211    pub fn begin_copy(
212        mut self,
213        memory: RuntimeMemory<M>,
214        source: Schema,
215        target: Schema,
216        incarnation: [u8; 16],
217    ) -> Result<SchemaCopy<M>, Error> {
218        admit(&source, &target, &self.transition)?;
219        if incarnation == [0; 16] || incarnation == self.incarnation {
220            return Err(Error::InvalidTransition);
221        }
222        let identity = Identity {
223            transition: self.transition.clone(),
224            source: self.incarnation,
225            target: incarnation,
226        };
227        let source_gate = identity.encode(&Phase::Source)?;
228        let phase = Phase::Copying(0, None);
229        let target_gate = identity.encode(&phase)?;
230        let metadata: Vec<_> = target
231            .entities()
232            .iter()
233            .map(|entity| entity_state_key(entity.id))
234            .collect();
235        if memory.size() != 0 {
236            return Err(Error::Exists);
237        }
238        let mut map = Map::create(memory);
239        map.insert(manifest_key(), target_gate);
240        for key in metadata {
241            map.insert(key, EntityState::default().encode());
242        }
243        self.map.insert(manifest_key(), source_gate);
244        Ok(SchemaCopy {
245            source: self,
246            source_schema: source,
247            target: Database {
248                map,
249                schema: target,
250                incarnation,
251            },
252            identity,
253            phase,
254        })
255    }
256}
257
258impl<M: Memory> SchemaCopy<M> {
259    /// Resume only the recorded source/target pair and exact transformation.
260    /// # Errors
261    /// Refuses swapped, unrelated, live, cancelled or corrupt allocations intact.
262    /// # Panics
263    /// Supplier corruption traps without repair.
264    pub fn resume(
265        source_memory: RuntimeMemory<M>,
266        target_memory: RuntimeMemory<M>,
267        source_schema: Schema,
268        target_schema: Schema,
269        expected: &SchemaTransition,
270    ) -> Result<Self, Error> {
271        admit(&source_schema, &target_schema, expected)?;
272        if source_memory.size() == 0 {
273            return Err(Error::Corrupt);
274        }
275        let source = Map::load(source_memory);
276        if target_memory.size() == 0 {
277            return Err(Error::Corrupt);
278        }
279        let target = Map::load(target_memory);
280        let (identity, role) = decode(&source.get(&manifest_key()).ok_or(Error::Corrupt)?)?;
281        let (target_identity, phase) = decode(&target.get(&manifest_key()).ok_or(Error::Corrupt)?)?;
282        if !matches!(role, Phase::Source)
283            || matches!(phase, Phase::Source | Phase::Cancelled | Phase::Retired)
284            || identity != target_identity
285            || identity.transition != *expected
286        {
287            return Err(Error::InvalidTransition);
288        }
289        if matches!(&phase, Phase::Copying(entity, _) if usize::from(*entity) >= source_schema.entities().len())
290        {
291            return Err(Error::Corrupt);
292        }
293        Ok(Self {
294            source: Maintenance {
295                map: source,
296                transition: expected.clone(),
297                incarnation: identity.source,
298            },
299            source_schema,
300            target: Database {
301                map: target,
302                schema: target_schema,
303                incarnation: identity.target,
304            },
305            identity,
306            phase,
307        })
308    }
309
310    /// Inspect the checkpoint already loaded by this handle. Inspection does no storage work.
311    #[must_use]
312    pub fn status(&self) -> CopyStatus {
313        match &self.phase {
314            Phase::Copying(entity, _) => {
315                CopyStatus::Copying(self.source_schema.entities()[usize::from(*entity)].name)
316            }
317            Phase::Copied | Phase::ValidatingSource(_) | Phase::ValidatingTarget(_) => {
318                CopyStatus::Validating
319            }
320            Phase::Ready => CopyStatus::ReadyToPublish,
321            Phase::Cancelling => CopyStatus::Cancelling,
322            Phase::Cancelled => CopyStatus::Cancelled,
323            Phase::Source | Phase::Retired => {
324                unreachable!("source-side checkpoint on a target copy handle")
325            }
326        }
327    }
328
329    /// Name of the next entity to copy, in canonical schema-name order.
330    /// Returns `None` after copying or once cancellation/validation has started.
331    #[must_use]
332    pub fn next_entity(&self) -> Option<&'static str> {
333        if let CopyStatus::Copying(entity) = self.status() {
334            Some(entity)
335        } else {
336            None
337        }
338    }
339
340    /// Explicitly preserve an unchanged entity through the same bounded copy path.
341    /// The entity's complete declaration must be admitted by both schemas.
342    /// # Errors
343    /// Refuses changed declarations, wrong copy order, bounds or corrupt source rows.
344    /// # Panics
345    /// Supplier mutation failures trap and roll back the whole IC message.
346    pub fn copy_unchanged<E: Entity>(
347        &mut self,
348        limit: usize,
349        bytes: usize,
350    ) -> Result<CopyStep, Error> {
351        self.copy_next::<E, E>(limit, bytes, |row, _| Ok(row))
352    }
353
354    /// Transform the next bounded source page and checkpoint its target inserts.
355    /// The function must be deterministic for the declared version/fixed inputs,
356    /// synchronous and free of external effects or reentrant database mutations.
357    /// Limits match source paging: 1..=32 candidates, 1 byte..=128 KiB source output.
358    /// Target preparation additionally enforces the ordinary batch/index envelope.
359    /// Managed timestamp roles and their values must be preserved; field renames
360    /// are allowed through the explicit transformation. No insertion clock runs.
361    /// Call for `next_entity()` only. Completion advances to the next schema entity;
362    /// `complete` becomes true only after all entities have been copied.
363    /// Repeated calls after completion return zero rows and `complete = true`.
364    /// # Errors
365    /// Refusals (including transform errors, changed keys and cross-page uniqueness
366    /// collisions) leave both rows and progress unchanged. Cancelling refuses copying.
367    /// # Panics
368    /// Mutation failures or a later enclosing-message trap roll back the whole chunk
369    /// on the IC. Native callers must discard the runtime after a mutation panic.
370    pub fn copy_next<S: Entity, T: Entity>(
371        &mut self,
372        limit: usize,
373        bytes: usize,
374        transform: fn(S, &[u8]) -> Result<T, Error>,
375    ) -> Result<CopyStep, Error> {
376        self.source_schema.admits(S::SCHEMA)?;
377        self.target.schema.admits(T::SCHEMA)?;
378        let (entity, cursor) = match &self.phase {
379            Phase::Copying(entity, cursor) => (*entity, cursor.as_ref()),
380            Phase::Copied => {
381                return Ok(CopyStep {
382                    rows: 0,
383                    complete: true,
384                });
385            }
386            _ => return Err(Error::InvalidTransition),
387        };
388        if S::SCHEMA.name != self.source_schema.entities()[usize::from(entity)].name
389            || S::SCHEMA.name != T::SCHEMA.name
390        {
391            return Err(Error::InvalidTransition);
392        }
393        let page = self
394            .source
395            .source_page::<S>(&self.source_schema, cursor, limit, bytes)?;
396        let rows = page.rows.len();
397        let phase = if page.next.is_none() {
398            if usize::from(entity) + 1 == self.source_schema.entities().len() {
399                Phase::Copied
400            } else {
401                Phase::Copying(entity + 1, None)
402            }
403        } else {
404            Phase::Copying(entity, page.next)
405        };
406        let complete = matches!(phase, Phase::Copied);
407        let checkpoint = self.identity.encode(&phase)?;
408        let mut batch = Batch::new();
409        for row in page.rows {
410            let key = row.key().into_row_key();
411            let times = if S::SCHEMA.has_managed() {
412                crate::managed::values(S::SCHEMA, &row.encode()?)?
413            } else {
414                [None; 2]
415            };
416            let result = transform(row, self.identity.transition.inputs())?;
417            if result.key().into_row_key() != key {
418                return Err(Error::InvalidTransition);
419            }
420            batch.put(&result, |bytes, info| {
421                crate::store::Kind::CopyInsert(bytes, info, times)
422            })?;
423        }
424        self.target.commit(batch)?;
425        // No recoverable refusal after commit begins. The IC message owns rollback.
426        self.target.map.insert(manifest_key(), checkpoint);
427        self.phase = phase;
428        Ok(CopyStep { rows, complete })
429    }
430
431    /// Remove at most 1..=32 target entries, retaining its ownership tombstone.
432    /// Copying cannot resume once cleanup starts. Return true only after cleanup
433    /// and restoration of the source live manifest; drop this handle before reopen.
434    /// No physical shrink or target allocation reuse is promised.
435    /// # Errors
436    /// Refuses invalid limits before mutation.
437    /// # Panics
438    /// Supplier mutation failures trap and roll back the entire IC message.
439    pub fn cancel_step(&mut self, limit: usize) -> Result<bool, Error> {
440        let (keys, complete) = cleanup_keys(&self.target.map, limit)?;
441        if matches!(self.phase, Phase::Cancelled) {
442            return Ok(true);
443        }
444        let phase = if complete {
445            Phase::Cancelled
446        } else {
447            Phase::Cancelling
448        };
449        let checkpoint = self.identity.encode(&phase)?;
450        let live = live_manifest(self.identity.transition.source, self.identity.source);
451        for key in &keys {
452            self.target.map.remove(key);
453        }
454        self.target.map.insert(manifest_key(), checkpoint);
455        if complete {
456            self.source.map.insert(manifest_key(), live);
457        }
458        self.phase = phase;
459        Ok(complete)
460    }
461
462    /// Validate at most 1..=32 physical source or target entries in one call.
463    /// Checks complete row framing, exact key coverage in both directions, revision
464    /// metadata, expected index membership and every stored index's owner/key.
465    /// Each row has at most eight indexes and sixteen references. Each pass first
466    /// checks all declared revisions (at most 32), including empty entities. No writes to
467    /// rows/indexes occur; only successful bounded progress is checkpointed.
468    /// Return true only after both passes finish. Copying cannot resume afterward.
469    /// # Errors
470    /// Refuses before copy completion, during cancellation, or on limits/corruption.
471    /// A refused chunk leaves its durable validation position unchanged.
472    /// # Panics
473    /// Supplier failures trap; an IC trap rolls back checkpoint advancement.
474    pub fn validate_next(&mut self, limit: usize) -> Result<bool, Error> {
475        if !(1..=32).contains(&limit) {
476            return Err(Error::Limit);
477        }
478        let phase = match &self.phase {
479            Phase::Copied | Phase::ValidatingSource(_) => {
480                let cursor = if let Phase::ValidatingSource(cursor) = &self.phase {
481                    cursor.as_ref()
482                } else {
483                    None
484                };
485                let next = validate_page(
486                    &self.source.map,
487                    &self.source_schema,
488                    (&self.target.map, &self.target.schema),
489                    cursor,
490                    limit,
491                )?;
492                match next {
493                    Some(key) => Phase::ValidatingSource(Some(key)),
494                    None => Phase::ValidatingTarget(None),
495                }
496            }
497            Phase::ValidatingTarget(cursor) => {
498                let next = validate_page(
499                    &self.target.map,
500                    &self.target.schema,
501                    (&self.source.map, &self.source_schema),
502                    cursor.as_ref(),
503                    limit,
504                )?;
505                match next {
506                    Some(key) => Phase::ValidatingTarget(Some(key)),
507                    None => Phase::Ready,
508                }
509            }
510            Phase::Ready => return Ok(true),
511            _ => return Err(Error::InvalidTransition),
512        };
513        let checkpoint = self.identity.encode(&phase)?;
514        let complete = matches!(phase, Phase::Ready);
515        self.target.map.insert(manifest_key(), checkpoint);
516        self.phase = phase;
517        Ok(complete)
518    }
519
520    /// Atomically retire source admission and publish the fully validated target.
521    /// The host selects the target allocation for subsequent ordinary opens.
522    /// Source rows remain preserved but closed: this is not an operational rollback
523    /// promise after target writes. Explicit `RetiredSource` cleanup may remove them.
524    /// # Errors
525    /// Refuses unless both validation passes have completed.
526    /// # Panics
527    /// Mutation failures or a later enclosing-message trap roll back both manifests.
528    pub fn publish(mut self) -> Result<Database<M>, Error> {
529        if !matches!(self.phase, Phase::Ready) {
530            return Err(Error::InvalidTransition);
531        }
532        let retired = self.identity.encode(&Phase::Retired)?;
533        let live = live_manifest(self.identity.transition.target, self.identity.target);
534        self.source.map.insert(manifest_key(), retired);
535        self.target.map.insert(manifest_key(), live);
536        Ok(self.target)
537    }
538}
539
540/// Exclusive cleanup authority for an entire source collection retired by cutover.
541/// Admission binds the exact transition and both database incarnations. Cleanup
542/// never opens the target and never clears the source's retired manifest.
543pub struct RetiredSource<M: Memory> {
544    map: Map<M>,
545}
546
547impl<M: Memory> RetiredSource<M> {
548    /// Admit only the expected retired allocation, without decoding historical rows.
549    /// The host decides when preservation/recovery obligations permit deletion.
550    /// # Errors
551    /// Refuses live, copying, cancelled, foreign or malformed allocations intact.
552    /// # Panics
553    /// Supplier corruption traps without repair.
554    pub fn resume(
555        memory: RuntimeMemory<M>,
556        expected: &SchemaTransition,
557        source_incarnation: [u8; 16],
558        target_incarnation: [u8; 16],
559    ) -> Result<Self, Error> {
560        if memory.size() == 0 {
561            return Err(Error::Corrupt);
562        }
563        let map = Map::load(memory);
564        let (identity, phase) = decode(&map.get(&manifest_key()).ok_or(Error::Corrupt)?)?;
565        if !matches!(phase, Phase::Retired)
566            || identity.transition != *expected
567            || identity.source != source_incarnation
568            || identity.target != target_incarnation
569        {
570            return Err(Error::InvalidTransition);
571        }
572        Ok(Self { map })
573    }
574
575    /// Delete at most 1..=32 retired entries, preserving the ownership manifest.
576    /// Return true when only that manifest remains. Repeated completion is a no-op.
577    /// Deletion itself records progress; no additional cursor or phase is stored.
578    /// This does not shrink physical memory, reset the allocation or reopen source.
579    /// # Errors
580    /// Refuses invalid limits before mutation.
581    /// # Panics
582    /// Supplier mutation failures trap; the IC rolls back the whole cleanup chunk.
583    pub fn cleanup_step(&mut self, limit: usize) -> Result<bool, Error> {
584        let (keys, complete) = cleanup_keys(&self.map, limit)?;
585        for key in &keys {
586            self.map.remove(key);
587        }
588        Ok(complete)
589    }
590}
591
592// Cancellation and retired cleanup share bounded selection, keeping their
593// different authority changes at the caller. Values are not decoded for deletion.
594fn cleanup_keys<M: Memory>(map: &Map<M>, limit: usize) -> Result<(Vec<StoreKey>, bool), Error> {
595    if !(1..=32).contains(&limit) {
596        return Err(Error::Limit);
597    }
598    let manifest = manifest_key();
599    let mut keys: Vec<_> = map
600        .keys()
601        .filter(|key| *key != manifest)
602        .take(limit + 1)
603        .collect();
604    let complete = keys.len() <= limit;
605    if !complete {
606        keys.pop();
607    }
608    Ok((keys, complete))
609}
610
611// Validate the physical collection in both directions. Forward row checks find
612// missing/wrong-owner indexes; reverse index checks find stale/extra entries.
613fn validate_page<M: Memory>(
614    map: &Map<M>,
615    schema: &Schema,
616    peer: (&Map<M>, &Schema),
617    after: Option<&StoreKey>,
618    limit: usize,
619) -> Result<Option<StoreKey>, Error> {
620    // At most 32 entities. Check missing metadata and equal counts for this
621    // key-preserving copy; target counts were rebuilt by atomic private inserts.
622    // Frozen allocations cannot change mid-pass.
623    if after.is_none() {
624        for entity in schema.entities() {
625            let state = read_entity_state(map, entity.id)?;
626            if peer.1.entities().iter().any(|other| other.id == entity.id) {
627                if state.count != read_entity_state(peer.0, entity.id)?.count {
628                    return Err(Error::Corrupt);
629                }
630            } else if state.count != 0 || state.revision != 0 {
631                // Only an added target entity can lack a peer. No copy operation owns its rows.
632                return Err(Error::Corrupt);
633            }
634        }
635    }
636    let lower = after.map_or(Bound::Unbounded, |key| Bound::Excluded(key.clone()));
637    let mut last = None;
638    let mut examined = 0;
639    for entry in map.range((lower, Bound::Unbounded)).take(limit) {
640        let key = entry.key();
641        if *key != manifest_key() {
642            let bytes = entry.value();
643            let id = u32::from_be_bytes(
644                key.get(1..5)
645                    .ok_or(Error::Corrupt)?
646                    .try_into()
647                    .map_err(|_| Error::Corrupt)?,
648            );
649            let entity = schema
650                .entities()
651                .iter()
652                .find(|entity| entity.id == id)
653                .ok_or(Error::Corrupt)?;
654            match key.first() {
655                Some(1) if *key == entity_state_key(entity.id) => {
656                    if bytes.len() != 16 {
657                        return Err(Error::Corrupt);
658                    }
659                }
660                Some(2) => {
661                    let peer_entity = peer
662                        .1
663                        .entities()
664                        .iter()
665                        .find(|entity| entity.id == id)
666                        .ok_or(Error::Corrupt)?;
667                    let info = entity.inspect_row(&bytes)?;
668                    let owner = info.key;
669                    if *key != row_key(entity.id, owner) {
670                        return Err(Error::Corrupt);
671                    }
672                    if entity.has_managed() {
673                        let other = peer.0.get(key).ok_or(Error::Corrupt)?;
674                        if crate::managed::values(entity, &bytes)?
675                            != crate::managed::values(peer_entity, &other)?
676                        {
677                            return Err(Error::ManagedField);
678                        }
679                    } else if !peer.0.contains_key(key) {
680                        return Err(Error::Corrupt);
681                    }
682                    for (index, _) in index_entries(entity, &info)? {
683                        let stored = map.get(&index).ok_or(Error::Corrupt)?;
684                        if RowKey::decode(&stored, entity.key_type()?)? != owner {
685                            return Err(Error::Corrupt);
686                        }
687                    }
688                    let mut required = BTreeSet::new();
689                    collect_references(entity, &info, &mut required)?;
690                    for (target, id) in required {
691                        validate_reference_target(map, schema, target, id)?;
692                    }
693                }
694                Some(3) => {
695                    let owner = RowKey::decode(&bytes, entity.key_type()?)?;
696                    let row = map.get(&row_key(entity.id, owner)).ok_or(Error::Corrupt)?;
697                    validate_index_entry(entity, &entity.inspect_row(&row)?, owner, key)?;
698                }
699                _ => return Err(Error::Corrupt),
700            }
701        }
702        last = Some(key.clone());
703        examined += 1;
704    }
705    Ok(if examined == limit { last } else { None })
706}