Skip to main content

elevator_core/
snapshot.rs

1//! World snapshot for save/load functionality.
2//!
3//! Provides [`WorldSnapshot`](crate::snapshot::WorldSnapshot) which captures the full simulation state
4//! (all entities, components, groups, metrics, tick counter) in a
5//! serializable form. Games choose the serialization format via serde.
6//!
7//! Extension component *data* is included in the snapshot. After restoring,
8//! call [`Simulation::load_extensions_with`](crate::sim::Simulation::load_extensions_with)
9//! to register types and materialize the data.
10
11use crate::components::{
12    AccessControl, CarCall, DestinationQueue, Elevator, HallCall, Line, Patience, Position,
13    Preferences, Rider, Route, Stop, Velocity,
14};
15use crate::entity::EntityId;
16use crate::ids::GroupId;
17use crate::metrics::Metrics;
18use crate::stop::StopId;
19use crate::tagged_metrics::MetricTags;
20use serde::{Deserialize, Serialize};
21use std::collections::{BTreeMap, HashMap, HashSet};
22
23/// Serializable snapshot of a single entity's components.
24#[derive(Debug, Clone, Serialize, Deserialize)]
25pub struct EntitySnapshot {
26    /// The original `EntityId` (used for remapping cross-references on restore).
27    pub original_id: EntityId,
28    /// Position component (if present).
29    pub position: Option<Position>,
30    /// Velocity component (if present).
31    pub velocity: Option<Velocity>,
32    /// Elevator component (if present).
33    pub elevator: Option<Elevator>,
34    /// Stop component (if present).
35    pub stop: Option<Stop>,
36    /// Rider component (if present).
37    pub rider: Option<Rider>,
38    /// Route component (if present).
39    pub route: Option<Route>,
40    /// Line component (if present).
41    #[serde(default)]
42    pub line: Option<Line>,
43    /// Patience component (if present).
44    pub patience: Option<Patience>,
45    /// Preferences component (if present).
46    pub preferences: Option<Preferences>,
47    /// Access control component (if present).
48    #[serde(default)]
49    pub access_control: Option<AccessControl>,
50    /// Whether this entity is disabled.
51    pub disabled: bool,
52    /// Energy profile (if present, requires `energy` feature).
53    #[cfg(feature = "energy")]
54    #[serde(default)]
55    pub energy_profile: Option<crate::energy::EnergyProfile>,
56    /// Energy metrics (if present, requires `energy` feature).
57    #[cfg(feature = "energy")]
58    #[serde(default)]
59    pub energy_metrics: Option<crate::energy::EnergyMetrics>,
60    /// Service mode (if present).
61    #[serde(default)]
62    pub service_mode: Option<crate::components::ServiceMode>,
63    /// Destination queue (per-elevator; absent in legacy snapshots).
64    #[serde(default)]
65    pub destination_queue: Option<DestinationQueue>,
66    /// Car calls pressed inside this elevator (per-car; absent in legacy snapshots).
67    #[serde(default)]
68    pub car_calls: Vec<CarCall>,
69}
70
71/// Serializable snapshot of the entire simulation state.
72///
73/// Capture via [`Simulation::snapshot()`](crate::sim::Simulation::snapshot)
74/// and restore via [`WorldSnapshot::restore()`]. The game chooses the serde format
75/// (RON, JSON, bincode, etc.).
76///
77/// **Determinism:** the map fields below all use `BTreeMap` instead of
78/// `HashMap` so postcard/RON/JSON serialize entries in a deterministic
79/// (key-sorted) order. With `HashMap`, two snapshots of the same sim
80/// taken in different processes produced different bytes, defeating
81/// content-addressed caching and bit-equality replay (#254).
82///
83/// **Extension components are included** (via `extensions`); games must
84/// register types via `register_ext` before `restore()` to materialize them.
85/// **Custom resources** inserted via `world.insert_resource` are NOT
86/// snapshotted — only the built-in `MetricTags` resource is captured
87/// in `metric_tags`. Games using custom resources must save and restore
88/// them out-of-band (#296).
89#[derive(Debug, Clone, Serialize, Deserialize)]
90pub struct WorldSnapshot {
91    /// Schema version of this snapshot. Bumped on incompatible changes
92    /// to the snapshot layout. Loading a snapshot whose version differs
93    /// from the current crate's expected version returns
94    /// [`SimError::SnapshotVersion`](crate::error::SimError::SnapshotVersion).
95    /// Legacy snapshots default to `0` (#295).
96    #[serde(default)]
97    pub version: u32,
98    /// Current simulation tick.
99    pub tick: u64,
100    /// Time delta per tick.
101    pub dt: f64,
102    /// All entities indexed by position in this vec.
103    /// `EntityId`s are regenerated on restore.
104    pub entities: Vec<EntitySnapshot>,
105    /// Elevator groups (references into entities by index).
106    pub groups: Vec<GroupSnapshot>,
107    /// Stop ID → entity index mapping. `BTreeMap` for deterministic
108    /// snapshot bytes across processes (#254).
109    pub stop_lookup: BTreeMap<StopId, usize>,
110    /// Global metrics at snapshot time.
111    pub metrics: Metrics,
112    /// Per-tag metric accumulators and entity-tag associations.
113    pub metric_tags: MetricTags,
114    /// Serialized extension component data: name → (`EntityId` → RON string).
115    /// Both maps are `BTreeMap` for deterministic snapshot bytes (#254).
116    pub extensions: BTreeMap<String, BTreeMap<EntityId, String>>,
117    /// Ticks per second (for `TimeAdapter` reconstruction).
118    pub ticks_per_second: f64,
119    /// All pending hall calls across every stop. Absent in legacy snapshots.
120    #[serde(default)]
121    pub hall_calls: Vec<HallCall>,
122    /// Rolling per-stop arrival log. Empty in legacy snapshots; on
123    /// restore the log's `(tick, stop)` entries have their stop IDs
124    /// remapped through `id_remap` so they line up with the newly
125    /// allocated entity IDs.
126    #[serde(default)]
127    pub arrival_log: crate::arrival_log::ArrivalLog,
128    /// Retention window for the arrival log (ticks). Captured so a
129    /// host-configured value (e.g. via
130    /// `Simulation::set_arrival_log_retention_ticks`) survives
131    /// snapshot round-trip; legacy snapshots default to
132    /// [`DEFAULT_ARRIVAL_WINDOW_TICKS`](crate::arrival_log::DEFAULT_ARRIVAL_WINDOW_TICKS).
133    #[serde(default)]
134    pub arrival_log_retention: crate::arrival_log::ArrivalLogRetention,
135    /// Mirror of `arrival_log` keyed on rider *destination* — what
136    /// powers the `DownPeak` classifier branch. Same remap semantics
137    /// as `arrival_log` on restore. Empty in legacy snapshots; the
138    /// detector silently under-classifies `DownPeak` until the post-
139    /// restore log refills.
140    #[serde(default)]
141    pub destination_log: crate::arrival_log::DestinationLog,
142    /// Traffic-mode classifier state. Carries the current mode,
143    /// thresholds, and last-update tick across snapshot round-trip
144    /// so a restored sim doesn't momentarily reset to `Idle` when
145    /// the metrics phase hasn't run yet.
146    #[serde(default)]
147    pub traffic_detector: crate::traffic_detector::TrafficDetector,
148    /// Per-car reposition cooldown eligibility. Entries map to the
149    /// tick when each car next becomes eligible for reposition. Empty
150    /// in legacy snapshots; on restore the map is remapped through
151    /// `id_remap` to match newly-allocated entity IDs.
152    #[serde(default)]
153    pub reposition_cooldowns: crate::dispatch::reposition::RepositionCooldowns,
154    /// Per-group serialized dispatcher configuration produced by
155    /// [`crate::dispatch::DispatchStrategy::snapshot_config`] and
156    /// replayed via
157    /// [`crate::dispatch::DispatchStrategy::restore_config`] on
158    /// restore. Round-trips the tunable weights configured via
159    /// `with_*` builder methods (e.g. `EtdDispatch::with_delay_weight`)
160    /// that [`BuiltinStrategy::instantiate`](crate::dispatch::BuiltinStrategy::instantiate)
161    /// can't reconstruct because it always calls `::new()`. Absent /
162    /// empty in legacy snapshots — they restore to default weights,
163    /// matching pre-fix behaviour.
164    #[serde(default)]
165    pub dispatch_config: BTreeMap<GroupId, String>,
166}
167
168/// Per-line snapshot info within a group.
169#[derive(Debug, Clone, Serialize, Deserialize)]
170pub struct LineSnapshotInfo {
171    /// Index into the `entities` vec for the line entity.
172    pub entity_index: usize,
173    /// Indices into the `entities` vec for elevators on this line.
174    pub elevator_indices: Vec<usize>,
175    /// Indices into the `entities` vec for stops served by this line.
176    pub stop_indices: Vec<usize>,
177}
178
179/// Serializable representation of an elevator group.
180#[derive(Debug, Clone, Serialize, Deserialize)]
181pub struct GroupSnapshot {
182    /// Group identifier.
183    pub id: GroupId,
184    /// Group name.
185    pub name: String,
186    /// Indices into the `entities` vec for elevators in this group.
187    pub elevator_indices: Vec<usize>,
188    /// Indices into the `entities` vec for stops in this group.
189    pub stop_indices: Vec<usize>,
190    /// The dispatch strategy used by this group.
191    pub strategy: crate::dispatch::BuiltinStrategy,
192    /// Per-line snapshot data. Empty in legacy snapshots.
193    #[serde(default)]
194    pub lines: Vec<LineSnapshotInfo>,
195    /// Optional repositioning strategy for idle elevators.
196    #[serde(default)]
197    pub reposition: Option<crate::dispatch::BuiltinReposition>,
198    /// Hall call mode for this group. Legacy snapshots default to `Classic`.
199    #[serde(default)]
200    pub hall_call_mode: crate::dispatch::HallCallMode,
201    /// Controller ack latency in ticks. Legacy snapshots default to `0`.
202    #[serde(default)]
203    pub ack_latency_ticks: u32,
204}
205
206/// Pending extension data from a snapshot, awaiting type registration.
207///
208/// Stored as a world resource after `restore()`. Call
209/// `sim.load_extensions()` after registering extension types to
210/// deserialize the data.
211pub(crate) struct PendingExtensions(pub(crate) BTreeMap<String, BTreeMap<EntityId, String>>);
212
213/// Factory function type for instantiating custom dispatch strategies by name.
214type CustomStrategyFactory<'a> =
215    Option<&'a dyn Fn(&str) -> Option<Box<dyn crate::dispatch::DispatchStrategy>>>;
216
217impl WorldSnapshot {
218    /// Schema version this build of `elevator-core` writes and accepts.
219    ///
220    /// Compare against [`WorldSnapshot::version`] to decide whether a
221    /// snapshot needs forward migration before [`WorldSnapshot::restore`]
222    /// will accept it.
223    pub const CURRENT_SCHEMA_VERSION: u32 = SNAPSHOT_SCHEMA_VERSION;
224
225    /// Forward-migrate a snapshot to [`CURRENT_SCHEMA_VERSION`](Self::CURRENT_SCHEMA_VERSION).
226    ///
227    /// `restore` rejects mismatched schema versions hard so silent
228    /// `#[serde(default)]` field-filling can't mask a mismatch. Callers
229    /// that want to load older snapshots route them through this method
230    /// first:
231    ///
232    /// ```no_run
233    /// # use elevator_core::snapshot::WorldSnapshot;
234    /// # fn load(snap: WorldSnapshot) -> Result<(), elevator_core::error::SimError> {
235    /// let sim = snap.migrate()?.restore(None)?;
236    /// # let _ = sim;
237    /// # Ok(()) }
238    /// ```
239    ///
240    /// Future schema bumps wire their step-up migrations into the match
241    /// arm below; each step consumes a snapshot at version `n` and
242    /// produces one at `n + 1`. The outer `while` drives the chain to
243    /// [`CURRENT_SCHEMA_VERSION`](Self::CURRENT_SCHEMA_VERSION) with
244    /// O(1) stack depth regardless of how far behind the input is.
245    ///
246    /// # Errors
247    ///
248    /// Returns [`SimError::SnapshotVersion`](crate::error::SimError::SnapshotVersion)
249    /// for snapshots from a version this build doesn't know how to
250    /// migrate (either `version > CURRENT_SCHEMA_VERSION`, or
251    /// `version < CURRENT_SCHEMA_VERSION` with no migration path
252    /// registered).
253    pub fn migrate(self) -> Result<Self, crate::error::SimError> {
254        // Snapshots from a future build can't be down-migrated — the
255        // newer build defines what the new shape *is*.
256        if self.version > Self::CURRENT_SCHEMA_VERSION {
257            return Err(crate::error::SimError::SnapshotVersion {
258                saved: format!("schema {}", self.version),
259                current: format!("schema {}", Self::CURRENT_SCHEMA_VERSION),
260            });
261        }
262        if self.version == Self::CURRENT_SCHEMA_VERSION {
263            return Ok(self);
264        }
265        // Schema is at v1 today, so no step-up arms exist; any
266        // version below current with no migration path errors out.
267        // The intended shape once schema bumps land is an iterative
268        // step_up loop with O(1) stack depth regardless of how many
269        // schema versions an archived snapshot has to traverse:
270        //
271        //     let mut snap = self;
272        //     while snap.version < Self::CURRENT_SCHEMA_VERSION {
273        //         snap = step_up_one(snap)?;
274        //     }
275        //     Ok(snap)
276        //
277        // where `step_up_one` matches on `snap.version` and emits one
278        // arm per `n -> n + 1` upgrade.
279        Err(crate::error::SimError::SnapshotVersion {
280            saved: format!("schema {}", self.version),
281            current: format!("schema {}", Self::CURRENT_SCHEMA_VERSION),
282        })
283    }
284
285    /// Restore a simulation from this snapshot.
286    ///
287    /// Built-in strategies (Scan, Look, `NearestCar`, ETD) are auto-restored.
288    /// For `Custom` strategies, provide a factory function that maps strategy
289    /// names to instances. Pass `None` if only using built-in strategies.
290    ///
291    /// # Errors
292    /// Returns [`SimError::UnresolvedCustomStrategy`](crate::error::SimError::UnresolvedCustomStrategy)
293    /// if a snapshot group uses a `Custom` strategy and the factory returns `None`.
294    ///
295    /// To restore extension components, call
296    /// [`Simulation::load_extensions_with`](crate::sim::Simulation::load_extensions_with)
297    /// on the returned simulation.
298    pub fn restore(
299        self,
300        custom_strategy_factory: CustomStrategyFactory<'_>,
301    ) -> Result<crate::sim::Simulation, crate::error::SimError> {
302        use crate::world::{SortedStops, World};
303
304        // Reject snapshots from incompatible schema versions. Without this
305        // guard, `#[serde(default)]` on newly-added fields would silently
306        // fill them in and mask the mismatch. The bytes envelope path
307        // separately checks the crate semver string.
308        if self.version != SNAPSHOT_SCHEMA_VERSION {
309            return Err(crate::error::SimError::SnapshotVersion {
310                saved: format!("schema {}", self.version),
311                current: format!("schema {SNAPSHOT_SCHEMA_VERSION}"),
312            });
313        }
314
315        let mut world = World::new();
316
317        // Phase 1: spawn all entities and build old→new EntityId mapping.
318        let (index_to_id, id_remap) = Self::spawn_entities(&mut world, &self.entities);
319
320        // Phase 2: attach components with remapped EntityIds.
321        Self::attach_components(&mut world, &self.entities, &index_to_id, &id_remap);
322
323        // Phase 2b: re-register hall calls (cross-reference stops/cars/riders).
324        self.attach_hall_calls(&mut world, &id_remap);
325
326        // Rebuild sorted stops index.
327        let mut sorted: Vec<(f64, EntityId)> = world
328            .iter_stops()
329            .map(|(eid, stop)| (stop.position, eid))
330            .collect();
331        sorted.sort_by(|a, b| a.0.total_cmp(&b.0));
332        world.insert_resource(SortedStops(sorted));
333
334        // Rebuild groups, stop lookup, dispatchers, and extensions (borrows self).
335        let (mut groups, stop_lookup, dispatchers, strategy_ids) =
336            self.rebuild_groups_and_dispatchers(&index_to_id, custom_strategy_factory)?;
337
338        Self::fix_legacy_line_entities(&mut groups, &mut world);
339
340        // Resource installation moves several fields out of self via partial
341        // moves; remaining fields (dispatch_config, groups, entities, hall_calls,
342        // metrics, etc.) stay accessible for the construction steps below.
343        Self::install_runtime_resources(
344            &mut world,
345            &id_remap,
346            self.tick,
347            &self.extensions,
348            self.metric_tags,
349            self.arrival_log,
350            self.arrival_log_retention,
351            self.destination_log,
352            self.traffic_detector,
353            self.reposition_cooldowns,
354        );
355
356        let mut sim = crate::sim::Simulation::from_parts(
357            world,
358            self.tick,
359            self.dt,
360            groups,
361            stop_lookup,
362            dispatchers,
363            strategy_ids,
364            self.metrics,
365            self.ticks_per_second,
366        );
367
368        Self::replay_dispatcher_tuning(&mut sim, &self.dispatch_config);
369        Self::restore_reposition_strategies(&mut sim, &self.groups);
370
371        Self::emit_dangling_warnings(
372            &self.entities,
373            &self.hall_calls,
374            &id_remap,
375            self.tick,
376            &mut sim,
377        );
378
379        Ok(sim)
380    }
381
382    /// Replace synthetic legacy `LineInfo` entries (entity = `EntityId::default()`)
383    /// with real line entities spawned in the world. Pre-line snapshots stored
384    /// only group-level elevator/stop indices; the legacy single-line `LineInfo`
385    /// is materialised here so dispatch and rendering see a real entity.
386    fn fix_legacy_line_entities(
387        groups: &mut [crate::dispatch::ElevatorGroup],
388        world: &mut crate::world::World,
389    ) {
390        for group in groups.iter_mut() {
391            let group_id = group.id();
392            for line_info in group.lines_mut().iter_mut() {
393                if line_info.entity() != EntityId::default() {
394                    continue;
395                }
396                let (min_pos, max_pos) = line_info
397                    .serves()
398                    .iter()
399                    .filter_map(|&sid| world.stop(sid).map(|s| s.position))
400                    .fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), p| {
401                        (lo.min(p), hi.max(p))
402                    });
403                let line_eid = world.spawn();
404                world.set_line(
405                    line_eid,
406                    Line {
407                        name: format!("Legacy-{group_id}"),
408                        group: group_id,
409                        orientation: crate::components::Orientation::Vertical,
410                        position: None,
411                        min_position: if min_pos.is_finite() { min_pos } else { 0.0 },
412                        max_position: if max_pos.is_finite() { max_pos } else { 0.0 },
413                        max_cars: None,
414                    },
415                );
416                for &elev_eid in line_info.elevators() {
417                    if let Some(car) = world.elevator_mut(elev_eid) {
418                        car.line = line_eid;
419                    }
420                }
421                line_info.set_entity(line_eid);
422            }
423        }
424    }
425
426    /// Insert all post-entity world resources, remapping `EntityId`s where
427    /// they cross-reference. Without these `PredictiveParking`,
428    /// `DispatchManifest::arrivals_at`, the down-peak classifier branch,
429    /// host-configured retention, and reposition cooldowns silently no-op
430    /// or fall back to defaults post-restore.
431    #[allow(clippy::too_many_arguments)]
432    fn install_runtime_resources(
433        world: &mut crate::world::World,
434        id_remap: &HashMap<EntityId, EntityId>,
435        tick: u64,
436        extensions: &BTreeMap<String, BTreeMap<EntityId, String>>,
437        metric_tags: MetricTags,
438        arrival_log: crate::arrival_log::ArrivalLog,
439        arrival_log_retention: crate::arrival_log::ArrivalLogRetention,
440        destination_log: crate::arrival_log::DestinationLog,
441        traffic_detector: crate::traffic_detector::TrafficDetector,
442        reposition_cooldowns: crate::dispatch::reposition::RepositionCooldowns,
443    ) {
444        let remapped_exts = Self::remap_extensions(extensions, id_remap);
445        world.insert_resource(PendingExtensions(remapped_exts));
446
447        let mut tags = metric_tags;
448        tags.remap_entity_ids(id_remap);
449        world.insert_resource(tags);
450
451        let mut log = arrival_log;
452        log.remap_entity_ids(id_remap);
453        world.insert_resource(log);
454        world.insert_resource(crate::arrival_log::CurrentTick(tick));
455        world.insert_resource(arrival_log_retention);
456
457        let mut dest_log = destination_log;
458        dest_log.remap_entity_ids(id_remap);
459        world.insert_resource(dest_log);
460
461        // Detector is re-inserted last-writer-wins so the *classified* state
462        // carries forward; refresh_traffic_detector updates on the next
463        // metrics phase with fresh counts.
464        world.insert_resource(traffic_detector);
465
466        let mut cooldowns = reposition_cooldowns;
467        cooldowns.remap_entity_ids(id_remap);
468        world.insert_resource(cooldowns);
469    }
470
471    /// Replay per-group dispatcher tuning captured in the snapshot. Built-ins
472    /// with `with_*` builders override `snapshot_config`/`restore_config` to
473    /// round-trip their weights; strategies that don't override silently skip
474    /// (default `restore_config` is `Ok(())`), preserving pre-fix behaviour. A
475    /// deserialization failure surfaces as an event rather than a hard error
476    /// — the restored sim runs with defaults, same as a legacy snapshot.
477    fn replay_dispatcher_tuning(
478        sim: &mut crate::sim::Simulation,
479        dispatch_config: &std::collections::BTreeMap<GroupId, String>,
480    ) {
481        for (gid, serialized) in dispatch_config {
482            if let Some(dispatcher) = sim.dispatchers_mut().get_mut(gid)
483                && let Err(err) = dispatcher.restore_config(serialized)
484            {
485                sim.push_event(crate::events::Event::DispatchConfigNotRestored {
486                    group: *gid,
487                    reason: err,
488                });
489            }
490        }
491    }
492
493    /// Restore reposition strategies from group snapshots, emitting
494    /// [`Event::RepositionStrategyNotRestored`](crate::events::Event::RepositionStrategyNotRestored)
495    /// when an id can't be re-instantiated.
496    fn restore_reposition_strategies(sim: &mut crate::sim::Simulation, groups: &[GroupSnapshot]) {
497        for gs in groups {
498            let Some(ref repo_id) = gs.reposition else {
499                continue;
500            };
501            if let Some(strategy) = repo_id.instantiate() {
502                sim.set_reposition(gs.id, strategy, repo_id.clone());
503            } else {
504                sim.push_event(crate::events::Event::RepositionStrategyNotRestored {
505                    group: gs.id,
506                });
507            }
508        }
509    }
510
511    /// Spawn entities in the world and build the old→new `EntityId` mapping.
512    fn spawn_entities(
513        world: &mut crate::world::World,
514        entities: &[EntitySnapshot],
515    ) -> (Vec<EntityId>, HashMap<EntityId, EntityId>) {
516        let mut index_to_id: Vec<EntityId> = Vec::with_capacity(entities.len());
517        let mut id_remap: HashMap<EntityId, EntityId> = HashMap::new();
518        for snap in entities {
519            let new_id = world.spawn();
520            index_to_id.push(new_id);
521            id_remap.insert(snap.original_id, new_id);
522        }
523        (index_to_id, id_remap)
524    }
525
526    /// Attach components to spawned entities, remapping cross-references.
527    fn attach_components(
528        world: &mut crate::world::World,
529        entities: &[EntitySnapshot],
530        index_to_id: &[EntityId],
531        id_remap: &HashMap<EntityId, EntityId>,
532    ) {
533        let remap = |old: EntityId| -> EntityId { id_remap.get(&old).copied().unwrap_or(old) };
534        let remap_opt = |old: Option<EntityId>| -> Option<EntityId> { old.map(&remap) };
535
536        for (i, snap) in entities.iter().enumerate() {
537            let eid = index_to_id[i];
538
539            if let Some(pos) = snap.position {
540                world.set_position(eid, pos);
541            }
542            if let Some(vel) = snap.velocity {
543                world.set_velocity(eid, vel);
544            }
545            if let Some(ref elev) = snap.elevator {
546                let mut e = elev.clone();
547                e.riders = e.riders.iter().map(|&r| remap(r)).collect();
548                e.target_stop = remap_opt(e.target_stop);
549                e.line = remap(e.line);
550                e.restricted_stops = e.restricted_stops.iter().map(|&s| remap(s)).collect();
551                e.phase = match e.phase {
552                    crate::components::ElevatorPhase::MovingToStop(s) => {
553                        crate::components::ElevatorPhase::MovingToStop(remap(s))
554                    }
555                    crate::components::ElevatorPhase::Repositioning(s) => {
556                        crate::components::ElevatorPhase::Repositioning(remap(s))
557                    }
558                    other => other,
559                };
560                world.set_elevator(eid, e);
561            }
562            if let Some(ref stop) = snap.stop {
563                world.set_stop(eid, stop.clone());
564            }
565            if let Some(ref rider) = snap.rider {
566                use crate::components::RiderPhase;
567                let mut r = rider.clone();
568                r.current_stop = remap_opt(r.current_stop);
569                r.phase = match r.phase {
570                    RiderPhase::Boarding(e) => RiderPhase::Boarding(remap(e)),
571                    RiderPhase::Riding(e) => RiderPhase::Riding(remap(e)),
572                    RiderPhase::Exiting(e) => RiderPhase::Exiting(remap(e)),
573                    other => other,
574                };
575                world.set_rider(eid, r);
576            }
577            if let Some(ref route) = snap.route {
578                let mut rt = route.clone();
579                for leg in &mut rt.legs {
580                    leg.from = remap(leg.from);
581                    leg.to = remap(leg.to);
582                    if let crate::components::TransportMode::Line(ref mut l) = leg.via {
583                        *l = remap(*l);
584                    }
585                }
586                world.set_route(eid, rt);
587            }
588            if let Some(ref line) = snap.line {
589                world.set_line(eid, line.clone());
590            }
591            if let Some(patience) = snap.patience {
592                world.set_patience(eid, patience);
593            }
594            if let Some(prefs) = snap.preferences {
595                world.set_preferences(eid, prefs);
596            }
597            if let Some(ref ac) = snap.access_control {
598                let remapped =
599                    AccessControl::new(ac.allowed_stops().iter().map(|&s| remap(s)).collect());
600                world.set_access_control(eid, remapped);
601            }
602            if snap.disabled {
603                world.disable(eid);
604            }
605            #[cfg(feature = "energy")]
606            if let Some(ref profile) = snap.energy_profile {
607                world.set_energy_profile(eid, profile.clone());
608            }
609            #[cfg(feature = "energy")]
610            if let Some(ref em) = snap.energy_metrics {
611                world.set_energy_metrics(eid, em.clone());
612            }
613            if let Some(mode) = snap.service_mode {
614                world.set_service_mode(eid, mode);
615            }
616            if let Some(ref dq) = snap.destination_queue {
617                use crate::components::DestinationQueue as DQ;
618                let mut new_dq = DQ::new();
619                for &e in dq.queue() {
620                    new_dq.push_back(remap(e));
621                }
622                world.set_destination_queue(eid, new_dq);
623            }
624            Self::attach_car_calls(world, eid, &snap.car_calls, id_remap);
625        }
626    }
627
628    /// Re-register per-car floor button presses after entities are spawned.
629    fn attach_car_calls(
630        world: &mut crate::world::World,
631        car: EntityId,
632        car_calls: &[CarCall],
633        id_remap: &HashMap<EntityId, EntityId>,
634    ) {
635        if car_calls.is_empty() {
636            return;
637        }
638        let remap = |old: EntityId| -> EntityId { id_remap.get(&old).copied().unwrap_or(old) };
639        let Some(slot) = world.car_calls_mut(car) else {
640            return;
641        };
642        for cc in car_calls {
643            let mut c = cc.clone();
644            c.car = car;
645            c.floor = remap(c.floor);
646            c.pending_riders = c.pending_riders.iter().map(|&r| remap(r)).collect();
647            slot.push(c);
648        }
649    }
650
651    /// Re-register hall calls in the world after entities are spawned.
652    ///
653    /// `HallCall` cross-references stops, cars, riders, and optional
654    /// destinations — all `EntityId`s must be remapped through `id_remap`.
655    /// Pre-15.23 snapshots stored a single `assigned_car` field, silently
656    /// dropped by `#[serde(default)]` on `assigned_cars_by_line`; the
657    /// next dispatch pass repopulates the empty map, so no explicit
658    /// migration is attempted here.
659    fn attach_hall_calls(
660        &self,
661        world: &mut crate::world::World,
662        id_remap: &HashMap<EntityId, EntityId>,
663    ) {
664        let remap = |old: EntityId| -> EntityId { id_remap.get(&old).copied().unwrap_or(old) };
665        let remap_opt = |old: Option<EntityId>| -> Option<EntityId> { old.map(&remap) };
666        for hc in &self.hall_calls {
667            let mut c = hc.clone();
668            c.stop = remap(c.stop);
669            c.destination = remap_opt(c.destination);
670            c.assigned_cars_by_line = c
671                .assigned_cars_by_line
672                .iter()
673                .map(|(&line, &car)| (remap(line), remap(car)))
674                .collect();
675            c.pending_riders = c.pending_riders.iter().map(|&r| remap(r)).collect();
676            world.set_hall_call(c);
677        }
678    }
679
680    /// Rebuild groups, stop lookup, and dispatchers from snapshot data.
681    #[allow(clippy::type_complexity)]
682    fn rebuild_groups_and_dispatchers(
683        &self,
684        index_to_id: &[EntityId],
685        custom_strategy_factory: CustomStrategyFactory<'_>,
686    ) -> Result<
687        (
688            Vec<crate::dispatch::ElevatorGroup>,
689            HashMap<StopId, EntityId>,
690            std::collections::BTreeMap<GroupId, Box<dyn crate::dispatch::DispatchStrategy>>,
691            std::collections::BTreeMap<GroupId, crate::dispatch::BuiltinStrategy>,
692        ),
693        crate::error::SimError,
694    > {
695        use crate::dispatch::ElevatorGroup;
696
697        let groups: Vec<ElevatorGroup> = self
698            .groups
699            .iter()
700            .map(|gs| {
701                let elevator_entities: Vec<EntityId> = gs
702                    .elevator_indices
703                    .iter()
704                    .filter_map(|&i| index_to_id.get(i).copied())
705                    .collect();
706                let stop_entities: Vec<EntityId> = gs
707                    .stop_indices
708                    .iter()
709                    .filter_map(|&i| index_to_id.get(i).copied())
710                    .collect();
711
712                let lines = if gs.lines.is_empty() {
713                    // Legacy snapshots have no per-line data; create a single
714                    // synthetic LineInfo containing all elevators and stops.
715                    vec![crate::dispatch::LineInfo::new(
716                        EntityId::default(),
717                        elevator_entities,
718                        stop_entities,
719                    )]
720                } else {
721                    gs.lines
722                        .iter()
723                        .filter_map(|lsi| {
724                            let entity = index_to_id.get(lsi.entity_index).copied()?;
725                            Some(crate::dispatch::LineInfo::new(
726                                entity,
727                                lsi.elevator_indices
728                                    .iter()
729                                    .filter_map(|&i| index_to_id.get(i).copied())
730                                    .collect(),
731                                lsi.stop_indices
732                                    .iter()
733                                    .filter_map(|&i| index_to_id.get(i).copied())
734                                    .collect(),
735                            ))
736                        })
737                        .collect()
738                };
739
740                ElevatorGroup::new(gs.id, gs.name.clone(), lines)
741                    .with_hall_call_mode(gs.hall_call_mode)
742                    .with_ack_latency_ticks(gs.ack_latency_ticks)
743            })
744            .collect();
745
746        let stop_lookup: HashMap<StopId, EntityId> = self
747            .stop_lookup
748            .iter()
749            .filter_map(|(sid, &idx)| index_to_id.get(idx).map(|&eid| (*sid, eid)))
750            .collect();
751
752        let mut dispatchers = std::collections::BTreeMap::new();
753        let mut strategy_ids = std::collections::BTreeMap::new();
754        for (gs, group) in self.groups.iter().zip(groups.iter()) {
755            let strategy: Box<dyn crate::dispatch::DispatchStrategy> =
756                if let Some(builtin) = gs.strategy.instantiate() {
757                    builtin
758                } else if let crate::dispatch::BuiltinStrategy::Custom(ref name) = gs.strategy {
759                    custom_strategy_factory
760                        .and_then(|f| f(name))
761                        .ok_or_else(|| crate::error::SimError::UnresolvedCustomStrategy {
762                            name: name.clone(),
763                            group: group.id(),
764                        })?
765                } else {
766                    Box::new(crate::dispatch::scan::ScanDispatch::new())
767                };
768            dispatchers.insert(group.id(), strategy);
769            strategy_ids.insert(group.id(), gs.strategy.clone());
770        }
771
772        Ok((groups, stop_lookup, dispatchers, strategy_ids))
773    }
774
775    /// Remap `EntityId`s in extension data using the old→new mapping.
776    fn remap_extensions(
777        extensions: &BTreeMap<String, BTreeMap<EntityId, String>>,
778        id_remap: &HashMap<EntityId, EntityId>,
779    ) -> BTreeMap<String, BTreeMap<EntityId, String>> {
780        extensions
781            .iter()
782            .map(|(name, entries)| {
783                let remapped: BTreeMap<EntityId, String> = entries
784                    .iter()
785                    .map(|(old_id, data)| {
786                        let new_id = id_remap.get(old_id).copied().unwrap_or(*old_id);
787                        (new_id, data.clone())
788                    })
789                    .collect();
790                (name.clone(), remapped)
791            })
792            .collect()
793    }
794
795    /// Emit `SnapshotDanglingReference` events for entity IDs not in `id_remap`.
796    fn emit_dangling_warnings(
797        entities: &[EntitySnapshot],
798        hall_calls: &[HallCall],
799        id_remap: &HashMap<EntityId, EntityId>,
800        tick: u64,
801        sim: &mut crate::sim::Simulation,
802    ) {
803        let mut seen = HashSet::new();
804        let mut check = |old: EntityId| {
805            if !id_remap.contains_key(&old) && seen.insert(old) {
806                sim.push_event(crate::events::Event::SnapshotDanglingReference {
807                    stale_id: old,
808                    tick,
809                });
810            }
811        };
812        for snap in entities {
813            Self::collect_referenced_ids(snap, &mut check);
814        }
815        for hc in hall_calls {
816            check(hc.stop);
817            for (&line, &car) in &hc.assigned_cars_by_line {
818                check(line);
819                check(car);
820            }
821            if let Some(dest) = hc.destination {
822                check(dest);
823            }
824            for &rider in &hc.pending_riders {
825                check(rider);
826            }
827        }
828    }
829
830    /// Visit all cross-referenced `EntityId`s inside an entity snapshot.
831    fn collect_referenced_ids(snap: &EntitySnapshot, mut visit: impl FnMut(EntityId)) {
832        if let Some(ref elev) = snap.elevator {
833            for &r in &elev.riders {
834                visit(r);
835            }
836            if let Some(t) = elev.target_stop {
837                visit(t);
838            }
839            visit(elev.line);
840            match elev.phase {
841                crate::components::ElevatorPhase::MovingToStop(s)
842                | crate::components::ElevatorPhase::Repositioning(s) => visit(s),
843                _ => {}
844            }
845            for &s in &elev.restricted_stops {
846                visit(s);
847            }
848        }
849        if let Some(ref rider) = snap.rider {
850            if let Some(s) = rider.current_stop {
851                visit(s);
852            }
853            match rider.phase {
854                crate::components::RiderPhase::Boarding(e)
855                | crate::components::RiderPhase::Riding(e)
856                | crate::components::RiderPhase::Exiting(e) => visit(e),
857                _ => {}
858            }
859        }
860        if let Some(ref route) = snap.route {
861            for leg in &route.legs {
862                visit(leg.from);
863                visit(leg.to);
864                if let crate::components::TransportMode::Line(l) = leg.via {
865                    visit(l);
866                }
867            }
868        }
869        if let Some(ref ac) = snap.access_control {
870            for &s in ac.allowed_stops() {
871                visit(s);
872            }
873        }
874        if let Some(ref dq) = snap.destination_queue {
875            for &e in dq.queue() {
876                visit(e);
877            }
878        }
879        for cc in &snap.car_calls {
880            visit(cc.floor);
881            for &r in &cc.pending_riders {
882                visit(r);
883            }
884        }
885    }
886}
887
888/// Magic bytes identifying a postcard snapshot blob.
889const SNAPSHOT_MAGIC: [u8; 8] = *b"ELEVSNAP";
890
891/// Schema version for [`WorldSnapshot`]. Bump on incompatible layout
892/// changes so RON/JSON restore can reject older snapshots loudly
893/// instead of silently filling new fields with `#[serde(default)]`.
894///
895/// See `docs/src/snapshot-versioning.md` for the full bump-trigger
896/// policy, the asymmetry between this `u32` and the crate-version
897/// string in the bytes envelope, and the migration path.
898const SNAPSHOT_SCHEMA_VERSION: u32 = 1;
899
900/// Byte-level snapshot envelope: magic + crate version + payload.
901///
902/// Serialized via postcard. The magic and version fields are checked on
903/// restore to reject blobs from other tools or from a different
904/// `elevator-core` version.
905#[derive(Debug, Serialize, Deserialize)]
906struct SnapshotEnvelope {
907    /// Magic bytes; must equal [`SNAPSHOT_MAGIC`] or the blob is rejected.
908    magic: [u8; 8],
909    /// `elevator-core` crate version that produced the blob.
910    version: String,
911    /// The captured simulation state.
912    payload: WorldSnapshot,
913}
914
915impl crate::sim::Simulation {
916    /// Create a serializable snapshot of the current simulation state.
917    ///
918    /// The snapshot captures all entities, components, groups, metrics,
919    /// the tick counter, and extension component data (game must
920    /// re-register types via `register_ext` before `restore`).
921    /// Custom resources inserted via `world.insert_resource` are NOT
922    /// captured — games using them must save/restore separately (#296).
923    ///
924    /// **Mid-tick safety:** `snapshot()` returns a snapshot regardless
925    /// of whether you are mid-tick (between phase calls in the substep
926    /// API). For substep callers that care about event-bus state, use
927    /// [`try_snapshot`](Self::try_snapshot) which returns
928    /// [`SimError::MidTickSnapshot`](crate::error::SimError::MidTickSnapshot)
929    /// when invoked between `run_*` and `advance_tick`. (#297)
930    #[must_use]
931    #[allow(clippy::too_many_lines)]
932    pub fn snapshot(&self) -> WorldSnapshot {
933        self.snapshot_inner()
934    }
935
936    /// Like [`snapshot`](Self::snapshot) but returns
937    /// [`SimError::MidTickSnapshot`](crate::error::SimError::MidTickSnapshot)
938    /// when called between phases of an in-progress tick. (#297)
939    ///
940    /// # Errors
941    ///
942    /// Returns [`SimError::MidTickSnapshot`](crate::error::SimError::MidTickSnapshot)
943    /// when invoked between a `run_*` phase call and the matching
944    /// `advance_tick`.
945    pub fn try_snapshot(&self) -> Result<WorldSnapshot, crate::error::SimError> {
946        if self.tick_in_progress {
947            return Err(crate::error::SimError::MidTickSnapshot);
948        }
949        Ok(self.snapshot())
950    }
951
952    /// Internal snapshot builder shared by [`snapshot`](Self::snapshot)
953    /// and [`try_snapshot`](Self::try_snapshot). Holds the line-count
954    /// allow so the public methods remain visible in nursery lints.
955    #[allow(clippy::too_many_lines)]
956    fn snapshot_inner(&self) -> WorldSnapshot {
957        let world = self.world();
958
959        // Build entity index: map EntityId → position in vec.
960        let all_ids: Vec<EntityId> = world.alive.keys().collect();
961        let id_to_index: HashMap<EntityId, usize> = all_ids
962            .iter()
963            .copied()
964            .enumerate()
965            .map(|(i, e)| (e, i))
966            .collect();
967
968        // Snapshot each entity.
969        let entities: Vec<EntitySnapshot> = all_ids
970            .iter()
971            .map(|&eid| EntitySnapshot {
972                original_id: eid,
973                position: world.position(eid).copied(),
974                velocity: world.velocity(eid).copied(),
975                elevator: world.elevator(eid).cloned(),
976                stop: world.stop(eid).cloned(),
977                rider: world.rider(eid).cloned(),
978                route: world.route(eid).cloned(),
979                line: world.line(eid).cloned(),
980                patience: world.patience(eid).copied(),
981                preferences: world.preferences(eid).copied(),
982                access_control: world.access_control(eid).cloned(),
983                disabled: world.is_disabled(eid),
984                #[cfg(feature = "energy")]
985                energy_profile: world.energy_profile(eid).cloned(),
986                #[cfg(feature = "energy")]
987                energy_metrics: world.energy_metrics(eid).cloned(),
988                service_mode: world.service_mode(eid).copied(),
989                destination_queue: world.destination_queue(eid).cloned(),
990                car_calls: world.car_calls(eid).to_vec(),
991            })
992            .collect();
993
994        // Snapshot groups (convert EntityIds to indices).
995        let groups: Vec<GroupSnapshot> = self
996            .groups()
997            .iter()
998            .map(|g| {
999                let lines: Vec<LineSnapshotInfo> = g
1000                    .lines()
1001                    .iter()
1002                    .filter_map(|li| {
1003                        let entity_index = id_to_index.get(&li.entity()).copied()?;
1004                        Some(LineSnapshotInfo {
1005                            entity_index,
1006                            elevator_indices: li
1007                                .elevators()
1008                                .iter()
1009                                .filter_map(|eid| id_to_index.get(eid).copied())
1010                                .collect(),
1011                            stop_indices: li
1012                                .serves()
1013                                .iter()
1014                                .filter_map(|eid| id_to_index.get(eid).copied())
1015                                .collect(),
1016                        })
1017                    })
1018                    .collect();
1019                GroupSnapshot {
1020                    id: g.id(),
1021                    name: g.name().to_owned(),
1022                    elevator_indices: g
1023                        .elevator_entities()
1024                        .iter()
1025                        .filter_map(|eid| id_to_index.get(eid).copied())
1026                        .collect(),
1027                    stop_indices: g
1028                        .stop_entities()
1029                        .iter()
1030                        .filter_map(|eid| id_to_index.get(eid).copied())
1031                        .collect(),
1032                    strategy: self
1033                        .strategy_id(g.id())
1034                        .cloned()
1035                        .unwrap_or(crate::dispatch::BuiltinStrategy::Scan),
1036                    lines,
1037                    reposition: self.reposition_id(g.id()).cloned(),
1038                    hall_call_mode: g.hall_call_mode(),
1039                    ack_latency_ticks: g.ack_latency_ticks(),
1040                }
1041            })
1042            .collect();
1043
1044        // Snapshot stop lookup (convert EntityIds to indices).
1045        let stop_lookup: BTreeMap<StopId, usize> = self
1046            .stop_lookup_iter()
1047            .filter_map(|(sid, eid)| id_to_index.get(eid).map(|&idx| (*sid, idx)))
1048            .collect();
1049
1050        WorldSnapshot {
1051            version: SNAPSHOT_SCHEMA_VERSION,
1052            tick: self.current_tick(),
1053            dt: self.dt(),
1054            entities,
1055            groups,
1056            stop_lookup,
1057            metrics: self.metrics().clone(),
1058            metric_tags: self
1059                .world()
1060                .resource::<MetricTags>()
1061                .cloned()
1062                .unwrap_or_default(),
1063            extensions: self.world().serialize_extensions(),
1064            ticks_per_second: 1.0 / self.dt(),
1065            hall_calls: world.iter_hall_calls().cloned().collect(),
1066            arrival_log: world
1067                .resource::<crate::arrival_log::ArrivalLog>()
1068                .cloned()
1069                .unwrap_or_default(),
1070            arrival_log_retention: world
1071                .resource::<crate::arrival_log::ArrivalLogRetention>()
1072                .copied()
1073                .unwrap_or_default(),
1074            destination_log: world
1075                .resource::<crate::arrival_log::DestinationLog>()
1076                .cloned()
1077                .unwrap_or_default(),
1078            traffic_detector: world
1079                .resource::<crate::traffic_detector::TrafficDetector>()
1080                .cloned()
1081                .unwrap_or_default(),
1082            reposition_cooldowns: world
1083                .resource::<crate::dispatch::reposition::RepositionCooldowns>()
1084                .cloned()
1085                .unwrap_or_default(),
1086            // Per-group dispatcher configuration. Only strategies that
1087            // override `snapshot_config` emit non-None here; the rest
1088            // default to empty and restore to built-in defaults,
1089            // preserving pre-fix behaviour for stateless strategies.
1090            dispatch_config: self
1091                .dispatchers()
1092                .iter()
1093                .filter_map(|(gid, d)| d.snapshot_config().map(|s| (*gid, s)))
1094                .collect(),
1095        }
1096    }
1097
1098    /// Serialize the current state to a self-describing byte blob.
1099    ///
1100    /// The blob is postcard-encoded and carries a magic prefix plus the
1101    /// `elevator-core` crate version. Use [`Self::restore_bytes`]
1102    /// on the receiving end. Determinism is bit-exact across builds of
1103    /// the same crate version; cross-version restores return
1104    /// [`SimError::SnapshotVersion`](crate::error::SimError::SnapshotVersion).
1105    ///
1106    /// Extension component *data* is serialized (identical to
1107    /// [`Self::snapshot`]); after restore, use
1108    /// [`Simulation::load_extensions_with`](crate::sim::Simulation::load_extensions_with)
1109    /// to register and load them.
1110    /// Custom dispatch strategies and arbitrary `World` resources are
1111    /// not included.
1112    ///
1113    /// # Errors
1114    /// - [`SimError::SnapshotFormat`](crate::error::SimError::SnapshotFormat)
1115    ///   if postcard encoding fails. Unreachable for well-formed
1116    ///   `WorldSnapshot` values, so callers that don't care can `unwrap`.
1117    /// - [`SimError::MidTickSnapshot`](crate::error::SimError::MidTickSnapshot)
1118    ///   if invoked between phases of an in-progress tick (substep API
1119    ///   path) — the in-flight `EventBus` would otherwise be lost. (#297)
1120    pub fn snapshot_bytes(&self) -> Result<Vec<u8>, crate::error::SimError> {
1121        let envelope = SnapshotEnvelope {
1122            magic: SNAPSHOT_MAGIC,
1123            version: env!("CARGO_PKG_VERSION").to_owned(),
1124            payload: self.try_snapshot()?,
1125        };
1126        postcard::to_allocvec(&envelope)
1127            .map_err(|e| crate::error::SimError::SnapshotFormat(e.to_string()))
1128    }
1129
1130    /// Cheap u64 checksum of the simulation's serializable state.
1131    /// FNV-1a over the postcard encoding of [`Self::snapshot`]'s
1132    /// `WorldSnapshot` payload — the envelope (magic + crate version
1133    /// string) is *not* hashed, so the value depends only on the
1134    /// logical sim state, not on the `elevator-core` version that
1135    /// produced it. The numeric value is FNV-1a-specific and not
1136    /// equivalent to other hash functions of the same bytes; consumers
1137    /// computing an independent hash for comparison must use this
1138    /// method (or run FNV-1a themselves with the same constants).
1139    ///
1140    /// Snapshot/restore is byte-symmetric: a fresh sim and a restored
1141    /// sim with the same logical state hash equal. (Earlier code had
1142    /// a first-restore asymmetry from the `AssignedCar` extension
1143    /// type registering on restore but not `new`; that was fixed.)
1144    ///
1145    /// Designed for divergence detection between runtimes that should
1146    /// be in lockstep (browser vs server, multi-client multiplayer)
1147    /// and for golden checksums that need to survive a
1148    /// release-please version bump. Two sims that have produced bit-
1149    /// identical inputs in bit-identical order must hash to the same
1150    /// value, regardless of `CARGO_PKG_VERSION`.
1151    ///
1152    /// # Errors
1153    /// - [`SimError::MidTickSnapshot`](crate::error::SimError::MidTickSnapshot)
1154    ///   when invoked between phases of an in-progress tick (substep
1155    ///   API path).
1156    /// - [`SimError::SnapshotFormat`](crate::error::SimError::SnapshotFormat)
1157    ///   if postcard encoding of the payload fails. Unreachable for
1158    ///   well-formed sims; callers that don't care can `unwrap`.
1159    pub fn snapshot_checksum(&self) -> Result<u64, crate::error::SimError> {
1160        // FNV-1a (64-bit). Small, allocation-free over the byte slice,
1161        // well-distributed for arbitrary input. Not cryptographic;
1162        // collision tolerance is fine for divergence detection.
1163        // Constants are the standard 64-bit FNV-1a parameters from
1164        // RFC draft-eastlake-fnv (offset basis and prime), not arbitrary.
1165        const FNV_OFFSET: u64 = 0xcbf2_9ce4_8422_2325;
1166        const FNV_PRIME: u64 = 0x0000_0100_0000_01b3;
1167        let snapshot = self.try_snapshot()?;
1168        let bytes = postcard::to_allocvec(&snapshot)
1169            .map_err(|e| crate::error::SimError::SnapshotFormat(e.to_string()))?;
1170        let mut h: u64 = FNV_OFFSET;
1171        for byte in &bytes {
1172            h ^= u64::from(*byte);
1173            h = h.wrapping_mul(FNV_PRIME);
1174        }
1175        Ok(h)
1176    }
1177
1178    /// Restore a simulation from bytes produced by [`Self::snapshot_bytes`].
1179    ///
1180    /// Built-in dispatch strategies are auto-restored. For groups using
1181    /// [`BuiltinStrategy::Custom`](crate::dispatch::BuiltinStrategy::Custom),
1182    /// provide a factory; pass `None` otherwise.
1183    ///
1184    /// # Errors
1185    /// - [`SimError::SnapshotFormat`](crate::error::SimError::SnapshotFormat)
1186    ///   if the bytes are not a valid envelope or the magic prefix does
1187    ///   not match.
1188    /// - [`SimError::SnapshotVersion`](crate::error::SimError::SnapshotVersion)
1189    ///   if the blob was produced by a different crate version.
1190    /// - [`SimError::UnresolvedCustomStrategy`](crate::error::SimError::UnresolvedCustomStrategy)
1191    ///   if a group uses a custom strategy that the factory cannot resolve.
1192    pub fn restore_bytes(
1193        bytes: &[u8],
1194        custom_strategy_factory: CustomStrategyFactory<'_>,
1195    ) -> Result<Self, crate::error::SimError> {
1196        let (envelope, tail): (SnapshotEnvelope, &[u8]) = postcard::take_from_bytes(bytes)
1197            .map_err(|e| crate::error::SimError::SnapshotFormat(e.to_string()))?;
1198        if !tail.is_empty() {
1199            return Err(crate::error::SimError::SnapshotFormat(format!(
1200                "trailing bytes: {} unread of {}",
1201                tail.len(),
1202                bytes.len()
1203            )));
1204        }
1205        if envelope.magic != SNAPSHOT_MAGIC {
1206            return Err(crate::error::SimError::SnapshotFormat(
1207                "magic bytes do not match".to_string(),
1208            ));
1209        }
1210        let current = env!("CARGO_PKG_VERSION");
1211        if envelope.version != current {
1212            return Err(crate::error::SimError::SnapshotVersion {
1213                saved: envelope.version,
1214                current: current.to_owned(),
1215            });
1216        }
1217        envelope.payload.restore(custom_strategy_factory)
1218    }
1219}