Skip to main content

elevator_core/
scenario.rs

1//! Scenario replay: timed rider spawns with pass/fail conditions.
2
3use crate::config::SimConfig;
4use crate::dispatch::DispatchStrategy;
5use crate::error::SimError;
6use crate::metrics::Metrics;
7use crate::sim::Simulation;
8use crate::stop::StopId;
9use serde::{Deserialize, Serialize};
10
11/// A timed rider spawn event within a scenario.
12#[derive(Debug, Clone, Serialize, Deserialize)]
13pub struct TimedSpawn {
14    /// Tick at which to spawn this rider.
15    pub tick: u64,
16    /// Origin stop for the rider.
17    pub origin: StopId,
18    /// Destination stop for the rider.
19    pub destination: StopId,
20    /// Weight of the rider.
21    pub weight: f64,
22}
23
24/// A pass/fail condition for scenario evaluation.
25#[derive(Debug, Clone, Serialize, Deserialize)]
26#[non_exhaustive]
27pub enum Condition {
28    /// Average wait time must be below this value (ticks).
29    AvgWaitBelow(f64),
30    /// Maximum wait time must be below this value (ticks).
31    MaxWaitBelow(u64),
32    /// Throughput must be above this value (riders per window).
33    ThroughputAbove(u64),
34    /// All spawned riders must reach a terminal state (delivered or abandoned)
35    /// by this tick. Riders that failed to spawn (see
36    /// [`ScenarioRunner::skipped_spawns`]) are not counted — check that
37    /// value separately when replay fidelity matters.
38    AllDeliveredByTick(u64),
39    /// Abandonment rate must be below this value (0.0 - 1.0).
40    AbandonmentRateBelow(f64),
41}
42
43/// A complete scenario: config + timed spawns + success conditions.
44#[derive(Debug, Clone, Serialize, Deserialize)]
45pub struct Scenario {
46    /// Human-readable scenario name.
47    pub name: String,
48    /// Simulation configuration.
49    pub config: SimConfig,
50    /// Timed rider spawn events.
51    pub spawns: Vec<TimedSpawn>,
52    /// Pass/fail conditions for evaluation.
53    pub conditions: Vec<Condition>,
54    /// Max ticks to run before declaring timeout.
55    pub max_ticks: u64,
56}
57
58/// Result of evaluating a single condition.
59#[derive(Debug, Clone)]
60pub struct ConditionResult {
61    /// The condition that was evaluated.
62    pub condition: Condition,
63    /// Whether the condition passed.
64    pub passed: bool,
65    /// The actual observed value.
66    pub actual_value: f64,
67}
68
69/// Result of running a complete scenario.
70#[derive(Debug, Clone)]
71pub struct ScenarioResult {
72    /// Scenario name.
73    pub name: String,
74    /// Whether all conditions passed.
75    pub passed: bool,
76    /// Number of ticks run.
77    pub ticks_run: u64,
78    /// Per-condition results.
79    pub conditions: Vec<ConditionResult>,
80    /// Final simulation metrics.
81    pub metrics: Metrics,
82}
83
84/// Runs a scenario to completion and evaluates conditions.
85pub struct ScenarioRunner {
86    /// The underlying simulation.
87    sim: Simulation,
88    /// Timed spawn events.
89    spawns: Vec<TimedSpawn>,
90    /// Index of the next spawn to process.
91    spawn_cursor: usize,
92    /// Pass/fail conditions.
93    conditions: Vec<Condition>,
94    /// Maximum ticks before timeout.
95    max_ticks: u64,
96    /// Scenario name.
97    name: String,
98    /// Number of spawn attempts that failed (e.g. disabled/removed stops).
99    skipped_spawns: u64,
100}
101
102impl ScenarioRunner {
103    /// Create a new runner from a scenario definition and dispatch strategy.
104    ///
105    /// Returns `Err` if the scenario's config is invalid.
106    ///
107    /// # Errors
108    ///
109    /// Returns [`SimError::InvalidConfig`] if the scenario's simulation config is invalid.
110    pub fn new(
111        scenario: Scenario,
112        dispatch: impl DispatchStrategy + 'static,
113    ) -> Result<Self, SimError> {
114        let sim = Simulation::new(&scenario.config, dispatch)?;
115        // Sort spawns by tick so the cursor advance in `tick()` cannot
116        // gate an earlier spawn behind a later one. `sort_by_key` is
117        // stable, so spawns with the same tick keep their declaration
118        // order — important for replay determinism (#271).
119        let mut spawns = scenario.spawns;
120        spawns.sort_by_key(|s| s.tick);
121        Ok(Self {
122            sim,
123            spawns,
124            spawn_cursor: 0,
125            conditions: scenario.conditions,
126            max_ticks: scenario.max_ticks,
127            name: scenario.name,
128            skipped_spawns: 0,
129        })
130    }
131
132    /// Access the underlying simulation.
133    #[must_use]
134    pub const fn sim(&self) -> &Simulation {
135        &self.sim
136    }
137
138    /// Number of rider spawn attempts that were skipped due to errors
139    /// (e.g. referencing disabled or removed stops).
140    #[must_use]
141    pub const fn skipped_spawns(&self) -> u64 {
142        self.skipped_spawns
143    }
144
145    /// Run one tick: spawn scheduled riders, then tick simulation.
146    pub fn tick(&mut self) {
147        // Spawn any riders scheduled for this tick.
148        while self.spawn_cursor < self.spawns.len()
149            && self.spawns[self.spawn_cursor].tick <= self.sim.current_tick()
150        {
151            let spawn = &self.spawns[self.spawn_cursor];
152            // Spawn errors are expected: scenario files may reference stops
153            // that were removed or disabled during the run. We skip the
154            // spawn but track the count so callers can detect divergence.
155            if self
156                .sim
157                .spawn_rider(spawn.origin, spawn.destination, spawn.weight)
158                .is_err()
159            {
160                self.skipped_spawns += 1;
161            }
162            self.spawn_cursor += 1;
163        }
164
165        self.sim.step();
166    }
167
168    /// Run to completion (all riders delivered or `max_ticks` reached).
169    pub fn run_to_completion(&mut self) -> ScenarioResult {
170        use crate::components::RiderPhase;
171
172        for _ in 0..self.max_ticks {
173            self.tick();
174
175            // Check if all spawns have happened and all riders are done.
176            if self.spawn_cursor >= self.spawns.len() {
177                let all_done =
178                    self.sim.world().iter_riders().all(|(_, r)| {
179                        matches!(r.phase, RiderPhase::Arrived | RiderPhase::Abandoned)
180                    });
181                if all_done {
182                    break;
183                }
184            }
185        }
186
187        self.evaluate()
188    }
189
190    /// Evaluate conditions against current metrics.
191    #[must_use]
192    pub fn evaluate(&self) -> ScenarioResult {
193        let metrics = self.sim.metrics().clone();
194        let condition_results: Vec<ConditionResult> = self
195            .conditions
196            .iter()
197            .map(|cond| evaluate_condition(cond, &metrics, self.sim.current_tick()))
198            .collect();
199
200        let passed = condition_results.iter().all(|r| r.passed);
201
202        ScenarioResult {
203            name: self.name.clone(),
204            passed,
205            ticks_run: self.sim.current_tick(),
206            conditions: condition_results,
207            metrics,
208        }
209    }
210}
211
212/// Evaluate a single condition against metrics and the current tick.
213fn evaluate_condition(
214    condition: &Condition,
215    metrics: &Metrics,
216    current_tick: u64,
217) -> ConditionResult {
218    match condition {
219        Condition::AvgWaitBelow(threshold) => ConditionResult {
220            condition: condition.clone(),
221            passed: metrics.avg_wait_time() < *threshold,
222            actual_value: metrics.avg_wait_time(),
223        },
224        Condition::MaxWaitBelow(threshold) => ConditionResult {
225            condition: condition.clone(),
226            passed: metrics.max_wait_time() < *threshold,
227            actual_value: metrics.max_wait_time() as f64,
228        },
229        Condition::ThroughputAbove(threshold) => ConditionResult {
230            condition: condition.clone(),
231            passed: metrics.throughput() > *threshold,
232            actual_value: metrics.throughput() as f64,
233        },
234        Condition::AllDeliveredByTick(deadline) => ConditionResult {
235            condition: condition.clone(),
236            passed: current_tick <= *deadline
237                && metrics.total_delivered() + metrics.total_abandoned() == metrics.total_spawned(),
238            actual_value: current_tick as f64,
239        },
240        Condition::AbandonmentRateBelow(threshold) => ConditionResult {
241            condition: condition.clone(),
242            passed: metrics.abandonment_rate() < *threshold,
243            actual_value: metrics.abandonment_rate(),
244        },
245    }
246}