1use std::cell::RefCell;
8use std::future::Future;
9use std::io::{BufRead, BufReader, Error};
10use std::path::{Path, PathBuf};
11use std::pin::Pin;
12use std::process::Stdio;
13use std::rc::Rc;
14
15use bytes::{Bytes, BytesMut};
16use dfir_lang::graph::{AsCodeOptions, DfirGraph};
17use futures::{Sink, Stream};
18use serde::Serialize;
19use serde::de::DeserializeOwned;
20use stageleft::{QuotedWithContext, RuntimeData};
21
22use super::deploy_runtime_maelstrom::*;
23use crate::compile::builder::ExternalPortId;
24use crate::compile::deploy_provider::{ClusterSpec, Deploy, Node, RegisterPort};
25use crate::compile::trybuild::generate::{
26 ExampleBuildConfig, LinkingMode, TrybuildConfig, compile_trybuild_example,
27 create_graph_trybuild,
28};
29use crate::location::dynamic::LocationId;
30use crate::location::{LocationKey, NetworkHint};
31
32pub enum MaelstromDeploy {}
39
40impl crate::compile::deploy_provider::SupportsMemberId<String> for MaelstromDeploy {}
42
43impl<'a> Deploy<'a> for MaelstromDeploy {
44 type Meta = ();
45 type InstantiateEnv = MaelstromDeployment;
46
47 type Process = MaelstromProcess;
48 type Cluster = MaelstromCluster;
49 type External = MaelstromExternal;
50
51 fn o2o_sink_source(
52 _env: &mut Self::InstantiateEnv,
53 _p1: &Self::Process,
54 _p1_port: &<Self::Process as Node>::Port,
55 _p2: &Self::Process,
56 _p2_port: &<Self::Process as Node>::Port,
57 _name: Option<&str>,
58 _networking_info: &crate::networking::NetworkingInfo,
59 _external_types: Option<(&syn::Type, &syn::Type)>,
60 ) -> (syn::Expr, syn::Expr) {
61 panic!("Maelstrom deployment does not support processes, only clusters")
62 }
63
64 fn o2o_connect(
65 _p1: &Self::Process,
66 _p1_port: &<Self::Process as Node>::Port,
67 _p2: &Self::Process,
68 _p2_port: &<Self::Process as Node>::Port,
69 ) -> Box<dyn FnOnce()> {
70 panic!("Maelstrom deployment does not support processes, only clusters")
71 }
72
73 fn o2m_sink_source(
74 _env: &mut Self::InstantiateEnv,
75 _p1: &Self::Process,
76 _p1_port: &<Self::Process as Node>::Port,
77 _c2: &Self::Cluster,
78 _c2_port: &<Self::Cluster as Node>::Port,
79 _name: Option<&str>,
80 _networking_info: &crate::networking::NetworkingInfo,
81 _external_types: Option<(&syn::Type, &syn::Type)>,
82 ) -> (syn::Expr, syn::Expr) {
83 panic!("Maelstrom deployment does not support processes, only clusters")
84 }
85
86 fn o2m_connect(
87 _p1: &Self::Process,
88 _p1_port: &<Self::Process as Node>::Port,
89 _c2: &Self::Cluster,
90 _c2_port: &<Self::Cluster as Node>::Port,
91 ) -> Box<dyn FnOnce()> {
92 panic!("Maelstrom deployment does not support processes, only clusters")
93 }
94
95 fn m2o_sink_source(
96 _env: &mut Self::InstantiateEnv,
97 _c1: &Self::Cluster,
98 _c1_port: &<Self::Cluster as Node>::Port,
99 _p2: &Self::Process,
100 _p2_port: &<Self::Process as Node>::Port,
101 _name: Option<&str>,
102 _networking_info: &crate::networking::NetworkingInfo,
103 _external_types: Option<(&syn::Type, &syn::Type)>,
104 ) -> (syn::Expr, syn::Expr) {
105 panic!("Maelstrom deployment does not support processes, only clusters")
106 }
107
108 fn m2o_connect(
109 _c1: &Self::Cluster,
110 _c1_port: &<Self::Cluster as Node>::Port,
111 _p2: &Self::Process,
112 _p2_port: &<Self::Process as Node>::Port,
113 ) -> Box<dyn FnOnce()> {
114 panic!("Maelstrom deployment does not support processes, only clusters")
115 }
116
117 fn m2m_sink_source(
118 env: &mut Self::InstantiateEnv,
119 _c1: &Self::Cluster,
120 _c1_port: &<Self::Cluster as Node>::Port,
121 _c2: &Self::Cluster,
122 _c2_port: &<Self::Cluster as Node>::Port,
123 _name: Option<&str>,
124 networking_info: &crate::networking::NetworkingInfo,
125 _external_types: Option<(&syn::Type, &syn::Type)>,
126 ) -> (syn::Expr, syn::Expr) {
127 use crate::networking::{NetworkingInfo, TcpFault};
128 match networking_info {
129 NetworkingInfo::Tcp { fault } => match (fault, env.nemesis.as_deref()) {
130 (TcpFault::Lossy | TcpFault::LossyDelayedForever, _) => {} (_, None) => {} (TcpFault::FailStop, Some("partition")) => {
133 panic!(
134 "Maelstrom partition nemesis requires lossy networking, but fail_stop was used. \
135 Use `TCP.lossy().bincode()` or `TCP.lossy_delayed_forever().bincode()` instead of `TCP.fail_stop().bincode()`."
136 );
137 }
138 (TcpFault::FailStop, Some(_)) => {} },
140 NetworkingInfo::Udp { .. } => {} NetworkingInfo::Embedded { .. } => {
142 unreachable!("`EMBEDDED` channels are only supported by the embedded backend")
143 }
144 }
145 deploy_maelstrom_m2m(RuntimeData::new("__hydro_lang_maelstrom_meta"))
146 }
147
148 fn m2m_connect(
149 _c1: &Self::Cluster,
150 _c1_port: &<Self::Cluster as Node>::Port,
151 _c2: &Self::Cluster,
152 _c2_port: &<Self::Cluster as Node>::Port,
153 ) -> Box<dyn FnOnce()> {
154 Box::new(|| {})
156 }
157
158 fn e2o_many_source(
159 _extra_stmts: &mut Vec<syn::Stmt>,
160 _p2: &Self::Process,
161 _p2_port: &<Self::Process as Node>::Port,
162 _codec_type: &syn::Type,
163 _encode_type: &syn::Type,
164 _shared_handle: String,
165 ) -> syn::Expr {
166 panic!("Maelstrom deployment does not support processes, only clusters")
167 }
168
169 fn e2o_many_sink(_shared_handle: String) -> syn::Expr {
170 panic!("Maelstrom deployment does not support processes, only clusters")
171 }
172
173 fn e2o_source(
174 _extra_stmts: &mut Vec<syn::Stmt>,
175 _p1: &Self::External,
176 _p1_port: &<Self::External as Node>::Port,
177 _p2: &Self::Process,
178 _p2_port: &<Self::Process as Node>::Port,
179 _codec_type: &syn::Type,
180 _encode_type: &syn::Type,
181 _shared_handle: String,
182 ) -> syn::Expr {
183 panic!("Maelstrom deployment does not support processes, only clusters")
184 }
185
186 fn e2o_connect(
187 _p1: &Self::External,
188 _p1_port: &<Self::External as Node>::Port,
189 _p2: &Self::Process,
190 _p2_port: &<Self::Process as Node>::Port,
191 _many: bool,
192 _server_hint: NetworkHint,
193 ) -> Box<dyn FnOnce()> {
194 panic!("Maelstrom deployment does not support processes, only clusters")
195 }
196
197 fn o2e_sink(
198 _p1: &Self::Process,
199 _p1_port: &<Self::Process as Node>::Port,
200 _p2: &Self::External,
201 _p2_port: &<Self::External as Node>::Port,
202 _shared_handle: String,
203 ) -> syn::Expr {
204 panic!("Maelstrom deployment does not support processes, only clusters")
205 }
206
207 fn cluster_ids(_of_cluster: LocationKey) -> syn::Expr {
208 cluster_members(RuntimeData::new("__hydro_lang_maelstrom_meta"), _of_cluster)
209 .splice_untyped()
210 }
211
212 fn cluster_self_id() -> syn::Expr {
213 cluster_self_id(RuntimeData::new("__hydro_lang_maelstrom_meta")).splice_untyped()
214 }
215
216 fn cluster_membership_stream(
217 _env: &mut Self::InstantiateEnv,
218 _at_location: &LocationId,
219 location_id: &LocationId,
220 ) -> syn::Expr {
221 cluster_membership_stream(location_id).splice_untyped()
222 }
223}
224
225#[derive(Clone)]
227pub struct MaelstromProcess {
228 _private: (),
229}
230
231impl Node for MaelstromProcess {
232 type Port = String;
233 type Meta = ();
234 type InstantiateEnv = MaelstromDeployment;
235
236 fn next_port(&self) -> Self::Port {
237 panic!("Maelstrom deployment does not support processes")
238 }
239
240 fn update_meta(&self, _meta: &Self::Meta) {}
241
242 fn instantiate(
243 &self,
244 _env: &mut Self::InstantiateEnv,
245 _meta: &mut Self::Meta,
246 _graph: DfirGraph,
247 _extra_stmts: &[syn::Stmt],
248 _sidecars: &[syn::Expr],
249 _as_code_options: &AsCodeOptions,
250 ) {
251 panic!("Maelstrom deployment does not support processes")
252 }
253}
254
255#[derive(Clone)]
257pub struct MaelstromCluster {
258 next_port: Rc<RefCell<usize>>,
259 name_hint: Option<String>,
260}
261
262impl Node for MaelstromCluster {
263 type Port = String;
264 type Meta = ();
265 type InstantiateEnv = MaelstromDeployment;
266
267 fn next_port(&self) -> Self::Port {
268 let next_port = *self.next_port.borrow();
269 *self.next_port.borrow_mut() += 1;
270 format!("port_{}", next_port)
271 }
272
273 fn update_meta(&self, _meta: &Self::Meta) {}
274
275 fn instantiate(
276 &self,
277 env: &mut Self::InstantiateEnv,
278 _meta: &mut Self::Meta,
279 graph: DfirGraph,
280 extra_stmts: &[syn::Stmt],
281 sidecars: &[syn::Expr],
282 as_code_options: &AsCodeOptions,
283 ) {
284 let (bin_name, config) = create_graph_trybuild(
285 graph,
286 extra_stmts,
287 sidecars,
288 as_code_options,
289 self.name_hint.as_deref(),
290 crate::compile::trybuild::generate::DeployMode::Maelstrom,
291 LinkingMode::Dynamic,
292 );
293
294 env.bin_name = Some(bin_name);
295 env.trybuild = Some(config);
296 }
297}
298
299#[derive(Clone)]
301pub enum MaelstromExternal {}
302
303impl Node for MaelstromExternal {
304 type Port = String;
305 type Meta = ();
306 type InstantiateEnv = MaelstromDeployment;
307
308 fn next_port(&self) -> Self::Port {
309 unreachable!()
310 }
311
312 fn update_meta(&self, _meta: &Self::Meta) {}
313
314 fn instantiate(
315 &self,
316 _env: &mut Self::InstantiateEnv,
317 _meta: &mut Self::Meta,
318 _graph: DfirGraph,
319 _extra_stmts: &[syn::Stmt],
320 _sidecars: &[syn::Expr],
321 _as_code_options: &AsCodeOptions,
322 ) {
323 unreachable!()
324 }
325}
326
327impl<'a> RegisterPort<'a, MaelstromDeploy> for MaelstromExternal {
328 fn register(&self, _external_port_id: ExternalPortId, _port: Self::Port) {
329 unreachable!()
330 }
331
332 #[expect(clippy::manual_async_fn, reason = "false positive, involves lifetimes")]
333 fn as_bytes_bidi(
334 &self,
335 _external_port_id: ExternalPortId,
336 ) -> impl Future<
337 Output = (
338 Pin<Box<dyn Stream<Item = Result<BytesMut, Error>>>>,
339 Pin<Box<dyn Sink<Bytes, Error = Error>>>,
340 ),
341 > + 'a {
342 async move { unreachable!() }
343 }
344
345 #[expect(clippy::manual_async_fn, reason = "false positive, involves lifetimes")]
346 fn as_bincode_bidi<InT, OutT>(
347 &self,
348 _external_port_id: ExternalPortId,
349 ) -> impl Future<
350 Output = (
351 Pin<Box<dyn Stream<Item = OutT>>>,
352 Pin<Box<dyn Sink<InT, Error = Error>>>,
353 ),
354 > + 'a
355 where
356 InT: Serialize + 'static,
357 OutT: DeserializeOwned + 'static,
358 {
359 async move { unreachable!() }
360 }
361
362 #[expect(clippy::manual_async_fn, reason = "false positive, involves lifetimes")]
363 fn as_bincode_sink<T: Serialize + 'static>(
364 &self,
365 _external_port_id: ExternalPortId,
366 ) -> impl Future<Output = Pin<Box<dyn Sink<T, Error = Error>>>> + 'a {
367 async move { unreachable!() }
368 }
369
370 #[expect(clippy::manual_async_fn, reason = "false positive, involves lifetimes")]
371 fn as_bincode_source<T: DeserializeOwned + 'static>(
372 &self,
373 _external_port_id: ExternalPortId,
374 ) -> impl Future<Output = Pin<Box<dyn Stream<Item = T>>>> + 'a {
375 async move { unreachable!() }
376 }
377}
378
379#[derive(Clone)]
381pub struct MaelstromClusterSpec;
382
383impl<'a> ClusterSpec<'a, MaelstromDeploy> for MaelstromClusterSpec {
384 fn build(self, key: LocationKey, name_hint: &str) -> MaelstromCluster {
385 assert_eq!(
386 key,
387 LocationKey::FIRST,
388 "there should only be one location for a Maelstrom deployment"
389 );
390 MaelstromCluster {
391 next_port: Rc::new(RefCell::new(0)),
392 name_hint: Some(name_hint.to_owned()),
393 }
394 }
395}
396
397pub struct MaelstromDeployment {
402 pub node_count: usize,
404 pub maelstrom_path: PathBuf,
406 pub workload: String,
408 pub time_limit: Option<u64>,
410 pub rate: Option<u64>,
412 pub availability: Option<String>,
414 pub nemesis: Option<String>,
416 pub extra_args: Vec<String>,
418
419 pub(crate) bin_name: Option<String>,
421 pub(crate) trybuild: Option<TrybuildConfig>,
422}
423
424impl MaelstromDeployment {
425 pub fn new(workload: impl Into<String>) -> Self {
427 Self {
428 node_count: 1,
429 maelstrom_path: PathBuf::from("maelstrom"),
430 workload: workload.into(),
431 time_limit: None,
432 rate: None,
433 availability: None,
434 nemesis: None,
435 extra_args: vec![],
436 bin_name: None,
437 trybuild: None,
438 }
439 }
440
441 #[must_use]
443 pub fn node_count(mut self, count: usize) -> Self {
444 self.node_count = count;
445 self
446 }
447
448 pub fn maelstrom_path(mut self, path: impl Into<PathBuf>) -> Self {
450 self.maelstrom_path = path.into();
451 self
452 }
453
454 #[must_use]
456 pub fn time_limit(mut self, seconds: u64) -> Self {
457 self.time_limit = Some(seconds);
458 self
459 }
460
461 #[must_use]
463 pub fn rate(mut self, rate: u64) -> Self {
464 self.rate = Some(rate);
465 self
466 }
467
468 pub fn availability(mut self, availability: impl Into<String>) -> Self {
470 self.availability = Some(availability.into());
471 self
472 }
473
474 pub fn nemesis(mut self, nemesis: impl Into<String>) -> Self {
476 self.nemesis = Some(nemesis.into());
477 self
478 }
479
480 pub fn extra_args(mut self, args: impl IntoIterator<Item = impl Into<String>>) -> Self {
482 self.extra_args.extend(args.into_iter().map(Into::into));
483 self
484 }
485
486 pub fn build(&self) -> Result<PathBuf, Error> {
494 let bin_name = self
495 .bin_name
496 .as_ref()
497 .expect("No binary name set - did you call deploy?");
498 let trybuild = self
499 .trybuild
500 .as_ref()
501 .expect("No trybuild config set - did you call deploy?");
502
503 compile_trybuild_example(ExampleBuildConfig {
504 trybuild: trybuild.clone(),
505 bin_name: bin_name.clone(),
506 runtime_feature: "hydro___feature_maelstrom_runtime",
507 example_name: bin_name.clone(),
509 crate_type: None,
510 set_trybuild_lib_name: false,
511 })
512 .map_err(|()| Error::other("Maelstrom binary compilation failed"))
513 }
514
515 pub fn run(self) -> Result<(), Error> {
519 let binary_path = self.build()?;
520
521 std::process::Command::new(&binary_path)
530 .stdin(Stdio::null())
531 .stdout(Stdio::null())
532 .stderr(Stdio::null())
533 .spawn()?
534 .wait()?;
535
536 let run_dir = tempfile::tempdir().map_err(Error::other)?;
538
539 let mut cmd = std::process::Command::new(&self.maelstrom_path);
540 cmd.arg("test")
541 .arg("-w")
542 .arg(&self.workload)
543 .arg("--bin")
544 .arg(&binary_path)
545 .arg("--node-count")
546 .arg(self.node_count.to_string())
547 .current_dir(run_dir.path())
548 .stdout(Stdio::piped());
549
550 if let Some(time_limit) = self.time_limit {
551 cmd.arg("--time-limit").arg(time_limit.to_string());
552 }
553
554 if let Some(rate) = self.rate {
555 cmd.arg("--rate").arg(rate.to_string());
556 }
557
558 if let Some(availability) = self.availability {
559 cmd.arg("--availability").arg(availability);
560 }
561
562 if let Some(nemesis) = self.nemesis {
563 cmd.arg("--nemesis").arg(nemesis);
564 }
565
566 for arg in &self.extra_args {
567 cmd.arg(arg);
568 }
569
570 let spawned = cmd.spawn()?;
571
572 for line in BufReader::new(spawned.stdout.unwrap()).lines() {
573 let line = line?;
574 eprintln!("{}", line);
575
576 if line.starts_with("Analysis invalid!") {
577 let path = run_dir.keep();
578 dump_node_logs(&path);
579 return Err(Error::other(format!(
580 "Analysis was invalid. Maelstrom store at: {}",
581 path.display()
582 )));
583 } else if line.starts_with("Errors occurred during analysis, but no anomalies found.")
584 || line.starts_with("Everything looks good!")
585 {
586 return Ok(());
587 }
588 }
589
590 let path = run_dir.keep();
591 dump_node_logs(&path);
592 Err(Error::other(format!(
593 "Maelstrom produced an unexpected result. Store at: {}",
594 path.display()
595 )))
596 }
597
598 pub fn binary_path(&self) -> Option<PathBuf> {
600 self.build().ok()
601 }
602}
603
604fn dump_node_logs(run_dir: &Path) {
612 fn collect(dir: &Path, out: &mut Vec<PathBuf>) {
613 let Ok(entries) = std::fs::read_dir(dir) else {
614 return;
615 };
616 for entry in entries.flatten() {
617 let path = entry.path();
618 if path.is_symlink() || !path.is_dir() {
620 continue;
621 }
622 if path.file_name().is_some_and(|name| name == "node-logs") {
623 if let Ok(logs) = std::fs::read_dir(&path) {
624 out.extend(logs.flatten().map(|e| e.path()));
625 }
626 } else {
627 collect(&path, out);
628 }
629 }
630 }
631
632 let mut log_files = Vec::new();
633 collect(&run_dir.join("store"), &mut log_files);
634 log_files.sort();
635
636 for log in log_files {
637 eprintln!("==== Maelstrom node log: {} ====", log.display());
638 match std::fs::read_to_string(&log) {
639 Ok(contents) => eprint!("{}", contents),
640 Err(e) => eprintln!("(failed to read log: {})", e),
641 }
642 eprintln!("==== end of node log: {} ====", log.display());
643 }
644}