pks-session 0.1.0

Session declaration and lifecycle composition for PocketStation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
use std::collections::HashSet;

use pks_caps::{ChannelLayout, MediaCaps};
use pks_frame::{EndpointId, RouteId, SessionId, StemId};
use pks_frame::{SampleFormat, SampleSpec};
use pks_graph::ir::GraphIr;
use pks_graph::{EdgeId, NodeRegistry, NodeTypeId, PrepareContext};
use pks_runtime::{
    plan_source_channel, ExecError, PlanEdgeReceiver, PlanRunnerCancellation, PlanRunnerError,
    PlanSourceInput, PlanSourceSender, RealtimePlanExecutor,
};

use crate::{
    CompiledSession, SessionSpec, Source, APPLICATION_SOURCE_NODE_TYPE_ID,
    MICROPHONE_SOURCE_NODE_TYPE_ID,
};

#[derive(Debug, thiserror::Error)]
pub enum SessionPrepareError {
    #[error(transparent)]
    Runtime(#[from] ExecError),
    #[error(transparent)]
    SourceChannel(#[from] PlanRunnerError),
    #[error("compiled stem {stem_id:?} has no matching source node")]
    MissingSourceNode { stem_id: StemId },
    #[error("compiled stem {stem_id:?} maps to more than one source node")]
    DuplicateSourceNode { stem_id: StemId },
    #[error(
        "compiled plan produced {actual_receivers} worker receivers for {expected_routes} routes"
    )]
    WorkerReceiverCountMismatch {
        expected_routes: usize,
        actual_receivers: usize,
    },
    #[error("worker edge {edge_id:?} target is absent from the compiled graph")]
    MissingWorkerTarget { edge_id: EdgeId },
    #[error("worker edge {edge_id:?} is absent from the compiled graph")]
    MissingWorkerEdge { edge_id: EdgeId },
    #[error("worker edge {edge_id:?} has no concrete audio sample specification")]
    MissingWorkerSampleSpec { edge_id: EdgeId },
    #[error("worker edge {edge_id:?} target is missing configuration key {key}")]
    MissingWorkerMetadata { edge_id: EdgeId, key: &'static str },
    #[error("worker edge {edge_id:?} target has invalid {key} value {value:?}")]
    InvalidWorkerMetadata {
        edge_id: EdgeId,
        key: &'static str,
        value: String,
    },
    #[error("worker edge {edge_id:?} maps to unknown route {route_id:?}")]
    UnknownWorkerRoute { edge_id: EdgeId, route_id: RouteId },
    #[error("worker route {route_id:?} is mapped more than once")]
    DuplicateWorkerRoute { route_id: RouteId },
    #[error(
        "worker edge {edge_id:?} metadata does not match route {route_id:?}: expected stem {expected_stem_id:?} and endpoint {expected_endpoint_id:?}, got stem {actual_stem_id:?} and endpoint {actual_endpoint_id:?}"
    )]
    WorkerRouteMismatch {
        edge_id: EdgeId,
        route_id: RouteId,
        expected_stem_id: StemId,
        actual_stem_id: StemId,
        expected_endpoint_id: EndpointId,
        actual_endpoint_id: EndpointId,
    },
}

pub struct PreparedSourceMapping {
    pub(crate) stem_id: StemId,
    pub(crate) sender: PlanSourceSender,
}

impl PreparedSourceMapping {
    pub const fn stem_id(&self) -> StemId {
        self.stem_id
    }

    pub fn sender_observations(&self) -> pks_runtime::PlanSourceInputObservations {
        self.sender.observations()
    }
}

pub struct PreparedWorkerMapping {
    pub(crate) route_id: RouteId,
    pub(crate) stem_id: StemId,
    pub(crate) endpoint_id: EndpointId,
    pub(crate) receiver: PlanEdgeReceiver,
    pub(crate) prepare_context: PrepareContext,
}

impl PreparedWorkerMapping {
    pub const fn route_id(&self) -> RouteId {
        self.route_id
    }

    pub const fn stem_id(&self) -> StemId {
        self.stem_id
    }

    pub const fn endpoint_id(&self) -> EndpointId {
        self.endpoint_id
    }

    pub fn receiver_observations(&self) -> pks_runtime::EdgeObservations {
        self.receiver.observations()
    }

    pub const fn prepare_context(&self) -> &PrepareContext {
        &self.prepare_context
    }
}

