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