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