/// Setup-time ownership for one compiled Session.
///
/// Preparation instantiates the realtime plan and allocates only bounded
/// channels. It does not open capture, start endpoint workers, spawn a runtime
/// thread, or publish a `Running` lifecycle state.
pub struct PreparedSession {
    pub(crate) spec: SessionSpec,
    pub(crate) executor: RealtimePlanExecutor,
    pub(crate) source_mappings: Vec<PreparedSourceMapping>,
    pub(crate) source_inputs: Vec<PlanSourceInput>,
    pub(crate) worker_mappings: Vec<PreparedWorkerMapping>,
    pub(crate) cancellation: PlanRunnerCancellation,
}

impl PreparedSession {
    pub const fn session_id(&self) -> SessionId {
        self.spec.session_id()
    }

    pub fn spec(&self) -> &SessionSpec {
        &self.spec
    }

    pub fn source_mappings(&self) -> &[PreparedSourceMapping] {
        &self.source_mappings
    }

    pub fn source_input_count(&self) -> usize {
        self.source_inputs.len()
    }

    pub fn worker_mappings(&self) -> &[PreparedWorkerMapping] {
        &self.worker_mappings
    }

    pub fn route_observations(&self, route_id: RouteId) -> Option<pks_runtime::EdgeObservations> {
        let mapping = self
            .worker_mappings
            .iter()
            .find(|mapping| mapping.route_id == route_id)?;
        self.executor.observations(mapping.receiver.edge_id())
    }

    pub fn cancellation_requested(&self) -> bool {
        self.cancellation.is_requested()
    }
}

pub fn prepare_session_runtime(
    compiled: CompiledSession,
    node_registry: &NodeRegistry,
    prepare_context: &PrepareContext,
    source_queue_capacity_frames: usize,
) -> Result<PreparedSession, SessionPrepareError> {
    let (spec, graph_ir, runtime_plan) = compiled.into_runtime_parts();
    let (executor, worker_receivers) =
        RealtimePlanExecutor::new(&runtime_plan, &graph_ir, node_registry, prepare_context)?;
    let cancellation = PlanRunnerCancellation::new();
    let (source_mappings, source_inputs) = prepare_sources(
        &spec,
        &graph_ir,
        source_queue_capacity_frames,
        &cancellation,
    )?;
    let worker_mappings = map_worker_receivers(&spec, &graph_ir, worker_receivers)?;

    Ok(PreparedSession {
        spec,
        executor,
        source_mappings,
        source_inputs,
        worker_mappings,
        cancellation,
    })
}

fn prepare_sources(
    spec: &SessionSpec,
    graph_ir: &GraphIr,
    source_queue_capacity_frames: usize,
    cancellation: &PlanRunnerCancellation,
) -> Result<(Vec<PreparedSourceMapping>, Vec<PlanSourceInput>), SessionPrepareError> {
    let mut mappings = Vec::with_capacity(spec.stems().len());
    let mut inputs = Vec::with_capacity(spec.stems().len());
    for stem in spec.stems() {
        let expected_type_id = source_node_type_id(stem.source());
        let stem_id = stem.id().0.to_string();
        let mut matches = graph_ir.nodes.iter().filter(|node| {
            node.spec.type_id == expected_type_id
                && node.spec.config.get("stem_id") == Some(stem_id.as_str())
        });
        let node = matches
            .next()
            .ok_or(SessionPrepareError::MissingSourceNode { stem_id: stem.id() })?;
        if matches.next().is_some() {
            return Err(SessionPrepareError::DuplicateSourceNode { stem_id: stem.id() });
        }
        let source_node_id = node.id();
        let (sender, input) = plan_source_channel(
            source_node_id,
            source_queue_capacity_frames,
            cancellation.clone(),
        )?;
        mappings.push(PreparedSourceMapping {
            stem_id: stem.id(),
            sender,
        });
        inputs.push(input);
    }
    Ok((mappings, inputs))
}

