Skip to main content

hydro_lang/deploy/maelstrom/
deploy_runtime_maelstrom.rs

1//! Runtime support for Maelstrom deployment backend.
2//!
3//! This module provides the runtime code that runs inside Maelstrom nodes,
4//! handling stdin/stdout JSON message passing according to the Maelstrom protocol.
5
6#![allow(
7    unused,
8    reason = "unused in trybuild but the __staged version is needed"
9)]
10#![allow(missing_docs, reason = "used internally")]
11
12use std::io::{BufRead, Write};
13use std::sync::Arc;
14use std::sync::atomic::{AtomicBool, Ordering};
15
16use futures::{Stream, StreamExt};
17use serde::{Deserialize, Serialize};
18use stageleft::{QuotedWithContext, RuntimeData, q};
19
20use crate::forward_handle::ForwardHandle;
21use crate::live_collections::boundedness::Unbounded;
22use crate::live_collections::keyed_stream::KeyedStream;
23use crate::live_collections::stream::{ExactlyOnce, NoOrder, TotalOrder};
24use crate::location::dynamic::LocationId;
25use crate::location::{Cluster, LocationKey, MembershipEvent};
26use crate::nondet::nondet;
27
28/// Maelstrom message envelope structure.
29#[derive(Debug, Clone, Serialize, Deserialize)]
30pub struct MaelstromMessage<T> {
31    pub src: String,
32    pub dest: String,
33    pub body: T,
34}
35
36/// Maelstrom init message body.
37#[derive(Debug, Clone, Serialize, Deserialize)]
38pub struct InitBody {
39    #[serde(rename = "type")]
40    pub msg_type: String,
41    pub msg_id: u64,
42    pub node_id: String,
43    pub node_ids: Vec<String>,
44}
45
46/// Maelstrom `init_ok` response body.
47#[derive(Debug, Clone, Serialize, Deserialize)]
48pub struct InitOkBody {
49    #[serde(rename = "type")]
50    pub msg_type: String,
51    pub in_reply_to: u64,
52}
53
54/// Metadata for a Maelstrom node, populated from the init message.
55/// Also manages a shared stdin reader that broadcasts lines to multiple subscribers.
56pub struct MaelstromMeta {
57    pub node_id: String,
58    pub node_ids: Vec<String>,
59    stdin_tx: tokio::sync::broadcast::Sender<String>,
60    /// Set once this node has received its first post-`init` message from a client or a
61    /// peer node. Until then, outbound node-to-node messages are dropped; see
62    /// [`MaelstromMeta::peers_ready`] for why this is necessary.
63    peers_ready: Arc<AtomicBool>,
64}
65
66impl MaelstromMeta {
67    /// Subscribe to stdin lines. Each subscriber receives all lines read from stdin.
68    /// Multiple subscribers can be created and each will receive a copy of every line.
69    pub fn subscribe_stdin(&self) -> tokio_stream::wrappers::BroadcastStream<String> {
70        tokio_stream::wrappers::BroadcastStream::new(self.stdin_tx.subscribe())
71    }
72
73    /// A flag that becomes `true` once it is safe to send node-to-node messages.
74    ///
75    /// Maelstrom sets up nodes concurrently: each node's process is launched, registered in
76    /// the simulated network, and sent `init` independently, with no barrier in between. A
77    /// node that answers `init` quickly may therefore start sending to a peer whose process
78    /// Maelstrom has not launched yet. Maelstrom treats a message to an unregistered
79    /// destination as a fatal assertion failure (`Invalid dest for message ...`) and
80    /// permanently stops reading the *sender's* stdout, so every later response from that
81    /// node (e.g. `topology_ok`) is silently lost and the test fails with
82    /// `Client read timeout`.
83    ///
84    /// Jepsen only opens clients after `db/setup!` (launch + `init`) has completed on every
85    /// node, so receiving a client message proves all peers are registered. A message from a
86    /// peer node proves the same thing transitively: peers also hold their outbound messages
87    /// until *they* have been activated, so any peer message we receive was sent after some
88    /// node observed a client message. Dropping outbound messages before activation is
89    /// permitted because node-to-node channels in the Maelstrom backend are lossy.
90    pub fn peers_ready(&self) -> Arc<AtomicBool> {
91        self.peers_ready.clone()
92    }
93
94    /// Start receiving incoming messages from clients and other nodes, after launching the DFIR.
95    pub fn start_receiving(&self) {
96        let tx_clone = self.stdin_tx.clone();
97        let peers_ready = self.peers_ready.clone();
98        let node_ids: std::collections::HashSet<String> = self.node_ids.iter().cloned().collect();
99
100        // Spawn thread to read stdin and broadcast lines
101        std::thread::spawn(move || {
102            let stdin = std::io::stdin();
103            for line in stdin.lock().lines() {
104                match line {
105                    Ok(l) => {
106                        if !peers_ready.load(Ordering::Relaxed)
107                            && message_activates_node(&l, &node_ids)
108                        {
109                            peers_ready.store(true, Ordering::Release);
110                        }
111                        // Ignore send errors (no receivers)
112                        let _ = tx_clone.send(l);
113                    }
114                    Err(_) => break,
115                }
116            }
117        });
118    }
119}
120
121/// Whether receiving `line` proves that every node in the cluster has been registered in the
122/// Maelstrom network (see [`MaelstromMeta::peers_ready`]). This is the case for messages from
123/// peer nodes and from Jepsen clients (`c1`, `c2`, ...). Replies from Maelstrom's built-in
124/// services (`lin-kv`, `seq-kv`, ...) do not count: services are registered before any node is
125/// launched, so a service reply can arrive while peers are still being set up.
126fn message_activates_node(line: &str, node_ids: &std::collections::HashSet<String>) -> bool {
127    let Ok(msg) = serde_json::from_str::<MaelstromMessage<serde_json::Value>>(line) else {
128        return false;
129    };
130    node_ids.contains(&msg.src) || msg.src.starts_with('c')
131}
132
133/// Initialize a Maelstrom node by reading the init message from stdin.
134/// Returns the node metadata and sends `init_ok` response.
135/// Also spawns a background thread to read stdin and broadcast lines to subscribers.
136pub fn maelstrom_init() -> MaelstromMeta {
137    let stdin = std::io::stdin();
138    let mut stdout = std::io::stdout();
139
140    // Read until the init message arrives. Maelstrom delivers node-to-node
141    // messages to a node's stdin as soon as the process starts, so a peer
142    // may already be sending `hydro_data` messages before the init RPC for
143    // this node is sent (e.g. after this node was killed and restarted by a
144    // nemesis) — the first line on stdin is not necessarily `init`. Such
145    // pre-init messages are dropped: inter-node channels in the Maelstrom
146    // backend are lossy, so dropped messages are handled the same as network
147    // loss.
148    let msg: MaelstromMessage<InitBody> = loop {
149        let mut line = String::new();
150        let bytes_read = stdin
151            .lock()
152            .read_line(&mut line)
153            .expect("Failed to read init message");
154
155        if bytes_read == 0 {
156            // stdin reached EOF before an init message arrived. This happens when
157            // Maelstrom tears the node down (e.g. after an init timeout) or during
158            // a warmup invocation with no input. Exit cleanly instead of panicking
159            // so the node is not reported as "crashed", which would mask the real
160            // error (such as the init timeout).
161            eprintln!("stdin closed before an init message was received; exiting");
162            std::process::exit(0);
163        }
164
165        let parsed: MaelstromMessage<serde_json::Value> =
166            serde_json::from_str(&line).expect("Failed to parse message while waiting for init");
167
168        if parsed.body.get("type").and_then(|t| t.as_str()) == Some("init") {
169            let body: InitBody =
170                serde_json::from_value(parsed.body).expect("Failed to parse init message");
171            break MaelstromMessage {
172                src: parsed.src,
173                dest: parsed.dest,
174                body,
175            };
176        }
177        eprintln!(
178            "dropping message received before init (lossy channel): {}",
179            line.trim_end()
180        );
181    };
182
183    // Set up broadcast channel for stdin lines
184    let (stdin_tx, _) = tokio::sync::broadcast::channel::<String>(1024);
185
186    let meta = MaelstromMeta {
187        node_id: msg.body.node_id.clone(),
188        node_ids: msg.body.node_ids.clone(),
189        stdin_tx,
190        peers_ready: Arc::new(AtomicBool::new(false)),
191    };
192
193    // Send init_ok response
194    let response = MaelstromMessage {
195        src: msg.body.node_id,
196        dest: msg.src,
197        body: InitOkBody {
198            msg_type: "init_ok".to_owned(),
199            in_reply_to: msg.body.msg_id,
200        },
201    };
202
203    let response_json = serde_json::to_string(&response).expect("Failed to serialize init_ok");
204    writeln!(stdout, "{}", response_json).expect("Failed to write init_ok");
205    stdout.flush().expect("Failed to flush stdout");
206
207    meta
208}
209
210/// Get the cluster member IDs from the Maelstrom metadata.
211/// The `meta` parameter is a `RuntimeData` reference to the `MaelstromMeta` that will be
212/// available at runtime as `__hydro_lang_maelstrom_meta`.
213pub(super) fn cluster_members<'a>(
214    meta: RuntimeData<&'a MaelstromMeta>,
215    _of_cluster: LocationKey,
216) -> impl QuotedWithContext<'a, &'a [String], ()> + Clone + 'a {
217    q!({
218        let members: &'static [String] = Box::leak(
219            meta.node_ids
220                .iter()
221                .cloned()
222                .collect::<Vec<String>>()
223                .into_boxed_slice(),
224        );
225        members
226    })
227}
228
229/// Get the self ID for this cluster member.
230pub(super) fn cluster_self_id<'a>(
231    meta: RuntimeData<&'a MaelstromMeta>,
232) -> impl QuotedWithContext<'a, String, ()> + Clone + 'a {
233    q!(meta.node_id.clone())
234}
235
236/// Get the cluster membership stream (static for Maelstrom - all members join at start).
237/// This references `__hydro_lang_maelstrom_meta` which will be in scope at runtime.
238pub(super) fn cluster_membership_stream<'a>(
239    _location_id: &LocationId,
240) -> impl QuotedWithContext<'a, Box<dyn Stream<Item = (String, MembershipEvent)> + Unpin>, ()> {
241    let meta: RuntimeData<&MaelstromMeta> = RuntimeData::new("__hydro_lang_maelstrom_meta");
242    q!(Box::new(futures::stream::iter(
243        meta.node_ids
244            .iter()
245            .map(|id| (id.clone(), MembershipEvent::Joined))
246            .collect::<Vec<_>>()
247    ))
248        as Box<
249            dyn futures::Stream<Item = (String, MembershipEvent)> + Unpin,
250        >)
251}
252
253/// Create sink and source for m2m (cluster member to cluster member) communication.
254/// Messages are routed through Maelstrom's network via stdin/stdout.
255pub(super) fn deploy_maelstrom_m2m(meta: RuntimeData<&MaelstromMeta>) -> (syn::Expr, syn::Expr) {
256    // Sink: serialize and write to stdout with Maelstrom message envelope.
257    // Messages are dropped until the node has been activated by an incoming
258    // client or peer message; see `MaelstromMeta::peers_ready`.
259    let sink_expr = q!({
260        let node_id = meta.node_id.clone();
261        let peers_ready = meta.peers_ready();
262        sinktools::map(
263            move |(dest_id, payload): (String, bytes::Bytes)| {
264                let msg = serde_json::json!({
265                    "src": node_id,
266                    "dest": dest_id.as_str(),
267                    "body": {
268                        "type": "hydro_data",
269                        "data": payload.to_vec()
270                    }
271                });
272                let mut line = serde_json::to_string(&msg).unwrap();
273                line.push('\n');
274                line
275            },
276            futures::sink::unfold(
277                peers_ready,
278                |peers_ready: std::sync::Arc<std::sync::atomic::AtomicBool>, line: String| {
279                    Box::pin(async move {
280                        if peers_ready.load(std::sync::atomic::Ordering::Acquire) {
281                            print!("{}", line);
282                            std::io::stdout().flush().ok();
283                        } else {
284                            eprintln!(
285                                "dropping message sent before peers are known to be up (lossy channel): {}",
286                                line.trim_end()
287                            );
288                        }
289                        Ok::<_, std::io::Error>(peers_ready)
290                    })
291                },
292            ),
293        )
294    })
295    .splice_untyped_ctx(&());
296
297    // Source: subscribe to the shared stdin broadcast stream
298    let source_expr = q!({
299        let node_ids: std::collections::HashSet<String> = meta.node_ids.iter().cloned().collect();
300        let lines = meta.subscribe_stdin();
301        futures::StreamExt::filter_map(lines, move |line_result| {
302            let node_ids = node_ids.clone();
303            Box::pin(async move {
304                let line = line_result.ok()?;
305                let mut msg =
306                    serde_json::from_str::<MaelstromMessage<serde_json::Value>>(&line).ok()?;
307                // Only process messages from other nodes (not clients)
308                if msg
309                    .body
310                    .get("type")
311                    .is_some_and(|t| t.as_str() == Some("hydro_data"))
312                {
313                    let deser: Vec<u8> =
314                        serde_json::from_value(msg.body.get_mut("data").unwrap().take()).unwrap();
315                    Some(Ok::<_, std::io::Error>((
316                        msg.src,
317                        bytes::BytesMut::from(&deser[..]),
318                    )))
319                } else {
320                    None
321                }
322            })
323        })
324    })
325    .splice_untyped_ctx(&());
326
327    (sink_expr, source_expr)
328}
329
330/// Creates a stream of client messages from Maelstrom stdin.
331/// Returns tuples of `(client_id, message_body)` where `client_id` is the source client
332/// and `message_body` is the JSON value of the message body.
333///
334/// This function is meant to be used with `source_stream` on a Cluster location.
335pub fn maelstrom_client_source(
336    meta: &MaelstromMeta,
337) -> impl Stream<Item = (String, serde_json::Value)> + Unpin {
338    use std::collections::HashSet;
339
340    let node_ids: HashSet<String> = meta.node_ids.iter().cloned().collect();
341    let lines = meta.subscribe_stdin();
342
343    Box::pin(lines.filter_map(move |line_result| {
344        let node_ids = node_ids.clone();
345        async move {
346            let line = line_result.ok()?;
347            let msg: MaelstromMessage<serde_json::Value> = serde_json::from_str(&line).ok()?;
348            // Only process messages from clients (not other nodes)
349            if !node_ids.contains(&msg.src) {
350                Some((msg.src, msg.body))
351            } else {
352                None
353            }
354        }
355    }))
356}
357
358/// Sends a response to a Maelstrom client via stdout.
359///
360/// This function is meant to be used with `for_each` on a stream of responses.
361pub fn maelstrom_send_response(node_id: &str, client_id: &str, body: serde_json::Value) {
362    use std::io::Write;
363
364    let msg = MaelstromMessage {
365        src: node_id.to_owned(),
366        dest: client_id.to_owned(),
367        body,
368    };
369
370    let json = serde_json::to_string(&msg).expect("Failed to serialize response");
371    println!("{}", json);
372    std::io::stdout().flush().ok();
373}