Skip to main content

ic_db/store/maintenance/
copy.rs

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