Skip to main content

hailstorm/controller/
actor.rs

1use std::collections::{HashMap, HashSet};
2use std::future::Future;
3use std::ops::Add;
4use std::time::{Duration, SystemTime};
5
6use actix::{
7    Actor, ActorFuture, ActorFutureExt, AtomicResponse, Context, Handler, Recipient,
8    ResponseFuture, WrapFuture,
9};
10
11use crate::communication::message::MultiAgentUpdateMessage;
12use crate::communication::protobuf::grpc;
13use crate::communication::protobuf::grpc::command_item::Command;
14use crate::communication::protobuf::grpc::{
15    AgentDistribution, AgentUpdate, LaunchCommand, LoadSimCommand, StopCommand,
16};
17use crate::controller::client::downstream::DownstreamClient;
18use crate::controller::message::{
19    AgentStatus, GetSimulationStatus, LoadSimulation, SimulationControlError, SimulationPhase,
20    SimulationStatus, StartSimulation, StopSimulation,
21};
22use crate::controller::model::simulation::SimulationState;
23use rand::Rng;
24
25#[derive(Clone, Debug)]
26struct AgentState {
27    timestamp: SystemTime,
28    state: grpc::AgentSimulationState,
29    simulation_id: String,
30    simulation_error: Option<String>,
31}
32
33impl AgentState {
34    fn from_update(timestamp: SystemTime, update: &AgentUpdate) -> Self {
35        Self {
36            timestamp,
37            state: update.state(),
38            simulation_id: update.simulation_id.clone(),
39            simulation_error: Some(update.simulation_error.clone()).filter(|err| !err.is_empty()),
40        }
41    }
42}
43
44/// Core controller actor that orchestrates distributed simulations.
45///
46/// Tracks connected agent states, distributes simulation commands, and ensures
47/// all agents converge to the desired simulation state (idle, ready, or launched).
48pub struct ControllerActor {
49    downstream: DownstreamClient,
50    metrics_storage: Recipient<MultiAgentUpdateMessage>,
51    agents_state: HashMap<u32, AgentState>,
52    simulation: SimulationState,
53}
54
55impl ControllerActor {
56    pub fn new(
57        downstream: DownstreamClient,
58        metrics_storage: Recipient<MultiAgentUpdateMessage>,
59    ) -> Self {
60        Self {
61            downstream,
62            metrics_storage,
63            agents_state: Default::default(),
64            simulation: SimulationState::Idle,
65        }
66    }
67}
68
69impl Actor for ControllerActor {
70    type Context = Context<Self>;
71}
72
73impl Handler<MultiAgentUpdateMessage> for ControllerActor {
74    type Result = ResponseFuture<()>;
75
76    fn handle(
77        &mut self,
78        MultiAgentUpdateMessage(agent_updates): MultiAgentUpdateMessage,
79        _ctx: &mut Self::Context,
80    ) -> Self::Result {
81        let pre_handle_agents = self.sorted_agent_ids();
82
83        let agent_alignment_fut = self.align_agents_simulation_state(&agent_updates);
84        let send_metrics_fut = self
85            .metrics_storage
86            .send(MultiAgentUpdateMessage(agent_updates));
87
88        let post_handle_agents = self.sorted_agent_ids();
89
90        let cmd_fut = if pre_handle_agents != post_handle_agents {
91            let pre_handle_agents_count = pre_handle_agents.len();
92            let post_handle_agents_count = post_handle_agents.len();
93            log::info!(
94                "Update agents count {pre_handle_agents_count} -> {post_handle_agents_count}"
95            );
96            Some(self.downstream.send_broadcast(self.distribution_commands()))
97        } else {
98            None
99        };
100
101        Box::pin(async move {
102            let (_, send_metrics_out) = futures::join!(agent_alignment_fut, send_metrics_fut);
103
104            if let Err(err) = send_metrics_out {
105                log::error!("Error sending metrics - {err}");
106            }
107
108            if let Some(recipient_req) = cmd_fut {
109                if let Err(err) = recipient_req.await {
110                    log::error!("Error sending count update - {err}");
111                }
112            }
113        })
114    }
115}
116
117impl ControllerActor {
118    fn sorted_agent_ids(&self) -> Vec<u32> {
119        let mut agent_ids = self.agents_state.keys().copied().collect::<Vec<_>>();
120        agent_ids.sort_unstable();
121        agent_ids
122    }
123
124    fn distribution_commands(&self) -> Vec<Command> {
125        vec![
126            Command::UpdateAgentsCount(self.count_agents() as u32),
127            Command::UpdateAgents(AgentDistribution {
128                agent_ids: self.sorted_agent_ids(),
129            }),
130        ]
131    }
132
133    fn count_agents(&self) -> usize {
134        self.agents_state.len()
135    }
136
137    fn alignment_commands(&self, agent: &AgentState) -> Vec<Command> {
138        if self
139            .simulation
140            .is_aligned(&agent.state, &agent.simulation_id)
141            || self.failed_current_simulation(agent)
142        {
143            return Vec::new();
144        }
145        if self.simulation.simulation_id() == Some(agent.simulation_id.as_str()) {
146            return match &self.simulation {
147                SimulationState::Launched { start_ts, .. } => {
148                    vec![Command::Launch(LaunchCommand {
149                        start_ts: Some((*start_ts).into()),
150                    })]
151                }
152                SimulationState::Ready { .. } => vec![Command::Stop(StopCommand { reset: false })],
153                SimulationState::Idle => unreachable!(),
154            };
155        }
156        self.generate_simulation_state_commands()
157    }
158
159    /// Agents that already failed to load the current simulation are not sent it again.
160    fn failed_current_simulation(&self, agent: &AgentState) -> bool {
161        agent.simulation_error.is_some()
162            && self.simulation.simulation_id() == Some(agent.simulation_id.as_str())
163    }
164
165    fn align_agents_simulation_state(
166        &mut self,
167        updates: &[AgentUpdate],
168    ) -> impl Future<Output = ()> {
169        let mut refreshed_agents = HashSet::new();
170        for update in updates {
171            if let Some(timestamp) = update
172                .timestamp
173                .clone()
174                .map(SystemTime::try_from)
175                .transpose()
176                .ok()
177                .flatten()
178            {
179                if self
180                    .agents_state
181                    .get(&update.agent_id)
182                    .map_or(true, |entry| entry.timestamp < timestamp)
183                {
184                    self.agents_state
185                        .insert(update.agent_id, AgentState::from_update(timestamp, update));
186                    refreshed_agents.insert(update.agent_id);
187                }
188            }
189        }
190        self.agents_state
191            .retain(|_id, state| state.timestamp.add(Duration::from_secs(60)) > SystemTime::now());
192
193        let mut requests = Vec::new();
194        for agent_id in refreshed_agents {
195            if let Some(agent) = self.agents_state.get(&agent_id) {
196                let commands = self.alignment_commands(agent);
197                if !commands.is_empty() {
198                    requests.push(self.downstream.send_to_agent(agent_id, commands));
199                }
200            }
201        }
202
203        async move {
204            for result in futures::future::join_all(requests).await {
205                if let Err(err) = result {
206                    log::error!("Error aligning simulation state - {err}");
207                }
208            }
209        }
210    }
211
212    fn generate_simulation_state_commands(&self) -> Vec<Command> {
213        let agents_count = self.count_agents();
214        match &self.simulation {
215            SimulationState::Idle => vec![
216                Command::Stop(StopCommand { reset: true }),
217                Command::UpdateAgentsCount(agents_count as u32),
218                Command::UpdateAgents(AgentDistribution {
219                    agent_ids: self.sorted_agent_ids(),
220                }),
221            ],
222            SimulationState::Ready { simulation } => vec![
223                Command::UpdateAgentsCount(agents_count as u32),
224                Command::UpdateAgents(AgentDistribution {
225                    agent_ids: self.sorted_agent_ids(),
226                }),
227                Command::Load(LoadSimCommand {
228                    clients_evolution: simulation.bots.iter().cloned().map(Into::into).collect(),
229                    script: simulation.script.clone(),
230                    simulation_id: simulation.id.clone(),
231                }),
232            ],
233            SimulationState::Launched {
234                start_ts,
235                simulation,
236            } => vec![
237                Command::UpdateAgentsCount(agents_count as u32),
238                Command::UpdateAgents(AgentDistribution {
239                    agent_ids: self.sorted_agent_ids(),
240                }),
241                Command::Load(LoadSimCommand {
242                    clients_evolution: simulation.bots.iter().cloned().map(Into::into).collect(),
243                    script: simulation.script.clone(),
244                    simulation_id: simulation.id.clone(),
245                }),
246                Command::Launch(LaunchCommand {
247                    start_ts: Some((*start_ts).into()),
248                }),
249            ],
250        }
251    }
252}
253
254impl ControllerActor {
255    fn broadcast_state_change(&mut self) -> impl ActorFuture<Self, Output = ()> + 'static {
256        self.broadcast_commands(self.generate_simulation_state_commands())
257    }
258
259    fn broadcast_commands(
260        &mut self,
261        commands: Vec<Command>,
262    ) -> impl ActorFuture<Self, Output = ()> + 'static {
263        self.downstream
264            .send_broadcast(commands)
265            .into_actor(self)
266            .map(|res, _, _| {
267                if let Err(err) = res {
268                    log::error!("Error broadcasting simulation state - {err}");
269                }
270            })
271    }
272}
273
274impl Handler<LoadSimulation> for ControllerActor {
275    type Result = AtomicResponse<Self, Result<String, SimulationControlError>>;
276
277    fn handle(
278        &mut self,
279        LoadSimulation(mut simulation): LoadSimulation,
280        _ctx: &mut Self::Context,
281    ) -> Self::Result {
282        if let Err(err) = simulation.validate() {
283            return AtomicResponse::new(Box::pin(
284                futures::future::err(SimulationControlError::InvalidSimulation(err))
285                    .into_actor(self),
286            ));
287        }
288        simulation.id = format!("{:016x}", rand::rng().random::<u64>());
289        let simulation_id = simulation.id.clone();
290        self.simulation = SimulationState::Ready { simulation };
291
292        AtomicResponse::new(Box::pin(
293            self.broadcast_state_change()
294                .map(move |_, _, _| Ok(simulation_id)),
295        ))
296    }
297}
298
299impl Handler<StartSimulation> for ControllerActor {
300    type Result = AtomicResponse<Self, Result<(), SimulationControlError>>;
301
302    fn handle(
303        &mut self,
304        StartSimulation(start_ts): StartSimulation,
305        _ctx: &mut Self::Context,
306    ) -> Self::Result {
307        self.simulation = match &self.simulation {
308            SimulationState::Idle => {
309                return AtomicResponse::new(Box::pin(
310                    futures::future::err(SimulationControlError::NotLoaded).into_actor(self),
311                ));
312            }
313            SimulationState::Ready { simulation }
314            | SimulationState::Launched { simulation, .. } => SimulationState::Launched {
315                start_ts,
316                simulation: simulation.clone(),
317            },
318        };
319
320        AtomicResponse::new(Box::pin(
321            self.broadcast_commands(vec![Command::Launch(LaunchCommand {
322                start_ts: Some(start_ts.into()),
323            })])
324            .map(|_, _, _| Ok(())),
325        ))
326    }
327}
328
329impl Handler<StopSimulation> for ControllerActor {
330    type Result = AtomicResponse<Self, ()>;
331
332    fn handle(&mut self, _msg: StopSimulation, _ctx: &mut Self::Context) -> Self::Result {
333        self.simulation = SimulationState::Idle;
334        AtomicResponse::new(Box::pin(self.broadcast_state_change()))
335    }
336}
337
338impl Handler<GetSimulationStatus> for ControllerActor {
339    type Result = SimulationStatus;
340
341    fn handle(&mut self, _msg: GetSimulationStatus, _ctx: &mut Self::Context) -> Self::Result {
342        let phase = match &self.simulation {
343            SimulationState::Idle => SimulationPhase::Idle,
344            SimulationState::Ready { .. } => SimulationPhase::Ready,
345            SimulationState::Launched { start_ts, .. } => SimulationPhase::Launched {
346                start_ts: *start_ts,
347            },
348        };
349        let agents = self
350            .sorted_agent_ids()
351            .into_iter()
352            .filter_map(|agent_id| {
353                self.agents_state.get(&agent_id).map(|agent| AgentStatus {
354                    agent_id,
355                    state: agent.state,
356                    simulation_id: agent.simulation_id.clone(),
357                    simulation_error: agent.simulation_error.clone(),
358                    last_update: agent.timestamp,
359                })
360            })
361            .collect();
362        SimulationStatus {
363            phase,
364            simulation_id: self.simulation.simulation_id().map(String::from),
365            agents,
366        }
367    }
368}
369
370#[cfg(test)]
371mod test {
372    use super::*;
373    use crate::communication::message::{ControllerCommandMessage, MultiAgentUpdateMessage};
374    use crate::communication::protobuf::grpc::{AgentUpdate, ControllerCommand};
375    use crate::communication::server_actor::GrpcServerActor;
376    use actix::{Actor, Context, Handler};
377    use std::sync::{Arc, Mutex};
378
379    struct MockMetricsStorage;
380    impl Actor for MockMetricsStorage {
381        type Context = Context<Self>;
382    }
383    impl Handler<MultiAgentUpdateMessage> for MockMetricsStorage {
384        type Result = ();
385        fn handle(&mut self, _msg: MultiAgentUpdateMessage, _ctx: &mut Self::Context) {}
386    }
387
388    #[actix::test]
389    async fn controller_tracks_new_agents() {
390        let metrics = MockMetricsStorage.start();
391        let grpc_server_ctx: Context<GrpcServerActor> = Context::new();
392        let grpc_server_actor = GrpcServerActor::new(metrics.clone().recipient());
393        let server_addr = grpc_server_ctx.run(grpc_server_actor);
394
395        let controller = ControllerActor::new(
396            DownstreamClient::new(server_addr.recipient()),
397            metrics.recipient(),
398        );
399        let controller_addr = controller.start();
400
401        let update = MultiAgentUpdateMessage(vec![AgentUpdate {
402            agent_id: 42,
403            stats: vec![],
404            update_id: 1,
405            timestamp: Some(SystemTime::now().into()),
406            name: String::new(),
407            state: grpc::AgentSimulationState::Idle as i32,
408            ..Default::default()
409        }]);
410
411        controller_addr.send(update).await.expect("send failed");
412    }
413
414    struct Capture {
415        commands: Arc<Mutex<Vec<ControllerCommand>>>,
416    }
417
418    impl Actor for Capture {
419        type Context = Context<Self>;
420    }
421
422    impl Handler<ControllerCommandMessage> for Capture {
423        type Result = ();
424
425        fn handle(&mut self, msg: ControllerCommandMessage, _: &mut Self::Context) {
426            self.commands.lock().unwrap().push(msg.0);
427        }
428    }
429
430    impl Handler<MultiAgentUpdateMessage> for Capture {
431        type Result = ();
432
433        fn handle(&mut self, _: MultiAgentUpdateMessage, _: &mut Self::Context) {}
434    }
435
436    #[actix::test]
437    async fn replacing_an_agent_broadcasts_membership_even_when_count_is_unchanged() {
438        let commands = Arc::new(Mutex::new(Vec::new()));
439        let capture = Capture {
440            commands: commands.clone(),
441        }
442        .start();
443        let mut controller = ControllerActor::new(
444            DownstreamClient::new(capture.clone().recipient()),
445            capture.recipient(),
446        );
447        let now = SystemTime::now();
448        for (id, timestamp) in [(0, now - Duration::from_secs(61)), (2, now)] {
449            controller.agents_state.insert(
450                id,
451                AgentState {
452                    timestamp,
453                    state: grpc::AgentSimulationState::Idle,
454                    simulation_id: String::new(),
455                    simulation_error: None,
456                },
457            );
458        }
459        controller
460            .handle(
461                MultiAgentUpdateMessage(vec![AgentUpdate {
462                    agent_id: 4,
463                    timestamp: Some(now.into()),
464                    state: grpc::AgentSimulationState::Idle as i32,
465                    ..Default::default()
466                }]),
467                &mut Context::new(),
468            )
469            .await;
470
471        let commands = commands.lock().unwrap();
472        assert_eq!(commands.len(), 1);
473        assert!(commands[0].commands.iter().any(|item| {
474            matches!(&item.command, Some(Command::UpdateAgents(distribution)) if distribution.agent_ids == vec![2, 4])
475        }));
476        assert_eq!(controller.count_agents(), 2);
477    }
478
479    fn started_controller() -> (
480        actix::Addr<ControllerActor>,
481        Arc<Mutex<Vec<ControllerCommand>>>,
482    ) {
483        let commands = Arc::new(Mutex::new(Vec::new()));
484        let capture = Capture {
485            commands: commands.clone(),
486        }
487        .start();
488        let controller = ControllerActor::new(
489            DownstreamClient::new(capture.clone().recipient()),
490            capture.recipient(),
491        )
492        .start();
493        (controller, commands)
494    }
495
496    fn definition(shape: &str) -> crate::controller::model::simulation::SimulationDef {
497        use crate::controller::model::simulation::{BotDef, SimulationDef};
498        SimulationDef::default()
499            .bots(vec![BotDef::default().model("Bot").shape(shape)])
500            .script(String::from("struct Bot;"))
501    }
502
503    fn loaded_ids(commands: &[ControllerCommand]) -> Vec<String> {
504        commands
505            .iter()
506            .flat_map(|cmd| &cmd.commands)
507            .filter_map(|item| match &item.command {
508                Some(Command::Load(load)) => Some(load.simulation_id.clone()),
509                _ => None,
510            })
511            .collect()
512    }
513
514    fn update(agent_id: u32, simulation_id: &str, error: &str) -> MultiAgentUpdateMessage {
515        MultiAgentUpdateMessage(vec![AgentUpdate {
516            agent_id,
517            timestamp: Some(SystemTime::now().into()),
518            state: grpc::AgentSimulationState::Idle as i32,
519            simulation_id: simulation_id.to_string(),
520            simulation_error: error.to_string(),
521            ..Default::default()
522        }])
523    }
524
525    fn state_update(
526        agent_id: u32,
527        simulation_id: &str,
528        state: grpc::AgentSimulationState,
529        timestamp: SystemTime,
530    ) -> MultiAgentUpdateMessage {
531        MultiAgentUpdateMessage(vec![AgentUpdate {
532            agent_id,
533            timestamp: Some(timestamp.into()),
534            state: state as i32,
535            simulation_id: simulation_id.to_string(),
536            ..Default::default()
537        }])
538    }
539
540    #[actix::test]
541    async fn starting_a_loaded_simulation_only_broadcasts_launch() {
542        let (controller, commands) = started_controller();
543        let id = controller
544            .send(LoadSimulation::new(definition("10")))
545            .await
546            .unwrap()
547            .unwrap();
548        commands.lock().unwrap().clear();
549        let start_ts = SystemTime::now();
550        controller
551            .send(StartSimulation::at(start_ts))
552            .await
553            .unwrap()
554            .unwrap();
555        let commands = commands.lock().unwrap();
556        assert_eq!(commands.len(), 1);
557        assert_eq!(commands[0].commands.len(), 1);
558        assert!(matches!(&commands[0].commands[0].command,
559            Some(Command::Launch(launch)) if launch.start_ts == Some(start_ts.into())));
560        assert!(loaded_ids(&commands).is_empty(), "{id} must remain loaded");
561    }
562
563    #[actix::test]
564    async fn ready_and_waiting_heartbeats_after_launch_only_receive_launch() {
565        let (controller, commands) = started_controller();
566        let id = controller
567            .send(LoadSimulation::new(definition("10")))
568            .await
569            .unwrap()
570            .unwrap();
571        let start_ts = SystemTime::now() - Duration::from_secs(10);
572        controller
573            .send(StartSimulation::at(start_ts))
574            .await
575            .unwrap()
576            .unwrap();
577        for state in [
578            grpc::AgentSimulationState::Ready,
579            grpc::AgentSimulationState::Waiting,
580        ] {
581            controller
582                .send(state_update(1, &id, state, SystemTime::now()))
583                .await
584                .unwrap();
585            let mut commands = commands.lock().unwrap();
586            let targeted = commands
587                .iter()
588                .filter(|command| {
589                    command.target == Some(grpc::controller_command::Target::AgentId(1))
590                })
591                .collect::<Vec<_>>();
592            assert_eq!(targeted.len(), 1);
593            assert_eq!(targeted[0].commands.len(), 1);
594            assert!(matches!(&targeted[0].commands[0].command,
595                Some(Command::Launch(launch)) if launch.start_ts == Some(start_ts.into())));
596            commands.clear();
597        }
598    }
599
600    #[actix::test]
601    async fn older_and_duplicate_heartbeats_do_not_trigger_reconciliation() {
602        let (controller, commands) = started_controller();
603        let id = controller
604            .send(LoadSimulation::new(definition("10")))
605            .await
606            .unwrap()
607            .unwrap();
608        let timestamp = SystemTime::now();
609        controller
610            .send(state_update(
611                1,
612                &id,
613                grpc::AgentSimulationState::Ready,
614                timestamp,
615            ))
616            .await
617            .unwrap();
618        controller
619            .send(StartSimulation::at(timestamp))
620            .await
621            .unwrap()
622            .unwrap();
623        commands.lock().unwrap().clear();
624        for ts in [timestamp, timestamp - Duration::from_secs(1)] {
625            controller
626                .send(state_update(1, "old", grpc::AgentSimulationState::Idle, ts))
627                .await
628                .unwrap();
629        }
630        assert!(commands.lock().unwrap().is_empty());
631        let status = controller.send(GetSimulationStatus).await.unwrap();
632        assert_eq!(status.agents[0].simulation_id, id);
633        assert_eq!(status.agents[0].state, grpc::AgentSimulationState::Ready);
634    }
635
636    #[actix::test]
637    async fn different_agents_receive_only_the_recovery_they_need() {
638        let (controller, commands) = started_controller();
639        let id = controller
640            .send(LoadSimulation::new(definition("10")))
641            .await
642            .unwrap()
643            .unwrap();
644        controller
645            .send(StartSimulation::at(SystemTime::now()))
646            .await
647            .unwrap()
648            .unwrap();
649        commands.lock().unwrap().clear();
650        let mut updates =
651            state_update(1, &id, grpc::AgentSimulationState::Ready, SystemTime::now());
652        updates.0.extend(
653            state_update(
654                2,
655                "old",
656                grpc::AgentSimulationState::Running,
657                SystemTime::now(),
658            )
659            .0,
660        );
661        controller.send(updates).await.unwrap();
662        let commands = commands.lock().unwrap();
663        let targeted = |id| {
664            commands
665                .iter()
666                .find(|command| {
667                    command.target == Some(grpc::controller_command::Target::AgentId(id))
668                })
669                .unwrap()
670        };
671        assert_eq!(targeted(1).commands.len(), 1);
672        assert!(matches!(
673            targeted(1).commands[0].command,
674            Some(Command::Launch(_))
675        ));
676        assert_eq!(loaded_ids(&[targeted(2).clone()]), vec![id]);
677        assert!(targeted(2)
678            .commands
679            .iter()
680            .any(|item| matches!(item.command, Some(Command::Launch(_)))));
681        assert!(!targeted(2)
682            .commands
683            .iter()
684            .any(|item| matches!(item.command, Some(Command::Stop(_)))));
685    }
686
687    #[actix::test]
688    async fn ready_reconciliation_stops_without_unloading_the_definition() {
689        let (controller, commands) = started_controller();
690        let id = controller
691            .send(LoadSimulation::new(definition("10")))
692            .await
693            .unwrap()
694            .unwrap();
695        commands.lock().unwrap().clear();
696        controller
697            .send(state_update(
698                1,
699                &id,
700                grpc::AgentSimulationState::Running,
701                SystemTime::now(),
702            ))
703            .await
704            .unwrap();
705        let commands = commands.lock().unwrap();
706        let targeted = commands
707            .iter()
708            .find(|command| command.target == Some(grpc::controller_command::Target::AgentId(1)))
709            .unwrap();
710        assert_eq!(targeted.commands.len(), 1);
711        assert!(matches!(
712            targeted.commands[0].command,
713            Some(Command::Stop(StopCommand { reset: false }))
714        ));
715    }
716
717    #[actix::test]
718    async fn other_agent_updates_do_not_retry_cached_misalignment() {
719        let (controller, commands) = started_controller();
720        let id = controller
721            .send(LoadSimulation::new(definition("10")))
722            .await
723            .unwrap()
724            .unwrap();
725        controller
726            .send(StartSimulation::at(SystemTime::now()))
727            .await
728            .unwrap()
729            .unwrap();
730        controller.send(update(1, "old", "")).await.unwrap();
731        commands.lock().unwrap().clear();
732        controller
733            .send(state_update(
734                2,
735                &id,
736                grpc::AgentSimulationState::Running,
737                SystemTime::now(),
738            ))
739            .await
740            .unwrap();
741        assert!(loaded_ids(&commands.lock().unwrap()).is_empty());
742    }
743
744    #[actix::test]
745    async fn invalid_definitions_are_rejected_before_reaching_agents() {
746        let (controller, commands) = started_controller();
747        let out = controller
748            .send(LoadSimulation::new(definition("10 *")))
749            .await
750            .unwrap();
751        assert!(matches!(
752            out,
753            Err(SimulationControlError::InvalidSimulation(_))
754        ));
755        assert!(commands.lock().unwrap().is_empty());
756        let status = controller.send(GetSimulationStatus).await.unwrap();
757        assert_eq!(status.phase, SimulationPhase::Idle);
758    }
759
760    #[actix::test]
761    async fn loading_assigns_an_identifier_sent_to_the_agents() {
762        let (controller, commands) = started_controller();
763        let id = controller
764            .send(LoadSimulation::new(definition("10")))
765            .await
766            .unwrap()
767            .unwrap();
768        assert_eq!(loaded_ids(&commands.lock().unwrap()), vec![id.clone()]);
769        let status = controller.send(GetSimulationStatus).await.unwrap();
770        assert_eq!(status.phase, SimulationPhase::Ready);
771        assert_eq!(status.simulation_id, Some(id));
772    }
773
774    #[actix::test]
775    async fn starting_without_a_loaded_simulation_fails() {
776        let (controller, commands) = started_controller();
777        let out = controller
778            .send(StartSimulation::at(SystemTime::now()))
779            .await
780            .unwrap();
781        assert!(matches!(out, Err(SimulationControlError::NotLoaded)));
782        assert!(commands.lock().unwrap().is_empty());
783    }
784
785    #[actix::test]
786    async fn agents_that_failed_the_current_simulation_are_not_reloaded() {
787        let (controller, commands) = started_controller();
788        let id = controller
789            .send(LoadSimulation::new(definition("10")))
790            .await
791            .unwrap()
792            .unwrap();
793
794        controller
795            .send(update(1, &id, "Invalid script"))
796            .await
797            .unwrap();
798        controller
799            .send(update(1, &id, "Invalid script"))
800            .await
801            .unwrap();
802        // Only the initial broadcast and the membership update after the first report.
803        assert_eq!(loaded_ids(&commands.lock().unwrap()), vec![id.clone()]);
804
805        // An agent reporting an older simulation is realigned.
806        controller.send(update(2, "previous", "")).await.unwrap();
807        assert_eq!(
808            loaded_ids(&commands.lock().unwrap()),
809            vec![id.clone(), id.clone()]
810        );
811
812        let status = controller.send(GetSimulationStatus).await.unwrap();
813        let failed = status
814            .agents
815            .iter()
816            .find(|agent| agent.agent_id == 1)
817            .unwrap();
818        assert_eq!(failed.simulation_error.as_deref(), Some("Invalid script"));
819    }
820
821    #[actix::test]
822    async fn stopping_unloads_the_simulation_from_every_agent() {
823        let (controller, commands) = started_controller();
824        controller
825            .send(LoadSimulation::new(definition("10")))
826            .await
827            .unwrap()
828            .unwrap();
829        controller
830            .send(StartSimulation::at(SystemTime::now()))
831            .await
832            .unwrap()
833            .unwrap();
834        controller.send(StopSimulation).await.unwrap();
835
836        let status = controller.send(GetSimulationStatus).await.unwrap();
837        assert_eq!(status.phase, SimulationPhase::Idle);
838        assert_eq!(status.simulation_id, None);
839        let commands = commands.lock().unwrap();
840        let last = commands.last().unwrap();
841        assert!(last.commands.iter().any(|item| matches!(
842            item.command,
843            Some(Command::Stop(StopCommand { reset: true }))
844        )));
845        assert!(!last
846            .commands
847            .iter()
848            .any(|item| matches!(item.command, Some(Command::Load(_)))));
849    }
850}