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