Skip to main content

hydro_lang/location/
cluster.rs

1//! Definitions for clusters, which represent a group of identical processes.
2//!
3//! A [`Cluster`] is a multi-node location in the Hydro distributed programming model.
4//! Unlike a [`super::Process`], which maps to a single machine, a cluster represents
5//! a dynamically-sized set of machines that all run the same code. Each member of the
6//! cluster is assigned a unique [`super::MemberId`] that can be used to address it.
7//!
8//! Clusters are useful for parallelism, replication, and sharding patterns. Data can
9//! be broadcast to all members, sent to a specific member by ID, or scattered across
10//! members.
11
12use std::fmt::{Debug, Formatter};
13use std::marker::PhantomData;
14
15use proc_macro2::Span;
16use quote::quote;
17use stageleft::runtime_support::{FreeVariableWithContextWithProps, QuoteTokens};
18use stageleft::{QuotedWithContextWithProps, quote_type};
19
20use super::dynamic::LocationId;
21use super::{Location, MemberId};
22use crate::compile::builder::FlowState;
23use crate::location::dynamic::ClusterConsistency;
24use crate::location::{LocationKey, TopLevel};
25use crate::staging_util::{Invariant, get_this_crate};
26
27/// A marker trait for levels of consistency that can be guaranteed for a live collection placed
28/// across members of a cluster.
29pub trait Consistency {
30    /// Gets the runtime enum variant associated with this consistency level.
31    fn consistency() -> ClusterConsistency;
32}
33
34/// No consistency is guaranteed across cluster members, which means that the live collection
35/// may take on arbitrarily different values across members.
36pub enum NoConsistency {}
37impl Consistency for NoConsistency {
38    fn consistency() -> ClusterConsistency {
39        ClusterConsistency::NoConsistency
40    }
41}
42
43/// Eventual consistency is guaranteed across cluster members, which means that at steady-state
44/// the live collection will always resolve to the same value across all members of the cluster.
45pub enum EventualConsistency {}
46impl Consistency for EventualConsistency {
47    fn consistency() -> ClusterConsistency {
48        ClusterConsistency::EventualConsistency
49    }
50}
51
52/// A multi-node location representing a group of identical processes.
53///
54/// Each member of the cluster runs the same dataflow program and is assigned a
55/// unique [`MemberId`] that can be used to address it. The number of members
56/// is determined at deployment time rather than at compile time.
57///
58/// The `ClusterTag` type parameter is a phantom tag used to distinguish between
59/// different clusters in the type system, preventing accidental mixing of
60/// member IDs across clusters. `Id` is the type of its members' IDs (see [`MemberId`]).
61pub struct Cluster<'a, ClusterTag, Id = u32, Con: Consistency = NoConsistency> {
62    pub(crate) key: LocationKey,
63    pub(crate) flow_state: FlowState,
64    pub(crate) _phantom: Invariant<'a, (ClusterTag, Con, Id)>,
65}
66
67impl<C, Con: Consistency, Id> Debug for Cluster<'_, C, Id, Con> {
68    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
69        write!(f, "Cluster({})", self.key)
70    }
71}
72
73impl<C, Con: Consistency, Id> Eq for Cluster<'_, C, Id, Con> {}
74impl<C, Con: Consistency, Id> PartialEq for Cluster<'_, C, Id, Con> {
75    fn eq(&self, other: &Self) -> bool {
76        self.key == other.key && FlowState::ptr_eq(&self.flow_state, &other.flow_state)
77    }
78}
79
80impl<C, Con: Consistency, Id> Clone for Cluster<'_, C, Id, Con> {
81    fn clone(&self) -> Self {
82        Cluster {
83            key: self.key,
84            flow_state: self.flow_state.clone(),
85            _phantom: PhantomData,
86        }
87    }
88}
89
90impl<'a, C, Con: Consistency, Id> super::dynamic::DynLocation for Cluster<'a, C, Id, Con> {
91    fn dyn_id(&self) -> LocationId {
92        LocationId::Cluster(self.key)
93    }
94
95    fn flow_state(&self) -> &FlowState {
96        &self.flow_state
97    }
98
99    fn is_top_level() -> bool {
100        true
101    }
102
103    fn multiversioned(&self) -> bool {
104        false // TODO(shadaj): enable multiversioning support for clusters
105    }
106
107    fn cluster_consistency() -> Option<ClusterConsistency> {
108        Some(Con::consistency())
109    }
110}
111
112impl<'a, C, Con: Consistency, Id> Location<'a> for Cluster<'a, C, Id, Con> {
113    type Root = Cluster<'a, C, Id, Con>;
114
115    type SimHookScope = crate::sim_hooks::OnCluster<C>;
116
117    type DropConsistency = Cluster<'a, C, Id>;
118
119    fn consistency() -> Option<ClusterConsistency> {
120        Some(Con::consistency())
121    }
122
123    fn root(&self) -> Self::Root {
124        self.clone()
125    }
126
127    fn drop_consistency(&self) -> Self::DropConsistency {
128        Cluster {
129            key: self.key,
130            flow_state: self.flow_state.clone(),
131            _phantom: PhantomData,
132        }
133    }
134
135    fn from_drop_consistency(l2: Self::DropConsistency) -> Self {
136        Cluster {
137            key: l2.key,
138            flow_state: l2.flow_state,
139            _phantom: PhantomData,
140        }
141    }
142}
143
144impl<'a, C, Con: Consistency, Id> TopLevel<'a> for Cluster<'a, C, Id, Con> {}
145
146#[cfg(feature = "sim")]
147impl<'a, C> Cluster<'a, C> {
148    /// Sets up a MessagePack-encoded simulated input port on this cluster for testing.
149    ///
150    /// Returns a `SimClusterSender` that sends `(member_id, T)` messages targeting
151    /// specific cluster members, and a `Stream<T>` received by each member. Use
152    /// [`Cluster::sim_input_with`] to select another codec.
153    ///
154    /// This method is generic over the [`Ordering`](crate::live_collections::stream::Ordering)
155    /// and [`Retries`](crate::live_collections::stream::Retries) guarantees of the produced
156    /// stream, mirroring [`Location::sim_input`]. For
157    /// unordered inputs (e.g. anything downstream of a `NoOrder` network channel), create the
158    /// input with `O = NoOrder` and drive it with
159    /// [`SimClusterSender::send_many_unordered`](crate::sim::SimClusterSender::send_many_unordered).
160    pub fn sim_input<
161        T,
162        O: crate::live_collections::stream::Ordering,
163        R: crate::live_collections::stream::Retries,
164    >(
165        &self,
166    ) -> (
167        crate::sim::SimClusterSender<T, O, R>,
168        crate::live_collections::Stream<
169            T,
170            Self,
171            crate::live_collections::boundedness::Unbounded,
172            O,
173            R,
174        >,
175    )
176    where
177        T: serde::Serialize + serde::de::DeserializeOwned,
178    {
179        self.sim_input_with::<crate::sim::codec::RmpCodec, T, O, R>()
180    }
181
182    /// Sets up a simulated input port on this cluster using the codec `Codec`.
183    ///
184    /// Returns a `SimClusterSender` that sends `(member_id, T)` messages targeting
185    /// specific cluster members, and a `Stream<T>` received by each member. The codec is a
186    /// type parameter; the message, ordering and retries types are usually inferred:
187    /// `cluster.sim_input_with::<MyCodec, _, _, _>()`. Custom codecs implement
188    /// [`SimCodec`](crate::sim::codec::SimCodec), which documents where they must be
189    /// defined. See [`Cluster::sim_input`] for the ordering and retries guarantees.
190    pub fn sim_input_with<
191        Codec: crate::sim::codec::SimCodec<T>,
192        T,
193        O: crate::live_collections::stream::Ordering,
194        R: crate::live_collections::stream::Retries,
195    >(
196        &self,
197    ) -> (
198        crate::sim::SimClusterSender<T, O, R>,
199        crate::live_collections::Stream<
200            T,
201            Self,
202            crate::live_collections::boundedness::Unbounded,
203            O,
204            R,
205        >,
206    ) {
207        let external_location: crate::location::External<'a, ()> = crate::location::External {
208            key: LocationKey::FIRST,
209            flow_state: self.flow_state.clone(),
210            _phantom: PhantomData,
211        };
212
213        let (external_port_id, stream) = super::register_serialized_external_input(
214            self,
215            &external_location,
216            crate::sim::codec::staged_deserialize::<T, Codec>(),
217        );
218
219        (
220            crate::sim::SimClusterSender(external_port_id, PhantomData, Codec::encode),
221            stream.weaken_ordering().weaken_retries(),
222        )
223    }
224}
225
226/// A free variable that resolves to the list of member IDs in a cluster at runtime.
227///
228/// When spliced into a quoted snippet, it gives the IDs of the cluster's members.
229pub struct ClusterIds<'a, Id> {
230    /// The location key identifying which cluster this refers to.
231    pub key: LocationKey,
232    /// Binds the lifetime and the ID type.
233    pub _phantom: PhantomData<&'a Id>,
234}
235
236impl<'a, Id> Clone for ClusterIds<'a, Id> {
237    fn clone(&self) -> Self {
238        Self {
239            key: self.key,
240            _phantom: Default::default(),
241        }
242    }
243}
244
245impl<'a, Ctx, Id: 'a> FreeVariableWithContextWithProps<Ctx, ()> for ClusterIds<'a, Id> {
246    type O = &'a [Id];
247
248    fn to_tokens(self, _ctx: &Ctx) -> (QuoteTokens, ())
249    where
250        Self: Sized,
251    {
252        let ident = syn::Ident::new(
253            &format!("__hydro_lang_cluster_ids_{}", self.key),
254            Span::call_site(),
255        );
256
257        (
258            QuoteTokens {
259                prelude: None,
260                expr: Some(quote! { #ident }),
261            },
262            (),
263        )
264    }
265}
266
267impl<'a, Ctx, Id: 'a> QuotedWithContextWithProps<'a, &'a [Id], Ctx, ()> for ClusterIds<'a, Id> {}
268
269/// Marker trait implemented by [`Cluster`] locations, providing access to the cluster tag type.
270pub trait IsCluster {
271    /// The phantom tag type that distinguishes this cluster from others.
272    type Tag;
273    /// The type of the cluster's member IDs.
274    type Id;
275}
276
277impl<C, Id> IsCluster for Cluster<'_, C, Id> {
278    type Tag = C;
279    type Id = Id;
280}
281
282/// A free variable representing the cluster's own ID. When spliced in
283/// a quoted snippet that will run on a cluster, this turns into a [`MemberId`].
284pub static CLUSTER_SELF_ID: ClusterSelfId<'static> = ClusterSelfId { _private: &() };
285
286/// The concrete type behind [`CLUSTER_SELF_ID`].
287///
288/// This is a compile-time variable that, when spliced into a quoted snippet running
289/// on a [`Cluster`], resolves to the [`MemberId`] of the current cluster member.
290#[derive(Clone, Copy)]
291pub struct ClusterSelfId<'a> {
292    _private: &'a (),
293}
294
295impl<'a, Ctx> FreeVariableWithContextWithProps<Ctx, ()> for ClusterSelfId<'a>
296where
297    Ctx: crate::live_collections::ContextWithLocation<'a>,
298    <Ctx::Location as Location<'a>>::Root: IsCluster,
299{
300    type O = MemberId<
301        <<Ctx::Location as Location<'a>>::Root as IsCluster>::Tag,
302        <<Ctx::Location as Location<'a>>::Root as IsCluster>::Id,
303    >;
304
305    fn to_tokens(self, ctx: &Ctx) -> (QuoteTokens, ())
306    where
307        Self: Sized,
308    {
309        let LocationId::Cluster(cluster_id) = ctx.context_location().root().id() else {
310            unreachable!()
311        };
312        crate::location::dynamic::DynLocation::flow_state(ctx.context_location())
313            .borrow_mut()
314            .clusters_reading_self_id
315            .insert(cluster_id);
316
317        let ident = syn::Ident::new(
318            &format!("__hydro_lang_cluster_self_id_{}", cluster_id),
319            Span::call_site(),
320        );
321        let root = get_this_crate();
322        let c_type: syn::Type =
323            quote_type::<<<Ctx::Location as Location<'a>>::Root as IsCluster>::Tag>();
324
325        (
326            QuoteTokens {
327                prelude: None,
328                expr: Some(
329                    quote! { #root::__staged::location::MemberId::<#c_type, _>::from_tagless((#ident).clone()) },
330                ),
331            },
332            (),
333        )
334    }
335}
336
337impl<'a, Ctx>
338    QuotedWithContextWithProps<
339        'a,
340        MemberId<
341            <<Ctx::Location as Location<'a>>::Root as IsCluster>::Tag,
342            <<Ctx::Location as Location<'a>>::Root as IsCluster>::Id,
343        >,
344        Ctx,
345        (),
346    > for ClusterSelfId<'a>
347where
348    Ctx: crate::live_collections::ContextWithLocation<'a>,
349    <Ctx::Location as Location<'a>>::Root: IsCluster,
350{
351}
352
353#[cfg(test)]
354mod tests {
355    #[cfg(feature = "sim")]
356    use stageleft::q;
357
358    #[cfg(feature = "sim")]
359    use super::CLUSTER_SELF_ID;
360    #[cfg(feature = "sim")]
361    use crate::location::{Location, MemberId, MembershipEvent};
362    #[cfg(feature = "sim")]
363    use crate::networking::TCP;
364    #[cfg(feature = "sim")]
365    use crate::nondet::nondet;
366    #[cfg(feature = "sim")]
367    use crate::prelude::FlowBuilder;
368
369    #[cfg(feature = "sim")]
370    #[test]
371    fn sim_cluster_self_id() {
372        let mut flow = FlowBuilder::new();
373        let cluster1 = flow.cluster::<(), u32>();
374        let cluster2 = flow.cluster::<(), u32>();
375
376        let node = flow.process::<()>();
377
378        let out_recv = cluster1
379            .source_iter(q!(vec![CLUSTER_SELF_ID]))
380            .send(&node, TCP.fail_stop().bincode())
381            .values()
382            .merge_unordered(
383                cluster2
384                    .source_iter(q!(vec![CLUSTER_SELF_ID]))
385                    .send(&node, TCP.fail_stop().bincode())
386                    .values(),
387            )
388            .sim_output();
389
390        flow.sim()
391            .with_cluster_size(&cluster1, 3)
392            .with_cluster_size(&cluster2, 4)
393            .exhaustive(async || {
394                out_recv
395                    .assert_yields_only_unordered([0, 1, 2, 0, 1, 2, 3].map(MemberId::from_raw_id))
396                    .await
397            });
398    }
399
400    #[cfg(feature = "sim")]
401    #[test]
402    fn sim_cluster_with_tick() {
403        use std::collections::HashMap;
404
405        let mut flow = FlowBuilder::new();
406        let cluster = flow.cluster::<(), u32>();
407        let node = flow.process::<()>();
408
409        let out_recv = cluster
410            .source_iter(q!(vec![1, 2, 3]))
411            .batch(&cluster.tick(), nondet!(/** test */))
412            .count()
413            .all_ticks()
414            .send(&node, TCP.fail_stop().bincode())
415            .entries()
416            .map(q!(|(id, v)| (id, v)))
417            .sim_output();
418
419        let count = flow
420            .sim()
421            .with_cluster_size(&cluster, 2)
422            .exhaustive(async || {
423                let grouped = out_recv.collect_sorted::<Vec<_>>().await.into_iter().fold(
424                    HashMap::new(),
425                    |mut acc: HashMap<MemberId<()>, usize>, (id, v)| {
426                        *acc.entry(id).or_default() += v;
427                        acc
428                    },
429                );
430
431                assert_eq!(grouped.len(), 2);
432                for (_id, v) in grouped {
433                    assert_eq!(v, 3);
434                }
435            });
436
437        assert_eq!(count, 106);
438        // not a square because we simulate all interleavings of ticks across 2 cluster members
439        // eventually, we should be able to identify that the members are independent (because
440        // there are no dataflow cycles) and avoid simulating redundant interleavings
441    }
442
443    #[cfg(feature = "sim")]
444    #[test]
445    fn sim_cluster_membership() {
446        let mut flow = FlowBuilder::new();
447        let cluster = flow.cluster::<(), u32>();
448        let node = flow.process::<()>();
449
450        let out_recv = node
451            .source_cluster_membership_stream(&cluster, nondet!(/** test */))
452            .entries()
453            .map(q!(|(id, v)| (id, v)))
454            .sim_output();
455
456        flow.sim()
457            .with_cluster_size(&cluster, 2)
458            .exhaustive(async || {
459                out_recv
460                    .assert_yields_only_unordered(vec![
461                        (MemberId::from_raw_id(0), MembershipEvent::Joined),
462                        (MemberId::from_raw_id(1), MembershipEvent::Joined),
463                    ])
464                    .await;
465            });
466    }
467}