fn map_worker_receivers(
    spec: &SessionSpec,
    graph_ir: &GraphIr,
    worker_receivers: Vec<PlanEdgeReceiver>,
) -> Result<Vec<PreparedWorkerMapping>, SessionPrepareError> {
    if worker_receivers.len() != spec.routes().len() {
        return Err(SessionPrepareError::WorkerReceiverCountMismatch {
            expected_routes: spec.routes().len(),
            actual_receivers: worker_receivers.len(),
        });
    }

    let mut mapped_routes = HashSet::with_capacity(worker_receivers.len());
    let mut mappings = Vec::with_capacity(worker_receivers.len());
    for receiver in worker_receivers {
        let edge_id = receiver.edge_id();
        let edge = graph_ir
            .edges
            .iter()
            .find(|edge| edge.spec.id == edge_id)
            .ok_or(SessionPrepareError::MissingWorkerEdge { edge_id })?;
        let prepare_context = prepare_context_for_media(edge.media)
            .ok_or(SessionPrepareError::MissingWorkerSampleSpec { edge_id })?;
        let target = graph_ir
            .node(receiver.to().node)
            .ok_or(SessionPrepareError::MissingWorkerTarget { edge_id })?;
        let route_id = RouteId(parse_metadata(&target.spec.config, edge_id, "route_id")?);
        let stem_id = StemId(parse_metadata(&target.spec.config, edge_id, "stem_id")?);
        let endpoint_id = EndpointId(parse_metadata(&target.spec.config, edge_id, "endpoint_id")?);
        let route = spec
            .routes()
            .iter()
            .find(|route| route.id() == route_id)
            .ok_or(SessionPrepareError::UnknownWorkerRoute { edge_id, route_id })?;
        if route.stem_id() != stem_id || route.endpoint_id() != endpoint_id {
            return Err(SessionPrepareError::WorkerRouteMismatch {
                edge_id,
                route_id,
                expected_stem_id: route.stem_id(),
                actual_stem_id: stem_id,
                expected_endpoint_id: route.endpoint_id(),
                actual_endpoint_id: endpoint_id,
            });
        }
        if !mapped_routes.insert(route_id) {
            return Err(SessionPrepareError::DuplicateWorkerRoute { route_id });
        }
        mappings.push(PreparedWorkerMapping {
            route_id,
            stem_id,
            endpoint_id,
            receiver,
            prepare_context,
        });
    }
    Ok(mappings)
}

fn prepare_context_for_media(media: MediaCaps) -> Option<PrepareContext> {
    let MediaCaps::Audio(audio) = media else {
        return None;
    };
    let channels = match audio.channel_layout {
        ChannelLayout::Mono => 1,
        ChannelLayout::Stereo => 2,
        ChannelLayout::Any => return None,
    };
    Some(PrepareContext::new(SampleSpec::new(
        audio.sample_rate_hz?,
        channels,
        match audio.format {
            SampleFormat::F32Interleaved => SampleFormat::F32Interleaved,
        },
    )))
}

fn parse_metadata(
    config: &pks_graph::NodeConfig,
    edge_id: EdgeId,
    key: &'static str,
) -> Result<u64, SessionPrepareError> {
    let value = config
        .get(key)
        .ok_or(SessionPrepareError::MissingWorkerMetadata { edge_id, key })?;
    value
        .parse()
        .map_err(|_| SessionPrepareError::InvalidWorkerMetadata {
            edge_id,
            key,
            value: value.to_owned(),
        })
}

fn source_node_type_id(source: &Source) -> NodeTypeId {
    match source {
        Source::Application(_) => NodeTypeId::from(APPLICATION_SOURCE_NODE_TYPE_ID),
        Source::Microphone(_) => NodeTypeId::from(MICROPHONE_SOURCE_NODE_TYPE_ID),
    }
}

#[cfg(test)]
mod tests {
    use std::sync::atomic::{AtomicUsize, Ordering};
    use std::sync::Arc;

    use pks_caps::{AudioCaps, ChannelLayout, MediaCaps, Multiplicity, PortDirection, PortSpec};
    use pks_frame::{AudioFrame, SampleFormat, SampleSpec};
    use pks_graph::{
        ConfigError, ExecutionPartition, NodeConfig, NodeDescriptor, NodeError, NodeFactory,
        RuntimeNode,
    };

    use super::*;
    use crate::{
        ApplicationSelector, EndpointConfiguration, OperatorId, OperatorRegistry, Session,
        SessionCompiler, BROWSER_NODE_TYPE_ID, BROWSER_OPERATOR_ID, CONNECTOR_NODE_TYPE_ID,
        RECORDER_NODE_TYPE_ID, RECORDER_OPERATOR_ID,
    };

    const TEST_CONNECTOR_OPERATOR_ID: &str = "example.connector.runtime-prepare.v1";

    struct TestFactory {
        descriptor: NodeDescriptor,
        live_nodes: Arc<AtomicUsize>,
    }

    struct TestNode {
        live_nodes: Arc<AtomicUsize>,
    }

    #[derive(Clone, Copy)]
    enum TestNodeRole {
        Source,
        Endpoint,
    }

    impl NodeFactory for TestFactory {
        fn descriptor(&self) -> NodeDescriptor {
            self.descriptor.clone()
        }

        fn validate_config(&self, _config: &NodeConfig) -> Result<(), ConfigError> {
            Ok(())
        }

