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