Skip to main content

saluki_core/topology/
blueprint.rs

1use std::{
2    collections::{HashMap, HashSet},
3    future::Future,
4    num::NonZeroUsize,
5    pin::Pin,
6    sync::Mutex,
7    time::Duration,
8};
9
10use async_trait::async_trait;
11use saluki_common::resource_tracking::Track as _;
12use saluki_common::sync::shutdown::ShutdownHandle;
13use saluki_error::{generic_error, ErrorContext as _, GenericError};
14use snafu::Snafu;
15use tokio::{pin, runtime::Handle, select, sync::oneshot};
16use tracing::info;
17
18use super::{
19    built::{BuiltTopology, WorkerPoolConfiguration},
20    condition::{ConditionKind, EdgeCondition, EdgeConditions, EdgeKey},
21    graph::{Graph, GraphError},
22    ComponentId, ComponentOutputId,
23};
24use crate::accounting::{ComponentRegistry, MemoryBounds, MemoryLimiter, UsageExpr};
25use crate::{
26    components::{
27        decoders::DecoderBuilder, destinations::DestinationBuilder, encoders::EncoderBuilder,
28        forwarders::ForwarderBuilder, relays::RelayBuilder, sources::SourceBuilder, transforms::TransformBuilder,
29        BuildContext, ComponentContext, ComponentType,
30    },
31    data_model::event::Event,
32    health::HealthRegistry,
33    runtime::{
34        halt::HaltWatch,
35        state::{DataspaceRegistry, ResourceRegistry},
36        InitializationError, ShutdownStrategy, Supervisable, SupervisorFuture, UnadoptedScope,
37    },
38    support::SubsystemIdentifier,
39    topology::{ids::AsComponentIds, topology_identifier, EventsBuffer, DEFAULT_EVENTS_BUFFER_CAPACITY},
40};
41
42const DEFAULT_SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(30);
43
44/// A topology blueprint error.
45#[derive(Debug, Snafu)]
46#[snafu(context(suffix(false)))]
47pub enum BlueprintError {
48    /// Adding a component/connection lead to an invalid graph.
49    #[snafu(display("Failed to build/validate topology graph: {}", source))]
50    InvalidGraph {
51        /// The underlying graph error.
52        source: GraphError,
53    },
54
55    /// Failed to build a component.
56    #[snafu(display("Failed to build component '{}': {}", id, source))]
57    FailedToBuildComponent {
58        /// Component ID for the component that failed to build.
59        id: ComponentId,
60
61        /// The underlying component build error.
62        source: GenericError,
63    },
64}
65
66/// A topology blueprint represents a directed graph of components.
67///
68/// A blueprint is assembled by adding components and connecting them together, and then run by adding it to a
69/// [`Supervisor`][crate::runtime::Supervisor]: `TopologyBlueprint` implements [`Supervisable`], so there is no
70/// standalone spawn/run method. A blueprint can only be initialized (and thus run) once.
71pub struct TopologyBlueprint {
72    name: String,
73    build_state: Mutex<Option<TopologyBuildState>>,
74    health_registry: Option<HealthRegistry>,
75    memory_limiter: Option<MemoryLimiter>,
76    resource_registry: Option<ResourceRegistry>,
77}
78
79/// The consumable build state of a [`TopologyBlueprint`].
80///
81/// This is taken out of the blueprint when it's first initialized, at which point the topology is built and spawned.
82struct TopologyBuildState {
83    topology_id: SubsystemIdentifier,
84    graph: Graph,
85    sources: HashMap<ComponentId, Box<dyn SourceBuilder + Send>>,
86    relays: HashMap<ComponentId, Box<dyn RelayBuilder + Send>>,
87    decoders: HashMap<ComponentId, Box<dyn DecoderBuilder + Send>>,
88    transforms: HashMap<ComponentId, Box<dyn TransformBuilder + Send>>,
89    destinations: HashMap<ComponentId, Box<dyn DestinationBuilder + Send>>,
90    encoders: HashMap<ComponentId, Box<dyn EncoderBuilder + Send>>,
91    forwarders: HashMap<ComponentId, Box<dyn ForwarderBuilder + Send>>,
92    component_registry: ComponentRegistry,
93    interconnect_capacity: NonZeroUsize,
94    shutdown_timeout: Duration,
95    worker_pool_config: WorkerPoolConfiguration,
96    environment_ready: Option<Pin<Box<dyn Future<Output = ()> + Send>>>,
97    ready_signal: Option<oneshot::Sender<()>>,
98    /// Components that lost an inbound connection because its condition was always false.
99    folded_targets: HashSet<ComponentId>,
100    /// Components that will be pruned when the topology is built, and whose memory bounds are cleared.
101    prunable_components: HashMap<ComponentId, ComponentType>,
102    /// Connections whose condition is resolved at runtime.
103    edge_conditions: EdgeConditions,
104}
105
106impl TopologyBlueprint {
107    /// Creates an empty `TopologyBlueprint` with the given name.
108    pub fn new(name: &str, component_registry: &ComponentRegistry) -> Self {
109        let topology_id = topology_identifier(name);
110        let component_registry = component_registry.clone();
111
112        let build_state = TopologyBuildState {
113            topology_id,
114            graph: Graph::default(),
115            sources: HashMap::new(),
116            relays: HashMap::new(),
117            decoders: HashMap::new(),
118            transforms: HashMap::new(),
119            destinations: HashMap::new(),
120            encoders: HashMap::new(),
121            forwarders: HashMap::new(),
122            component_registry,
123            interconnect_capacity: super::DEFAULT_INTERCONNECT_CAPACITY,
124            shutdown_timeout: DEFAULT_SHUTDOWN_TIMEOUT,
125            worker_pool_config: WorkerPoolConfiguration::Dedicated,
126            environment_ready: None,
127            ready_signal: None,
128            folded_targets: HashSet::new(),
129            prunable_components: HashMap::new(),
130            edge_conditions: EdgeConditions::default(),
131        };
132
133        Self {
134            name: name.to_string(),
135            build_state: Mutex::new(Some(build_state)),
136            health_registry: None,
137            memory_limiter: None,
138            resource_registry: None,
139        }
140    }
141
142    /// Gets a mutable reference to the build state.
143    ///
144    /// # Panics
145    ///
146    /// Panics if the blueprint has already been initialized (its build state having been consumed).
147    fn state_mut(&mut self) -> &mut TopologyBuildState {
148        self.build_state
149            .get_mut()
150            .expect("topology blueprint mutex poisoned")
151            .as_mut()
152            .expect("topology blueprint already initialized")
153    }
154
155    /// Sets the capacity of interconnects in the topology.
156    ///
157    /// Interconnects are used to connect components to one another. Once their capacity is reached, no more items can be sent
158    /// through until in-flight items are processed. This will apply backpressure to the upstream components. Raising or lowering
159    /// the capacity allows trading off throughput at the expense of memory usage.
160    ///
161    /// Defaults to 128.
162    pub fn with_interconnect_capacity(&mut self, capacity: NonZeroUsize) -> &mut Self {
163        self.state_mut().set_interconnect_capacity(capacity);
164        self
165    }
166
167    /// Sets how long the topology waits for components to stop during graceful shutdown.
168    ///
169    /// Defaults to 30 seconds.
170    pub fn with_shutdown_timeout(&mut self, timeout: Duration) -> &mut Self {
171        self.state_mut().shutdown_timeout = timeout;
172        self
173    }
174
175    /// Sets the health registry used when the topology is spawned.
176    ///
177    /// This must be set before the blueprint is added to a supervisor; initialization fails otherwise.
178    pub fn with_health_registry(&mut self, health_registry: HealthRegistry) -> &mut Self {
179        self.health_registry = Some(health_registry);
180        self
181    }
182
183    /// Sets the memory limiter used when the topology is spawned.
184    ///
185    /// This must be set before the blueprint is added to a supervisor; initialization fails otherwise.
186    pub fn with_memory_limiter(&mut self, memory_limiter: MemoryLimiter) -> &mut Self {
187        self.memory_limiter = Some(memory_limiter);
188        self
189    }
190
191    /// Sets the resource registry used when the topology is built and spawned.
192    ///
193    /// Components acquire scarce resources, such as bound network sockets, from this registry rather than creating
194    /// them directly, so that the registry outlives them and can hand the same resource back when a component is
195    /// rebuilt.
196    ///
197    /// This must be set before the blueprint is added to a supervisor; initialization fails otherwise.
198    pub fn with_resource_registry(&mut self, resource_registry: ResourceRegistry) -> &mut Self {
199        self.resource_registry = Some(resource_registry);
200        self
201    }
202
203    /// Sets a readiness signal that must resolve before the topology starts its components.
204    ///
205    /// When set, the topology is still built up front during initialization, but its components are not spawned until
206    /// the given future resolves (or the topology is asked to shut down first). This is used to defer the topology from
207    /// processing data until its dependencies -- such as the environment provider's metadata collectors -- are ready.
208    pub fn with_environment_readiness<F>(&mut self, ready: F) -> &mut Self
209    where
210        F: Future<Output = ()> + Send + 'static,
211    {
212        self.state_mut().environment_ready = Some(Box::pin(ready));
213        self
214    }
215
216    /// Returns a handle for awaiting the readiness of the topology once it's running.
217    ///
218    /// This handle depends on observing the readiness of the individual topology components, and so must be called after
219    /// [`with_health_registry`][Self::with_health_registry].
220    ///
221    /// # Panics
222    ///
223    /// Panics if the health registry has not been set, or if the blueprint has already been initialized.
224    pub fn topology_ready(&mut self) -> TopologyReady {
225        let health_registry = self
226            .health_registry
227            .clone()
228            .expect("health registry must be set before acquiring a topology readiness handle");
229        let component_root = super::topology_identifier(&self.name);
230
231        let (registered_tx, registered_rx) = oneshot::channel();
232        self.state_mut().ready_signal = Some(registered_tx);
233
234        TopologyReady {
235            registered_rx,
236            health_registry,
237            component_root,
238        }
239    }
240
241    /// Configures the topology to use the ambient Tokio runtime for component subtasks.
242    ///
243    /// Component subtasks will be spawned on whatever runtime is currently active when the topology is initialized.
244    /// This avoids creating a dedicated thread pool, which is useful for resource-constrained environments.
245    pub fn with_ambient_worker_pool(&mut self) -> &mut Self {
246        self.state_mut().worker_pool_config = WorkerPoolConfiguration::Ambient;
247        self
248    }
249
250    /// Configures the topology to use an externally provided Tokio runtime for component subtasks.
251    ///
252    /// Component subtasks will be spawned on the runtime associated with the given handle.
253    pub fn with_explicit_worker_pool(&mut self, handle: Handle) -> &mut Self {
254        self.state_mut().worker_pool_config = WorkerPoolConfiguration::Explicit(handle);
255        self
256    }
257
258    /// Adds a source component to the blueprint.
259    ///
260    /// # Errors
261    ///
262    /// If the component ID is invalid or the component can't be added to the graph, an error is returned.
263    pub fn add_source<I, B>(&mut self, component_id: I, builder: B) -> Result<&mut Self, GenericError>
264    where
265        I: AsRef<str>,
266        B: SourceBuilder + Send + 'static,
267    {
268        self.state_mut().add_source(component_id, builder)?;
269        Ok(self)
270    }
271
272    /// Adds a relay component to the blueprint.
273    ///
274    /// # Errors
275    ///
276    /// If the component ID is invalid or the component can't be added to the graph, an error is returned.
277    pub fn add_relay<I, B>(&mut self, component_id: I, builder: B) -> Result<&mut Self, GenericError>
278    where
279        I: AsRef<str>,
280        B: RelayBuilder + Send + 'static,
281    {
282        self.state_mut().add_relay(component_id, builder)?;
283        Ok(self)
284    }
285
286    /// Adds a decoder component to the blueprint.
287    ///
288    /// # Errors
289    ///
290    /// If the component ID is invalid or the component can't be added to the graph, an error is returned.
291    pub fn add_decoder<I, B>(&mut self, component_id: I, builder: B) -> Result<&mut Self, GenericError>
292    where
293        I: AsRef<str>,
294        B: DecoderBuilder + Send + 'static,
295    {
296        self.state_mut().add_decoder(component_id, builder)?;
297        Ok(self)
298    }
299
300    /// Adds a transform component to the blueprint.
301    ///
302    /// # Errors
303    ///
304    /// If the component ID is invalid or the component can't be added to the graph, an error is returned.
305    pub fn add_transform<I, B>(&mut self, component_id: I, builder: B) -> Result<&mut Self, GenericError>
306    where
307        I: AsRef<str>,
308        B: TransformBuilder + Send + 'static,
309    {
310        self.state_mut().add_transform(component_id, builder)?;
311        Ok(self)
312    }
313
314    /// Adds a destination component to the blueprint.
315    ///
316    /// # Errors
317    ///
318    /// If the component ID is invalid or the component can't be added to the graph, an error is returned.
319    pub fn add_destination<I, B>(&mut self, component_id: I, builder: B) -> Result<&mut Self, GenericError>
320    where
321        I: AsRef<str>,
322        B: DestinationBuilder + Send + 'static,
323    {
324        self.state_mut().add_destination(component_id, builder)?;
325        Ok(self)
326    }
327
328    /// Adds an encoder component to the blueprint.
329    ///
330    /// # Errors
331    ///
332    /// If the component ID is invalid or the component can't be added to the graph, an error is returned.
333    pub fn add_encoder<I, B>(&mut self, component_id: I, builder: B) -> Result<&mut Self, GenericError>
334    where
335        I: AsRef<str>,
336        B: EncoderBuilder + Send + 'static,
337    {
338        self.state_mut().add_encoder(component_id, builder)?;
339        Ok(self)
340    }
341
342    /// Adds a forwarder component to the blueprint.
343    ///
344    /// # Errors
345    ///
346    /// If the component ID is invalid or the component can't be added to the graph, an error is returned.
347    pub fn add_forwarder<I, B>(&mut self, component_id: I, builder: B) -> Result<&mut Self, GenericError>
348    where
349        I: AsRef<str>,
350        B: ForwarderBuilder + Send + 'static,
351    {
352        self.state_mut().add_forwarder(component_id, builder)?;
353        Ok(self)
354    }
355
356    /// Connects one or more upstream component outputs to one or more downstream components.
357    ///
358    /// This method allows for ergonomically defining many-to-one, one-to-many, and many-to-many connections to
359    /// facilitate common patterns like fanning in many upstream components to a single downstream component, or fanning
360    /// out a single upstream component to many downstream components.
361    ///
362    /// When both there are both multiple upstream _and_ downstream component IDs, connections resemble a mesh: every
363    /// upstream component will be connected to every downstream component. This should be rare, but is technically
364    /// supported.
365    ///
366    /// # Errors
367    ///
368    /// If any of the upstream or downstream component IDs are invalid or don't exist, or if the data types between one
369    /// of the upstream/downstream component pairs is incompatible, an error is returned.
370    pub fn connect_components<MS, SI, MD, DI>(
371        &mut self, upstream_output_component_ids: SI, downstream_component_ids: DI,
372    ) -> Result<&mut Self, GenericError>
373    where
374        SI: AsComponentIds<MS>,
375        DI: AsComponentIds<MD>,
376    {
377        self.state_mut()
378            .connect_components(upstream_output_component_ids, downstream_component_ids)?;
379        Ok(self)
380    }
381
382    /// Connects a set of component IDs to one another in a pairwise fashion.
383    ///
384    /// This can be used to connect multiple components -- each sharing only a single edge between one another -- in a
385    /// single call instead of multiple calls.
386    ///
387    /// For example, passing `["first", "second", "third"]` would connect `first`'s output to `second`'s input, and
388    /// `second`'s output to `third`'s input.
389    ///
390    /// One caveat is that only the default output of a component can be used for connections past the first pair, as
391    /// the identifier given must be able to describe both the component ID to _send_ to as well as the component output
392    /// ID to connect to the subsequent component. This limitation does not exist on the first component ID, since it is
393    /// only used in the context of being a component output ID.
394    ///
395    /// # Errors
396    ///
397    /// If any of the component IDs are invalid or don't exist, or if the data types between one of the
398    /// upstream/downstream component pairs is incompatible, or if less than two component IDs are provided, an error is
399    /// returned.
400    ///
401    /// Care should be taken on failure as this method will not rollback any previously successful connections, which
402    /// could leave the blueprint in an indeterminate state if some connections are made prior to hitting an error.
403    pub fn connect_components_in_order<IT, I>(&mut self, ordered_component_ids: IT) -> Result<&mut Self, GenericError>
404    where
405        IT: IntoIterator<Item = I>,
406        I: AsRef<str>,
407    {
408        self.state_mut().connect_components_in_order(ordered_component_ids)?;
409        Ok(self)
410    }
411
412    /// Connects a component output to a downstream component, sending events over the connection only while
413    /// `condition` is true.
414    ///
415    /// A condition that's always false removes the connection when the topology is built. If the downstream component
416    /// is left without any inbound connections as a result, it's removed as well, along with any components that are
417    /// only reachable through it: they're never built or spawned.
418    ///
419    /// A condition that changes at runtime keeps the connection, but events are only sent to the downstream component
420    /// while the condition is true. Events dispatched while the condition is false are dropped for this connection
421    /// only, and aren't replayed when the condition becomes true.
422    ///
423    /// # Errors
424    ///
425    /// If either component ID is invalid or doesn't exist, or if the data types of the two components are incompatible,
426    /// an error is returned.
427    pub fn connect_components_when<F, T>(
428        &mut self, upstream_output_component_id: F, downstream_component_id: T, condition: EdgeCondition,
429    ) -> Result<&mut Self, GenericError>
430    where
431        F: AsRef<str>,
432        T: AsRef<str>,
433    {
434        self.state_mut().connect_components_when(
435            upstream_output_component_id.as_ref(),
436            downstream_component_id.as_ref(),
437            condition,
438        )?;
439        Ok(self)
440    }
441}
442
443/// A handle for awaiting the readiness of a running topology.
444pub struct TopologyReady {
445    registered_rx: oneshot::Receiver<()>,
446    health_registry: HealthRegistry,
447    component_root: SubsystemIdentifier,
448}
449
450impl TopologyReady {
451    /// Waits until the topology has registered its components and all of them have reported ready.
452    ///
453    /// Returns `true` once the topology is fully ready, or `false` if the topology was torn down before it finished
454    /// registering its components. The topology might be torn down before readiness is achieved if shutdown is
455    /// requested while still waiting on an upstream dependency such as the environment provider.
456    pub async fn wait(self) -> bool {
457        // First, wait for the topology to actually register its components in the health registry.
458        //
459        // If we didn't do this, we could observe `all_ready_matching` return immediately (due to no matching components)
460        // which would not correctly represent the topology being ready.
461        if self.registered_rx.await.is_err() {
462            return false;
463        }
464
465        // Now wait for all registered topology components to actually become ready.
466        self.health_registry.all_ready_under(self.component_root).await;
467
468        true
469    }
470}
471
472impl TopologyBuildState {
473    fn set_interconnect_capacity(&mut self, capacity: NonZeroUsize) {
474        self.interconnect_capacity = capacity;
475        self.recalculate_bounds();
476    }
477
478    /// Clears the memory bounds of components that will be pruned when the topology is built.
479    ///
480    /// Memory bounds are verified before the topology is built, so pruning is simulated here, on a copy of the graph,
481    /// whenever the bounds are recalculated. A component whose bounds were cleared has them specified again if a later
482    /// connection means it will no longer be pruned.
483    fn sync_prunable_component_bounds(&mut self) {
484        let prunable: HashMap<_, _> = self
485            .graph
486            .clone()
487            .prune_components_without_inputs(self.folded_targets.iter().cloned())
488            .into_iter()
489            .collect();
490
491        for (id, component_type) in &prunable {
492            if !self.prunable_components.contains_key(id) {
493                let identity = self.component_identity(*component_type, id);
494                self.component_registry.bounds_builder(&identity).reset();
495            }
496        }
497        for (id, component_type) in &self.prunable_components {
498            if !prunable.contains_key(id) {
499                if let Some(bounds) = self.component_bounds(id, *component_type) {
500                    let identity = self.component_identity(*component_type, id);
501                    bounds.specify_bounds(&mut self.component_registry.bounds_builder(&identity));
502                }
503            }
504        }
505
506        self.prunable_components = prunable;
507    }
508
509    fn component_bounds(&self, id: &ComponentId, component_type: ComponentType) -> Option<&dyn MemoryBounds> {
510        match component_type {
511            ComponentType::Source => self.sources.get(id).map(|b| b.as_ref() as &dyn MemoryBounds),
512            ComponentType::Relay => self.relays.get(id).map(|b| b.as_ref() as &dyn MemoryBounds),
513            ComponentType::Decoder => self.decoders.get(id).map(|b| b.as_ref() as &dyn MemoryBounds),
514            ComponentType::Transform => self.transforms.get(id).map(|b| b.as_ref() as &dyn MemoryBounds),
515            ComponentType::Destination => self.destinations.get(id).map(|b| b.as_ref() as &dyn MemoryBounds),
516            ComponentType::Encoder => self.encoders.get(id).map(|b| b.as_ref() as &dyn MemoryBounds),
517            ComponentType::Forwarder => self.forwarders.get(id).map(|b| b.as_ref() as &dyn MemoryBounds),
518        }
519    }
520
521    fn recalculate_bounds(&mut self) {
522        self.sync_prunable_component_bounds();
523        let live_transforms = self
524            .transforms
525            .keys()
526            .filter(|id| !self.prunable_components.contains_key(*id))
527            .count();
528        let live_destinations = self
529            .destinations
530            .keys()
531            .filter(|id| !self.prunable_components.contains_key(*id))
532            .count();
533        let live_decoders = self
534            .decoders
535            .keys()
536            .filter(|id| !self.prunable_components.contains_key(*id))
537            .count();
538
539        let interconnect_capacity = self.interconnect_capacity.get();
540
541        let mut bounds_builder = self.component_registry.bounds_builder(&self.topology_id);
542        let mut bounds_builder = bounds_builder.subcomponent("interconnects");
543        bounds_builder.reset();
544
545        // Adjust the bounds related to interconnects.
546        //
547        // This deals with the minimum size of the interconnects themselves, since they're bounded and thus allocated
548        // up-front. Every non-source component has an interconnect.
549        let total_interconnect_capacity = interconnect_capacity * (live_transforms + live_destinations);
550        bounds_builder
551            .minimum()
552            .with_array::<EventsBuffer>("events", total_interconnect_capacity);
553
554        // TODO: Add a minimum subitem for payloads when we have payload interconnects.
555
556        // Adjust the bounds related to event buffers themselves.
557        //
558        // We calculate the maximum number of event buffers by adding up the total capacity of all non-source components, plus the count
559        // of non-destination components. This is the effective upper bound because once all component channels are full, sending
560        // components can only allocate one more event buffer before being blocked on sending, which is then the effective upper bound.
561        //
562        // TODO: Somewhat fragile. Need to revisit this.
563        // TODO: Add a firm subitem for payloads when we have payload interconnects.
564        let max_in_flight_event_buffers = ((live_transforms + live_destinations) * interconnect_capacity)
565            + self.sources.len()
566            + live_decoders
567            + live_transforms;
568
569        bounds_builder
570            .firm()
571            // max_in_flight_event_buffers * (size_of<EventsContainer> + (size_of<Event> * default_event_buffer_capacity))
572            .with_expr(UsageExpr::product(
573                "events",
574                UsageExpr::constant("max in-flight event buffers", max_in_flight_event_buffers),
575                UsageExpr::sum(
576                    "",
577                    UsageExpr::struct_size::<EventsBuffer>("events buffer"),
578                    UsageExpr::product(
579                        "",
580                        UsageExpr::struct_size::<Event>("event"),
581                        UsageExpr::constant("default event buffer capacity", DEFAULT_EVENTS_BUFFER_CAPACITY),
582                    ),
583                ),
584            ));
585    }
586
587    fn component_identity(&self, component_type: ComponentType, component_id: &ComponentId) -> SubsystemIdentifier {
588        ComponentContext::new(&self.topology_id, component_id.clone(), component_type).identity()
589    }
590
591    fn add_source<I, B>(&mut self, component_id: I, builder: B) -> Result<(), GenericError>
592    where
593        I: AsRef<str>,
594        B: SourceBuilder + Send + 'static,
595    {
596        let component_id = self
597            .graph
598            .add_source(component_id, &builder)
599            .error_context("Failed to add source to topology graph.")?;
600
601        let identity = self.component_identity(ComponentType::Source, &component_id);
602        builder.specify_bounds(&mut self.component_registry.bounds_builder(&identity));
603
604        self.recalculate_bounds();
605
606        let _ = self.sources.insert(component_id, Box::new(builder));
607
608        Ok(())
609    }
610
611    fn add_relay<I, B>(&mut self, component_id: I, builder: B) -> Result<(), GenericError>
612    where
613        I: AsRef<str>,
614        B: RelayBuilder + Send + 'static,
615    {
616        let component_id = self
617            .graph
618            .add_relay(component_id, &builder)
619            .error_context("Failed to add relay to topology graph.")?;
620
621        let identity = self.component_identity(ComponentType::Relay, &component_id);
622        builder.specify_bounds(&mut self.component_registry.bounds_builder(&identity));
623
624        self.recalculate_bounds();
625
626        let _ = self.relays.insert(component_id, Box::new(builder));
627
628        Ok(())
629    }
630
631    fn add_decoder<I, B>(&mut self, component_id: I, builder: B) -> Result<(), GenericError>
632    where
633        I: AsRef<str>,
634        B: DecoderBuilder + Send + 'static,
635    {
636        let component_id = self
637            .graph
638            .add_decoder(component_id, &builder)
639            .error_context("Failed to add decoder to topology graph.")?;
640
641        let identity = self.component_identity(ComponentType::Decoder, &component_id);
642        builder.specify_bounds(&mut self.component_registry.bounds_builder(&identity));
643
644        self.recalculate_bounds();
645
646        let _ = self.decoders.insert(component_id, Box::new(builder));
647
648        Ok(())
649    }
650
651    fn add_transform<I, B>(&mut self, component_id: I, builder: B) -> Result<(), GenericError>
652    where
653        I: AsRef<str>,
654        B: TransformBuilder + Send + 'static,
655    {
656        let component_id = self
657            .graph
658            .add_transform(component_id, &builder)
659            .error_context("Failed to add transform to topology graph.")?;
660
661        let identity = self.component_identity(ComponentType::Transform, &component_id);
662        builder.specify_bounds(&mut self.component_registry.bounds_builder(&identity));
663
664        self.recalculate_bounds();
665
666        let _ = self.transforms.insert(component_id, Box::new(builder));
667
668        Ok(())
669    }
670
671    fn add_destination<I, B>(&mut self, component_id: I, builder: B) -> Result<(), GenericError>
672    where
673        I: AsRef<str>,
674        B: DestinationBuilder + Send + 'static,
675    {
676        let component_id = self
677            .graph
678            .add_destination(component_id, &builder)
679            .error_context("Failed to add destination to topology graph.")?;
680
681        let identity = self.component_identity(ComponentType::Destination, &component_id);
682        builder.specify_bounds(&mut self.component_registry.bounds_builder(&identity));
683
684        self.recalculate_bounds();
685
686        let _ = self.destinations.insert(component_id, Box::new(builder));
687
688        Ok(())
689    }
690
691    fn add_encoder<I, B>(&mut self, component_id: I, builder: B) -> Result<(), GenericError>
692    where
693        I: AsRef<str>,
694        B: EncoderBuilder + Send + 'static,
695    {
696        let component_id = self
697            .graph
698            .add_encoder(component_id, &builder)
699            .error_context("Failed to add encoder to topology graph.")?;
700
701        let identity = self.component_identity(ComponentType::Encoder, &component_id);
702        builder.specify_bounds(&mut self.component_registry.bounds_builder(&identity));
703
704        self.recalculate_bounds();
705
706        let _ = self.encoders.insert(component_id, Box::new(builder));
707
708        Ok(())
709    }
710
711    fn add_forwarder<I, B>(&mut self, component_id: I, builder: B) -> Result<(), GenericError>
712    where
713        I: AsRef<str>,
714        B: ForwarderBuilder + Send + 'static,
715    {
716        let component_id = self
717            .graph
718            .add_forwarder(component_id, &builder)
719            .error_context("Failed to add forwarder to topology graph.")?;
720
721        let identity = self.component_identity(ComponentType::Forwarder, &component_id);
722        builder.specify_bounds(&mut self.component_registry.bounds_builder(&identity));
723
724        self.recalculate_bounds();
725
726        let _ = self.forwarders.insert(component_id, Box::new(builder));
727
728        Ok(())
729    }
730
731    fn connect_components<MS, SI, MD, DI>(
732        &mut self, upstream_output_component_ids: SI, downstream_component_ids: DI,
733    ) -> Result<(), GenericError>
734    where
735        SI: AsComponentIds<MS>,
736        DI: AsComponentIds<MD>,
737    {
738        for upstream_output_component_id in upstream_output_component_ids.as_component_ids() {
739            for downstream_component_id in downstream_component_ids.as_component_ids() {
740                self.graph
741                    .add_edge(upstream_output_component_id.as_ref(), downstream_component_id.as_ref())
742                    .error_context("Failed to add component connection to topology graph.")?;
743            }
744        }
745
746        // A new connection can give an input to a component that would otherwise have been pruned.
747        self.recalculate_bounds();
748
749        Ok(())
750    }
751
752    fn connect_components_in_order<IT, I>(&mut self, ordered_component_ids: IT) -> Result<(), GenericError>
753    where
754        IT: IntoIterator<Item = I>,
755        I: AsRef<str>,
756    {
757        let mut pending_output_component_id: Option<I> = None;
758        let mut connected_any = false;
759
760        for component_id in ordered_component_ids.into_iter() {
761            if let Some(output_component_id) = pending_output_component_id.take() {
762                self.graph
763                    .add_edge(output_component_id.as_ref(), component_id.as_ref())
764                    .error_context("Failed to add component connection to topology graph.")?;
765
766                connected_any = true;
767            }
768
769            // Store the _current_ component ID so we can chain its connection to the next component, and so on.
770            pending_output_component_id = Some(component_id);
771        }
772
773        // Make sure we connected at least one pair of components together, otherwise this is an invalid connection attempt.
774        if !connected_any {
775            return Err(generic_error!(
776                "Two or more components must be provided for connection."
777            ));
778        }
779
780        // A new connection can give an input to a component that would otherwise have been pruned.
781        self.recalculate_bounds();
782
783        Ok(())
784    }
785
786    fn connect_components_when(
787        &mut self, upstream_output_component_id: &str, downstream_component_id: &str, condition: EdgeCondition,
788    ) -> Result<(), GenericError> {
789        self.graph
790            .add_edge(upstream_output_component_id, downstream_component_id)
791            .error_context("Failed to add component connection to topology graph.")?;
792
793        // Adding the edge validated both identifiers.
794        let upstream_output = ComponentOutputId::try_from(upstream_output_component_id)
795            .map_err(|e| generic_error!("Invalid component output ID '{}': {}", upstream_output_component_id, e))?;
796        let downstream = ComponentId::try_from(downstream_component_id)
797            .map_err(|e| generic_error!("Invalid component ID '{}': {}", downstream_component_id, e))?;
798
799        match condition.0 {
800            ConditionKind::Fixed(true) => {}
801            ConditionKind::Fixed(false) => {
802                // The connection can never be active, so remove it now. The downstream component is pruned when the
803                // topology is built if this leaves it without inputs.
804                self.graph.remove_edge(&upstream_output, &downstream);
805                self.folded_targets.insert(downstream);
806            }
807            ConditionKind::Dynamic { initial, updates } => {
808                let key = EdgeKey {
809                    upstream: upstream_output.component_id(),
810                    output: upstream_output.output(),
811                    downstream,
812                };
813                self.edge_conditions.insert(key, initial, updates);
814            }
815        }
816
817        self.recalculate_bounds();
818
819        Ok(())
820    }
821
822    /// Removes components left without inputs because their inbound connections had conditions that were always false.
823    ///
824    /// Removed components are never built or spawned. Their memory bounds were already cleared when the connections
825    /// were made.
826    fn prune_folded_components(&mut self) {
827        let folded_targets = std::mem::take(&mut self.folded_targets);
828        for (id, component_type) in self.graph.prune_components_without_inputs(folded_targets) {
829            match component_type {
830                ComponentType::Source => drop(self.sources.remove(&id)),
831                ComponentType::Relay => drop(self.relays.remove(&id)),
832                ComponentType::Decoder => drop(self.decoders.remove(&id)),
833                ComponentType::Transform => drop(self.transforms.remove(&id)),
834                ComponentType::Destination => drop(self.destinations.remove(&id)),
835                ComponentType::Encoder => drop(self.encoders.remove(&id)),
836                ComponentType::Forwarder => drop(self.forwarders.remove(&id)),
837            }
838            self.edge_conditions.remove_component(&id);
839
840            info!(component_id = %id, component_type = component_type.as_str(), "Removed component with no active inputs.");
841        }
842    }
843
844    /// Builds the topology.
845    ///
846    /// # Errors
847    ///
848    /// If any of the components couldn't be built, an error is returned.
849    async fn build(
850        mut self, name: String, resource_registry: &ResourceRegistry,
851    ) -> Result<BuiltTopology, GenericError> {
852        self.prune_folded_components();
853        self.graph.validate().error_context("Failed to build topology graph.")?;
854
855        let mut component_scopes = HashMap::new();
856
857        let mut sources = HashMap::new();
858        for (id, builder) in self.sources {
859            let component_context = ComponentContext::source(&self.topology_id, id.clone());
860            let allocation_token = self
861                .component_registry
862                .get_resource_group_token(&component_context.identity());
863            // While the component is built, it can spawn tasks into the current scope, for example the background tasks
864            // of a cache. This scope holds these tasks until the component runs. Then the tasks belong to the
865            // component.
866            let scope = UnadoptedScope::new(component_context.identity().to_string());
867            let source = scope
868                .scope()
869                .enter(builder.build(BuildContext::new(component_context.clone(), resource_registry.clone())))
870                .track_resources(allocation_token)
871                .await
872                .with_error_context(|| format!("Failed to build source '{}'.", id))?;
873
874            component_scopes.insert(component_context.clone(), scope);
875            sources.insert(component_context, (source, self.component_registry.clone()));
876        }
877
878        let mut relays = HashMap::new();
879        for (id, builder) in self.relays {
880            let component_context = ComponentContext::relay(&self.topology_id, id.clone());
881            let allocation_token = self
882                .component_registry
883                .get_resource_group_token(&component_context.identity());
884            // While the component is built, it can spawn tasks into the current scope, for example the background tasks
885            // of a cache. This scope holds these tasks until the component runs. Then the tasks belong to the
886            // component.
887            let scope = UnadoptedScope::new(component_context.identity().to_string());
888            let relay = scope
889                .scope()
890                .enter(builder.build(BuildContext::new(component_context.clone(), resource_registry.clone())))
891                .track_resources(allocation_token)
892                .await
893                .with_error_context(|| format!("Failed to build relay '{}'.", id))?;
894
895            component_scopes.insert(component_context.clone(), scope);
896            relays.insert(component_context, (relay, self.component_registry.clone()));
897        }
898
899        let mut decoders = HashMap::new();
900        for (id, builder) in self.decoders {
901            let component_context = ComponentContext::decoder(&self.topology_id, id.clone());
902            let allocation_token = self
903                .component_registry
904                .get_resource_group_token(&component_context.identity());
905            // While the component is built, it can spawn tasks into the current scope, for example the background tasks
906            // of a cache. This scope holds these tasks until the component runs. Then the tasks belong to the
907            // component.
908            let scope = UnadoptedScope::new(component_context.identity().to_string());
909            let decoder = scope
910                .scope()
911                .enter(builder.build(BuildContext::new(component_context.clone(), resource_registry.clone())))
912                .track_resources(allocation_token)
913                .await
914                .with_error_context(|| format!("Failed to build decoder '{}'.", id))?;
915
916            component_scopes.insert(component_context.clone(), scope);
917            decoders.insert(component_context, (decoder, self.component_registry.clone()));
918        }
919
920        let mut transforms = HashMap::new();
921        for (id, builder) in self.transforms {
922            let component_context = ComponentContext::transform(&self.topology_id, id.clone());
923            let allocation_token = self
924                .component_registry
925                .get_resource_group_token(&component_context.identity());
926            // While the component is built, it can spawn tasks into the current scope, for example the background tasks
927            // of a cache. This scope holds these tasks until the component runs. Then the tasks belong to the
928            // component.
929            let scope = UnadoptedScope::new(component_context.identity().to_string());
930            let transform = scope
931                .scope()
932                .enter(builder.build(BuildContext::new(component_context.clone(), resource_registry.clone())))
933                .track_resources(allocation_token)
934                .await
935                .with_error_context(|| format!("Failed to build transform '{}'.", id))?;
936
937            component_scopes.insert(component_context.clone(), scope);
938            transforms.insert(component_context, (transform, self.component_registry.clone()));
939        }
940
941        let mut destinations = HashMap::new();
942        for (id, builder) in self.destinations {
943            let component_context = ComponentContext::destination(&self.topology_id, id.clone());
944            let allocation_token = self
945                .component_registry
946                .get_resource_group_token(&component_context.identity());
947            // While the component is built, it can spawn tasks into the current scope, for example the background tasks
948            // of a cache. This scope holds these tasks until the component runs. Then the tasks belong to the
949            // component.
950            let scope = UnadoptedScope::new(component_context.identity().to_string());
951            let destination = scope
952                .scope()
953                .enter(builder.build(BuildContext::new(component_context.clone(), resource_registry.clone())))
954                .track_resources(allocation_token)
955                .await
956                .with_error_context(|| format!("Failed to build destination '{}'.", id))?;
957
958            component_scopes.insert(component_context.clone(), scope);
959            destinations.insert(component_context, (destination, self.component_registry.clone()));
960        }
961
962        let mut encoders = HashMap::new();
963        for (id, builder) in self.encoders {
964            let component_context = ComponentContext::encoder(&self.topology_id, id.clone());
965            let allocation_token = self
966                .component_registry
967                .get_resource_group_token(&component_context.identity());
968            // While the component is built, it can spawn tasks into the current scope, for example the background tasks
969            // of a cache. This scope holds these tasks until the component runs. Then the tasks belong to the
970            // component.
971            let scope = UnadoptedScope::new(component_context.identity().to_string());
972            let encoder = scope
973                .scope()
974                .enter(builder.build(BuildContext::new(component_context.clone(), resource_registry.clone())))
975                .track_resources(allocation_token)
976                .await
977                .with_error_context(|| format!("Failed to build encoder '{}'.", id))?;
978
979            component_scopes.insert(component_context.clone(), scope);
980            encoders.insert(component_context, (encoder, self.component_registry.clone()));
981        }
982
983        let mut forwarders = HashMap::new();
984        for (id, builder) in self.forwarders {
985            let component_context = ComponentContext::forwarder(&self.topology_id, id.clone());
986            let allocation_token = self
987                .component_registry
988                .get_resource_group_token(&component_context.identity());
989            // While the component is built, it can spawn tasks into the current scope, for example the background tasks
990            // of a cache. This scope holds these tasks until the component runs. Then the tasks belong to the
991            // component.
992            let scope = UnadoptedScope::new(component_context.identity().to_string());
993            let forwarder = scope
994                .scope()
995                .enter(builder.build(BuildContext::new(component_context.clone(), resource_registry.clone())))
996                .track_resources(allocation_token)
997                .await
998                .with_error_context(|| format!("Failed to build forwarder '{}'.", id))?;
999
1000            component_scopes.insert(component_context.clone(), scope);
1001            forwarders.insert(component_context, (forwarder, self.component_registry.clone()));
1002        }
1003
1004        let topology_token = self.component_registry.get_resource_group_token(&self.topology_id);
1005
1006        Ok(BuiltTopology::from_parts(
1007            name,
1008            self.topology_id,
1009            self.graph,
1010            sources,
1011            relays,
1012            decoders,
1013            transforms,
1014            destinations,
1015            encoders,
1016            forwarders,
1017            component_scopes,
1018            topology_token,
1019            self.interconnect_capacity,
1020            self.worker_pool_config,
1021            self.edge_conditions,
1022        ))
1023    }
1024}
1025
1026#[async_trait]
1027impl Supervisable for TopologyBlueprint {
1028    fn name(&self) -> &str {
1029        &self.name
1030    }
1031
1032    fn shutdown_strategy(&self) -> ShutdownStrategy {
1033        // Each component's own shutdown timeout bounds the topology, so we don't need one.
1034        ShutdownStrategy::Graceful(Duration::MAX)
1035    }
1036
1037    fn can_restart(&self) -> bool {
1038        // The first start consumes the build state, so a topology can only be run once.
1039        false
1040    }
1041
1042    async fn initialize(&self, shutdown: ShutdownHandle) -> Result<SupervisorFuture, InitializationError> {
1043        // Consume the build state.
1044        //
1045        // Topologies currently can't be initialized more than once.
1046        let mut build_state = self
1047            .build_state
1048            .lock()
1049            .expect("topology blueprint mutex poisoned")
1050            .take()
1051            .ok_or_else(|| generic_error!("Topology has already been initialized and cannot be run more than once."))?;
1052
1053        let health_registry = self
1054            .health_registry
1055            .clone()
1056            .ok_or_else(|| generic_error!("Topology blueprint is missing its health registry."))?;
1057        let memory_limiter = self
1058            .memory_limiter
1059            .clone()
1060            .ok_or_else(|| generic_error!("Topology blueprint is missing its memory limiter."))?;
1061
1062        let resource_registry = self
1063            .resource_registry
1064            .clone()
1065            .ok_or_else(|| generic_error!("Topology blueprint is missing its resource registry."))?;
1066
1067        let dataspace = DataspaceRegistry::try_current()
1068            .ok_or_else(|| generic_error!("Topology must be initialized within a supervised process context."))?;
1069
1070        // Build our topology components.
1071        //
1072        // This creates the topology components but does not actually spawn them or run them in any way.
1073        //
1074        // We do this outside of the supervisor future to ensure that we fail during initialization, which bubbles up as
1075        // a non-restartable error that ultimately leads to the process exiting. This is the desired behavior at present
1076        // time, but maybe change in the future.
1077        let environment_ready = build_state.environment_ready.take();
1078        let ready_signal = build_state.ready_signal.take();
1079        let shutdown_timeout = build_state.shutdown_timeout;
1080        let built = build_state.build(self.name.clone(), &resource_registry).await?;
1081
1082        Ok(Box::pin(async move {
1083            pin!(shutdown);
1084
1085            // If a readiness signal was provided, wait for it before building the components, but remain responsive to
1086            // shutdown so we exit promptly if asked to stop before we've started.
1087            if let Some(environment_ready) = environment_ready {
1088                select! {
1089                    _ = &mut shutdown => return Ok(()),
1090                    _ = environment_ready => {},
1091                }
1092            }
1093
1094            // Build the topology supervisor. It is a single supervisor that owns failure detection and graceful
1095            // shutdown, with one worker for each component. Each worker owns everything that it spawns.
1096            let mut topology_sup = built
1097                .spawn_inner(&health_registry, memory_limiter, dataspace.clone(), shutdown_timeout)
1098                .await?;
1099
1100            // Signal that the topology has registered all of its components in the health registry, so any readiness
1101            // handle can begin waiting on those components. `spawn_inner` registers every component before returning, so
1102            // readiness can't be observed before the topology's components exist.
1103            if let Some(ready_signal) = ready_signal {
1104                let _ = ready_signal.send(());
1105            }
1106
1107            // Run the topology supervisor, forwarding our own shutdown signal into it. We run it here, and not as our
1108            // own child, so that its process name stays rooted at the identifier of the topology. This makes the
1109            // process name of each component its canonical identity. We use the internal variant so we can pass down
1110            // the inherited dataspace (the public `run_with_shutdown` would create a fresh, empty one). The topology
1111            // supervisor returns `Ok(())` on an intentional shutdown that drained cleanly, and an error if any
1112            // component exits on its own (how a component failure fails the topology) or if a component had to be
1113            // forcefully aborted after ignoring graceful shutdown (`SupervisorError::ShutdownTimedOut`). That error is
1114            // preserved here as a `GenericError` so the root supervisor can still recover the aborted-worker count.
1115            //
1116            // Nothing halts the topology supervisor, since each component is bounded by its own timeout.
1117            let (topology_shutdown_trigger, topology_shutdown) = ShutdownHandle::paired();
1118            let run = topology_sup.run_with_shutdown_inner(topology_shutdown, HaltWatch::never(), Some(dataspace));
1119            pin!(run);
1120
1121            let mut topology_shutdown_trigger = Some(topology_shutdown_trigger);
1122            loop {
1123                select! {
1124                    result = &mut run => return result.map_err(Into::into),
1125                    _ = &mut shutdown, if topology_shutdown_trigger.is_some() => {
1126                        info!("Topology received shutdown signal. Shutting down...");
1127                        topology_shutdown_trigger.take().expect("present per select guard").shutdown();
1128                    }
1129                }
1130            }
1131        }))
1132    }
1133}
1134
1135#[cfg(test)]
1136mod tests {
1137    use std::num::NonZeroUsize;
1138    use std::sync::atomic::{AtomicUsize, Ordering};
1139    use std::sync::Arc;
1140    use std::time::Duration;
1141
1142    use async_trait::async_trait;
1143    use saluki_common::sync::shutdown::ShutdownHandle;
1144    use saluki_error::GenericError;
1145    use tokio::sync::oneshot;
1146
1147    use super::{TopologyBlueprint, TopologyReady, WorkerPoolConfiguration};
1148    use crate::accounting::{ComponentRegistry, MemoryBounds, MemoryBoundsBuilder, MemoryLimiter};
1149    use crate::components::BuildContext;
1150    use crate::data_model::event::Event;
1151    use crate::runtime::{self, state::ResourceRegistry, Name};
1152    use crate::test_support::wait_until;
1153    use crate::topology::{ids::get_component_relative_identifier, topology_identifier, ComponentId};
1154    use crate::topology::{EventsBuffer, DEFAULT_EVENTS_BUFFER_CAPACITY};
1155    use crate::{
1156        components::{
1157            destinations::{Destination, DestinationBuilder, DestinationContext},
1158            sources::{Source, SourceBuilder, SourceContext},
1159            ComponentContext,
1160        },
1161        data_model::{event::EventType, payload::PayloadType},
1162        health::HealthRegistry,
1163        runtime::{InitializationError, RestartStrategy, Supervisable, Supervisor, SupervisorError, SupervisorFuture},
1164        support::SubsystemIdentifier,
1165        topology::{
1166            test_util::{
1167                TestDecoderBuilder, TestDestinationBuilder, TestRelayBuilder, TestSourceBuilder, TestTransformBuilder,
1168            },
1169            EdgeCondition, OutputDefinition,
1170        },
1171    };
1172
1173    /// A dynamic child worker for exercising [`SourceContext::spawn_handle`].
1174    ///
1175    /// Records that it started, then runs until its supervisor shuts it down.
1176    struct CountingChild {
1177        started: Arc<AtomicUsize>,
1178    }
1179
1180    #[async_trait]
1181    impl Supervisable for CountingChild {
1182        fn name(&self) -> &str {
1183            "child"
1184        }
1185
1186        async fn initialize(&self, process_shutdown: ShutdownHandle) -> Result<SupervisorFuture, InitializationError> {
1187            let started = Arc::clone(&self.started);
1188            Ok(Box::pin(async move {
1189                started.fetch_add(1, Ordering::SeqCst);
1190                // Run until torn down, so the test can observe structured teardown of dynamic children.
1191                process_shutdown.await;
1192                Ok(())
1193            }))
1194        }
1195    }
1196
1197    /// A source that runs until shutdown, optionally spawning a dynamic child on its ambient supervisor first.
1198    ///
1199    /// Records that it started (so tests can wait for readiness rather than sleeping) before running.
1200    struct ControlSource {
1201        started: Arc<AtomicUsize>,
1202        spawned_child: Option<Arc<AtomicUsize>>,
1203    }
1204
1205    #[async_trait]
1206    impl Source for ControlSource {
1207        async fn run(self: Box<Self>, mut context: SourceContext) -> Result<(), GenericError> {
1208            self.started.fetch_add(1, Ordering::SeqCst);
1209            let shutdown = context.take_shutdown_handle();
1210            if let Some(started) = self.spawned_child {
1211                // Ambient spawning is how a component reaches its own supervisor: nothing is threaded to it, and the
1212                // child still has to land under this component rather than anywhere else.
1213                runtime::supervisable(CountingChild { started }).spawn();
1214            }
1215            shutdown.await;
1216            Ok(())
1217        }
1218    }
1219
1220    struct ControlSourceBuilder {
1221        outputs: Vec<OutputDefinition<EventType>>,
1222        started: Arc<AtomicUsize>,
1223        spawned_child: Option<Arc<AtomicUsize>>,
1224    }
1225
1226    impl ControlSourceBuilder {
1227        fn new(started: Arc<AtomicUsize>, spawned_child: Option<Arc<AtomicUsize>>) -> Self {
1228            Self {
1229                outputs: vec![OutputDefinition::default_output(EventType::EventD)],
1230                started,
1231                spawned_child,
1232            }
1233        }
1234    }
1235
1236    #[async_trait]
1237    impl SourceBuilder for ControlSourceBuilder {
1238        fn outputs(&self) -> &[OutputDefinition<EventType>] {
1239            &self.outputs
1240        }
1241
1242        async fn build(&self, _: BuildContext) -> Result<Box<dyn Source + Send>, GenericError> {
1243            Ok(Box::new(ControlSource {
1244                started: Arc::clone(&self.started),
1245                spawned_child: self.spawned_child.clone(),
1246            }))
1247        }
1248    }
1249
1250    impl MemoryBounds for ControlSourceBuilder {
1251        fn specify_bounds(&self, _builder: &mut MemoryBoundsBuilder) {}
1252    }
1253
1254    /// A source whose builder spawns a child into the current scope while it builds the source.
1255    ///
1256    /// The child records when it starts and when it stops. It runs until something tells it to stop.
1257    struct BuildSpawningSourceBuilder {
1258        outputs: Vec<OutputDefinition<EventType>>,
1259        source_started: Arc<AtomicUsize>,
1260        child_started: Arc<AtomicUsize>,
1261        child_stopped: Arc<AtomicUsize>,
1262    }
1263
1264    #[async_trait]
1265    impl SourceBuilder for BuildSpawningSourceBuilder {
1266        fn outputs(&self) -> &[OutputDefinition<EventType>] {
1267            &self.outputs
1268        }
1269
1270        async fn build(&self, _: BuildContext) -> Result<Box<dyn Source + Send>, GenericError> {
1271            let (started, stopped) = (Arc::clone(&self.child_started), Arc::clone(&self.child_stopped));
1272            runtime::worker_with_shutdown("built_child", move |shutdown| async move {
1273                started.fetch_add(1, Ordering::SeqCst);
1274                shutdown.await;
1275                stopped.fetch_add(1, Ordering::SeqCst);
1276            })
1277            .spawn_or_detached();
1278
1279            Ok(Box::new(ControlSource {
1280                started: Arc::clone(&self.source_started),
1281                spawned_child: None,
1282            }))
1283        }
1284    }
1285
1286    impl MemoryBounds for BuildSpawningSourceBuilder {
1287        fn specify_bounds(&self, _builder: &mut MemoryBoundsBuilder) {}
1288    }
1289
1290    /// A destination that drains its input until the upstream closes (which happens when the source stops).
1291    struct DrainingDestination;
1292
1293    #[async_trait]
1294    impl Destination for DrainingDestination {
1295        async fn run(self: Box<Self>, mut context: DestinationContext) -> Result<(), GenericError> {
1296            while context.events().next().await.is_some() {}
1297            Ok(())
1298        }
1299    }
1300
1301    struct DrainingDestinationBuilder {
1302        input_event_ty: EventType,
1303    }
1304
1305    #[async_trait]
1306    impl DestinationBuilder for DrainingDestinationBuilder {
1307        fn input_event_type(&self) -> EventType {
1308            self.input_event_ty
1309        }
1310
1311        async fn build(&self, _: BuildContext) -> Result<Box<dyn Destination + Send>, GenericError> {
1312            Ok(Box::new(DrainingDestination))
1313        }
1314    }
1315
1316    impl MemoryBounds for DrainingDestinationBuilder {
1317        fn specify_bounds(&self, _builder: &mut MemoryBoundsBuilder) {}
1318    }
1319
1320    /// A destination that ignores both its input and shutdown, running forever until it is forcefully aborted.
1321    ///
1322    /// Records that it started (so tests can wait for it to actually be running before triggering shutdown).
1323    struct StuckDestination {
1324        started: Arc<AtomicUsize>,
1325    }
1326
1327    #[async_trait]
1328    impl Destination for StuckDestination {
1329        async fn run(self: Box<Self>, _context: DestinationContext) -> Result<(), GenericError> {
1330            self.started.fetch_add(1, Ordering::SeqCst);
1331            std::future::pending::<()>().await;
1332            Ok(())
1333        }
1334    }
1335
1336    struct StuckDestinationBuilder {
1337        input_event_ty: EventType,
1338        started: Arc<AtomicUsize>,
1339    }
1340
1341    #[async_trait]
1342    impl DestinationBuilder for StuckDestinationBuilder {
1343        fn input_event_type(&self) -> EventType {
1344            self.input_event_ty
1345        }
1346
1347        async fn build(&self, _: BuildContext) -> Result<Box<dyn Destination + Send>, GenericError> {
1348            Ok(Box::new(StuckDestination {
1349                started: Arc::clone(&self.started),
1350            }))
1351        }
1352    }
1353
1354    impl MemoryBounds for StuckDestinationBuilder {
1355        fn specify_bounds(&self, _builder: &mut MemoryBoundsBuilder) {}
1356    }
1357
1358    /// Builds a connected `source` -> `destination` blueprint of long-running components.
1359    ///
1360    /// The source runs until shutdown; the destination drains until its upstream closes. If `spawned_child` is
1361    /// provided, the source spawns a dynamic child through its spawn handle that records when it starts.
1362    ///
1363    /// Returns the blueprint together with the source's "started" counter, so a test can wait for the source to
1364    /// actually be running (readiness polling) rather than sleeping for a fixed duration.
1365    fn long_running_blueprint(spawned_child: Option<Arc<AtomicUsize>>) -> (TopologyBlueprint, Arc<AtomicUsize>) {
1366        let source_started = Arc::new(AtomicUsize::new(0));
1367        let component_registry = ComponentRegistry::default();
1368        let mut blueprint = TopologyBlueprint::new("test", &component_registry);
1369        blueprint
1370            .add_source(
1371                "source",
1372                ControlSourceBuilder::new(Arc::clone(&source_started), spawned_child),
1373            )
1374            .expect("should not fail to add source")
1375            .add_destination(
1376                "destination",
1377                DrainingDestinationBuilder {
1378                    input_event_ty: EventType::EventD,
1379                },
1380            )
1381            .expect("should not fail to add destination");
1382        blueprint
1383            .connect_components_in_order(["source", "destination"])
1384            .expect("should not fail to connect components");
1385        blueprint
1386            .with_health_registry(HealthRegistry::new())
1387            .with_memory_limiter(MemoryLimiter::noop())
1388            .with_resource_registry(ResourceRegistry::new());
1389        (blueprint, source_started)
1390    }
1391
1392    /// Builds a connected `source` -> `destination` blueprint whose destination must be forcefully aborted on shutdown.
1393    ///
1394    /// The source stops cleanly when it gets the shutdown signal. The destination ignores shutdown and runs forever, so
1395    /// the topology supervisor aborts it after `shutdown_timeout`. Thus, exactly one component is aborted: the
1396    /// destination. This lets a test assert an exact abort count.
1397    ///
1398    /// Returns the blueprint together with the destination's "started" counter, so a test can wait until the stuck
1399    /// destination is actually running before triggering shutdown.
1400    fn stuck_destination_blueprint(shutdown_timeout: Duration) -> (TopologyBlueprint, Arc<AtomicUsize>) {
1401        let destination_started = Arc::new(AtomicUsize::new(0));
1402        let component_registry = ComponentRegistry::default();
1403        let mut blueprint = TopologyBlueprint::new("test", &component_registry);
1404        blueprint
1405            .add_source("source", ControlSourceBuilder::new(Arc::new(AtomicUsize::new(0)), None))
1406            .expect("should not fail to add source")
1407            .add_destination(
1408                "destination",
1409                StuckDestinationBuilder {
1410                    input_event_ty: EventType::EventD,
1411                    started: Arc::clone(&destination_started),
1412                },
1413            )
1414            .expect("should not fail to add destination");
1415        blueprint
1416            .connect_components_in_order(["source", "destination"])
1417            .expect("should not fail to connect components");
1418        blueprint
1419            .with_health_registry(HealthRegistry::new())
1420            .with_memory_limiter(MemoryLimiter::noop())
1421            .with_resource_registry(ResourceRegistry::new())
1422            .with_shutdown_timeout(shutdown_timeout);
1423        (blueprint, destination_started)
1424    }
1425
1426    /// Spawns `blueprint` under a fresh `test-topology` supervisor, returning the shutdown sender and the run's join
1427    /// handle.
1428    ///
1429    /// This is the shared spawn/shutdown scaffold used by the topology-lifecycle tests below, replacing the
1430    /// copy-pasted supervisor construction repeated across them.
1431    fn spawn_supervised_blueprint(
1432        blueprint: TopologyBlueprint,
1433    ) -> (
1434        oneshot::Sender<()>,
1435        tokio::task::JoinHandle<Result<(), SupervisorError>>,
1436    ) {
1437        let mut supervisor = Supervisor::new("test-topology").expect("should not fail to create supervisor");
1438        supervisor.add_worker(blueprint);
1439
1440        let (tx, rx) = oneshot::channel::<()>();
1441        let handle = tokio::spawn(async move { supervisor.run_with_shutdown(rx).await });
1442        (tx, handle)
1443    }
1444
1445    /// Runs `blueprint` under a fresh `test-topology` supervisor with the given restart strategy until it exits on its
1446    /// own (no shutdown is ever signalled), returning the supervisor's result.
1447    async fn run_blueprint_until_exit(
1448        blueprint: TopologyBlueprint, strategy: RestartStrategy,
1449    ) -> Result<(), SupervisorError> {
1450        // The supervisor needs the topology, as the root supervisor of the real binary does.
1451        let mut supervisor = Supervisor::new("test-topology")
1452            .expect("should not fail to create supervisor")
1453            .with_restart_strategy(strategy);
1454        supervisor.add_worker(runtime::supervisable(blueprint).needed().build());
1455
1456        // Hold the sender so shutdown is never triggered; the supervisor exits only when the topology does.
1457        let (_tx, rx) = oneshot::channel::<()>();
1458        tokio::time::timeout(Duration::from_secs(5), supervisor.run_with_shutdown(rx))
1459            .await
1460            .expect("supervisor should exit promptly")
1461    }
1462
1463    /// Awaits a spawned topology-supervisor run to completion under a bounded timeout, unwrapping the join.
1464    async fn join_topology(
1465        handle: tokio::task::JoinHandle<Result<(), SupervisorError>>,
1466    ) -> Result<(), SupervisorError> {
1467        tokio::time::timeout(Duration::from_secs(5), handle)
1468            .await
1469            .expect("supervisor should exit promptly")
1470            .expect("supervisor task should not panic")
1471    }
1472
1473    /// Builds a blueprint pre-populated with a source, transform, and destination, all dealing in event-D events.
1474    ///
1475    /// No connections are made between the components.
1476    fn blueprint_with_components() -> TopologyBlueprint {
1477        let component_registry = ComponentRegistry::default();
1478        let mut blueprint = TopologyBlueprint::new("test", &component_registry);
1479
1480        blueprint
1481            .add_source("source", TestSourceBuilder::default_output(EventType::EventD))
1482            .expect("should not fail to add source")
1483            .add_transform(
1484                "transform",
1485                TestTransformBuilder::default_output(EventType::EventD, EventType::EventD),
1486            )
1487            .expect("should not fail to add transform")
1488            .add_destination(
1489                "destination",
1490                TestDestinationBuilder::with_input_type(EventType::EventD),
1491            )
1492            .expect("should not fail to add destination");
1493
1494        blueprint
1495    }
1496
1497    /// Builds a blueprint pre-populated with the given source and destination component IDs, all dealing in event-D
1498    /// events.
1499    ///
1500    /// No connections are made between the components.
1501    fn blueprint_with_sources_and_destinations(source_ids: &[&str], destination_ids: &[&str]) -> TopologyBlueprint {
1502        let component_registry = ComponentRegistry::default();
1503        let mut blueprint = TopologyBlueprint::new("test", &component_registry);
1504
1505        for source_id in source_ids {
1506            blueprint
1507                .add_source(*source_id, TestSourceBuilder::default_output(EventType::EventD))
1508                .expect("should not fail to add source");
1509        }
1510
1511        for destination_id in destination_ids {
1512            blueprint
1513                .add_destination(
1514                    *destination_id,
1515                    TestDestinationBuilder::with_input_type(EventType::EventD),
1516                )
1517                .expect("should not fail to add destination");
1518        }
1519
1520        blueprint
1521    }
1522
1523    /// Collects the blueprint's directed connections as a sorted list of `(from, to)` component ID pairs.
1524    fn connected_pairs(blueprint: &TopologyBlueprint) -> Vec<(String, String)> {
1525        let guard = blueprint.build_state.lock().expect("topology blueprint mutex poisoned");
1526        let outbound_edges = guard
1527            .as_ref()
1528            .expect("topology blueprint already initialized")
1529            .graph
1530            .get_outbound_directed_edges();
1531
1532        let mut pairs = Vec::new();
1533        for (from, outputs) in &outbound_edges {
1534            for targets in outputs.values() {
1535                for to in targets {
1536                    pairs.push((from.component_id().to_string(), to.component_id().to_string()));
1537                }
1538            }
1539        }
1540        pairs.sort();
1541        pairs
1542    }
1543
1544    #[test]
1545    fn connect_components_in_order_errors_with_fewer_than_two_ids() {
1546        let mut blueprint = blueprint_with_components();
1547
1548        // No component IDs at all.
1549        let result = blueprint.connect_components_in_order(Vec::<&str>::new()).map(|_| ());
1550        assert!(result.is_err());
1551
1552        // A single component ID is still not enough to form a connection.
1553        let result = blueprint.connect_components_in_order(["source"]).map(|_| ());
1554        assert!(result.is_err());
1555
1556        // Neither attempt should have added any connections to the graph.
1557        assert!(connected_pairs(&blueprint).is_empty());
1558    }
1559
1560    #[test]
1561    fn connect_components_in_order_connects_pairwise_left_to_right() {
1562        let mut blueprint = blueprint_with_components();
1563
1564        blueprint
1565            .connect_components_in_order(["source", "transform", "destination"])
1566            .expect("should not fail to connect components in order");
1567
1568        // Adjacent components should be connected from left to right (`source` -> `transform` -> `destination`), with
1569        // a single edge shared between each pair.
1570        assert_eq!(
1571            connected_pairs(&blueprint),
1572            vec![
1573                ("source".to_string(), "transform".to_string()),
1574                ("transform".to_string(), "destination".to_string()),
1575            ],
1576        );
1577    }
1578
1579    #[test]
1580    fn connect_component_one_to_many_fans_out() {
1581        // A single upstream component is fanned out to multiple downstream components. The upstream ID is given as a
1582        // bare string (`Single`), while the downstream IDs are given as a slice (`Multiple`).
1583        let mut blueprint = blueprint_with_sources_and_destinations(&["source"], &["dest_a", "dest_b"]);
1584
1585        blueprint
1586            .connect_components("source", ["dest_a", "dest_b"])
1587            .expect("should not fail to connect component");
1588
1589        assert_eq!(
1590            connected_pairs(&blueprint),
1591            vec![
1592                ("source".to_string(), "dest_a".to_string()),
1593                ("source".to_string(), "dest_b".to_string()),
1594            ],
1595        );
1596    }
1597
1598    #[test]
1599    fn connect_component_many_to_one_fans_in() {
1600        // Multiple upstream components are fanned in to a single downstream component. The upstream IDs are given as a
1601        // slice (`Multiple`), while the downstream ID is given as a bare string (`Single`).
1602        let mut blueprint = blueprint_with_sources_and_destinations(&["source_a", "source_b"], &["dest"]);
1603
1604        blueprint
1605            .connect_components(["source_a", "source_b"], "dest")
1606            .expect("should not fail to connect component");
1607
1608        assert_eq!(
1609            connected_pairs(&blueprint),
1610            vec![
1611                ("source_a".to_string(), "dest".to_string()),
1612                ("source_b".to_string(), "dest".to_string()),
1613            ],
1614        );
1615    }
1616
1617    #[test]
1618    fn connect_component_many_to_many_creates_mesh() {
1619        // Multiple upstream components are meshed with multiple downstream components: every upstream component is
1620        // connected to every downstream component. Both sides are given as slices (`Multiple`).
1621        let mut blueprint = blueprint_with_sources_and_destinations(&["source_a", "source_b"], &["dest_a", "dest_b"]);
1622
1623        blueprint
1624            .connect_components(["source_a", "source_b"], ["dest_a", "dest_b"])
1625            .expect("should not fail to connect component");
1626
1627        assert_eq!(
1628            connected_pairs(&blueprint),
1629            vec![
1630                ("source_a".to_string(), "dest_a".to_string()),
1631                ("source_a".to_string(), "dest_b".to_string()),
1632                ("source_b".to_string(), "dest_a".to_string()),
1633                ("source_b".to_string(), "dest_b".to_string()),
1634            ],
1635        );
1636    }
1637
1638    /// Builds a connected `source` -> `transform` -> `destination` blueprint using the immediate-exit test components.
1639    fn connected_blueprint() -> TopologyBlueprint {
1640        let mut blueprint = blueprint_with_components();
1641        blueprint
1642            .connect_components_in_order(["source", "transform", "destination"])
1643            .expect("should not fail to connect components");
1644        blueprint
1645    }
1646
1647    #[tokio::test]
1648    async fn topology_failure_shuts_down_supervisor_without_a_restart() {
1649        // The test components all finish immediately, which the topology worker treats as an unexpected component
1650        // finish -- a topology failure. The supervisor needs the topology, so the failure must stop the supervisor (and,
1651        // in the real binary, exit the process).
1652        //
1653        // The default restart strategy allows a restart. But the first start of a topology consumes the build state of
1654        // the blueprint, and the blueprint reports that it cannot start again. Thus, the supervisor stops because of
1655        // the failure of the topology, and not because a second start failed to initialize.
1656        let mut blueprint = connected_blueprint();
1657        blueprint
1658            .with_health_registry(HealthRegistry::new())
1659            .with_memory_limiter(MemoryLimiter::noop())
1660            .with_resource_registry(ResourceRegistry::new());
1661        assert!(!blueprint.can_restart());
1662
1663        let result = run_blueprint_until_exit(blueprint, RestartStrategy::default()).await;
1664
1665        assert!(
1666            matches!(result, Err(SupervisorError::SignificantChildExited)),
1667            "the topology failure should stop the supervisor: {result:?}"
1668        );
1669    }
1670
1671    #[tokio::test]
1672    async fn topology_waits_for_environment_readiness_before_starting() {
1673        // The topology must not start its components until the environment readiness signal resolves. We provide a
1674        // signal that never resolves, then trigger shutdown: the topology should exit cleanly without ever spawning
1675        // its components (which would otherwise finish immediately and fail the supervisor), and the supervisor should
1676        // shut down successfully.
1677        // A readiness gate that records when the topology first reaches it, then never resolves. This lets us wait for
1678        // the topology to actually be blocked on readiness before shutting down, rather than sleeping.
1679        let gate_reached = Arc::new(AtomicUsize::new(0));
1680        let gate = {
1681            let gate_reached = Arc::clone(&gate_reached);
1682            async move {
1683                gate_reached.fetch_add(1, Ordering::SeqCst);
1684                std::future::pending::<()>().await;
1685            }
1686        };
1687
1688        let mut blueprint = connected_blueprint();
1689        blueprint
1690            .with_health_registry(HealthRegistry::new())
1691            .with_memory_limiter(MemoryLimiter::noop())
1692            .with_resource_registry(ResourceRegistry::new())
1693            .with_environment_readiness(gate);
1694
1695        let (tx, handle) = spawn_supervised_blueprint(blueprint);
1696
1697        // Once the topology is blocked on the readiness gate (and thus has NOT started its components), trigger
1698        // shutdown; it must exit cleanly.
1699        wait_until("the topology reached the readiness gate", || {
1700            gate_reached.load(Ordering::SeqCst) >= 1
1701        })
1702        .await;
1703        tx.send(()).expect("should send shutdown signal");
1704
1705        let result = join_topology(handle).await;
1706        assert!(result.is_ok(), "supervisor should shut down cleanly, got: {:?}", result);
1707    }
1708
1709    #[test]
1710    fn topology_ready_waits_for_registration_before_checking_readiness() {
1711        use tokio_test::{assert_pending, assert_ready, task::spawn};
1712
1713        let health_registry = HealthRegistry::new();
1714
1715        // Simulate an unrelated subsystem that has already registered and become ready. A naive readiness check against
1716        // the shared registry could resolve immediately here, even though the topology hasn't registered anything yet.
1717        let mut other = health_registry
1718            .register_component(&SubsystemIdentifier::from_dotted("env_provider.workload.foo"))
1719            .expect("should register component");
1720        other.mark_ready();
1721
1722        let (registered_tx, registered_rx) = oneshot::channel();
1723        let topology_ready = TopologyReady {
1724            registered_rx,
1725            health_registry: health_registry.clone(),
1726            component_root: topology_identifier("primary"),
1727        };
1728
1729        let mut wait = spawn(topology_ready.wait());
1730
1731        // Despite no topology components being registered yet, `wait` must not resolve: it's gated on the registration
1732        // signal, which is precisely what prevents a false-ready observation.
1733        assert_pending!(wait.poll());
1734
1735        // Now register a topology component (as the topology does when it spawns), but leave it not-ready.
1736        let mut source = health_registry
1737            .register_component(&SubsystemIdentifier::from_dotted("topology.primary.sources.in"))
1738            .expect("should register component");
1739
1740        // Fire the registration signal. `wait` advances to the scoped readiness check, which is still pending because
1741        // the topology component hasn't reported ready.
1742        registered_tx.send(()).expect("receiver should be alive");
1743        assert_pending!(wait.poll());
1744
1745        // Once the topology component reports ready, `wait` resolves to `true`.
1746        source.mark_ready();
1747        assert!(assert_ready!(wait.poll()));
1748    }
1749
1750    #[tokio::test]
1751    async fn topology_ready_returns_false_when_torn_down_before_registration() {
1752        let health_registry = HealthRegistry::new();
1753
1754        let (registered_tx, registered_rx) = oneshot::channel::<()>();
1755        let topology_ready = TopologyReady {
1756            registered_rx,
1757            health_registry,
1758            component_root: topology_identifier("primary"),
1759        };
1760
1761        // Drop the sender without ever signaling, as happens when the topology is torn down before it registers its
1762        // components. `wait` should report that readiness will never be reached.
1763        drop(registered_tx);
1764
1765        assert!(!topology_ready.wait().await);
1766    }
1767
1768    #[tokio::test]
1769    async fn topology_clean_shutdown_returns_ok() {
1770        // A source that runs until shutdown feeds a destination that drains until its upstream closes. On shutdown,
1771        // the source stops (it observes its supervisor's shutdown signal), the destination drains and stops, and the
1772        // topology supervisor returns cleanly -- which is the intentional-shutdown path, distinct from a component
1773        // unexpectedly finishing.
1774        let (blueprint, source_started) = long_running_blueprint(None);
1775        let (tx, handle) = spawn_supervised_blueprint(blueprint);
1776
1777        // Wait until the source is actually running before requesting shutdown, so we exercise shutting down live
1778        // components rather than shutting down before they start.
1779        wait_until("the source has started", || source_started.load(Ordering::SeqCst) == 1).await;
1780        tx.send(()).expect("should send shutdown signal");
1781
1782        let result = join_topology(handle).await;
1783        assert!(result.is_ok(), "topology should shut down cleanly, got: {:?}", result);
1784    }
1785
1786    #[tokio::test]
1787    async fn topology_with_dynamic_condition_shuts_down_cleanly() {
1788        // A dynamic condition is driven by a worker that runs alongside the components. It has to stop when the
1789        // topology shuts down, even though its condition's updates never end.
1790        let (mut blueprint, source_started) = long_running_blueprint(None);
1791        let (condition_tx, condition_rx) = tokio::sync::watch::channel(false);
1792        blueprint
1793            .add_destination(
1794                "observer",
1795                DrainingDestinationBuilder {
1796                    input_event_ty: EventType::EventD,
1797                },
1798            )
1799            .expect("should not fail to add destination")
1800            .connect_components_when("source", "observer", EdgeCondition::from_watch(condition_rx))
1801            .expect("should not fail to connect components");
1802        let (tx, handle) = spawn_supervised_blueprint(blueprint);
1803
1804        wait_until("the source has started", || source_started.load(Ordering::SeqCst) == 1).await;
1805        condition_tx
1806            .send(true)
1807            .expect("condition should still be watched while the topology runs");
1808        tx.send(()).expect("should send shutdown signal");
1809
1810        let result = join_topology(handle).await;
1811        assert!(result.is_ok(), "topology should shut down cleanly, got: {:?}", result);
1812    }
1813
1814    #[tokio::test]
1815    async fn component_can_spawn_dynamic_child_via_spawn_handle() {
1816        // The source spawns a dynamic child through its context's spawn handle. The child records that it started and
1817        // then runs until torn down. We verify the child actually ran, then shut the topology down cleanly. The dynamic
1818        // child still runs at that time, and the clean shutdown stops it together with its component. Otherwise, the
1819        // drain does not complete, and the test times out.
1820        let child_started = Arc::new(AtomicUsize::new(0));
1821        let (blueprint, _source_started) = long_running_blueprint(Some(Arc::clone(&child_started)));
1822        let (tx, handle) = spawn_supervised_blueprint(blueprint);
1823
1824        // Wait until the dynamic child has started.
1825        wait_until("the dynamic child has started", || {
1826            child_started.load(Ordering::SeqCst) == 1
1827        })
1828        .await;
1829        assert_eq!(
1830            child_started.load(Ordering::SeqCst),
1831            1,
1832            "dynamic child should have started exactly once"
1833        );
1834
1835        tx.send(()).expect("should send shutdown signal");
1836        let result = join_topology(handle).await;
1837        assert!(result.is_ok(), "topology should shut down cleanly, got: {:?}", result);
1838    }
1839
1840    #[tokio::test]
1841    async fn each_component_runs_as_a_worker_named_by_its_canonical_identity() {
1842        // Components run directly under the topology supervisor, with no supervisor of their own. The process name of
1843        // each worker must be the canonical identity of its component. The health registry and resource accounting also
1844        // use this identity. The worker must also own that resource group, so that the component still has its own
1845        // figures.
1846        let (blueprint, source_started) = long_running_blueprint(None);
1847
1848        let mut supervisor = Supervisor::new("test-topology").expect("should not fail to create supervisor");
1849        let tree = supervisor.tree_handle();
1850        supervisor.add_worker(blueprint);
1851        let (tx, rx) = oneshot::channel::<()>();
1852        let handle = tokio::spawn(async move { supervisor.run_with_shutdown(rx).await });
1853
1854        wait_until("the source has started", || source_started.load(Ordering::SeqCst) == 1).await;
1855
1856        fn find<'a>(node: &'a runtime::NodeSnapshot, name: &str) -> Option<&'a runtime::NodeSnapshot> {
1857            if node.name == name {
1858                return Some(node);
1859            }
1860            node.children.iter().find_map(|child| find(child, name))
1861        }
1862
1863        let root = tree.snapshot().root;
1864        let topology = find(&root, "topology.test").expect("the topology supervisor is in the tree");
1865        for (name, identity) in [
1866            ("sources.source", "topology.test.sources.source"),
1867            ("destinations.destination", "topology.test.destinations.destination"),
1868        ] {
1869            let component = topology
1870                .children
1871                .iter()
1872                .find(|child| child.name == name)
1873                .unwrap_or_else(|| panic!("{name} should run directly under the topology supervisor"));
1874            assert_eq!(component.kind, runtime::NodeKind::Worker);
1875            assert_eq!(component.process_name.as_deref(), Some(identity));
1876            assert_eq!(
1877                component.resource_group.as_deref(),
1878                Some(identity),
1879                "{name} should own its resource group"
1880            );
1881        }
1882
1883        tx.send(()).expect("should send shutdown signal");
1884        let result = join_topology(handle).await;
1885        assert!(result.is_ok(), "topology should shut down cleanly, got: {:?}", result);
1886    }
1887
1888    #[tokio::test]
1889    async fn work_spawned_while_a_component_is_built_belongs_to_the_component() {
1890        // The builder of a component runs inside the blueprint, before the process of the component exists. At that
1891        // time, the builder can spawn tasks into the current scope, for example the background tasks of a cache. The
1892        // scope holds these tasks until the component runs. Then the tasks belong to the component: they run beneath
1893        // the component, and stop with it.
1894        let source_started = Arc::new(AtomicUsize::new(0));
1895        let child_started = Arc::new(AtomicUsize::new(0));
1896        let child_stopped = Arc::new(AtomicUsize::new(0));
1897
1898        let component_registry = ComponentRegistry::default();
1899        let mut blueprint = TopologyBlueprint::new("test", &component_registry);
1900        blueprint
1901            .add_source(
1902                "spawner",
1903                BuildSpawningSourceBuilder {
1904                    outputs: vec![OutputDefinition::default_output(EventType::EventD)],
1905                    source_started: Arc::clone(&source_started),
1906                    child_started: Arc::clone(&child_started),
1907                    child_stopped: Arc::clone(&child_stopped),
1908                },
1909            )
1910            .expect("should not fail to add source")
1911            .add_destination(
1912                "destination",
1913                DrainingDestinationBuilder {
1914                    input_event_ty: EventType::EventD,
1915                },
1916            )
1917            .expect("should not fail to add destination");
1918        blueprint
1919            .connect_components_in_order(["spawner", "destination"])
1920            .expect("should not fail to connect components");
1921        blueprint
1922            .with_health_registry(HealthRegistry::new())
1923            .with_memory_limiter(MemoryLimiter::noop())
1924            .with_resource_registry(ResourceRegistry::new());
1925
1926        let mut supervisor = Supervisor::new("test-topology").expect("should not fail to create supervisor");
1927        let tree = supervisor.tree_handle();
1928        supervisor.add_worker(blueprint);
1929        let (tx, rx) = oneshot::channel::<()>();
1930        let handle = tokio::spawn(async move { supervisor.run_with_shutdown(rx).await });
1931
1932        fn find<'a>(node: &'a runtime::NodeSnapshot, name: &str) -> Option<&'a runtime::NodeSnapshot> {
1933            if node.name == name {
1934                return Some(node);
1935            }
1936            node.children.iter().find_map(|child| find(child, name))
1937        }
1938
1939        // The source worker gets its name from the component.
1940        wait_until("the child spawned while building runs beneath its component", || {
1941            let root = tree.snapshot().root;
1942            find(&root, "sources.spawner").is_some_and(|source| find(source, "built_child").is_some())
1943        })
1944        .await;
1945        assert_eq!(source_started.load(Ordering::SeqCst), 1);
1946        assert_eq!(child_started.load(Ordering::SeqCst), 1);
1947
1948        tx.send(()).expect("should send shutdown signal");
1949        let result = join_topology(handle).await;
1950        assert!(result.is_ok(), "topology should shut down cleanly, got: {:?}", result);
1951        assert_eq!(
1952            child_stopped.load(Ordering::SeqCst),
1953            1,
1954            "the child should have been stopped with its component"
1955        );
1956    }
1957
1958    #[tokio::test]
1959    async fn forced_abort_count_survives_topology_boundary_to_root() {
1960        // A component that ignores graceful shutdown is forcefully aborted, and that abort count must survive the
1961        // `TopologyBlueprint` boundary -- where the topology supervisor's `SupervisorError` is flattened into a
1962        // `GenericError` -- and be recovered by the root supervisor as `ShutdownTimedOut`. This exercises the
1963        // `downcast` recovery path in `reported_abort_count`, which the production topology depends on but the direct
1964        // nested-supervisor tests in `supervisor.rs` do not cover: those hit the structured `WorkerError` variant,
1965        // never the flattened-`GenericError` path taken here.
1966        //
1967        // The source stops cleanly on shutdown; the destination ignores shutdown and runs forever, so exactly one
1968        // component (the destination) is force-aborted after the (short) shutdown timeout.
1969        let (blueprint, destination_started) = stuck_destination_blueprint(Duration::from_millis(100));
1970        let (tx, handle) = spawn_supervised_blueprint(blueprint);
1971
1972        // The forced abort only happens if the stuck destination is actually running when shutdown arrives, so wait
1973        // for it to start before triggering shutdown.
1974        wait_until("the stuck destination has started", || {
1975            destination_started.load(Ordering::SeqCst) == 1
1976        })
1977        .await;
1978        tx.send(()).expect("should send shutdown signal");
1979
1980        let result = join_topology(handle).await;
1981        assert!(
1982            matches!(result, Err(SupervisorError::ShutdownTimedOut { aborted: 1 })),
1983            "a component that ignored shutdown must surface as an unclean shutdown with a count of 1, got {result:?}"
1984        );
1985    }
1986
1987    #[test]
1988    fn component_identity_is_byte_identical_across_subsystems() {
1989        // We want to ensure that when using a component's canonical identity, we are able to use that canonical
1990        // identical to reference the same entity across subsystems like the health registry, resource accounting, the
1991        // supervision/process tree, and so on.
1992
1993        for (topology_name, raw_id) in [("primary", "dsd_in"), ("secondary", "dsd_agg")] {
1994            // Calculate the root topology identifier, our component context, and the identifiers for the component.
1995            let topology_root = topology_identifier(topology_name);
1996            let component_context = ComponentContext::source(&topology_root, ComponentId::try_from(raw_id).unwrap());
1997            let component_canonical_id = component_context.identity().to_string();
1998            let component_relative_id =
1999                get_component_relative_identifier(component_context.component_type(), component_context.component_id());
2000
2001            assert_eq!(
2002                component_canonical_id,
2003                format!("topology.{topology_name}.sources.{raw_id}")
2004            );
2005
2006            // Resource accounting: the component is addressed by its canonical identity directly, so declaring bounds
2007            // for it must create a node whose full path -- segment by segment -- is exactly that canonical identity.
2008            let registry = ComponentRegistry::default();
2009            registry
2010                .bounds_builder(&component_context.identity())
2011                .firm()
2012                .with_fixed_amount("marker", 1);
2013
2014            let bounds = registry.as_bounds();
2015            let mut node = &bounds;
2016            for segment in component_canonical_id.split('.') {
2017                node = node
2018                    .subcomponents()
2019                    .into_iter()
2020                    .find_map(|(name, child)| (name.as_str() == segment).then_some(child))
2021                    .expect("resource-accounting node path must match the canonical identity segment by segment");
2022            }
2023            assert_eq!(
2024                node.total_firm_limit_bytes(),
2025                1,
2026                "the resource-accounting node at the canonical path must hold the declared bounds"
2027            );
2028
2029            // Supervision: when using relative subsystem identifiers in a nested fashion, we should end up with
2030            // a process name that matches the canonical identity.
2031            let topology_sup = Name::root(topology_root.to_string()).expect("topology name is non-empty");
2032            let process_name =
2033                Name::scoped(&topology_sup, component_relative_id.to_string()).expect("component name is non-empty");
2034            assert_eq!(
2035                &*process_name,
2036                component_canonical_id.as_str(),
2037                "component worker process name must match the canonical identity"
2038            );
2039        }
2040    }
2041
2042    /// Adds an `observer` destination to a blueprint from [`blueprint_with_components`], and connects the primary path.
2043    fn blueprint_with_observer() -> TopologyBlueprint {
2044        let mut blueprint = blueprint_with_components();
2045        blueprint
2046            .add_destination("observer", TestDestinationBuilder::with_input_type(EventType::EventD))
2047            .unwrap()
2048            .connect_components_in_order(["source", "transform", "destination"])
2049            .unwrap();
2050        blueprint
2051    }
2052
2053    fn component_id(id: &str) -> ComponentId {
2054        ComponentId::try_from(id).unwrap()
2055    }
2056
2057    fn firm_bound_bytes(blueprint: &TopologyBlueprint) -> usize {
2058        let guard = blueprint.build_state.lock().unwrap();
2059        guard
2060            .as_ref()
2061            .unwrap()
2062            .component_registry
2063            .as_bounds()
2064            .total_firm_limit_bytes()
2065    }
2066
2067    #[test]
2068    fn connection_with_false_condition_prunes_downstream_component() {
2069        // A connection whose condition is always false is removed, and the observer it was the only input of is pruned
2070        // before anything is built. Its share of the memory bounds is removed as soon as the connection is made, since
2071        // bounds are verified before the topology is built.
2072        let mut blueprint = blueprint_with_observer();
2073        let firm_before = firm_bound_bytes(&blueprint);
2074        blueprint
2075            .connect_components_when("source", "observer", EdgeCondition::fixed(false))
2076            .unwrap();
2077        let firm_after = firm_bound_bytes(&blueprint);
2078        assert!(firm_after < firm_before);
2079
2080        let mut guard = blueprint.build_state.lock().unwrap();
2081        let state = guard.as_mut().unwrap();
2082        state.prune_folded_components();
2083
2084        assert!(!state.destinations.contains_key(&component_id("observer")));
2085        assert!(state.destinations.contains_key(&component_id("destination")));
2086        assert!(state.graph.validate().is_ok());
2087        assert_eq!(
2088            state.component_registry.as_bounds().total_firm_limit_bytes(),
2089            firm_after
2090        );
2091    }
2092
2093    #[test]
2094    fn later_connection_keeps_folded_component() {
2095        // A component that lost a connection to a false condition isn't pruned if another connection gives it an input,
2096        // and its share of the memory bounds is restored.
2097        let mut blueprint = blueprint_with_observer();
2098        blueprint
2099            .connect_components_when("source", "observer", EdgeCondition::fixed(false))
2100            .unwrap();
2101        let firm_folded = firm_bound_bytes(&blueprint);
2102        blueprint.connect_components("transform", "observer").unwrap();
2103        assert!(firm_bound_bytes(&blueprint) > firm_folded);
2104
2105        let mut guard = blueprint.build_state.lock().unwrap();
2106        let state = guard.as_mut().unwrap();
2107        state.prune_folded_components();
2108
2109        assert!(state.destinations.contains_key(&component_id("observer")));
2110        assert!(state.graph.validate().is_ok());
2111    }
2112
2113    #[test]
2114    fn pruned_decoder_is_excluded_from_event_buffer_bounds() {
2115        // A decoder whose only input is a connection with a false condition is pruned, so it shouldn't contribute an
2116        // in-flight event buffer to the memory bounds: the bounds should match a topology without the decoder at all.
2117        let with_pruned_decoder = {
2118            let mut blueprint = blueprint_with_observer();
2119            blueprint
2120                .add_relay("relay", TestRelayBuilder::default_output(PayloadType::Raw))
2121                .unwrap()
2122                .add_decoder(
2123                    "decoder",
2124                    TestDecoderBuilder::with_input_and_output_type(PayloadType::Raw, EventType::EventD),
2125                )
2126                .unwrap()
2127                .connect_components_when("relay", "decoder", EdgeCondition::fixed(false))
2128                .unwrap()
2129                .connect_components("decoder", "observer")
2130                .unwrap()
2131                .connect_components("source", "observer")
2132                .unwrap();
2133            blueprint
2134        };
2135        let without_decoder = {
2136            let mut blueprint = blueprint_with_observer();
2137            blueprint
2138                .add_relay("relay", TestRelayBuilder::default_output(PayloadType::Raw))
2139                .unwrap()
2140                .connect_components("source", "observer")
2141                .unwrap();
2142            blueprint
2143        };
2144
2145        assert_eq!(
2146            firm_bound_bytes(&with_pruned_decoder),
2147            firm_bound_bytes(&without_decoder)
2148        );
2149    }
2150
2151    #[test]
2152    fn connection_with_true_condition_is_a_normal_connection() {
2153        let mut blueprint = blueprint_with_observer();
2154        blueprint
2155            .connect_components_when("source", "observer", EdgeCondition::fixed(true))
2156            .unwrap();
2157
2158        let mut guard = blueprint.build_state.lock().unwrap();
2159        let state = guard.as_mut().unwrap();
2160        state.prune_folded_components();
2161
2162        assert!(state.destinations.contains_key(&component_id("observer")));
2163        assert!(state.edge_conditions.is_empty());
2164        assert!(state.graph.validate().is_ok());
2165    }
2166
2167    #[test]
2168    fn connection_with_dynamic_condition_keeps_downstream_component() {
2169        let mut blueprint = blueprint_with_observer();
2170        blueprint
2171            .connect_components_when(
2172                "source",
2173                "observer",
2174                EdgeCondition::dynamic(false, futures::stream::empty()),
2175            )
2176            .unwrap();
2177
2178        let mut guard = blueprint.build_state.lock().unwrap();
2179        let state = guard.as_mut().unwrap();
2180        state.prune_folded_components();
2181
2182        assert!(state.destinations.contains_key(&component_id("observer")));
2183        assert!(!state.edge_conditions.is_empty());
2184        assert!(state.graph.validate().is_ok());
2185    }
2186
2187    #[test]
2188    fn recalculate_bounds_accounts_for_interconnect_and_event_buffer_memory() {
2189        // `recalculate_bounds` sizes the topology's interconnect and event-buffer memory from the component counts and
2190        // the interconnect capacity. Build a source -> transform -> destination topology, then set a distinctive
2191        // interconnect capacity so the recalculation runs with all components present, and assert the exact byte
2192        // totals against the documented arithmetic.
2193        let interconnect_capacity = 4usize;
2194        let mut blueprint = blueprint_with_components();
2195        blueprint.with_interconnect_capacity(NonZeroUsize::new(interconnect_capacity).unwrap());
2196
2197        // Component counts once all three components are registered.
2198        let (sources, transforms, destinations, decoders) = (1usize, 1usize, 1usize, 0usize);
2199
2200        // Minimum: one preallocated interconnect (holding `capacity` event buffers) per non-source component (that is,
2201        // every transform and destination).
2202        let total_interconnect_capacity = interconnect_capacity * (transforms + destinations);
2203        let expected_min = total_interconnect_capacity * std::mem::size_of::<EventsBuffer>();
2204
2205        // Firm: the maximum number of in-flight event buffers, each sized as one events-buffer container plus the
2206        // events it holds at the default per-buffer capacity. The firm total is additive with the minimum.
2207        let max_in_flight = ((transforms + destinations) * interconnect_capacity) + sources + decoders + transforms;
2208        let per_buffer =
2209            std::mem::size_of::<EventsBuffer>() + (std::mem::size_of::<Event>() * DEFAULT_EVENTS_BUFFER_CAPACITY);
2210        let expected_firm = expected_min + (max_in_flight * per_buffer);
2211
2212        let bounds = {
2213            let guard = blueprint.build_state.lock().expect("topology blueprint mutex poisoned");
2214            guard
2215                .as_ref()
2216                .expect("topology blueprint already initialized")
2217                .component_registry
2218                .as_bounds()
2219        };
2220
2221        assert_eq!(
2222            bounds.total_minimum_required_bytes(),
2223            expected_min,
2224            "interconnect minimum bytes should be capacity * non-source components * size_of::<EventsBuffer>()"
2225        );
2226        assert_eq!(
2227            bounds.total_firm_limit_bytes(),
2228            expected_firm,
2229            "firm bytes should add the max in-flight event-buffer memory on top of the minimum"
2230        );
2231    }
2232
2233    #[test]
2234    fn worker_pool_configuration_defaults_to_dedicated() {
2235        let blueprint = blueprint_with_components();
2236        let guard = blueprint.build_state.lock().expect("topology blueprint mutex poisoned");
2237        let config = &guard
2238            .as_ref()
2239            .expect("topology blueprint already initialized")
2240            .worker_pool_config;
2241        assert!(
2242            matches!(config, WorkerPoolConfiguration::Dedicated),
2243            "the default worker-pool configuration must be dedicated"
2244        );
2245    }
2246
2247    #[test]
2248    fn with_ambient_worker_pool_selects_ambient() {
2249        let mut blueprint = blueprint_with_components();
2250        blueprint.with_ambient_worker_pool();
2251
2252        let guard = blueprint.build_state.lock().expect("topology blueprint mutex poisoned");
2253        let config = &guard
2254            .as_ref()
2255            .expect("topology blueprint already initialized")
2256            .worker_pool_config;
2257        assert!(matches!(config, WorkerPoolConfiguration::Ambient));
2258    }
2259
2260    #[tokio::test]
2261    async fn with_explicit_worker_pool_selects_explicit() {
2262        let mut blueprint = blueprint_with_components();
2263        blueprint.with_explicit_worker_pool(tokio::runtime::Handle::current());
2264
2265        let guard = blueprint.build_state.lock().expect("topology blueprint mutex poisoned");
2266        let config = &guard
2267            .as_ref()
2268            .expect("topology blueprint already initialized")
2269            .worker_pool_config;
2270        assert!(matches!(config, WorkerPoolConfiguration::Explicit(_)));
2271    }
2272}