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}
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: Maintenance<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.clone(),
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 metadata: Vec<_> = target
251            .entities()
252            .iter()
253            .map(|entity| entity_state_key(entity.id))
254            .collect();
255        if memory.size() != 0 {
256            return Err(Error::Exists);
257        }
258        let mut map = Map::create(memory);
259        map.insert(manifest_key(), target_gate);
260        for key in metadata {
261            map.insert(key, EntityState::default().encode());
262        }
263        self.map.insert(manifest_key(), source_gate);
264
265        Ok(SchemaCopy {
266            source: self,
267            source_schema: source,
268            target: Database {
269                map,
270                schema: target,
271                incarnation,
272            },
273            identity,
274            phase,
275        })
276    }
277}
278
279impl<M: Memory> SchemaCopy<M> {
280    /// Resume only the recorded source/target pair and exact transformation.
281    /// # Errors
282    /// Refuses swapped, unrelated, live, cancelled or corrupt allocations intact.
283    /// # Panics
284    /// Supplier corruption traps without repair.
285    pub fn resume(
286        source_memory: RuntimeMemory<M>,
287        target_memory: RuntimeMemory<M>,
288        source_schema: Schema,
289        target_schema: Schema,
290        expected: &SchemaTransition,
291    ) -> Result<Self, Error> {
292        admit(&source_schema, &target_schema, expected)?;
293        if source_memory.size() == 0 {
294            return Err(Error::Corrupt);
295        }
296        let source = Map::load(source_memory);
297        if target_memory.size() == 0 {
298            return Err(Error::Corrupt);
299        }
300        let target = Map::load(target_memory);
301        let (identity, role) = decode(&source.get(&manifest_key()).ok_or(Error::Corrupt)?)?;
302        let (target_identity, target_role) =
303            decode(&target.get(&manifest_key()).ok_or(Error::Corrupt)?)?;
304        let (AllocationRole::Source, AllocationRole::Target(phase)) = (role, target_role) else {
305            return Err(Error::InvalidTransition);
306        };
307        if matches!(phase, TargetProgress::Cancelled)
308            || identity != target_identity
309            || identity.transition != *expected
310        {
311            return Err(Error::InvalidTransition);
312        }
313        if matches!(&phase, TargetProgress::Copying(entity, _) if usize::from(*entity) >= source_schema.entities().len())
314        {
315            return Err(Error::Corrupt);
316        }
317
318        Ok(Self {
319            source: Maintenance {
320                map: source,
321                transition: expected.clone(),
322                incarnation: identity.source,
323            },
324            source_schema,
325            target: Database {
326                map: target,
327                schema: target_schema,
328                incarnation: identity.target,
329            },
330            identity,
331            phase,
332        })
333    }
334
335    /// Inspect the checkpoint already loaded by this handle. Inspection does no storage work.
336    #[must_use]
337    pub fn status(&self) -> CopyStatus {
338        match &self.phase {
339            TargetProgress::Copying(entity, _) => {
340                CopyStatus::Copying(self.source_schema.entities()[usize::from(*entity)].name)
341            }
342            TargetProgress::Copied
343            | TargetProgress::ValidatingSource(_)
344            | TargetProgress::ValidatingTarget(_) => CopyStatus::Validating,
345            TargetProgress::Ready => CopyStatus::ReadyToPublish,
346            TargetProgress::Cancelling => CopyStatus::Cancelling,
347            TargetProgress::Cancelled => CopyStatus::Cancelled,
348        }
349    }
350
351    /// Name of the next entity to copy, in canonical schema-name order.
352    /// Returns `None` after copying or once cancellation/validation has started.
353    #[must_use]
354    pub fn next_entity(&self) -> Option<&'static str> {
355        if let CopyStatus::Copying(entity) = self.status() {
356            Some(entity)
357        } else {
358            None
359        }
360    }
361
362    /// Explicitly preserve an unchanged entity through the same bounded copy path.
363    /// The entity's complete declaration must be admitted by both schemas.
364    /// # Errors
365    /// Refuses changed declarations, wrong copy order, bounds or corrupt source rows.
366    /// # Panics
367    /// Supplier mutation failures trap and roll back the whole IC message.
368    pub fn copy_unchanged<E: Entity>(
369        &mut self,
370        limit: usize,
371        bytes: usize,
372    ) -> Result<CopyStep, Error> {
373        self.copy_next::<E, E>(limit, bytes, |row, _| Ok(row))
374    }
375
376    /// Transform the next bounded source page and checkpoint its target inserts.
377    /// The function must be deterministic for the declared version/fixed inputs,
378    /// synchronous and free of external effects or reentrant database mutations.
379    /// Limits match source paging: 1..=32 candidates, 1 byte..=128 KiB source output.
380    /// Target preparation additionally enforces the ordinary batch/index envelope.
381    /// Managed timestamp roles and their values must be preserved; field renames
382    /// are allowed through the explicit transformation. No insertion clock runs.
383    /// Call for `next_entity()` only. Completion advances to the next schema entity;
384    /// `complete` becomes true only after all entities have been copied.
385    /// Repeated calls after completion return zero rows and `complete = true`.
386    /// # Errors
387    /// Refusals (including transform errors, changed keys and cross-page uniqueness
388    /// collisions) leave both rows and progress unchanged. Cancelling refuses copying.
389    /// # Panics
390    /// Mutation failures or a later enclosing-message trap roll back the whole chunk
391    /// on the IC. Native callers must discard the runtime after a mutation panic.
392    pub fn copy_next<S: Entity, T: Entity>(
393        &mut self,
394        limit: usize,
395        bytes: usize,
396        transform: fn(S, &[u8]) -> Result<T, Error>,
397    ) -> Result<CopyStep, Error> {
398        self.source_schema.admits(S::SCHEMA)?;
399        self.target.schema.admits(T::SCHEMA)?;
400        let (entity, cursor) = match &self.phase {
401            TargetProgress::Copying(entity, cursor) => (*entity, cursor.as_ref()),
402            TargetProgress::Copied => {
403                return Ok(CopyStep {
404                    rows: 0,
405                    complete: true,
406                });
407            }
408            _ => return Err(Error::InvalidTransition),
409        };
410        if S::SCHEMA.name != self.source_schema.entities()[usize::from(entity)].name
411            || S::SCHEMA.name != T::SCHEMA.name
412        {
413            return Err(Error::InvalidTransition);
414        }
415        let page = self
416            .source
417            .source_page::<S>(&self.source_schema, cursor, limit, bytes)?;
418        let rows = page.rows.len();
419        let phase = if page.next.is_none() {
420            if usize::from(entity) + 1 == self.source_schema.entities().len() {
421                TargetProgress::Copied
422            } else {
423                TargetProgress::Copying(entity + 1, None)
424            }
425        } else {
426            TargetProgress::Copying(entity, page.next)
427        };
428        let complete = matches!(phase, TargetProgress::Copied);
429        let checkpoint = self.identity.encode(AllocationRole::Target(&phase))?;
430        let mut batch = Batch::new();
431        for row in page.rows {
432            let key = row.key().into_row_key();
433            let times = if S::SCHEMA.has_managed() {
434                crate::managed::values(S::SCHEMA, &row.encode()?)?
435            } else {
436                [None; 2]
437            };
438            let result = transform(row, self.identity.transition.inputs())?;
439            if result.key().into_row_key() != key {
440                return Err(Error::InvalidTransition);
441            }
442            batch.put(&result, |bytes, info| {
443                crate::store::Kind::CopyInsert(bytes, info, times)
444            })?;
445        }
446        self.target.commit(batch)?;
447        // No recoverable refusal after commit begins. The IC message owns rollback.
448        self.target.map.insert(manifest_key(), checkpoint);
449        self.phase = phase;
450
451        Ok(CopyStep { rows, complete })
452    }
453
454    /// Remove at most 1..=32 target entries, retaining its ownership tombstone.
455    /// Copying cannot resume once cleanup starts. Return true only after cleanup
456    /// and restoration of the source live manifest; drop this handle before reopen.
457    /// No physical shrink or target allocation reuse is promised.
458    /// # Errors
459    /// Refuses invalid limits before mutation.
460    /// # Panics
461    /// Supplier mutation failures trap and roll back the entire IC message.
462    pub fn cancel_step(&mut self, limit: usize) -> Result<bool, Error> {
463        let (keys, complete) = cleanup_keys(&self.target.map, limit)?;
464        if matches!(self.phase, TargetProgress::Cancelled) {
465            return Ok(true);
466        }
467        let phase = if complete {
468            TargetProgress::Cancelled
469        } else {
470            TargetProgress::Cancelling
471        };
472        let checkpoint = self.identity.encode(AllocationRole::Target(&phase))?;
473        let live = live_manifest(self.identity.transition.source, self.identity.source);
474        for key in &keys {
475            self.target.map.remove(key);
476        }
477        self.target.map.insert(manifest_key(), checkpoint);
478        if complete {
479            self.source.map.insert(manifest_key(), live);
480        }
481        self.phase = phase;
482
483        Ok(complete)
484    }
485
486    /// Validate at most 1..=32 physical source or target entries in one call.
487    /// Checks complete row framing, exact key coverage in both directions, revision
488    /// metadata, expected index membership and every stored index's owner/key.
489    /// Each row has at most eight declared indexes and 32 list-reference entries. Each pass first
490    /// checks all declared revisions (up to the schema entity limit), including empty entities. No writes to
491    /// rows/indexes occur; only successful bounded progress is checkpointed.
492    /// Return true only after both passes finish. Copying cannot resume afterward.
493    /// # Errors
494    /// Refuses before copy completion, during cancellation, or on limits/corruption.
495    /// A refused chunk leaves its durable validation position unchanged.
496    /// # Panics
497    /// Supplier failures trap; an IC trap rolls back checkpoint advancement.
498    pub fn validate_next(&mut self, limit: usize) -> Result<bool, Error> {
499        if !(1..=32).contains(&limit) {
500            return Err(Error::Limit);
501        }
502        let phase = match &self.phase {
503            TargetProgress::Copied | TargetProgress::ValidatingSource(_) => {
504                let cursor = if let TargetProgress::ValidatingSource(cursor) = &self.phase {
505                    cursor.as_ref()
506                } else {
507                    None
508                };
509                let next = validate_page(
510                    &self.source.map,
511                    &self.source_schema,
512                    (&self.target.map, &self.target.schema),
513                    cursor,
514                    limit,
515                )?;
516
517                match next {
518                    Some(key) => TargetProgress::ValidatingSource(Some(key)),
519                    None => TargetProgress::ValidatingTarget(None),
520                }
521            }
522            TargetProgress::ValidatingTarget(cursor) => {
523                let next = validate_page(
524                    &self.target.map,
525                    &self.target.schema,
526                    (&self.source.map, &self.source_schema),
527                    cursor.as_ref(),
528                    limit,
529                )?;
530
531                match next {
532                    Some(key) => TargetProgress::ValidatingTarget(Some(key)),
533                    None => TargetProgress::Ready,
534                }
535            }
536            TargetProgress::Ready => return Ok(true),
537            _ => return Err(Error::InvalidTransition),
538        };
539        let checkpoint = self.identity.encode(AllocationRole::Target(&phase))?;
540        let complete = matches!(phase, TargetProgress::Ready);
541        self.target.map.insert(manifest_key(), checkpoint);
542        self.phase = phase;
543
544        Ok(complete)
545    }
546
547    /// Atomically retire source admission and publish the fully validated target.
548    /// The host selects the target allocation for subsequent ordinary opens.
549    /// Source rows remain preserved but closed: this is not an operational rollback
550    /// promise after target writes. Explicit `RetiredSource` cleanup may remove them.
551    /// # Errors
552    /// Refuses unless both validation passes have completed.
553    /// # Panics
554    /// Mutation failures or a later enclosing-message trap roll back both manifests.
555    pub fn publish(mut self) -> Result<Database<M>, Error> {
556        if !matches!(self.phase, TargetProgress::Ready) {
557            return Err(Error::InvalidTransition);
558        }
559        let retired = self.identity.encode(AllocationRole::Retired)?;
560        let live = live_manifest(self.identity.transition.target, self.identity.target);
561        self.source.map.insert(manifest_key(), retired);
562        self.target.map.insert(manifest_key(), live);
563
564        Ok(self.target)
565    }
566}
567
568/// Exclusive cleanup authority for an entire source collection retired by cutover.
569/// Admission binds the exact transition and both database incarnations. Cleanup
570/// never opens the target and never clears the source's retired manifest.
571pub struct RetiredSource<M: Memory> {
572    map: Map<M>,
573}
574
575impl<M: Memory> RetiredSource<M> {
576    /// Admit only the expected retired allocation, without decoding historical rows.
577    /// The host decides when preservation/recovery obligations permit deletion.
578    /// # Errors
579    /// Refuses live, copying, cancelled, foreign or malformed allocations intact.
580    /// # Panics
581    /// Supplier corruption traps without repair.
582    pub fn resume(
583        memory: RuntimeMemory<M>,
584        expected: &SchemaTransition,
585        source_incarnation: [u8; 16],
586        target_incarnation: [u8; 16],
587    ) -> Result<Self, Error> {
588        if memory.size() == 0 {
589            return Err(Error::Corrupt);
590        }
591        let map = Map::load(memory);
592        let (identity, role) = decode(&map.get(&manifest_key()).ok_or(Error::Corrupt)?)?;
593        if !matches!(role, AllocationRole::Retired)
594            || identity.transition != *expected
595            || identity.source != source_incarnation
596            || identity.target != target_incarnation
597        {
598            return Err(Error::InvalidTransition);
599        }
600
601        Ok(Self { map })
602    }
603
604    /// Delete at most 1..=32 retired entries, preserving the ownership manifest.
605    /// Return true when only that manifest remains. Repeated completion is a no-op.
606    /// Deletion itself records progress; no additional cursor or phase is stored.
607    /// This does not shrink physical memory, reset the allocation or reopen source.
608    /// # Errors
609    /// Refuses invalid limits before mutation.
610    /// # Panics
611    /// Supplier mutation failures trap; the IC rolls back the whole cleanup chunk.
612    pub fn cleanup_step(&mut self, limit: usize) -> Result<bool, Error> {
613        let (keys, complete) = cleanup_keys(&self.map, limit)?;
614        for key in &keys {
615            self.map.remove(key);
616        }
617
618        Ok(complete)
619    }
620}
621
622// Cancellation and retired cleanup share bounded selection, keeping their
623// different authority changes at the caller. Values are not decoded for deletion.
624fn cleanup_keys<M: Memory>(map: &Map<M>, limit: usize) -> Result<(Vec<StoreKey>, bool), Error> {
625    if !(1..=32).contains(&limit) {
626        return Err(Error::Limit);
627    }
628    let manifest = manifest_key();
629    let mut keys: Vec<_> = map
630        .keys()
631        .filter(|key| *key != manifest)
632        .take(limit + 1)
633        .collect();
634    let complete = keys.len() <= limit;
635    if !complete {
636        keys.pop();
637    }
638
639    Ok((keys, complete))
640}
641
642// Validate the physical collection in both directions. Forward row checks find
643// missing/wrong-owner indexes; reverse index checks find stale/extra entries.
644fn validate_page<M: Memory>(
645    map: &Map<M>,
646    schema: &Schema,
647    peer: (&Map<M>, &Schema),
648    after: Option<&StoreKey>,
649    limit: usize,
650) -> Result<Option<StoreKey>, Error> {
651    // Check every declared entity for missing metadata and equal counts for this
652    // key-preserving copy; target counts were rebuilt by atomic private inserts.
653    // Frozen allocations cannot change mid-pass.
654    if after.is_none() {
655        for entity in schema.entities() {
656            let state = read_entity_state(map, entity.id)?;
657
658            if peer.1.entity_by_id(entity.id).is_some() {
659                if state.count != read_entity_state(peer.0, entity.id)?.count {
660                    return Err(Error::Corrupt);
661                }
662            } else if state.count != 0 || state.revision != 0 {
663                // Only an added target entity can lack a peer. No copy operation owns its rows.
664                return Err(Error::Corrupt);
665            }
666        }
667    }
668    let lower = after.map_or(Bound::Unbounded, |key| Bound::Excluded(key.clone()));
669    let mut last = None;
670    let mut examined = 0;
671    for entry in map.range((lower, Bound::Unbounded)).take(limit) {
672        let key = entry.key();
673        if *key != manifest_key() {
674            let bytes = entry.value();
675            let id = u32::from_be_bytes(
676                key.get(1..crate::store::ENTITY_PREFIX_BYTES)
677                    .ok_or(Error::Corrupt)?
678                    .try_into()
679                    .map_err(|_| Error::Corrupt)?,
680            );
681            let entity = schema.entity_by_id(id).ok_or(Error::Corrupt)?;
682
683            match key.first() {
684                Some(1) if *key == entity_state_key(entity.id) => {
685                    if bytes.len() != 16 {
686                        return Err(Error::Corrupt);
687                    }
688                }
689                Some(2) => {
690                    let peer_entity = peer.1.entity_by_id(id).ok_or(Error::Corrupt)?;
691                    let info = entity.inspect_row(&bytes)?;
692                    let owner = info.key;
693                    if *key != row_key(entity.id, owner) {
694                        return Err(Error::Corrupt);
695                    }
696                    if entity.has_managed() {
697                        let other = peer.0.get(key).ok_or(Error::Corrupt)?;
698                        if crate::managed::values(entity, &bytes)?
699                            != crate::managed::values(peer_entity, &other)?
700                        {
701                            return Err(Error::ManagedField);
702                        }
703                    } else if !peer.0.contains_key(key) {
704                        return Err(Error::Corrupt);
705                    }
706                    for (index, _) in index_entries(entity, &info)? {
707                        let stored = map.get(&index).ok_or(Error::Corrupt)?;
708                        if RowKey::decode(&stored, entity.key_type()?)? != owner {
709                            return Err(Error::Corrupt);
710                        }
711                    }
712                    let mut required = BTreeSet::new();
713                    collect_references(entity, &info, &mut required)?;
714                    for (target, id) in required {
715                        validate_reference_target(map, schema, target, id)?;
716                    }
717                }
718                Some(3 | 4) => {
719                    let (owner, row) =
720                        read_index_owner(map, entity.id, entity.key_type()?, &bytes)?;
721                    validate_index_entry(entity, &entity.inspect_row(&row)?, owner, key)?;
722                }
723                _ => return Err(Error::Corrupt),
724            }
725        }
726        last = Some(key.clone());
727        examined += 1;
728    }
729
730    Ok(if examined == limit { last } else { None })
731}