Skip to main content

hydro_lang/live_collections/stream/
networking.rs

1//! Networking APIs for [`Stream`].
2
3use std::marker::PhantomData;
4
5use serde::Serialize;
6use serde::de::DeserializeOwned;
7use stageleft::{q, quote_type};
8use syn::parse_quote;
9
10use super::{ExactlyOnce, MinOrder, Ordering, Stream, TotalOrder};
11use crate::compile::builder::ExternalPortId;
12use crate::compile::ir::{
13    DebugInstantiate, HydroIrOpMetadata, HydroNode, HydroRoot, NetworkRecv, NetworkSend,
14};
15use crate::live_collections::boundedness::{Boundedness, Unbounded};
16use crate::live_collections::keyed_singleton::{KeyedSingleton, MonotonicKeys};
17use crate::live_collections::keyed_stream::KeyedStream;
18use crate::live_collections::sliced::sliced;
19use crate::live_collections::stream::Retries;
20#[cfg(feature = "sim")]
21use crate::location::LocationKey;
22use crate::location::cluster::{ClusterIds, Consistency, NoConsistency};
23#[cfg(stageleft_runtime)]
24use crate::location::dynamic::DynLocation;
25use crate::location::external_process::ExternalBincodeStream;
26use crate::location::{Cluster, External, Location, MemberId, MembershipEvent, Process};
27use crate::networking::{NetworkFor, TCP};
28use crate::nondet::{NonDet, nondet};
29use crate::properties::manual_proof;
30#[cfg(feature = "sim")]
31use crate::sim::SimReceiver;
32use crate::staging_util::get_this_crate;
33
34// same as the one in `hydro_std`, but internal use only
35fn track_membership<'a, C, L: Location<'a>>(
36    membership: KeyedStream<MemberId<C>, MembershipEvent, L, Unbounded>,
37) -> KeyedSingleton<MemberId<C>, bool, L, MonotonicKeys> {
38    membership.fold(
39        q!(|| false),
40        q!(|present, event| {
41            match event {
42                MembershipEvent::Joined => *present = true,
43                MembershipEvent::Left => *present = false,
44            }
45        }),
46    )
47}
48
49fn serialize_bincode_with_type(is_demux: bool, t_type: &syn::Type) -> syn::Expr {
50    let root = get_this_crate();
51
52    if is_demux {
53        parse_quote! {
54            #root::runtime_support::stageleft::runtime_support::fn1_type_hint::<(#root::__staged::location::MemberId<_>, #t_type), _>(
55                |(id, data)| {
56                    (id.into_tagless(), #root::runtime_support::bincode::serialize(&data).unwrap().into())
57                }
58            )
59        }
60    } else {
61        parse_quote! {
62            #root::runtime_support::stageleft::runtime_support::fn1_type_hint::<#t_type, _>(
63                |data| {
64                    #root::runtime_support::bincode::serialize(&data).unwrap().into()
65                }
66            )
67        }
68    }
69}
70
71pub(crate) fn serialize_bincode<T: Serialize>(is_demux: bool) -> syn::Expr {
72    serialize_bincode_with_type(is_demux, &quote_type::<T>())
73}
74
75fn deserialize_bincode_with_type(tagged: Option<&syn::Type>, t_type: &syn::Type) -> syn::Expr {
76    let root = get_this_crate();
77    if let Some(c_type) = tagged {
78        parse_quote! {
79            |res| {
80                let (id, b) = res.unwrap();
81                (#root::__staged::location::MemberId::<#c_type>::from_tagless(id as #root::__staged::location::TaglessMemberId), #root::runtime_support::bincode::deserialize::<#t_type>(&b).unwrap())
82            }
83        }
84    } else {
85        parse_quote! {
86            |res| {
87                #root::runtime_support::bincode::deserialize::<#t_type>(&res.unwrap()).unwrap()
88            }
89        }
90    }
91}
92
93pub(crate) fn deserialize_bincode<T: DeserializeOwned>(tagged: Option<&syn::Type>) -> syn::Expr {
94    deserialize_bincode_with_type(tagged, &quote_type::<T>())
95}
96
97impl<'a, T, L, B: Boundedness, O: Ordering, R: Retries> Stream<T, Process<'a, L>, B, O, R> {
98    #[deprecated = "use Stream::send(..., TCP.fail_stop().bincode()) instead"]
99    /// "Moves" elements of this stream to a new distributed location by sending them over the network,
100    /// using [`bincode`] to serialize/deserialize messages.
101    ///
102    /// The returned stream captures the elements received at the destination, where values will
103    /// asynchronously arrive over the network. Sending from a [`Process`] to another [`Process`]
104    /// preserves ordering and retries guarantees by using a single TCP channel to send the values. The
105    /// recipient is guaranteed to receive a _prefix_ or the sent messages; if the TCP connection is
106    /// dropped no further messages will be sent.
107    ///
108    /// # Example
109    /// ```rust
110    /// # #[cfg(feature = "deploy")] {
111    /// # use hydro_lang::prelude::*;
112    /// # use futures::StreamExt;
113    /// # tokio_test::block_on(hydro_lang::test_util::multi_location_test(|flow, p_out| {
114    /// let p1 = flow.process::<()>();
115    /// let numbers: Stream<_, Process<_>, Bounded> = p1.source_iter(q!(vec![1, 2, 3]));
116    /// let p2 = flow.process::<()>();
117    /// let on_p2: Stream<_, Process<_>, Unbounded> = numbers.send_bincode(&p2);
118    /// // 1, 2, 3
119    /// # on_p2.send_bincode(&p_out)
120    /// # }, |mut stream| async move {
121    /// # for w in 1..=3 {
122    /// #     assert_eq!(stream.next().await, Some(w));
123    /// # }
124    /// # }));
125    /// # }
126    /// ```
127    pub fn send_bincode<L2>(
128        self,
129        other: &Process<'a, L2>,
130    ) -> Stream<T, Process<'a, L2>, Unbounded, O, R>
131    where
132        T: Serialize + DeserializeOwned,
133    {
134        self.send(other, TCP.fail_stop().bincode())
135    }
136
137    /// "Moves" elements of this stream to a new distributed location by sending them over the network,
138    /// using the configuration in `via` to set up the message transport.
139    ///
140    /// The returned stream captures the elements received at the destination, where values will
141    /// asynchronously arrive over the network. Sending from a [`Process`] to another [`Process`]
142    /// preserves ordering and retries guarantees when using a single TCP channel to send the values.
143    /// The recipient is guaranteed to receive a _prefix_ or the sent messages; if the connection is
144    /// dropped no further messages will be sent.
145    ///
146    /// # Example
147    /// ```rust
148    /// # #[cfg(feature = "deploy")] {
149    /// # use hydro_lang::prelude::*;
150    /// # use futures::StreamExt;
151    /// # tokio_test::block_on(hydro_lang::test_util::multi_location_test(|flow, p_out| {
152    /// let p1 = flow.process::<()>();
153    /// let numbers: Stream<_, Process<_>, Bounded> = p1.source_iter(q!(vec![1, 2, 3]));
154    /// let p2 = flow.process::<()>();
155    /// let on_p2: Stream<_, Process<_>, Unbounded> = numbers.send(&p2, TCP.fail_stop().bincode());
156    /// // 1, 2, 3
157    /// # on_p2.send(&p_out, TCP.fail_stop().bincode())
158    /// # }, |mut stream| async move {
159    /// # for w in 1..=3 {
160    /// #     assert_eq!(stream.next().await, Some(w));
161    /// # }
162    /// # }));
163    /// # }
164    /// ```
165    pub fn send<L2, N: NetworkFor<T>>(
166        self,
167        to: &Process<'a, L2>,
168        via: N,
169    ) -> Stream<T, Process<'a, L2>, Unbounded, <O as MinOrder<N::OrderingGuarantee>>::Min, R>
170    where
171        O: MinOrder<N::OrderingGuarantee>,
172    {
173        let name = via.name();
174        if to.multiversioned() && name.is_none() {
175            panic!(
176                "Cannot send to a multiversioned location without a channel name. Please provide a name for the network."
177            );
178        }
179
180        let (serialize, deserialize) = if N::is_embedded() {
181            (
182                NetworkSend::Embedded {
183                    tag: None,
184                    element_type: quote_type::<T>().into(),
185                },
186                NetworkRecv::Embedded {
187                    tag: None,
188                    element_type: quote_type::<T>().into(),
189                },
190            )
191        } else {
192            (
193                NetworkSend::Custom {
194                    serialize_fn: Some(N::serialize_thunk(false).into()),
195                },
196                NetworkRecv::Custom {
197                    deserialize_fn: Some(N::deserialize_thunk(None).into()),
198                },
199            )
200        };
201
202        Stream::new(
203            to.clone(),
204            HydroNode::Network {
205                name: name.map(ToOwned::to_owned),
206                networking_info: N::networking_info(),
207                serialize,
208                deserialize,
209                instantiate_fn: DebugInstantiate::Building,
210                input: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
211                metadata: to.new_node_metadata(Stream::<
212                    T,
213                    Process<'a, L2>,
214                    Unbounded,
215                    <O as MinOrder<N::OrderingGuarantee>>::Min,
216                    R,
217                >::collection_kind()),
218            },
219        )
220    }
221
222    #[deprecated = "use Stream::broadcast(..., TCP.fail_stop().bincode()) instead"]
223    /// Broadcasts elements of this stream to all members of a cluster by sending them over the network,
224    /// using [`bincode`] to serialize/deserialize messages.
225    ///
226    /// Each element in the stream will be sent to **every** member of the cluster based on the latest
227    /// membership information. This is a common pattern in distributed systems for broadcasting data to
228    /// all nodes in a cluster. Unlike [`Stream::demux_bincode`], which requires `(MemberId, T)` tuples to
229    /// target specific members, `broadcast_bincode` takes a stream of **only data elements** and sends
230    /// each element to all cluster members.
231    ///
232    /// # Non-Determinism
233    /// The set of cluster members may asynchronously change over time. Each element is only broadcast
234    /// to the current cluster members _at that point in time_. Depending on when we are notified of
235    /// membership changes, we will broadcast each element to different members.
236    ///
237    /// # Example
238    /// ```rust
239    /// # #[cfg(feature = "deploy")] {
240    /// # use hydro_lang::prelude::*;
241    /// # use futures::StreamExt;
242    /// # tokio_test::block_on(hydro_lang::test_util::multi_location_test(|flow, p2| {
243    /// let p1 = flow.process::<()>();
244    /// let workers: Cluster<()> = flow.cluster::<()>();
245    /// let numbers: Stream<_, Process<_>, _> = p1.source_iter(q!(vec![123]));
246    /// let on_worker: Stream<_, Cluster<_>, _> = numbers.broadcast_bincode(&workers, nondet!(/** assuming stable membership */));
247    /// # on_worker.send_bincode(&p2).entries()
248    /// // if there are 4 members in the cluster, each receives one element
249    /// // - MemberId::<()>(0): [123]
250    /// // - MemberId::<()>(1): [123]
251    /// // - MemberId::<()>(2): [123]
252    /// // - MemberId::<()>(3): [123]
253    /// # }, |mut stream| async move {
254    /// # let mut results = Vec::new();
255    /// # for w in 0..4 {
256    /// #     results.push(format!("{:?}", stream.next().await.unwrap()));
257    /// # }
258    /// # results.sort();
259    /// # assert_eq!(results, vec!["(MemberId::<()>(0), 123)", "(MemberId::<()>(1), 123)", "(MemberId::<()>(2), 123)", "(MemberId::<()>(3), 123)"]);
260    /// # }));
261    /// # }
262    /// ```
263    pub fn broadcast_bincode<L2: 'a>(
264        self,
265        other: &Cluster<'a, L2>,
266        nondet_membership: NonDet,
267    ) -> Stream<T, Cluster<'a, L2>, Unbounded, O, R>
268    where
269        T: Clone + Serialize + DeserializeOwned,
270    {
271        self.broadcast(other, TCP.fail_stop().bincode(), nondet_membership)
272    }
273
274    /// Broadcasts elements of this stream to all members of a cluster by sending them over the network,
275    /// using the configuration in `via` to set up the message transport.
276    ///
277    /// Each element in the stream will be sent to **every** member of the cluster based on the latest
278    /// membership information. This is a common pattern in distributed systems for broadcasting data to
279    /// all nodes in a cluster. Unlike [`Stream::demux`], which requires `(MemberId, T)` tuples to
280    /// target specific members, `broadcast` takes a stream of **only data elements** and sends
281    /// each element to all cluster members.
282    ///
283    /// # Non-Determinism
284    /// The set of cluster members may asynchronously change over time. Each element is only broadcast
285    /// to the current cluster members _at that point in time_. Depending on when we are notified of
286    /// membership changes, we will broadcast each element to different members.
287    ///
288    /// # Example
289    /// ```rust
290    /// # #[cfg(feature = "deploy")] {
291    /// # use hydro_lang::prelude::*;
292    /// # use futures::StreamExt;
293    /// # tokio_test::block_on(hydro_lang::test_util::multi_location_test(|flow, p2| {
294    /// let p1 = flow.process::<()>();
295    /// let workers: Cluster<()> = flow.cluster::<()>();
296    /// let numbers: Stream<_, Process<_>, _> = p1.source_iter(q!(vec![123]));
297    /// let on_worker: Stream<_, Cluster<_>, _> = numbers.broadcast(&workers, TCP.fail_stop().bincode(), nondet!(/** assuming stable membership */));
298    /// # on_worker.send(&p2, TCP.fail_stop().bincode()).entries()
299    /// // if there are 4 members in the cluster, each receives one element
300    /// // - MemberId::<()>(0): [123]
301    /// // - MemberId::<()>(1): [123]
302    /// // - MemberId::<()>(2): [123]
303    /// // - MemberId::<()>(3): [123]
304    /// # }, |mut stream| async move {
305    /// # let mut results = Vec::new();
306    /// # for w in 0..4 {
307    /// #     results.push(format!("{:?}", stream.next().await.unwrap()));
308    /// # }
309    /// # results.sort();
310    /// # assert_eq!(results, vec!["(MemberId::<()>(0), 123)", "(MemberId::<()>(1), 123)", "(MemberId::<()>(2), 123)", "(MemberId::<()>(3), 123)"]);
311    /// # }));
312    /// # }
313    /// ```
314    pub fn broadcast<L2: 'a, N: NetworkFor<T>>(
315        self,
316        to: &Cluster<'a, L2>,
317        via: N,
318        nondet_membership: NonDet,
319    ) -> Stream<T, Cluster<'a, L2>, Unbounded, <O as MinOrder<N::OrderingGuarantee>>::Min, R>
320    where
321        T: Clone,
322        O: MinOrder<N::OrderingGuarantee>,
323    {
324        // TODO(#1875): the membership snapshot below is over a `KeyedSingleton`, and keyed
325        // sim hooks do not exist yet. Once they do, expose a composite hook payload here
326        // (`NonDet<(Option<KeyedSnapshotHook<..>>, Option<BatchHook<T, O, R>>)>`) so tests
327        // can script the membership snapshot and the element batching independently.
328        let ids = track_membership(self.location.source_cluster_membership_stream(
329            to,
330            nondet!(/** dropped prefixes don't affect broadcast */),
331        ));
332        sliced! {
333            let members_snapshot = use::snapshot(ids, nondet!(
334                /// membership timing is captured by the caller's guard
335                nondet_membership
336            ));
337            let elements = use::batch(self, nondet!(
338                /// batching timing is captured by the caller's guard
339                nondet_membership
340            ));
341
342            let current_members = members_snapshot.filter(q!(|b| *b));
343            elements.repeat_with_keys(current_members)
344        }
345        .demux(to, via)
346    }
347
348    /// Broadcasts elements of this stream to all members of a cluster,
349    /// assuming membership is closed (fixed at deploy time).
350    ///
351    /// Unlike [`Stream::broadcast`], this does not require a [`NonDet`] guard.
352    /// The membership set is obtained from deploy metadata via
353    /// [`ClusterIds`], producing a
354    /// `Bounded` stream. The cross-product of data × members is fully
355    /// deterministic.
356    ///
357    /// The consistency guarantee of the output depends on the network's failure policy
358    /// ([`NetworkFor::ConsistencyGuarantee`]). Policies like `fail_stop` and
359    /// `lossy_delayed_forever` guarantee that every live member eventually materializes the same
360    /// elements, so the output is
361    /// [`EventualConsistency`](crate::location::cluster::EventualConsistency). A plain `lossy`
362    /// policy can drop individual messages for some members while delivering them to others, so
363    /// replicas may permanently diverge and the output only has
364    /// [`NoConsistency`].
365    ///
366    /// This is only available in deployment targets with static cluster
367    /// membership (legacy Hydro Deploy and simulation). There are no late
368    /// joiners in that context, so broadcast receivers are guaranteed to
369    /// get data from the start of the stream. On dynamic targets
370    /// (e.g. ECS), use [`Stream::broadcast`] instead.
371    ///
372    /// # Example
373    /// ```rust
374    /// # #[cfg(feature = "deploy")] {
375    /// # use hydro_lang::prelude::*;
376    /// # use futures::StreamExt;
377    /// # tokio_test::block_on(hydro_lang::test_util::multi_location_test(|flow, p2| {
378    /// let p1 = flow.process::<()>();
379    /// let workers: Cluster<()> = flow.cluster::<()>();
380    /// let numbers: Stream<_, Process<_>, _> = p1.source_iter(q!(vec![123]));
381    /// let on_worker = numbers.broadcast_closed(&workers, TCP.fail_stop().bincode());
382    /// # on_worker.send(&p2, TCP.fail_stop().bincode()).entries()
383    /// // each of the 4 cluster members receives 123
384    /// # }, |mut stream| async move {
385    /// # let mut results = Vec::new();
386    /// # for _ in 0..4 {
387    /// #     results.push(format!("{:?}", stream.next().await.unwrap()));
388    /// # }
389    /// # results.sort();
390    /// # assert_eq!(results, vec!["(MemberId::<()>(0), 123)", "(MemberId::<()>(1), 123)", "(MemberId::<()>(2), 123)", "(MemberId::<()>(3), 123)"]);
391    /// # }));
392    /// # }
393    /// ```
394    pub fn broadcast_closed<L2: 'a, N: NetworkFor<T>>(
395        self,
396        to: &Cluster<'a, L2>,
397        via: N,
398    ) -> Stream<
399        T,
400        Cluster<'a, L2, N::ConsistencyGuarantee>,
401        Unbounded,
402        <O as MinOrder<N::OrderingGuarantee>>::Min,
403        R,
404    >
405    where
406        T: Clone,
407        O: MinOrder<N::OrderingGuarantee>,
408    {
409        let cluster_ids = ClusterIds {
410            key: to.key,
411            _phantom: PhantomData,
412        };
413        let member_ids = self.location.source_iter(q!(cluster_ids
414            .iter()
415            .map(|id| MemberId::from_tagless(id.clone()))));
416
417        // Late joiners will receive no data from this broadcast, which is
418        // future-monotone and eventually consistent (a safe under-approximation).
419        self.cross_product(member_ids)
420            .map(q!(|(data, member_id)| (member_id, data)))
421            .into_keyed()
422            .demux(to, via)
423            .assert_has_consistency_of_trusted(manual_proof!(
424                /// With a network whose failure policy delivers the same messages to every live
425                /// member (tracked by `NetworkFor::ConsistencyGuarantee`), a closed broadcast
426                /// will materialize the same elements on each member.
427            ))
428    }
429
430    /// Sends the elements of this stream to an external (non-Hydro) process, using [`bincode`]
431    /// serialization. The external process can receive these elements by establishing a TCP
432    /// connection and decoding using [`tokio_util::codec::LengthDelimitedCodec`].
433    ///
434    /// # Example
435    /// ```rust
436    /// # #[cfg(feature = "deploy")] {
437    /// # use hydro_lang::prelude::*;
438    /// # use futures::StreamExt;
439    /// # tokio_test::block_on(async move {
440    /// let mut flow = FlowBuilder::new();
441    /// let process = flow.process::<()>();
442    /// let numbers: Stream<_, Process<_>, Bounded> = process.source_iter(q!(vec![1, 2, 3]));
443    /// let external = flow.external::<()>();
444    /// let external_handle = numbers.send_bincode_external(&external);
445    ///
446    /// let mut deployment = hydro_deploy::Deployment::new();
447    /// let nodes = flow
448    ///     .with_process(&process, deployment.Localhost())
449    ///     .with_external(&external, deployment.Localhost())
450    ///     .deploy(&mut deployment);
451    ///
452    /// deployment.deploy().await.unwrap();
453    /// // establish the TCP connection
454    /// let mut external_recv_stream = nodes.connect(external_handle).await;
455    /// deployment.start().await.unwrap();
456    ///
457    /// for w in 1..=3 {
458    ///     assert_eq!(external_recv_stream.next().await, Some(w));
459    /// }
460    /// # });
461    /// # }
462    /// ```
463    pub fn send_bincode_external<L2>(
464        self,
465        other: &External<'_, L2>,
466    ) -> ExternalBincodeStream<T, O, R>
467    where
468        T: Serialize + DeserializeOwned,
469    {
470        let external_port_id =
471            self.register_serialized_external_port(other, serialize_bincode::<T>(false));
472
473        ExternalBincodeStream {
474            process_key: other.key,
475            port_id: external_port_id,
476            _phantom: PhantomData,
477        }
478    }
479
480    // TODO: Add a codec-parameterized external stream handle once deployment supports custom codecs.
481    fn register_serialized_external_port<L2>(
482        self,
483        other: &External<'_, L2>,
484        serialize_pipeline: syn::Expr,
485    ) -> ExternalPortId {
486        let mut flow_state_borrow = self.location.flow_state().borrow_mut();
487
488        let external_port_id = flow_state_borrow.next_external_port();
489
490        flow_state_borrow.push_root(HydroRoot::SendExternal {
491            to_external_key: other.key,
492            to_port_id: external_port_id,
493            to_many: false,
494            unpaired: true,
495            serialize_fn: Some(serialize_pipeline.into()),
496            instantiate_fn: DebugInstantiate::Building,
497            input: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
498            op_metadata: HydroIrOpMetadata::new(),
499        });
500
501        external_port_id
502    }
503
504    #[cfg(feature = "sim")]
505    /// Sets up a bincode-encoded simulation output port for this stream, allowing test code to
506    /// receive elements sent to this stream during simulation. Use [`Stream::sim_output_with`] to
507    /// select another codec.
508    pub fn sim_output(self) -> SimReceiver<T, O, R>
509    where
510        T: Serialize + DeserializeOwned,
511    {
512        self.sim_output_with(crate::sim::codec::BincodeCodec)
513    }
514
515    #[cfg(feature = "sim")]
516    /// Sets up a simulation output port using `codec`, allowing test code to receive elements
517    /// sent to this stream during simulation. Custom codecs implement
518    /// [`SimCodec`](crate::sim::codec::SimCodec), which documents where they must be defined.
519    pub fn sim_output_with<C>(self, _codec: C) -> SimReceiver<T, O, R>
520    where
521        C: crate::sim::codec::SimCodec<T>,
522    {
523        let external_location: External<'a, ()> = External {
524            key: LocationKey::FIRST,
525            flow_state: self.location.flow_state().clone(),
526            _phantom: PhantomData,
527        };
528
529        let external_port_id = self.register_serialized_external_port(
530            &external_location,
531            crate::sim::codec::staged_serialize::<T, C>(),
532        );
533
534        SimReceiver(external_port_id, PhantomData, C::decode)
535    }
536}
537
538impl<'a, T, L: Location<'a>, B: Boundedness> Stream<T, L, B, TotalOrder, ExactlyOnce> {
539    /// Creates an external output for embedded deployment mode.
540    ///
541    /// The `name` parameter specifies the name of the field in the generated
542    /// `EmbeddedOutputs` struct that will receive elements from this stream.
543    /// The generated function will accept an `EmbeddedOutputs` struct with an
544    /// `impl FnMut(T)` field with this name.
545    pub fn embedded_output(self, name: impl Into<String>) {
546        let ident = syn::Ident::new(&name.into(), proc_macro2::Span::call_site());
547
548        self.location
549            .flow_state()
550            .borrow_mut()
551            .push_root(HydroRoot::EmbeddedOutput {
552                ident,
553                input: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
554                op_metadata: HydroIrOpMetadata::new(),
555            });
556    }
557}
558
559impl<'a, T, L, L2, B: Boundedness, O: Ordering, R: Retries>
560    Stream<(MemberId<L2>, T), Process<'a, L>, B, O, R>
561{
562    #[deprecated = "use Stream::demux(..., TCP.fail_stop().bincode()) instead"]
563    /// Sends elements of this stream to specific members of a cluster, identified by a [`MemberId`],
564    /// using [`bincode`] to serialize/deserialize messages.
565    ///
566    /// Each element in the stream must be a tuple `(MemberId<L2>, T)` where the first element
567    /// specifies which cluster member should receive the data. Unlike [`Stream::broadcast_bincode`],
568    /// this API allows precise targeting of specific cluster members rather than broadcasting to
569    /// all members.
570    ///
571    /// # Example
572    /// ```rust
573    /// # #[cfg(feature = "deploy")] {
574    /// # use hydro_lang::prelude::*;
575    /// # use futures::StreamExt;
576    /// # tokio_test::block_on(hydro_lang::test_util::multi_location_test(|flow, p2| {
577    /// let p1 = flow.process::<()>();
578    /// let workers: Cluster<()> = flow.cluster::<()>();
579    /// let numbers: Stream<_, Process<_>, _> = p1.source_iter(q!(vec![0, 1, 2, 3]));
580    /// let on_worker: Stream<_, Cluster<_>, _> = numbers
581    ///     .map(q!(|x| (hydro_lang::location::MemberId::from_raw_id(x), x)))
582    ///     .demux_bincode(&workers);
583    /// # on_worker.send_bincode(&p2).entries()
584    /// // if there are 4 members in the cluster, each receives one element
585    /// // - MemberId::<()>(0): [0]
586    /// // - MemberId::<()>(1): [1]
587    /// // - MemberId::<()>(2): [2]
588    /// // - MemberId::<()>(3): [3]
589    /// # }, |mut stream| async move {
590    /// # let mut results = Vec::new();
591    /// # for w in 0..4 {
592    /// #     results.push(format!("{:?}", stream.next().await.unwrap()));
593    /// # }
594    /// # results.sort();
595    /// # assert_eq!(results, vec!["(MemberId::<()>(0), 0)", "(MemberId::<()>(1), 1)", "(MemberId::<()>(2), 2)", "(MemberId::<()>(3), 3)"]);
596    /// # }));
597    /// # }
598    /// ```
599    pub fn demux_bincode(
600        self,
601        other: &Cluster<'a, L2>,
602    ) -> Stream<T, Cluster<'a, L2>, Unbounded, O, R>
603    where
604        T: Serialize + DeserializeOwned,
605    {
606        self.demux(other, TCP.fail_stop().bincode())
607    }
608
609    /// Sends elements of this stream to specific members of a cluster, identified by a [`MemberId`],
610    /// using the configuration in `via` to set up the message transport.
611    ///
612    /// Each element in the stream must be a tuple `(MemberId<L2>, T)` where the first element
613    /// specifies which cluster member should receive the data. Unlike [`Stream::broadcast`],
614    /// this API allows precise targeting of specific cluster members rather than broadcasting to
615    /// all members.
616    ///
617    /// # Example
618    /// ```rust
619    /// # #[cfg(feature = "deploy")] {
620    /// # use hydro_lang::prelude::*;
621    /// # use futures::StreamExt;
622    /// # tokio_test::block_on(hydro_lang::test_util::multi_location_test(|flow, p2| {
623    /// let p1 = flow.process::<()>();
624    /// let workers: Cluster<()> = flow.cluster::<()>();
625    /// let numbers: Stream<_, Process<_>, _> = p1.source_iter(q!(vec![0, 1, 2, 3]));
626    /// let on_worker: Stream<_, Cluster<_>, _> = numbers
627    ///     .map(q!(|x| (hydro_lang::location::MemberId::from_raw_id(x), x)))
628    ///     .demux(&workers, TCP.fail_stop().bincode());
629    /// # on_worker.send(&p2, TCP.fail_stop().bincode()).entries()
630    /// // if there are 4 members in the cluster, each receives one element
631    /// // - MemberId::<()>(0): [0]
632    /// // - MemberId::<()>(1): [1]
633    /// // - MemberId::<()>(2): [2]
634    /// // - MemberId::<()>(3): [3]
635    /// # }, |mut stream| async move {
636    /// # let mut results = Vec::new();
637    /// # for w in 0..4 {
638    /// #     results.push(format!("{:?}", stream.next().await.unwrap()));
639    /// # }
640    /// # results.sort();
641    /// # assert_eq!(results, vec!["(MemberId::<()>(0), 0)", "(MemberId::<()>(1), 1)", "(MemberId::<()>(2), 2)", "(MemberId::<()>(3), 3)"]);
642    /// # }));
643    /// # }
644    /// ```
645    pub fn demux<N: NetworkFor<T>>(
646        self,
647        to: &Cluster<'a, L2>,
648        via: N,
649    ) -> Stream<
650        T,
651        Cluster<'a, L2, NoConsistency>,
652        Unbounded,
653        <O as MinOrder<N::OrderingGuarantee>>::Min,
654        R,
655    >
656    where
657        O: MinOrder<N::OrderingGuarantee>,
658    {
659        self.into_keyed().demux(to, via)
660    }
661}
662
663impl<'a, T, L, B: Boundedness> Stream<T, Process<'a, L>, B, TotalOrder, ExactlyOnce> {
664    #[deprecated = "use Stream::round_robin(..., TCP.fail_stop().bincode()) instead"]
665    /// Distributes elements of this stream to cluster members in a round-robin fashion, using
666    /// [`bincode`] to serialize/deserialize messages.
667    ///
668    /// This provides load balancing by evenly distributing work across cluster members. The
669    /// distribution is deterministic based on element order - the first element goes to member 0,
670    /// the second to member 1, and so on, wrapping around when reaching the end of the member list.
671    ///
672    /// # Non-Determinism
673    /// The set of cluster members may asynchronously change over time. Each element is distributed
674    /// based on the current cluster membership _at that point in time_. Depending on when cluster
675    /// members join and leave, the round-robin pattern will change. Furthermore, even when the
676    /// membership is stable, the order of members in the round-robin pattern may change across runs.
677    ///
678    /// # Ordering Requirements
679    /// This method is only available on streams with [`TotalOrder`] and [`ExactlyOnce`], since the
680    /// order of messages and retries affects the round-robin pattern.
681    ///
682    /// # Example
683    /// ```rust
684    /// # #[cfg(feature = "deploy")] {
685    /// # use hydro_lang::prelude::*;
686    /// # use hydro_lang::live_collections::stream::{TotalOrder, ExactlyOnce};
687    /// # use futures::StreamExt;
688    /// # tokio_test::block_on(hydro_lang::test_util::multi_location_test(|flow, p2| {
689    /// let p1 = flow.process::<()>();
690    /// let workers: Cluster<()> = flow.cluster::<()>();
691    /// let numbers: Stream<_, Process<_>, _, TotalOrder, ExactlyOnce> = p1.source_iter(q!(vec![1, 2, 3, 4]));
692    /// let on_worker: Stream<_, Cluster<_>, _> = numbers.round_robin_bincode(&workers, nondet!(/** assuming stable membership */));
693    /// on_worker.send_bincode(&p2)
694    /// # .first().values() // we use first to assert that each member gets one element
695    /// // with 4 cluster members, elements are distributed (with a non-deterministic round-robin order):
696    /// // - MemberId::<()>(?): [1]
697    /// // - MemberId::<()>(?): [2]
698    /// // - MemberId::<()>(?): [3]
699    /// // - MemberId::<()>(?): [4]
700    /// # }, |mut stream| async move {
701    /// # let mut results = Vec::new();
702    /// # for w in 0..4 {
703    /// #     results.push(stream.next().await.unwrap());
704    /// # }
705    /// # results.sort();
706    /// # assert_eq!(results, vec![1, 2, 3, 4]);
707    /// # }));
708    /// # }
709    /// ```
710    pub fn round_robin_bincode<L2: 'a>(
711        self,
712        other: &Cluster<'a, L2>,
713        nondet_membership: NonDet,
714    ) -> Stream<T, Cluster<'a, L2>, Unbounded, TotalOrder, ExactlyOnce>
715    where
716        T: Serialize + DeserializeOwned,
717    {
718        self.round_robin(other, TCP.fail_stop().bincode(), nondet_membership)
719    }
720
721    /// Distributes elements of this stream to cluster members in a round-robin fashion, using
722    /// the configuration in `via` to set up the message transport.
723    ///
724    /// This provides load balancing by evenly distributing work across cluster members. The
725    /// distribution is deterministic based on element order - the first element goes to member 0,
726    /// the second to member 1, and so on, wrapping around when reaching the end of the member list.
727    ///
728    /// # Non-Determinism
729    /// The set of cluster members may asynchronously change over time. Each element is distributed
730    /// based on the current cluster membership _at that point in time_. Depending on when cluster
731    /// members join and leave, the round-robin pattern will change. Furthermore, even when the
732    /// membership is stable, the order of members in the round-robin pattern may change across runs.
733    ///
734    /// # Ordering Requirements
735    /// This method is only available on streams with [`TotalOrder`] and [`ExactlyOnce`], since the
736    /// order of messages and retries affects the round-robin pattern.
737    ///
738    /// # Example
739    /// ```rust
740    /// # #[cfg(feature = "deploy")] {
741    /// # use hydro_lang::prelude::*;
742    /// # use hydro_lang::live_collections::stream::{TotalOrder, ExactlyOnce};
743    /// # use futures::StreamExt;
744    /// # tokio_test::block_on(hydro_lang::test_util::multi_location_test(|flow, p2| {
745    /// let p1 = flow.process::<()>();
746    /// let workers: Cluster<()> = flow.cluster::<()>();
747    /// let numbers: Stream<_, Process<_>, _, TotalOrder, ExactlyOnce> = p1.source_iter(q!(vec![1, 2, 3, 4]));
748    /// let on_worker: Stream<_, Cluster<_>, _> = numbers.round_robin(&workers, TCP.fail_stop().bincode(), nondet!(/** assuming stable membership */));
749    /// on_worker.send(&p2, TCP.fail_stop().bincode())
750    /// # .first().values() // we use first to assert that each member gets one element
751    /// // with 4 cluster members, elements are distributed (with a non-deterministic round-robin order):
752    /// // - MemberId::<()>(?): [1]
753    /// // - MemberId::<()>(?): [2]
754    /// // - MemberId::<()>(?): [3]
755    /// // - MemberId::<()>(?): [4]
756    /// # }, |mut stream| async move {
757    /// # let mut results = Vec::new();
758    /// # for w in 0..4 {
759    /// #     results.push(stream.next().await.unwrap());
760    /// # }
761    /// # results.sort();
762    /// # assert_eq!(results, vec![1, 2, 3, 4]);
763    /// # }));
764    /// # }
765    /// ```
766    pub fn round_robin<L2: 'a, N: NetworkFor<T>>(
767        self,
768        to: &Cluster<'a, L2>,
769        via: N,
770        nondet_membership: NonDet,
771    ) -> Stream<T, Cluster<'a, L2>, Unbounded, N::OrderingGuarantee, ExactlyOnce> {
772        // TODO(#1875): the membership snapshot below is over a `KeyedSingleton`, and keyed
773        // sim hooks do not exist yet. Once they do, expose a composite hook payload here
774        // (`NonDet<(Option<KeyedSnapshotHook<..>>, Option<BatchHook<T, O, R>>)>`) so tests
775        // can script the membership snapshot and the element batching independently.
776        let ids = track_membership(self.location.source_cluster_membership_stream(
777            to,
778            nondet!(/** dropped prefixes don't affect broadcast */),
779        ));
780        sliced! {
781            let members_snapshot = use::snapshot(ids, nondet!(
782                /// membership timing is captured by the caller's guard
783                nondet_membership
784            ));
785            let elements = use::batch(self.enumerate(), nondet!(
786                /// batching timing is captured by the caller's guard
787                nondet_membership
788            ));
789
790            let current_members = members_snapshot
791                .filter(q!(|b| *b))
792                .keys()
793                .assume_ordering::<TotalOrder>(nondet!(/** membership timing is captured by the caller guard */ nondet_membership))
794                .collect_vec();
795
796            elements
797                .cross_singleton(current_members)
798                .filter_map(q!(|(data, members)| {
799                    if members.is_empty() {
800                        None
801                    } else {
802                        Some((members[data.0 % members.len()].clone(), data.1))
803                    }
804                }))
805        }
806        .demux(to, via)
807    }
808}
809
810impl<'a, T, L, B: Boundedness, C: Consistency>
811    Stream<T, Cluster<'a, L, C>, B, TotalOrder, ExactlyOnce>
812{
813    #[deprecated = "use Stream::round_robin(..., TCP.fail_stop().bincode()) instead"]
814    /// Distributes elements of this stream to cluster members in a round-robin fashion, using
815    /// [`bincode`] to serialize/deserialize messages.
816    ///
817    /// This provides load balancing by evenly distributing work across cluster members. The
818    /// distribution is deterministic based on element order - the first element goes to member 0,
819    /// the second to member 1, and so on, wrapping around when reaching the end of the member list.
820    ///
821    /// # Non-Determinism
822    /// The set of cluster members may asynchronously change over time. Each element is distributed
823    /// based on the current cluster membership _at that point in time_. Depending on when cluster
824    /// members join and leave, the round-robin pattern will change. Furthermore, even when the
825    /// membership is stable, the order of members in the round-robin pattern may change across runs.
826    ///
827    /// # Ordering Requirements
828    /// This method is only available on streams with [`TotalOrder`] and [`ExactlyOnce`], since the
829    /// order of messages and retries affects the round-robin pattern.
830    ///
831    /// # Example
832    /// ```rust
833    /// # #[cfg(feature = "deploy")] {
834    /// # use hydro_lang::prelude::*;
835    /// # use hydro_lang::live_collections::stream::{TotalOrder, ExactlyOnce, NoOrder};
836    /// # use hydro_lang::location::MemberId;
837    /// # use futures::StreamExt;
838    /// # tokio_test::block_on(hydro_lang::test_util::multi_location_test(|flow, p2| {
839    /// let p1 = flow.process::<()>();
840    /// let workers1: Cluster<()> = flow.cluster::<()>();
841    /// let workers2: Cluster<()> = flow.cluster::<()>();
842    /// let numbers: Stream<_, Process<_>, _, TotalOrder, ExactlyOnce> = p1.source_iter(q!(0..=16));
843    /// let on_worker1: Stream<_, Cluster<_>, _> = numbers.round_robin_bincode(&workers1, nondet!(/** assuming stable membership */));
844    /// let on_worker2: Stream<_, Cluster<_>, _> = on_worker1.round_robin_bincode(&workers2, nondet!(/** assuming stable membership */)).entries().assume_ordering(nondet!(/** assuming stable membership */));
845    /// on_worker2.send_bincode(&p2)
846    /// # .entries()
847    /// # .map(q!(|(w2, (w1, v))| ((w2, w1), v)))
848    /// # }, |mut stream| async move {
849    /// # let mut results = Vec::new();
850    /// # let mut locations = std::collections::HashSet::new();
851    /// # for w in 0..=16 {
852    /// #     let (location, v) = stream.next().await.unwrap();
853    /// #     locations.insert(location);
854    /// #     results.push(v);
855    /// # }
856    /// # results.sort();
857    /// # assert_eq!(results, (0..=16).collect::<Vec<_>>());
858    /// # assert_eq!(locations.len(), 16);
859    /// # }));
860    /// # }
861    /// ```
862    pub fn round_robin_bincode<L2: 'a>(
863        self,
864        other: &Cluster<'a, L2>,
865        nondet_membership: NonDet,
866    ) -> KeyedStream<MemberId<L>, T, Cluster<'a, L2>, Unbounded, TotalOrder, ExactlyOnce>
867    where
868        T: Serialize + DeserializeOwned,
869    {
870        self.round_robin(other, TCP.fail_stop().bincode(), nondet_membership)
871    }
872
873    /// Distributes elements of this stream to cluster members in a round-robin fashion, using
874    /// the configuration in `via` to set up the message transport.
875    ///
876    /// This provides load balancing by evenly distributing work across cluster members. The
877    /// distribution is deterministic based on element order - the first element goes to member 0,
878    /// the second to member 1, and so on, wrapping around when reaching the end of the member list.
879    ///
880    /// # Non-Determinism
881    /// The set of cluster members may asynchronously change over time. Each element is distributed
882    /// based on the current cluster membership _at that point in time_. Depending on when cluster
883    /// members join and leave, the round-robin pattern will change. Furthermore, even when the
884    /// membership is stable, the order of members in the round-robin pattern may change across runs.
885    ///
886    /// # Ordering Requirements
887    /// This method is only available on streams with [`TotalOrder`] and [`ExactlyOnce`], since the
888    /// order of messages and retries affects the round-robin pattern.
889    ///
890    /// # Example
891    /// ```rust
892    /// # #[cfg(feature = "deploy")] {
893    /// # use hydro_lang::prelude::*;
894    /// # use hydro_lang::live_collections::stream::{TotalOrder, ExactlyOnce, NoOrder};
895    /// # use hydro_lang::location::MemberId;
896    /// # use futures::StreamExt;
897    /// # tokio_test::block_on(hydro_lang::test_util::multi_location_test(|flow, p2| {
898    /// let p1 = flow.process::<()>();
899    /// let workers1: Cluster<()> = flow.cluster::<()>();
900    /// let workers2: Cluster<()> = flow.cluster::<()>();
901    /// let numbers: Stream<_, Process<_>, _, TotalOrder, ExactlyOnce> = p1.source_iter(q!(0..=16));
902    /// let on_worker1: Stream<_, Cluster<_>, _> = numbers.round_robin(&workers1, TCP.fail_stop().bincode(), nondet!(/** assuming stable membership */));
903    /// let on_worker2: Stream<_, Cluster<_>, _> = on_worker1.round_robin(&workers2, TCP.fail_stop().bincode(), nondet!(/** assuming stable membership */)).entries().assume_ordering(nondet!(/** assuming stable membership */));
904    /// on_worker2.send(&p2, TCP.fail_stop().bincode())
905    /// # .entries()
906    /// # .map(q!(|(w2, (w1, v))| ((w2, w1), v)))
907    /// # }, |mut stream| async move {
908    /// # let mut results = Vec::new();
909    /// # let mut locations = std::collections::HashSet::new();
910    /// # for w in 0..=16 {
911    /// #     let (location, v) = stream.next().await.unwrap();
912    /// #     locations.insert(location);
913    /// #     results.push(v);
914    /// # }
915    /// # results.sort();
916    /// # assert_eq!(results, (0..=16).collect::<Vec<_>>());
917    /// # assert_eq!(locations.len(), 16);
918    /// # }));
919    /// # }
920    /// ```
921    pub fn round_robin<L2: 'a, N: NetworkFor<T>>(
922        self,
923        to: &Cluster<'a, L2>,
924        via: N,
925        nondet_membership: NonDet,
926    ) -> KeyedStream<MemberId<L>, T, Cluster<'a, L2>, Unbounded, N::OrderingGuarantee, ExactlyOnce>
927    {
928        // TODO(#1875): the membership snapshot below is over a `KeyedSingleton`, and keyed
929        // sim hooks do not exist yet. Once they do, expose a composite hook payload here
930        // (`NonDet<(Option<KeyedSnapshotHook<..>>, Option<BatchHook<T, O, R>>)>`) so tests
931        // can script the membership snapshot and the element batching independently.
932        let ids = track_membership(self.location.source_cluster_membership_stream(
933            to,
934            nondet!(/** dropped prefixes don't affect broadcast */),
935        ));
936        sliced! {
937            let members_snapshot = use::snapshot(ids, nondet!(
938                /// membership timing is captured by the caller's guard
939                nondet_membership
940            ));
941            let elements = use::batch(self.enumerate(), nondet!(
942                /// batching timing is captured by the caller's guard
943                nondet_membership
944            ));
945
946            let current_members = members_snapshot
947                .filter(q!(|b| *b))
948                .keys()
949                .assume_ordering::<TotalOrder>(nondet!(/** membership timing is captured by the caller guard */ nondet_membership))
950                .collect_vec();
951
952            elements
953                .cross_singleton(current_members)
954                .filter_map(q!(|(data, members)| {
955                    if members.is_empty() {
956                        None
957                    } else {
958                        Some((members[data.0 % members.len()].clone(), data.1))
959                    }
960                }))
961        }
962        .demux(to, via)
963    }
964}
965
966impl<'a, T, L, B: Boundedness, C: Consistency, O: Ordering, R: Retries>
967    Stream<T, Cluster<'a, L, C>, B, O, R>
968{
969    #[deprecated = "use Stream::send(..., TCP.fail_stop().bincode()) instead"]
970    /// "Moves" elements of this stream from a cluster to a process by sending them over the network,
971    /// using [`bincode`] to serialize/deserialize messages.
972    ///
973    /// Each cluster member sends its local stream elements, and they are collected at the destination
974    /// as a [`KeyedStream`] where keys identify the source cluster member.
975    ///
976    /// # Example
977    /// ```rust
978    /// # #[cfg(feature = "deploy")] {
979    /// # use hydro_lang::prelude::*;
980    /// # use futures::StreamExt;
981    /// # tokio_test::block_on(hydro_lang::test_util::multi_location_test(|flow, process| {
982    /// let workers: Cluster<()> = flow.cluster::<()>();
983    /// let numbers: Stream<_, Cluster<_>, _> = workers.source_iter(q!(vec![1]));
984    /// let all_received = numbers.send_bincode(&process); // KeyedStream<MemberId<()>, i32, ...>
985    /// # all_received.entries()
986    /// # }, |mut stream| async move {
987    /// // if there are 4 members in the cluster, we should receive 4 elements
988    /// // { MemberId::<()>(0): [1], MemberId::<()>(1): [1], MemberId::<()>(2): [1], MemberId::<()>(3): [1] }
989    /// # let mut results = Vec::new();
990    /// # for w in 0..4 {
991    /// #     results.push(format!("{:?}", stream.next().await.unwrap()));
992    /// # }
993    /// # results.sort();
994    /// # assert_eq!(results, vec!["(MemberId::<()>(0), 1)", "(MemberId::<()>(1), 1)", "(MemberId::<()>(2), 1)", "(MemberId::<()>(3), 1)"]);
995    /// # }));
996    /// # }
997    /// ```
998    ///
999    /// If you don't need to know the source for each element, you can use `.values()`
1000    /// to get just the data:
1001    /// ```rust
1002    /// # #[cfg(feature = "deploy")] {
1003    /// # use hydro_lang::prelude::*;
1004    /// # use hydro_lang::live_collections::stream::NoOrder;
1005    /// # use futures::StreamExt;
1006    /// # tokio_test::block_on(hydro_lang::test_util::multi_location_test(|flow, process| {
1007    /// # let workers: Cluster<()> = flow.cluster::<()>();
1008    /// # let numbers: Stream<_, Cluster<_>, _> = workers.source_iter(q!(vec![1]));
1009    /// let values: Stream<i32, _, _, NoOrder> = numbers.send_bincode(&process).values();
1010    /// # values
1011    /// # }, |mut stream| async move {
1012    /// # let mut results = Vec::new();
1013    /// # for w in 0..4 {
1014    /// #     results.push(format!("{:?}", stream.next().await.unwrap()));
1015    /// # }
1016    /// # results.sort();
1017    /// // if there are 4 members in the cluster, we should receive 4 elements
1018    /// // 1, 1, 1, 1
1019    /// # assert_eq!(results, vec!["1", "1", "1", "1"]);
1020    /// # }));
1021    /// # }
1022    /// ```
1023    pub fn send_bincode<L2>(
1024        self,
1025        other: &Process<'a, L2>,
1026    ) -> KeyedStream<MemberId<L>, T, Process<'a, L2>, Unbounded, O, R>
1027    where
1028        T: Serialize + DeserializeOwned,
1029    {
1030        self.send(other, TCP.fail_stop().bincode())
1031    }
1032
1033    /// "Moves" elements of this stream from a cluster to a process by sending them over the network,
1034    /// using the configuration in `via` to set up the message transport.
1035    ///
1036    /// Each cluster member sends its local stream elements, and they are collected at the destination
1037    /// as a [`KeyedStream`] where keys identify the source cluster member.
1038    ///
1039    /// # Example
1040    /// ```rust
1041    /// # #[cfg(feature = "deploy")] {
1042    /// # use hydro_lang::prelude::*;
1043    /// # use futures::StreamExt;
1044    /// # tokio_test::block_on(hydro_lang::test_util::multi_location_test(|flow, process| {
1045    /// let workers: Cluster<()> = flow.cluster::<()>();
1046    /// let numbers: Stream<_, Cluster<_>, _> = workers.source_iter(q!(vec![1]));
1047    /// let all_received = numbers.send(&process, TCP.fail_stop().bincode()); // KeyedStream<MemberId<()>, i32, ...>
1048    /// # all_received.entries()
1049    /// # }, |mut stream| async move {
1050    /// // if there are 4 members in the cluster, we should receive 4 elements
1051    /// // { MemberId::<()>(0): [1], MemberId::<()>(1): [1], MemberId::<()>(2): [1], MemberId::<()>(3): [1] }
1052    /// # let mut results = Vec::new();
1053    /// # for w in 0..4 {
1054    /// #     results.push(format!("{:?}", stream.next().await.unwrap()));
1055    /// # }
1056    /// # results.sort();
1057    /// # assert_eq!(results, vec!["(MemberId::<()>(0), 1)", "(MemberId::<()>(1), 1)", "(MemberId::<()>(2), 1)", "(MemberId::<()>(3), 1)"]);
1058    /// # }));
1059    /// # }
1060    /// ```
1061    ///
1062    /// If you don't need to know the source for each element, you can use `.values()`
1063    /// to get just the data:
1064    /// ```rust
1065    /// # #[cfg(feature = "deploy")] {
1066    /// # use hydro_lang::prelude::*;
1067    /// # use hydro_lang::live_collections::stream::NoOrder;
1068    /// # use futures::StreamExt;
1069    /// # tokio_test::block_on(hydro_lang::test_util::multi_location_test(|flow, process| {
1070    /// # let workers: Cluster<()> = flow.cluster::<()>();
1071    /// # let numbers: Stream<_, Cluster<_>, _> = workers.source_iter(q!(vec![1]));
1072    /// let values: Stream<i32, _, _, NoOrder> =
1073    ///     numbers.send(&process, TCP.fail_stop().bincode()).values();
1074    /// # values
1075    /// # }, |mut stream| async move {
1076    /// # let mut results = Vec::new();
1077    /// # for w in 0..4 {
1078    /// #     results.push(format!("{:?}", stream.next().await.unwrap()));
1079    /// # }
1080    /// # results.sort();
1081    /// // if there are 4 members in the cluster, we should receive 4 elements
1082    /// // 1, 1, 1, 1
1083    /// # assert_eq!(results, vec!["1", "1", "1", "1"]);
1084    /// # }));
1085    /// # }
1086    /// ```
1087    pub fn send<L2, N: NetworkFor<T>>(
1088        self,
1089        to: &Process<'a, L2>,
1090        via: N,
1091    ) -> KeyedStream<
1092        MemberId<L>,
1093        T,
1094        Process<'a, L2>,
1095        Unbounded,
1096        <O as MinOrder<N::OrderingGuarantee>>::Min,
1097        R,
1098    >
1099    where
1100        O: MinOrder<N::OrderingGuarantee>,
1101    {
1102        let name = via.name();
1103        if to.multiversioned() && name.is_none() {
1104            panic!(
1105                "Cannot send to a multiversioned location without a channel name. Please provide a name for the network."
1106            );
1107        }
1108
1109        let (serialize, deserialize) = if N::is_embedded() {
1110            (
1111                NetworkSend::Embedded {
1112                    tag: None,
1113                    element_type: quote_type::<T>().into(),
1114                },
1115                NetworkRecv::Embedded {
1116                    tag: Some(quote_type::<L>().into()),
1117                    element_type: quote_type::<T>().into(),
1118                },
1119            )
1120        } else {
1121            (
1122                NetworkSend::Custom {
1123                    serialize_fn: Some(N::serialize_thunk(false).into()),
1124                },
1125                NetworkRecv::Custom {
1126                    deserialize_fn: Some(N::deserialize_thunk(Some(&quote_type::<L>())).into()),
1127                },
1128            )
1129        };
1130
1131        let raw_stream: Stream<
1132            (MemberId<L>, T),
1133            Process<'a, L2>,
1134            Unbounded,
1135            <O as MinOrder<N::OrderingGuarantee>>::Min,
1136            R,
1137        > = Stream::new(
1138            to.clone(),
1139            HydroNode::Network {
1140                name: name.map(ToOwned::to_owned),
1141                networking_info: N::networking_info(),
1142                serialize,
1143                deserialize,
1144                instantiate_fn: DebugInstantiate::Building,
1145                input: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
1146                metadata: to.new_node_metadata(Stream::<
1147                    (MemberId<L>, T),
1148                    Process<'a, L2>,
1149                    Unbounded,
1150                    <O as MinOrder<N::OrderingGuarantee>>::Min,
1151                    R,
1152                >::collection_kind()),
1153            },
1154        );
1155
1156        raw_stream.into_keyed()
1157    }
1158
1159    #[deprecated = "use Stream::broadcast(..., TCP.fail_stop().bincode()) instead"]
1160    /// Broadcasts elements of this stream at each source member to all members of a destination
1161    /// cluster, using [`bincode`] to serialize/deserialize messages.
1162    ///
1163    /// Each source member sends each of its stream elements to **every** member of the cluster
1164    /// based on its latest membership information. Unlike [`Stream::demux_bincode`], which requires
1165    /// `(MemberId, T)` tuples to target specific members, `broadcast_bincode` takes a stream of
1166    /// **only data elements** and sends each element to all cluster members.
1167    ///
1168    /// # Non-Determinism
1169    /// The set of cluster members may asynchronously change over time. Each element is only broadcast
1170    /// to the current cluster members known _at that point in time_ at the source member. Depending
1171    /// on when each source member is notified of membership changes, it will broadcast each element
1172    /// to different members.
1173    ///
1174    /// # Example
1175    /// ```rust
1176    /// # #[cfg(feature = "deploy")] {
1177    /// # use hydro_lang::prelude::*;
1178    /// # use hydro_lang::location::MemberId;
1179    /// # use futures::StreamExt;
1180    /// # tokio_test::block_on(hydro_lang::test_util::multi_location_test(|flow, p2| {
1181    /// # type Source = ();
1182    /// # type Destination = ();
1183    /// let source: Cluster<Source> = flow.cluster::<Source>();
1184    /// let numbers: Stream<_, Cluster<Source>, _> = source.source_iter(q!(vec![123]));
1185    /// let destination: Cluster<Destination> = flow.cluster::<Destination>();
1186    /// let on_destination: KeyedStream<MemberId<Source>, _, Cluster<Destination>, _> = numbers.broadcast_bincode(&destination, nondet!(/** assuming stable membership */));
1187    /// # on_destination.entries().send_bincode(&p2).entries()
1188    /// // if there are 4 members in the desination, each receives one element from each source member
1189    /// // - Destination(0): { Source(0): [123], Source(1): [123], ... }
1190    /// // - Destination(1): { Source(0): [123], Source(1): [123], ... }
1191    /// // - ...
1192    /// # }, |mut stream| async move {
1193    /// # let mut results = Vec::new();
1194    /// # for w in 0..16 {
1195    /// #     results.push(format!("{:?}", stream.next().await.unwrap()));
1196    /// # }
1197    /// # results.sort();
1198    /// # assert_eq!(results, vec![
1199    /// #   "(MemberId::<()>(0), (MemberId::<()>(0), 123))", "(MemberId::<()>(0), (MemberId::<()>(1), 123))", "(MemberId::<()>(0), (MemberId::<()>(2), 123))", "(MemberId::<()>(0), (MemberId::<()>(3), 123))",
1200    /// #   "(MemberId::<()>(1), (MemberId::<()>(0), 123))", "(MemberId::<()>(1), (MemberId::<()>(1), 123))", "(MemberId::<()>(1), (MemberId::<()>(2), 123))", "(MemberId::<()>(1), (MemberId::<()>(3), 123))",
1201    /// #   "(MemberId::<()>(2), (MemberId::<()>(0), 123))", "(MemberId::<()>(2), (MemberId::<()>(1), 123))", "(MemberId::<()>(2), (MemberId::<()>(2), 123))", "(MemberId::<()>(2), (MemberId::<()>(3), 123))",
1202    /// #   "(MemberId::<()>(3), (MemberId::<()>(0), 123))", "(MemberId::<()>(3), (MemberId::<()>(1), 123))", "(MemberId::<()>(3), (MemberId::<()>(2), 123))", "(MemberId::<()>(3), (MemberId::<()>(3), 123))"
1203    /// # ]);
1204    /// # }));
1205    /// # }
1206    /// ```
1207    pub fn broadcast_bincode<L2: 'a>(
1208        self,
1209        other: &Cluster<'a, L2>,
1210        nondet_membership: NonDet,
1211    ) -> KeyedStream<MemberId<L>, T, Cluster<'a, L2>, Unbounded, O, R>
1212    where
1213        T: Clone + Serialize + DeserializeOwned,
1214    {
1215        self.broadcast(other, TCP.fail_stop().bincode(), nondet_membership)
1216    }
1217
1218    /// Broadcasts elements of this stream at each source member to all members of a destination
1219    /// cluster, using the configuration in `via` to set up the message transport.
1220    ///
1221    /// Each source member sends each of its stream elements to **every** member of the cluster
1222    /// based on its latest membership information. Unlike [`Stream::demux`], which requires
1223    /// `(MemberId, T)` tuples to target specific members, `broadcast` takes a stream of
1224    /// **only data elements** and sends each element to all cluster members.
1225    ///
1226    /// # Non-Determinism
1227    /// The set of cluster members may asynchronously change over time. Each element is only broadcast
1228    /// to the current cluster members known _at that point in time_ at the source member. Depending
1229    /// on when each source member is notified of membership changes, it will broadcast each element
1230    /// to different members.
1231    ///
1232    /// # Example
1233    /// ```rust
1234    /// # #[cfg(feature = "deploy")] {
1235    /// # use hydro_lang::prelude::*;
1236    /// # use hydro_lang::location::MemberId;
1237    /// # use futures::StreamExt;
1238    /// # tokio_test::block_on(hydro_lang::test_util::multi_location_test(|flow, p2| {
1239    /// # type Source = ();
1240    /// # type Destination = ();
1241    /// let source: Cluster<Source> = flow.cluster::<Source>();
1242    /// let numbers: Stream<_, Cluster<Source>, _> = source.source_iter(q!(vec![123]));
1243    /// let destination: Cluster<Destination> = flow.cluster::<Destination>();
1244    /// let on_destination: KeyedStream<MemberId<Source>, _, Cluster<Destination>, _> = numbers.broadcast(&destination, TCP.fail_stop().bincode(), nondet!(/** assuming stable membership */));
1245    /// # on_destination.entries().send(&p2, TCP.fail_stop().bincode()).entries()
1246    /// // if there are 4 members in the desination, each receives one element from each source member
1247    /// // - Destination(0): { Source(0): [123], Source(1): [123], ... }
1248    /// // - Destination(1): { Source(0): [123], Source(1): [123], ... }
1249    /// // - ...
1250    /// # }, |mut stream| async move {
1251    /// # let mut results = Vec::new();
1252    /// # for w in 0..16 {
1253    /// #     results.push(format!("{:?}", stream.next().await.unwrap()));
1254    /// # }
1255    /// # results.sort();
1256    /// # assert_eq!(results, vec![
1257    /// #   "(MemberId::<()>(0), (MemberId::<()>(0), 123))", "(MemberId::<()>(0), (MemberId::<()>(1), 123))", "(MemberId::<()>(0), (MemberId::<()>(2), 123))", "(MemberId::<()>(0), (MemberId::<()>(3), 123))",
1258    /// #   "(MemberId::<()>(1), (MemberId::<()>(0), 123))", "(MemberId::<()>(1), (MemberId::<()>(1), 123))", "(MemberId::<()>(1), (MemberId::<()>(2), 123))", "(MemberId::<()>(1), (MemberId::<()>(3), 123))",
1259    /// #   "(MemberId::<()>(2), (MemberId::<()>(0), 123))", "(MemberId::<()>(2), (MemberId::<()>(1), 123))", "(MemberId::<()>(2), (MemberId::<()>(2), 123))", "(MemberId::<()>(2), (MemberId::<()>(3), 123))",
1260    /// #   "(MemberId::<()>(3), (MemberId::<()>(0), 123))", "(MemberId::<()>(3), (MemberId::<()>(1), 123))", "(MemberId::<()>(3), (MemberId::<()>(2), 123))", "(MemberId::<()>(3), (MemberId::<()>(3), 123))"
1261    /// # ]);
1262    /// # }));
1263    /// # }
1264    /// ```
1265    pub fn broadcast<L2: 'a, N: NetworkFor<T>>(
1266        self,
1267        to: &Cluster<'a, L2>,
1268        via: N,
1269        nondet_membership: NonDet,
1270    ) -> KeyedStream<
1271        MemberId<L>,
1272        T,
1273        Cluster<'a, L2>,
1274        Unbounded,
1275        <O as MinOrder<N::OrderingGuarantee>>::Min,
1276        R,
1277    >
1278    where
1279        T: Clone,
1280        O: MinOrder<N::OrderingGuarantee>,
1281    {
1282        // TODO(#1875): the membership snapshot below is over a `KeyedSingleton`, and keyed
1283        // sim hooks do not exist yet. Once they do, expose a composite hook payload here
1284        // (`NonDet<(Option<KeyedSnapshotHook<..>>, Option<BatchHook<T, O, R>>)>`) so tests
1285        // can script the membership snapshot and the element batching independently.
1286        let ids = track_membership(self.location.source_cluster_membership_stream(
1287            to,
1288            nondet!(/** dropped prefixes don't affect broadcast */),
1289        ));
1290        sliced! {
1291            let members_snapshot = use::snapshot(ids, nondet!(
1292                /// membership timing is captured by the caller's guard
1293                nondet_membership
1294            ));
1295            let elements = use::batch(self, nondet!(
1296                /// batching timing is captured by the caller's guard
1297                nondet_membership
1298            ));
1299
1300            let current_members = members_snapshot.filter(q!(|b| *b));
1301            elements.repeat_with_keys(current_members)
1302        }
1303        .demux(to, via)
1304    }
1305
1306    /// Broadcasts elements of this stream at each source member to all members of a destination
1307    /// cluster, assuming membership is closed (fixed at deploy time).
1308    ///
1309    /// Unlike [`Stream::broadcast`], this does not require a [`NonDet`] guard.
1310    /// The membership set is obtained from deploy metadata via [`ClusterIds`], making the
1311    /// broadcast fully deterministic.
1312    ///
1313    /// The consistency guarantee of the output depends on the network's failure policy
1314    /// ([`NetworkFor::ConsistencyGuarantee`]). Policies like `fail_stop` and
1315    /// `lossy_delayed_forever` guarantee that every live destination member eventually
1316    /// materializes the same elements from each source, so the output is
1317    /// [`EventualConsistency`](crate::location::cluster::EventualConsistency). A plain `lossy`
1318    /// policy can drop individual messages for some
1319    /// members while delivering them to others, so replicas may permanently diverge and the
1320    /// output only has [`NoConsistency`].
1321    ///
1322    /// This is only available in deployment targets with static cluster membership
1323    /// (legacy Hydro Deploy and simulation). On dynamic targets, use [`Stream::broadcast`].
1324    pub fn broadcast_closed<L2: 'a, N: NetworkFor<T>>(
1325        self,
1326        to: &Cluster<'a, L2>,
1327        via: N,
1328    ) -> KeyedStream<
1329        MemberId<L>,
1330        T,
1331        Cluster<'a, L2, N::ConsistencyGuarantee>,
1332        Unbounded,
1333        <O as MinOrder<N::OrderingGuarantee>>::Min,
1334        R,
1335    >
1336    where
1337        T: Clone,
1338        O: MinOrder<N::OrderingGuarantee>,
1339    {
1340        let cluster_ids = ClusterIds {
1341            key: to.key,
1342            _phantom: PhantomData,
1343        };
1344        let member_ids = self
1345            .location
1346            .source_iter(q!(cluster_ids
1347                .iter()
1348                .map(|id| MemberId::from_tagless(id.clone()))))
1349            .assert_has_consistency_of_trusted::<Cluster<'a, L, C>>(manual_proof!(
1350                /// ClusterIds is deploy-time metadata, identical on every cluster member.
1351            ));
1352
1353        self.cross_product(member_ids)
1354            .map(q!(|(data, member_id)| (member_id, data)))
1355            .into_keyed()
1356            .demux(to, via)
1357            .assert_has_consistency_of_trusted(manual_proof!(
1358                /// Closed broadcast with fixed membership: every source member sends to every
1359                /// destination member, and the network's failure policy (tracked by
1360                /// `NetworkFor::ConsistencyGuarantee`) delivers the same messages to every live
1361                /// member, so all destinations materialize the same elements.
1362            ))
1363    }
1364
1365    #[cfg(feature = "sim")]
1366    /// Sends elements of this cluster stream to an external location using bincode serialization.
1367    fn send_bincode_external<L2>(self, other: &External<'_, L2>) -> ExternalBincodeStream<T, O, R>
1368    where
1369        T: Serialize + DeserializeOwned,
1370    {
1371        let serialize_pipeline = Some(serialize_bincode::<T>(false));
1372
1373        let mut flow_state_borrow = self.location.flow_state().borrow_mut();
1374
1375        let external_port_id = flow_state_borrow.next_external_port();
1376
1377        flow_state_borrow.push_root(HydroRoot::SendExternal {
1378            to_external_key: other.key,
1379            to_port_id: external_port_id,
1380            to_many: false,
1381            unpaired: true,
1382            serialize_fn: serialize_pipeline.map(|e| e.into()),
1383            instantiate_fn: DebugInstantiate::Building,
1384            input: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
1385            op_metadata: HydroIrOpMetadata::new(),
1386        });
1387
1388        ExternalBincodeStream {
1389            process_key: other.key,
1390            port_id: external_port_id,
1391            _phantom: PhantomData,
1392        }
1393    }
1394
1395    #[cfg(feature = "sim")]
1396    /// Sets up a simulation output port for this cluster stream, allowing test code
1397    /// to receive `(member_id, T)` pairs during simulation.
1398    pub fn sim_cluster_output(self) -> crate::sim::SimClusterReceiver<T, O, R>
1399    where
1400        T: Serialize + DeserializeOwned,
1401    {
1402        let external_location: External<'a, ()> = External {
1403            key: LocationKey::FIRST,
1404            flow_state: self.location.flow_state().clone(),
1405            _phantom: PhantomData,
1406        };
1407
1408        let external = self.send_bincode_external(&external_location);
1409
1410        crate::sim::SimClusterReceiver(external.port_id, PhantomData)
1411    }
1412}
1413
1414impl<'a, T, L, L2, B: Boundedness, C: Consistency, O: Ordering, R: Retries>
1415    Stream<(MemberId<L2>, T), Cluster<'a, L, C>, B, O, R>
1416{
1417    #[deprecated = "use Stream::demux(..., TCP.fail_stop().bincode()) instead"]
1418    /// Sends elements of this stream at each source member to specific members of a destination
1419    /// cluster, identified by a [`MemberId`], using [`bincode`] to serialize/deserialize messages.
1420    ///
1421    /// Each element in the stream must be a tuple `(MemberId<L2>, T)` where the first element
1422    /// specifies which cluster member should receive the data. Unlike [`Stream::broadcast_bincode`],
1423    /// this API allows precise targeting of specific cluster members rather than broadcasting to
1424    /// all members.
1425    ///
1426    /// Each cluster member sends its local stream elements, and they are collected at each
1427    /// destination member as a [`KeyedStream`] where keys identify the source cluster member.
1428    ///
1429    /// # Example
1430    /// ```rust
1431    /// # #[cfg(feature = "deploy")] {
1432    /// # use hydro_lang::prelude::*;
1433    /// # use futures::StreamExt;
1434    /// # tokio_test::block_on(hydro_lang::test_util::multi_location_test(|flow, p2| {
1435    /// # type Source = ();
1436    /// # type Destination = ();
1437    /// let source: Cluster<Source> = flow.cluster::<Source>();
1438    /// let to_send: Stream<_, Cluster<_>, _> = source
1439    ///     .source_iter(q!(vec![0, 1, 2, 3]))
1440    ///     .map(q!(|x| (hydro_lang::location::MemberId::from_raw_id(x), x)));
1441    /// let destination: Cluster<Destination> = flow.cluster::<Destination>();
1442    /// let all_received = to_send.demux_bincode(&destination); // KeyedStream<MemberId<Source>, i32, ...>
1443    /// # all_received.entries().send_bincode(&p2).entries()
1444    /// # }, |mut stream| async move {
1445    /// // if there are 4 members in the destination cluster, each receives one message from each source member
1446    /// // - Destination(0): { Source(0): [0], Source(1): [0], ... }
1447    /// // - Destination(1): { Source(0): [1], Source(1): [1], ... }
1448    /// // - ...
1449    /// # let mut results = Vec::new();
1450    /// # for w in 0..16 {
1451    /// #     results.push(format!("{:?}", stream.next().await.unwrap()));
1452    /// # }
1453    /// # results.sort();
1454    /// # assert_eq!(results, vec![
1455    /// #   "(MemberId::<()>(0), (MemberId::<()>(0), 0))", "(MemberId::<()>(0), (MemberId::<()>(1), 0))", "(MemberId::<()>(0), (MemberId::<()>(2), 0))", "(MemberId::<()>(0), (MemberId::<()>(3), 0))",
1456    /// #   "(MemberId::<()>(1), (MemberId::<()>(0), 1))", "(MemberId::<()>(1), (MemberId::<()>(1), 1))", "(MemberId::<()>(1), (MemberId::<()>(2), 1))", "(MemberId::<()>(1), (MemberId::<()>(3), 1))",
1457    /// #   "(MemberId::<()>(2), (MemberId::<()>(0), 2))", "(MemberId::<()>(2), (MemberId::<()>(1), 2))", "(MemberId::<()>(2), (MemberId::<()>(2), 2))", "(MemberId::<()>(2), (MemberId::<()>(3), 2))",
1458    /// #   "(MemberId::<()>(3), (MemberId::<()>(0), 3))", "(MemberId::<()>(3), (MemberId::<()>(1), 3))", "(MemberId::<()>(3), (MemberId::<()>(2), 3))", "(MemberId::<()>(3), (MemberId::<()>(3), 3))"
1459    /// # ]);
1460    /// # }));
1461    /// # }
1462    /// ```
1463    pub fn demux_bincode(
1464        self,
1465        other: &Cluster<'a, L2>,
1466    ) -> KeyedStream<MemberId<L>, T, Cluster<'a, L2>, Unbounded, O, R>
1467    where
1468        T: Serialize + DeserializeOwned,
1469    {
1470        self.demux(other, TCP.fail_stop().bincode())
1471    }
1472
1473    /// Sends elements of this stream at each source member to specific members of a destination
1474    /// cluster, identified by a [`MemberId`], using the configuration in `via` to set up the
1475    /// message transport.
1476    ///
1477    /// Each element in the stream must be a tuple `(MemberId<L2>, T)` where the first element
1478    /// specifies which cluster member should receive the data. Unlike [`Stream::broadcast`],
1479    /// this API allows precise targeting of specific cluster members rather than broadcasting to
1480    /// all members.
1481    ///
1482    /// Each cluster member sends its local stream elements, and they are collected at each
1483    /// destination member as a [`KeyedStream`] where keys identify the source cluster member.
1484    ///
1485    /// # Example
1486    /// ```rust
1487    /// # #[cfg(feature = "deploy")] {
1488    /// # use hydro_lang::prelude::*;
1489    /// # use futures::StreamExt;
1490    /// # tokio_test::block_on(hydro_lang::test_util::multi_location_test(|flow, p2| {
1491    /// # type Source = ();
1492    /// # type Destination = ();
1493    /// let source: Cluster<Source> = flow.cluster::<Source>();
1494    /// let to_send: Stream<_, Cluster<_>, _> = source
1495    ///     .source_iter(q!(vec![0, 1, 2, 3]))
1496    ///     .map(q!(|x| (hydro_lang::location::MemberId::from_raw_id(x), x)));
1497    /// let destination: Cluster<Destination> = flow.cluster::<Destination>();
1498    /// let all_received = to_send.demux(&destination, TCP.fail_stop().bincode()); // KeyedStream<MemberId<Source>, i32, ...>
1499    /// # all_received.entries().send(&p2, TCP.fail_stop().bincode()).entries()
1500    /// # }, |mut stream| async move {
1501    /// // if there are 4 members in the destination cluster, each receives one message from each source member
1502    /// // - Destination(0): { Source(0): [0], Source(1): [0], ... }
1503    /// // - Destination(1): { Source(0): [1], Source(1): [1], ... }
1504    /// // - ...
1505    /// # let mut results = Vec::new();
1506    /// # for w in 0..16 {
1507    /// #     results.push(format!("{:?}", stream.next().await.unwrap()));
1508    /// # }
1509    /// # results.sort();
1510    /// # assert_eq!(results, vec![
1511    /// #   "(MemberId::<()>(0), (MemberId::<()>(0), 0))", "(MemberId::<()>(0), (MemberId::<()>(1), 0))", "(MemberId::<()>(0), (MemberId::<()>(2), 0))", "(MemberId::<()>(0), (MemberId::<()>(3), 0))",
1512    /// #   "(MemberId::<()>(1), (MemberId::<()>(0), 1))", "(MemberId::<()>(1), (MemberId::<()>(1), 1))", "(MemberId::<()>(1), (MemberId::<()>(2), 1))", "(MemberId::<()>(1), (MemberId::<()>(3), 1))",
1513    /// #   "(MemberId::<()>(2), (MemberId::<()>(0), 2))", "(MemberId::<()>(2), (MemberId::<()>(1), 2))", "(MemberId::<()>(2), (MemberId::<()>(2), 2))", "(MemberId::<()>(2), (MemberId::<()>(3), 2))",
1514    /// #   "(MemberId::<()>(3), (MemberId::<()>(0), 3))", "(MemberId::<()>(3), (MemberId::<()>(1), 3))", "(MemberId::<()>(3), (MemberId::<()>(2), 3))", "(MemberId::<()>(3), (MemberId::<()>(3), 3))"
1515    /// # ]);
1516    /// # }));
1517    /// # }
1518    /// ```
1519    pub fn demux<N: NetworkFor<T>>(
1520        self,
1521        to: &Cluster<'a, L2>,
1522        via: N,
1523    ) -> KeyedStream<
1524        MemberId<L>,
1525        T,
1526        Cluster<'a, L2, NoConsistency>,
1527        Unbounded,
1528        <O as MinOrder<N::OrderingGuarantee>>::Min,
1529        R,
1530    >
1531    where
1532        O: MinOrder<N::OrderingGuarantee>,
1533    {
1534        self.into_keyed().demux(to, via)
1535    }
1536}
1537
1538#[cfg(test)]
1539mod tests {
1540    #[cfg(feature = "sim")]
1541    use stageleft::q;
1542
1543    #[cfg(feature = "sim")]
1544    use crate::live_collections::sliced::sliced;
1545    #[cfg(feature = "sim")]
1546    use crate::location::{Location, MemberId};
1547    #[cfg(feature = "sim")]
1548    use crate::networking::TCP;
1549    #[cfg(feature = "sim")]
1550    use crate::nondet::nondet;
1551    #[cfg(feature = "sim")]
1552    use crate::prelude::FlowBuilder;
1553
1554    #[cfg(feature = "sim")]
1555    #[test]
1556    fn sim_send_bincode_o2o() {
1557        use crate::networking::TCP;
1558
1559        let mut flow = FlowBuilder::new();
1560        let node = flow.process::<()>();
1561        let node2 = flow.process::<()>();
1562
1563        let (in_send, input) = node.sim_input();
1564
1565        let out_recv = input
1566            .send(&node2, TCP.fail_stop().bincode())
1567            .batch(&node2.tick(), nondet!(/** test */))
1568            .count()
1569            .all_ticks()
1570            .sim_output();
1571
1572        let instances = flow.sim().exhaustive(async || {
1573            in_send.send(());
1574            in_send.send(());
1575            in_send.send(());
1576
1577            let received = out_recv.collect::<Vec<_>>().await;
1578            assert!(received.into_iter().sum::<usize>() == 3);
1579        });
1580
1581        assert_eq!(instances, 4); // 2^{3 - 1}
1582    }
1583
1584    #[cfg(feature = "sim")]
1585    #[test]
1586    fn sim_send_bincode_m2o() {
1587        let mut flow = FlowBuilder::new();
1588        let cluster = flow.cluster::<()>();
1589        let node = flow.process::<()>();
1590
1591        let input = cluster.source_iter(q!(vec![1]));
1592
1593        let out_recv = input
1594            .send(&node, TCP.fail_stop().bincode())
1595            .entries()
1596            .batch(&node.tick(), nondet!(/** test */))
1597            .all_ticks()
1598            .sim_output();
1599
1600        let instances = flow
1601            .sim()
1602            .with_cluster_size(&cluster, 4)
1603            .exhaustive(async || {
1604                out_recv
1605                    .assert_yields_only_unordered(vec![
1606                        (MemberId::from_raw_id(0), 1),
1607                        (MemberId::from_raw_id(1), 1),
1608                        (MemberId::from_raw_id(2), 1),
1609                        (MemberId::from_raw_id(3), 1),
1610                    ])
1611                    .await
1612            });
1613
1614        assert_eq!(instances, 75); // ∑ (k=1 to 4) S(4,k) × k! = 75
1615    }
1616
1617    #[cfg(feature = "sim")]
1618    #[test]
1619    fn sim_send_bincode_multiple_m2o() {
1620        let mut flow = FlowBuilder::new();
1621        let cluster1 = flow.cluster::<()>();
1622        let cluster2 = flow.cluster::<()>();
1623        let node = flow.process::<()>();
1624
1625        let out_recv_1 = cluster1
1626            .source_iter(q!(vec![1]))
1627            .send(&node, TCP.fail_stop().bincode())
1628            .entries()
1629            .sim_output();
1630
1631        let out_recv_2 = cluster2
1632            .source_iter(q!(vec![2]))
1633            .send(&node, TCP.fail_stop().bincode())
1634            .entries()
1635            .sim_output();
1636
1637        let instances = flow
1638            .sim()
1639            .with_cluster_size(&cluster1, 3)
1640            .with_cluster_size(&cluster2, 4)
1641            .exhaustive(async || {
1642                out_recv_1
1643                    .assert_yields_only_unordered(vec![
1644                        (MemberId::from_raw_id(0), 1),
1645                        (MemberId::from_raw_id(1), 1),
1646                        (MemberId::from_raw_id(2), 1),
1647                    ])
1648                    .await;
1649
1650                out_recv_2
1651                    .assert_yields_only_unordered(vec![
1652                        (MemberId::from_raw_id(0), 2),
1653                        (MemberId::from_raw_id(1), 2),
1654                        (MemberId::from_raw_id(2), 2),
1655                        (MemberId::from_raw_id(3), 2),
1656                    ])
1657                    .await;
1658            });
1659
1660        assert_eq!(instances, 1);
1661    }
1662
1663    #[cfg(feature = "sim")]
1664    #[test]
1665    fn sim_send_bincode_o2m() {
1666        let mut flow = FlowBuilder::new();
1667        let cluster = flow.cluster::<()>();
1668        let node = flow.process::<()>();
1669
1670        let input = node.source_iter(q!(vec![
1671            (MemberId::from_raw_id(0), 123),
1672            (MemberId::from_raw_id(1), 456),
1673        ]));
1674
1675        let out_recv = input
1676            .demux(&cluster, TCP.fail_stop().bincode())
1677            .map(q!(|x| x + 1))
1678            .send(&node, TCP.fail_stop().bincode())
1679            .entries()
1680            .sim_output();
1681
1682        flow.sim()
1683            .with_cluster_size(&cluster, 4)
1684            .exhaustive(async || {
1685                out_recv
1686                    .assert_yields_only_unordered(vec![
1687                        (MemberId::from_raw_id(0), 124),
1688                        (MemberId::from_raw_id(1), 457),
1689                    ])
1690                    .await
1691            });
1692    }
1693
1694    #[cfg(feature = "sim")]
1695    #[test]
1696    fn sim_broadcast_bincode_o2m() {
1697        let mut flow = FlowBuilder::new();
1698        let cluster = flow.cluster::<()>();
1699        let node = flow.process::<()>();
1700
1701        let input = node.source_iter(q!(vec![123, 456]));
1702
1703        let out_recv = input
1704            .broadcast(&cluster, TCP.fail_stop().bincode(), nondet!(/** test */))
1705            .map(q!(|x| x + 1))
1706            .send(&node, TCP.fail_stop().bincode())
1707            .entries()
1708            .sim_output();
1709
1710        let mut c_1_produced = false;
1711        let mut c_2_produced = false;
1712        let mut c_1_saw_457_but_not_124 = false;
1713
1714        flow.sim()
1715            .with_cluster_size(&cluster, 2)
1716            .exhaustive(async || {
1717                let all_out = out_recv.collect_sorted::<Vec<_>>().await;
1718
1719                // check that order is preserved
1720                if all_out.contains(&(MemberId::from_raw_id(0), 124)) {
1721                    assert!(all_out.contains(&(MemberId::from_raw_id(0), 457)));
1722                    c_1_produced = true;
1723                }
1724
1725                if all_out.contains(&(MemberId::from_raw_id(1), 124)) {
1726                    assert!(all_out.contains(&(MemberId::from_raw_id(1), 457)));
1727                    c_2_produced = true;
1728                }
1729
1730                if all_out.contains(&(MemberId::from_raw_id(0), 457))
1731                    && !all_out.contains(&(MemberId::from_raw_id(0), 124))
1732                {
1733                    c_1_saw_457_but_not_124 = true;
1734                }
1735            });
1736
1737        assert!(c_1_produced && c_2_produced); // in at least one execution each, the cluster member received both messages
1738
1739        // in at least one execution, the cluster member received 457 but not 124, this tests
1740        // that the simulator properly explores dynamic membership additions (a member that joins after 123 is broadcast)
1741        assert!(c_1_saw_457_but_not_124);
1742    }
1743
1744    #[cfg(feature = "sim")]
1745    #[test]
1746    fn sim_send_bincode_m2m() {
1747        let mut flow = FlowBuilder::new();
1748        let cluster = flow.cluster::<()>();
1749        let node = flow.process::<()>();
1750
1751        let input = node.source_iter(q!(vec![
1752            (MemberId::from_raw_id(0), 123),
1753            (MemberId::from_raw_id(1), 456),
1754        ]));
1755
1756        let out_recv = input
1757            .demux(&cluster, TCP.fail_stop().bincode())
1758            .map(q!(|x| x + 1))
1759            .flat_map_ordered(q!(|x| vec![
1760                (MemberId::from_raw_id(0), x),
1761                (MemberId::from_raw_id(1), x),
1762            ]))
1763            .demux(&cluster, TCP.fail_stop().bincode())
1764            .entries()
1765            .send(&node, TCP.fail_stop().bincode())
1766            .entries()
1767            .sim_output();
1768
1769        flow.sim()
1770            .with_cluster_size(&cluster, 4)
1771            .exhaustive(async || {
1772                out_recv
1773                    .assert_yields_only_unordered(vec![
1774                        (MemberId::from_raw_id(0), (MemberId::from_raw_id(0), 124)),
1775                        (MemberId::from_raw_id(0), (MemberId::from_raw_id(1), 457)),
1776                        (MemberId::from_raw_id(1), (MemberId::from_raw_id(0), 124)),
1777                        (MemberId::from_raw_id(1), (MemberId::from_raw_id(1), 457)),
1778                    ])
1779                    .await
1780            });
1781    }
1782
1783    #[cfg(feature = "sim")]
1784    #[test]
1785    fn sim_lossy_delayed_forever_o2o() {
1786        use std::collections::HashSet;
1787
1788        use crate::properties::manual_proof;
1789
1790        let mut flow = FlowBuilder::new();
1791        let node = flow.process::<()>();
1792        let node2 = flow.process::<()>();
1793
1794        let received = node
1795            .source_iter(q!(0..3_u32))
1796            .send(&node2, TCP.lossy_delayed_forever().bincode())
1797            .fold(
1798                q!(|| std::collections::HashSet::<u32>::new()),
1799                q!(
1800                    |set, v| {
1801                        set.insert(v);
1802                    },
1803                    commutative = manual_proof!(/** set insert is commutative */)
1804                ),
1805            );
1806
1807        let out_recv = sliced! {
1808            let snapshot = use::snapshot(received, nondet!(/** test */));
1809            snapshot.into_stream()
1810        }
1811        .sim_output();
1812
1813        let mut saw_non_contiguous = false;
1814
1815        flow.sim().test_safety_only().exhaustive(async || {
1816            let snapshots = out_recv.collect::<Vec<HashSet<u32>>>().await;
1817
1818            // Check each individual snapshot for a non-contiguous subset.
1819            for set in &snapshots {
1820                #[expect(clippy::disallowed_methods, reason = "min / max are deterministic")]
1821                if set.len() >= 2 && set.len() < 3 {
1822                    let min = *set.iter().min().unwrap();
1823                    let max = *set.iter().max().unwrap();
1824                    if set.len() < (max - min + 1) as usize {
1825                        saw_non_contiguous = true;
1826                    }
1827                }
1828            }
1829        });
1830
1831        assert!(
1832            saw_non_contiguous,
1833            "Expected at least one execution with a non-contiguous subset of inputs"
1834        );
1835    }
1836
1837    #[cfg(feature = "sim")]
1838    #[test]
1839    fn sim_udp_lossy_delayed_forever_o2o() {
1840        use std::collections::HashSet;
1841
1842        use crate::networking::UDP;
1843        use crate::properties::manual_proof;
1844
1845        let mut flow = FlowBuilder::new();
1846        let node = flow.process::<()>();
1847        let node2 = flow.process::<()>();
1848
1849        let received = node
1850            .source_iter(q!(0..3_u32))
1851            .send(&node2, UDP.lossy_delayed_forever().bincode())
1852            .fold(
1853                q!(|| std::collections::HashSet::<u32>::new()),
1854                q!(
1855                    |set, v| {
1856                        set.insert(v);
1857                    },
1858                    commutative = manual_proof!(/** set insert is commutative */)
1859                ),
1860            );
1861
1862        let out_recv = sliced! {
1863            let snapshot = use::snapshot(received, nondet!(/** test */));
1864            snapshot.into_stream()
1865        }
1866        .sim_output();
1867
1868        let mut saw_non_contiguous = false;
1869
1870        flow.sim().test_safety_only().exhaustive(async || {
1871            let snapshots = out_recv.collect::<Vec<HashSet<u32>>>().await;
1872
1873            // Check each individual snapshot for a non-contiguous subset.
1874            for set in &snapshots {
1875                #[expect(clippy::disallowed_methods, reason = "min / max are deterministic")]
1876                if set.len() >= 2 && set.len() < 3 {
1877                    let min = *set.iter().min().unwrap();
1878                    let max = *set.iter().max().unwrap();
1879                    if set.len() < (max - min + 1) as usize {
1880                        saw_non_contiguous = true;
1881                    }
1882                }
1883            }
1884        });
1885
1886        assert!(
1887            saw_non_contiguous,
1888            "Expected at least one execution with a non-contiguous subset of inputs"
1889        );
1890    }
1891
1892    #[cfg(feature = "sim")]
1893    #[test]
1894    fn sim_broadcast_closed_o2m() {
1895        let mut flow = FlowBuilder::new();
1896        let cluster = flow.cluster::<()>();
1897        let node = flow.process::<()>();
1898
1899        let input = node.source_iter(q!(vec![123, 456]));
1900
1901        let out_recv = input
1902            .broadcast_closed(&cluster, TCP.fail_stop().bincode())
1903            .send(&node, TCP.fail_stop().bincode())
1904            .entries()
1905            .sim_output();
1906
1907        flow.sim()
1908            .with_cluster_size(&cluster, 2)
1909            .exhaustive(async || {
1910                out_recv
1911                    .assert_yields_only_unordered(vec![
1912                        (MemberId::from_raw_id(0), 123),
1913                        (MemberId::from_raw_id(0), 456),
1914                        (MemberId::from_raw_id(1), 123),
1915                        (MemberId::from_raw_id(1), 456),
1916                    ])
1917                    .await
1918            });
1919    }
1920
1921    #[cfg(feature = "sim")]
1922    #[test]
1923    fn sim_broadcast_closed_m2m() {
1924        let mut flow = FlowBuilder::new();
1925        let source = flow.cluster::<()>();
1926        let dest: crate::location::Cluster<'_, ()> = flow.cluster::<()>();
1927        let node = flow.process::<()>();
1928
1929        let input = source.source_iter(q!(vec![123]));
1930
1931        // Broadcast from source cluster to dest cluster, then collect at a process.
1932        let out_recv = input
1933            .broadcast_closed(&dest, TCP.fail_stop().bincode())
1934            .entries()
1935            .send(&node, TCP.fail_stop().bincode())
1936            .entries()
1937            .sim_output();
1938
1939        flow.sim()
1940            .with_cluster_size(&source, 2)
1941            .with_cluster_size(&dest, 2)
1942            .exhaustive(async || {
1943                // Each source member (0, 1) broadcasts 123 to each dest member (0, 1).
1944                // The dest members then send to the process keyed by dest member id.
1945                // Each dest member receives (source_0, 123) and (source_1, 123).
1946                out_recv
1947                    .assert_yields_only_unordered(vec![
1948                        (MemberId::from_raw_id(0), (MemberId::from_raw_id(0), 123)),
1949                        (MemberId::from_raw_id(0), (MemberId::from_raw_id(1), 123)),
1950                        (MemberId::from_raw_id(1), (MemberId::from_raw_id(0), 123)),
1951                        (MemberId::from_raw_id(1), (MemberId::from_raw_id(1), 123)),
1952                    ])
1953                    .await
1954            });
1955    }
1956
1957    /// Compile-time check that the consistency guarantee of `broadcast_closed` output tracks
1958    /// the network's failure policy: `fail_stop` and `lossy_delayed_forever` preserve
1959    /// [`EventualConsistency`], while plain `lossy` only provides [`NoConsistency`].
1960    #[cfg(feature = "sim")]
1961    #[test]
1962    fn broadcast_closed_consistency_tracks_failure_policy() {
1963        use crate::live_collections::keyed_stream::KeyedStream;
1964        use crate::live_collections::stream::Stream;
1965        use crate::location::Cluster;
1966        use crate::location::cluster::{EventualConsistency, NoConsistency};
1967
1968        let mut flow = FlowBuilder::new();
1969        let cluster = flow.cluster::<()>();
1970        let source = flow.cluster::<()>();
1971        let node = flow.process::<()>();
1972
1973        // `fail_stop` models a failed connection as the recipient having failed, preserving
1974        // eventual consistency across live members.
1975        let _: Stream<u32, Cluster<'_, (), EventualConsistency>, _, _, _> = node
1976            .source_iter(q!(vec![1u32]))
1977            .broadcast_closed(&cluster, TCP.fail_stop().bincode());
1978
1979        // `lossy_delayed_forever` models drops as indefinite delays, preserving eventual
1980        // consistency.
1981        let _: Stream<u32, Cluster<'_, (), EventualConsistency>, _, _, _> = node
1982            .source_iter(q!(vec![1u32]))
1983            .broadcast_closed(&cluster, TCP.lossy_delayed_forever().bincode());
1984
1985        // Plain `lossy` can drop messages for some members while delivering them to others,
1986        // so replicas may permanently diverge.
1987        let _: Stream<u32, Cluster<'_, (), NoConsistency>, _, _, _> = node
1988            .source_iter(q!(vec![1u32]))
1989            .broadcast_closed(&cluster, TCP.lossy(nondet!(/** test */)).bincode());
1990
1991        // The same applies to cluster-to-cluster closed broadcasts.
1992        let _: KeyedStream<MemberId<()>, u32, Cluster<'_, (), EventualConsistency>, _, _, _> =
1993            source
1994                .source_iter(q!(vec![1u32]))
1995                .broadcast_closed(&cluster, TCP.fail_stop().bincode());
1996
1997        let _: KeyedStream<MemberId<()>, u32, Cluster<'_, (), NoConsistency>, _, _, _> = source
1998            .source_iter(q!(vec![1u32]))
1999            .broadcast_closed(&cluster, TCP.lossy(nondet!(/** test */)).bincode());
2000
2001        let _ = flow.finalize();
2002    }
2003}