        fn instantiate(
            &self,
            _context: &PrepareContext,
            _config: &NodeConfig,
        ) -> Result<Box<dyn RuntimeNode>, NodeError> {
            self.live_nodes.fetch_add(1, Ordering::Relaxed);
            Ok(Box::new(TestNode {
                live_nodes: Arc::clone(&self.live_nodes),
            }))
        }
    }

    impl RuntimeNode for TestNode {
        fn prepare(&mut self, _context: &PrepareContext) -> Result<(), NodeError> {
            Ok(())
        }

        fn process(&mut self, frame: AudioFrame) -> Result<Option<AudioFrame>, NodeError> {
            Ok(Some(frame))
        }
    }

    impl Drop for TestNode {
        fn drop(&mut self) {
            self.live_nodes.fetch_sub(1, Ordering::Relaxed);
        }
    }

    fn audio_port(name: &str, direction: PortDirection) -> PortSpec {
        PortSpec {
            name: name.to_owned(),
            direction,
            media: MediaCaps::Audio(AudioCaps {
                sample_rate_hz: Some(48_000),
                frame_samples: Some(960),
                channel_layout: ChannelLayout::Mono,
                format: SampleFormat::F32Interleaved,
            }),
            multiplicity: Multiplicity::One,
            required: true,
        }
    }

    fn descriptor(
        node_type_id: &'static str,
        partition: ExecutionPartition,
        role: TestNodeRole,
    ) -> NodeDescriptor {
        let (inputs, outputs) = match role {
            TestNodeRole::Source => (Vec::new(), vec![audio_port("audio", PortDirection::Output)]),
            TestNodeRole::Endpoint => (vec![audio_port("audio", PortDirection::Input)], Vec::new()),
        };
        NodeDescriptor {
            type_id: NodeTypeId::from(node_type_id),
            display_name: "Explicit runtime preparation test node",
            inputs,
            outputs,
            execution: partition,
            realtime_safe: partition.requires_realtime_safety(),
            stateful: true,
        }
    }

    fn registries(
        endpoint_partition: ExecutionPartition,
        live_nodes: &Arc<AtomicUsize>,
    ) -> (NodeRegistry, OperatorRegistry) {
        let mut node_registry = NodeRegistry::new();
        for node_type_id in [
            APPLICATION_SOURCE_NODE_TYPE_ID,
            MICROPHONE_SOURCE_NODE_TYPE_ID,
        ] {
            node_registry.register(Arc::new(TestFactory {
                descriptor: descriptor(
                    node_type_id,
                    ExecutionPartition::RealtimeCpu,
                    TestNodeRole::Source,
                ),
                live_nodes: Arc::clone(live_nodes),
            }));
        }
        for node_type_id in [
            CONNECTOR_NODE_TYPE_ID,
            BROWSER_NODE_TYPE_ID,
            RECORDER_NODE_TYPE_ID,
        ] {
            node_registry.register(Arc::new(TestFactory {
                descriptor: descriptor(node_type_id, endpoint_partition, TestNodeRole::Endpoint),
                live_nodes: Arc::clone(live_nodes),
            }));
        }

        let mut operator_registry = OperatorRegistry::new();
        for (operator_id, node_type_id) in [
            (TEST_CONNECTOR_OPERATOR_ID, CONNECTOR_NODE_TYPE_ID),
            (BROWSER_OPERATOR_ID, BROWSER_NODE_TYPE_ID),
            (RECORDER_OPERATOR_ID, RECORDER_NODE_TYPE_ID),
        ] {
            operator_registry
                .register(OperatorId::new(operator_id), NodeTypeId::from(node_type_id))
                .expect("test operator registration must succeed");
        }
        (node_registry, operator_registry)
    }

    fn product_spec() -> SessionSpec {
        let session = Session::new();
        let application = session
            .capture(Source::application(ApplicationSelector::name(
                "Meeting App",
            )))
            .expect("application declaration must succeed");
        let microphone = session
            .capture(Source::microphone_default())
            .expect("microphone declaration must succeed");
        let connector = session
            .connector(
                OperatorId::new(TEST_CONNECTOR_OPERATOR_ID),
                EndpointConfiguration::new(),
            )
            .expect("connector declaration must succeed");
        let browser = session
            .browser("wss://receiver.example.test")
            .expect("browser declaration must succeed");

        for stem in [&application, &microphone] {
            stem.send(connector).expect("connector route must succeed");
            stem.send(browser).expect("browser route must succeed");
        }
        application
            .record("application")
            .expect("application recording route must succeed");
        microphone
            .record("microphone")
            .expect("microphone recording route must succeed");
        session.freeze().expect("product spec must freeze")
    }

