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