    fn prepare_context() -> PrepareContext {
        PrepareContext::new(SampleSpec::new(48_000, 1, SampleFormat::F32Interleaved))
    }

    #[test]
    fn given_product_plan_when_prepared_then_two_sources_and_six_workers_are_owned() {
        let live_nodes = Arc::new(AtomicUsize::new(0));
        let (node_registry, operator_registry) =
            registries(ExecutionPartition::AsyncWorker, &live_nodes);
        let compiled = SessionCompiler::new(&node_registry, &operator_registry)
            .compile(product_spec())
            .expect("product Session must compile");

        let prepared = prepare_session_runtime(compiled, &node_registry, &prepare_context(), 8)
            .expect("runtime preparation must succeed");

        assert_eq!(prepared.source_mappings().len(), 2);
        assert_eq!(prepared.source_input_count(), 2);
        assert_eq!(prepared.worker_mappings().len(), 6);
        assert!(prepared
            .source_mappings()
            .iter()
            .all(|mapping| mapping.sender_observations().queue_capacity_frames == 8));
        assert_eq!(
            prepared
                .source_inputs
                .iter()
                .map(PlanSourceInput::source_node_id)
                .collect::<HashSet<_>>()
                .len(),
            2
        );
        assert_eq!(
            prepared
                .worker_mappings()
                .iter()
                .map(PreparedWorkerMapping::route_id)
                .collect::<HashSet<_>>()
                .len(),
            6
        );
        assert_eq!(
            prepared
                .worker_mappings()
                .iter()
                .map(|mapping| mapping.receiver.edge_id())
                .collect::<HashSet<_>>()
                .len(),
            6
        );
        assert_eq!(live_nodes.load(Ordering::Relaxed), 2);
        drop(prepared);
        assert_eq!(live_nodes.load(Ordering::Relaxed), 0);
    }

    #[test]
    fn given_worker_partition_mismatch_when_prepared_then_error_is_typed_and_nodes_roll_back() {
        let live_nodes = Arc::new(AtomicUsize::new(0));
        let (node_registry, operator_registry) =
            registries(ExecutionPartition::RealtimeCpu, &live_nodes);
        let compiled = SessionCompiler::new(&node_registry, &operator_registry)
            .compile(product_spec())
            .expect("mismatched product Session must still compile");

        let result = prepare_session_runtime(compiled, &node_registry, &prepare_context(), 8);

        assert!(matches!(
            result,
            Err(SessionPrepareError::WorkerReceiverCountMismatch {
                expected_routes: 6,
                actual_receivers: 0,
            })
        ));
        assert_eq!(live_nodes.load(Ordering::Relaxed), 0);
    }

    #[test]
    fn given_unknown_worker_route_when_prepared_then_error_is_typed_and_nodes_roll_back() {
        let live_nodes = Arc::new(AtomicUsize::new(0));
        let (node_registry, operator_registry) =
            registries(ExecutionPartition::AsyncWorker, &live_nodes);
        let mut compiled = SessionCompiler::new(&node_registry, &operator_registry)
            .compile(product_spec())
            .expect("product Session must compile");
        let endpoint_node = compiled
            .graph_ir_mut()
            .nodes
            .iter_mut()
            .find(|node| node.spec.config.get("route_id").is_some())
            .expect("compiled endpoint node must carry route identity");
        endpoint_node.spec.config = endpoint_node.spec.config.clone().with("route_id", "999999");

        let result = prepare_session_runtime(compiled, &node_registry, &prepare_context(), 8);

        assert!(matches!(
            result,
            Err(SessionPrepareError::UnknownWorkerRoute {
                route_id: RouteId(999_999),
                ..
            })
        ));
        assert_eq!(live_nodes.load(Ordering::Relaxed), 0);
    }

    #[test]
    fn given_zero_source_capacity_when_prepared_then_error_is_typed_and_nodes_roll_back() {
        let live_nodes = Arc::new(AtomicUsize::new(0));
        let (node_registry, operator_registry) =
            registries(ExecutionPartition::AsyncWorker, &live_nodes);
        let compiled = SessionCompiler::new(&node_registry, &operator_registry)
            .compile(product_spec())
            .expect("product Session must compile");

        let result = prepare_session_runtime(compiled, &node_registry, &prepare_context(), 0);

        assert!(matches!(
            result,
            Err(SessionPrepareError::SourceChannel(
                PlanRunnerError::ZeroSourceCapacity { .. }
            ))
        ));
        assert_eq!(live_nodes.load(Ordering::Relaxed), 0);
    }
}