Skip to main content

dora_core/descriptor/
expand.rs

1use super::classify;
2use dora_message::{
3    config::{Input, InputMapping, LogSubscriptionFilter, UserInputMapping},
4    descriptor::{
5        DYNAMIC_SOURCE, Descriptor, EnvValue, Node, OperatorConfig, OperatorSource, SHELL_SOURCE,
6    },
7    id::{DataId, NodeId},
8};
9use eyre::{Context, bail};
10use serde::Deserialize;
11use std::{
12    collections::{BTreeMap, BTreeSet, HashSet},
13    path::{Path, PathBuf},
14};
15
16use super::normalize_path;
17
18/// Check if a path string is absolute on any platform.
19/// On Windows, `Path::is_absolute()` returns false for Unix-style `/foo` paths,
20/// so we also check for a leading `/` to catch cross-platform absolute paths.
21fn is_absolute_any_platform(path: &str) -> bool {
22    Path::new(path).is_absolute() || path.starts_with('/')
23}
24
25/// Maximum nesting depth for recursive module expansion. Prevents unbounded
26/// recursion from deeply nested or circular module graphs that evade the
27/// path-based cycle check. 8 levels covers realistic robotics pipelines
28/// while keeping memory usage bounded.
29const MAX_MODULE_DEPTH: u8 = 8;
30
31/// Maximum module file size (1 MB). Prevents DoS from huge or infinite files.
32const MAX_MODULE_FILE_SIZE: u64 = 1_048_576;
33
34/// Reserved node-ID prefix used inside module files to reference module inputs.
35/// Usage in module YAML: `_mod/port_name`
36const MODULE_INPUT_SOURCE: &str = "_mod";
37
38const MODULE_DIR_TOKEN: &str = "$MODULE_DIR";
39
40/// Where the outputs a module declares end up after expansion: maps each
41/// declared output name to the mapping a consumer must use to read it — the
42/// prefixed inner node ID plus the output name as that node addresses it
43/// (see [`node_output_refs`]).
44type ModuleOutputMap = BTreeMap<String, UserInputMapping>;
45
46/// Header section of a module definition file.
47#[derive(Debug, Clone, Deserialize)]
48#[serde(deny_unknown_fields)]
49struct ModuleHeader {
50    name: String,
51    #[serde(default)]
52    inputs: Vec<DataId>,
53    #[serde(default)]
54    inputs_optional: Vec<DataId>,
55    #[serde(default)]
56    outputs: Vec<DataId>,
57}
58
59/// A module definition file (`*_module.yml`).
60#[derive(Debug, Clone, Deserialize)]
61#[serde(deny_unknown_fields)]
62struct ModuleFile {
63    module: ModuleHeader,
64    nodes: Vec<Node>,
65    /// Module-level build command, runs before inner node builds.
66    #[serde(default)]
67    build: Option<String>,
68}
69
70/// Metadata about which nodes came from which module, used for graph
71/// visualization with subgraph boundaries.
72#[derive(Debug, Clone, Default)]
73pub struct ModuleBoundaries {
74    /// Maps module_id -> list of expanded node IDs that belong to it.
75    pub modules: BTreeMap<String, Vec<String>>,
76}
77
78/// Result of expanding modules, including boundary metadata for visualization.
79#[derive(Debug, Clone)]
80pub struct ExpandedDescriptor {
81    pub descriptor: Descriptor,
82    pub boundaries: ModuleBoundaries,
83}
84
85/// Expand all module references in `descriptor` into flat nodes.
86///
87/// Module nodes are replaced by the inner nodes from the referenced module
88/// file. Internal IDs are prefixed with `{module_id}.` and all input/output
89/// wiring is rewritten so the result is a plain flat descriptor.
90pub fn expand_modules(descriptor: &Descriptor, base_dir: &Path) -> eyre::Result<Descriptor> {
91    Ok(expand_modules_with_boundaries(descriptor, base_dir)?.descriptor)
92}
93
94/// Like [`expand_modules`] but also returns module boundary metadata for
95/// visualization.
96pub fn expand_modules_with_boundaries(
97    descriptor: &Descriptor,
98    base_dir: &Path,
99) -> eyre::Result<ExpandedDescriptor> {
100    let has_modules = descriptor.nodes.iter().any(|n| n.module.is_some());
101    if !has_modules {
102        return Ok(ExpandedDescriptor {
103            descriptor: descriptor.clone(),
104            boundaries: ModuleBoundaries::default(),
105        });
106    }
107
108    let project_root = normalize_path(dunce::simplified(
109        &std::path::absolute(base_dir)
110            .with_context(|| format!("failed to make base_dir absolute: {}", base_dir.display()))?,
111    ));
112    let canonical_project_root = dunce::canonicalize(&project_root)
113        .with_context(|| format!("failed to resolve project root: {}", project_root.display()))?;
114    let mut seen = HashSet::new();
115    let mut flat_nodes = Vec::new();
116    let mut output_maps: BTreeMap<String, ModuleOutputMap> = BTreeMap::new();
117    let mut boundaries = ModuleBoundaries::default();
118
119    for node in &descriptor.nodes {
120        if node.module.is_some() {
121            // Field validation happens inside `expand_module_node`, so top-level
122            // and nested module nodes go through the same whitelist.
123            let (mut expanded, omap) = expand_module_node(
124                node,
125                base_dir,
126                &project_root,
127                &canonical_project_root,
128                0,
129                &mut seen,
130            )?;
131            // Propagate the module node's own `build` to each expanded leaf node,
132            // mirroring how a nested module node's build is propagated in Phase 2
133            // of `expand_module_node`. `check_module` accepts `build` for exactly
134            // this reason.
135            if let Some(ref outer_build) = node.build {
136                for expanded_node in &mut expanded {
137                    prepend_module_build_to_node(expanded_node, outer_build);
138                }
139            }
140            let module_id = node.id.to_string();
141            output_maps.insert(module_id.clone(), omap);
142            let node_ids: Vec<String> = expanded.iter().map(|n| n.id.to_string()).collect();
143            boundaries.modules.insert(module_id, node_ids);
144            flat_nodes.extend(expanded);
145        } else {
146            flat_nodes.push(node.clone());
147        }
148    }
149
150    rewrite_external_refs(&mut flat_nodes, &output_maps)?;
151
152    // Verify expanded node IDs are unique
153    let mut id_set = HashSet::new();
154    for node in &flat_nodes {
155        if !id_set.insert(node.id.to_string()) {
156            bail!(
157                "duplicate node ID `{}` after module expansion — check for \
158                 conflicting node names across modules and top-level nodes",
159                node.id
160            );
161        }
162    }
163
164    // Expansion rewrites `nodes` and nothing else, so clone the source
165    // descriptor and swap that one field. Listing the dataflow-level options
166    // individually would silently drop any option added later — `Descriptor` is
167    // `#[non_exhaustive]`, so a missing field is no longer a compile error. This
168    // also keeps the with-modules path structurally identical to the early
169    // return above, which already clones.
170    let mut expanded = descriptor.clone();
171    expanded.nodes = flat_nodes;
172
173    Ok(ExpandedDescriptor {
174        descriptor: expanded,
175        boundaries,
176    })
177}
178
179/// Validate a module file in isolation without expanding it into a dataflow.
180///
181/// Checks:
182/// - Module header is well-formed (required name, optional inputs/outputs)
183/// - All inner nodes are parseable
184/// - All `_mod/X` references point to declared inputs or optional inputs
185/// - All declared outputs are produced by some inner node (or nested module)
186/// - No circular references within the module
187pub fn check_module_file(module_path: &Path) -> eyre::Result<()> {
188    let canonical = module_path
189        .canonicalize()
190        .with_context(|| format!("module file not found: {}", module_path.display()))?;
191    let mut seen = HashSet::new();
192    check_module_file_inner(&canonical, 0, &mut seen)
193}
194
195fn check_module_file_inner(
196    canonical: &Path,
197    depth: u8,
198    seen: &mut HashSet<PathBuf>,
199) -> eyre::Result<()> {
200    if depth >= MAX_MODULE_DEPTH {
201        bail!(
202            "module nesting exceeds depth limit of {MAX_MODULE_DEPTH} while checking module file: {}",
203            canonical.display()
204        );
205    }
206
207    if !seen.insert(canonical.to_path_buf()) {
208        bail!(
209            "circular module reference detected while checking module file: {}\n\
210             hint: check that module files do not reference each other in a cycle",
211            canonical.display()
212        );
213    }
214
215    let module_file = load_module_file(canonical, ".")?;
216    validate_module_header(&module_file.module)?;
217    let module_dir = canonical
218        .parent()
219        .expect("module file must have a parent directory");
220
221    // Collect all declared + optional input names
222    let all_input_names: BTreeSet<String> = module_file
223        .module
224        .inputs
225        .iter()
226        .chain(module_file.module.inputs_optional.iter())
227        .map(|d| d.to_string())
228        .collect();
229
230    // Check _mod/ references point to declared inputs. Runtime (operator)
231    // and legacy custom nodes wire their inputs through config.inputs /
232    // run_config.inputs rather than the node-level `inputs` map, so those
233    // need the same check (see #2441).
234    for node in &module_file.nodes {
235        reject_path_fallback(node, Some(&module_file.module.name))?;
236        for inputs in node_input_maps(node) {
237            check_mod_refs(&module_file.module.name, &node.id, inputs, &all_input_names)?;
238        }
239    }
240    let module_outputs = collect_module_source_outputs(&module_file, module_dir)?;
241    check_internal_wiring(
242        &module_file.module.name,
243        &module_file.nodes,
244        &module_outputs,
245    )?;
246
247    // Check outputs: each declared output should be produced by some inner node.
248    // For nested module children, recursively load their declared outputs.
249    // Runtime (operator) and legacy custom nodes declare their outputs in
250    // config.outputs / run_config.outputs rather than the node-level `outputs`
251    // set, so `node_output_refs` collects those too (see #2817).
252    let mut inner_outputs: BTreeMap<String, Vec<String>> = BTreeMap::new();
253    for node in module_file.nodes.iter().filter(|n| n.module.is_none()) {
254        for (name, output_ref) in node_output_refs(node) {
255            inner_outputs
256                .entry(name)
257                .or_default()
258                .push(format!("{}/{}", node.id, output_ref));
259        }
260    }
261
262    // Check nested module files exist and collect their declared outputs
263    for node in &module_file.nodes {
264        if let Some(ref mod_path) = node.module {
265            if is_absolute_any_platform(mod_path) {
266                bail!(
267                    "module `{}`: nested module path `{}` must be relative (node `{}`)",
268                    module_file.module.name,
269                    mod_path,
270                    node.id,
271                );
272            }
273            // The same field whitelist applies at every nesting level.
274            // Without this, `dora expand --module m.yml` reports a file as
275            // valid while `dora run` on a dataflow using it hard-fails.
276            classify::check_module(node)
277                .with_context(|| format!("invalid module node `{}`", node.id))?;
278            let nested = module_dir.join(mod_path);
279            let nested_canonical = nested.canonicalize().with_context(|| {
280                format!(
281                    "module `{}`: nested module `{}` referenced by node `{}` not found",
282                    module_file.module.name, mod_path, node.id,
283                )
284            })?;
285            // Note: unlike `expand_module_node`, we intentionally do NOT reject
286            // a nested reference that leaves `module_dir`. The real expansion
287            // path confines nested modules to the *project root*
288            // (`project_root`, threaded through recursion), which routinely
289            // sits above an individual module's directory -- a module in
290            // `modules/a/` may reference a sibling module in `modules/shared/`
291            // via `../shared/base.yml`. This linter runs on a module file in
292            // isolation, with no project root to bound against, so a
293            // `module_dir` containment check would spuriously reject
294            // cross-directory references that `dora run` / `dora build` accept
295            // and run fine (see #2851). We keep the absolute-path rejection and
296            // the `canonicalize()` existence check above; the containment
297            // boundary is enforced by the real expansion path, not this lint.
298            //
299            // Load nested module to collect its declared outputs.
300            let nested_module = load_module_file(&nested_canonical, ".")?;
301            check_nested_module_required_inputs(
302                &module_file.module.name,
303                &node.id,
304                &nested_module.module,
305                &node.inputs,
306            )?;
307            check_module_file_inner(&nested_canonical, depth + 1, seen).with_context(|| {
308                format!(
309                    "module `{}`: while checking nested module `{}` referenced by node `{}`",
310                    module_file.module.name, nested_module.module.name, node.id,
311                )
312            })?;
313            for output in &nested_module.module.outputs {
314                inner_outputs
315                    .entry(output.to_string())
316                    .or_default()
317                    .push(format!("{}/{}", node.id, output));
318            }
319        }
320    }
321
322    for declared_output in &module_file.module.outputs {
323        let output_str = declared_output.to_string();
324        match inner_outputs.get(&output_str) {
325            None => {
326                bail!(
327                    "module `{}` declares output `{}` but no inner node produces it",
328                    module_file.module.name,
329                    declared_output,
330                );
331            }
332            Some(producers) if producers.len() > 1 => {
333                bail!(
334                    "module `{}` declares output `{}` but multiple inner nodes produce it: {}",
335                    module_file.module.name,
336                    declared_output,
337                    producers.join(", "),
338                );
339            }
340            Some(_) => {}
341        }
342    }
343
344    seen.remove(canonical);
345    Ok(())
346}
347
348fn collect_module_source_outputs(
349    module_file: &ModuleFile,
350    module_dir: &Path,
351) -> eyre::Result<BTreeMap<String, BTreeSet<String>>> {
352    let mut outputs = BTreeMap::new();
353    for node in &module_file.nodes {
354        let node_id = node.id.to_string();
355        if outputs.contains_key(&node_id) {
356            bail!(
357                "module `{}` has duplicate node ID `{}`",
358                module_file.module.name,
359                node.id,
360            );
361        }
362
363        let node_outputs = if let Some(ref mod_path) = node.module {
364            if is_absolute_any_platform(mod_path) {
365                bail!(
366                    "module `{}`: nested module path `{}` must be relative (node `{}`)",
367                    module_file.module.name,
368                    mod_path,
369                    node.id,
370                );
371            }
372            let nested = module_dir.join(mod_path);
373            let nested_canonical = nested.canonicalize().with_context(|| {
374                format!(
375                    "module `{}`: nested module `{}` referenced by node `{}` not found",
376                    module_file.module.name, mod_path, node.id,
377                )
378            })?;
379            let nested_module = load_module_file(&nested_canonical, ".")?;
380            nested_module
381                .module
382                .outputs
383                .iter()
384                .map(|output| output.to_string())
385                .collect()
386        } else {
387            node_output_refs(node)
388                .into_iter()
389                .map(|(_, output_ref)| output_ref)
390                .collect()
391        };
392
393        outputs.insert(node_id, node_outputs);
394    }
395    Ok(outputs)
396}
397
398fn check_internal_wiring(
399    module_name: &str,
400    nodes: &[Node],
401    module_outputs: &BTreeMap<String, BTreeSet<String>>,
402) -> eyre::Result<()> {
403    for node in nodes {
404        for inputs in node_input_maps(node) {
405            for (input_id, input) in inputs {
406                if let InputMapping::User(mapping) = &input.mapping {
407                    let source = mapping.source.to_string();
408                    if source == MODULE_INPUT_SOURCE {
409                        continue;
410                    }
411                    if let Some(outputs) = module_outputs.get(&source) {
412                        let output = mapping.output.to_string();
413                        if !outputs.contains(&output) {
414                            bail!(
415                                "module `{}`: node `{}` input `{}` references \
416                                 `{}/{}` but that output is not produced",
417                                module_name,
418                                node.id,
419                                input_id,
420                                source,
421                                output,
422                            );
423                        }
424                    }
425                }
426            }
427        }
428    }
429    Ok(())
430}
431
432fn validate_module_header(module: &ModuleHeader) -> eyre::Result<()> {
433    reject_duplicate_ports(&module.name, "inputs", &module.inputs)?;
434    reject_duplicate_ports(&module.name, "inputs_optional", &module.inputs_optional)?;
435    reject_duplicate_ports(&module.name, "outputs", &module.outputs)?;
436
437    let required: BTreeSet<_> = module.inputs.iter().collect();
438    if let Some(overlap) = module
439        .inputs_optional
440        .iter()
441        .find(|input| required.contains(input))
442    {
443        bail!(
444            "module `{}` input `{}` is declared as both required and optional",
445            module.name,
446            overlap
447        );
448    }
449    Ok(())
450}
451
452fn reject_duplicate_ports(module_name: &str, field: &str, ports: &[DataId]) -> eyre::Result<()> {
453    let mut seen = BTreeSet::new();
454    for port in ports {
455        if !seen.insert(port) {
456            bail!("module `{module_name}` has duplicate `{field}` entry `{port}`");
457        }
458    }
459    Ok(())
460}
461
462fn check_nested_module_required_inputs(
463    module_name: &str,
464    node_id: &NodeId,
465    nested_module: &ModuleHeader,
466    node_inputs: &BTreeMap<DataId, Input>,
467) -> eyre::Result<()> {
468    for declared_input in &nested_module.inputs {
469        if !node_inputs.contains_key(declared_input) {
470            bail!(
471                "module `{}`: nested module `{}` declares required input `{}` \
472                 but node `{}` does not provide it",
473                module_name,
474                nested_module.name,
475                declared_input,
476                node_id,
477            );
478        }
479    }
480    Ok(())
481}
482
483/// Check that every `_mod/X` reference in `inputs` points to a declared
484/// module input (or optional input). Shared by the node-level `inputs`
485/// check and the operator/custom `config.inputs` / `run_config.inputs`
486/// checks in [`check_module_file`].
487fn check_mod_refs(
488    module_name: &str,
489    node_id: &NodeId,
490    inputs: &BTreeMap<DataId, Input>,
491    all_input_names: &BTreeSet<String>,
492) -> eyre::Result<()> {
493    for (input_id, input) in inputs {
494        if let InputMapping::User(m) = &input.mapping
495            && m.source.to_string() == MODULE_INPUT_SOURCE
496        {
497            let port = m.output.to_string();
498            if !all_input_names.contains(&port) {
499                bail!(
500                    "module `{}`: node `{}` input `{}` references \
501                         `_mod/{}` but `{}` is not declared in module \
502                         inputs or inputs_optional",
503                    module_name,
504                    node_id,
505                    input_id,
506                    port,
507                    port,
508                );
509            }
510        }
511    }
512    Ok(())
513}
514
515/// All the places a node's inputs can live: the node-level `inputs` map,
516/// plus the operator/custom `config.inputs` / `run_config.inputs` maps for
517/// runtime (operator) and legacy custom inner nodes. Centralizes the
518/// node-kind enumeration so `_mod/`-reference validation and rewriting stay
519/// in sync as node kinds are added or change (see #2441).
520fn node_input_maps(node: &Node) -> Vec<&BTreeMap<DataId, Input>> {
521    let mut maps = vec![&node.inputs];
522    if let Some(ref operators) = node.operators {
523        maps.extend(operators.operators.iter().map(|op| &op.config.inputs));
524    }
525    if let Some(ref operator) = node.operator {
526        maps.push(&operator.config.inputs);
527    }
528    maps
529}
530
531/// Mutable counterpart of [`node_input_maps`], used by the Phase 1 rewrite
532/// pass in [`expand_module_node`].
533fn node_input_maps_mut(node: &mut Node) -> Vec<&mut BTreeMap<DataId, Input>> {
534    let mut maps = vec![&mut node.inputs];
535    if let Some(ref mut operators) = node.operators {
536        maps.extend(
537            operators
538                .operators
539                .iter_mut()
540                .map(|op| &mut op.config.inputs),
541        );
542    }
543    if let Some(ref mut operator) = node.operator {
544        maps.push(&mut operator.config.inputs);
545    }
546    maps
547}
548
549/// Every output an inner node produces, as `(output_name, output_ref)` pairs
550/// where `output_ref` is how a consumer addresses that output on this node.
551///
552/// The two differ only for multi-operator runtime nodes: their outputs live in
553/// `operators[].config.outputs` and must be referenced as
554/// `<operator_id>/<output>`. Node-level `outputs` and single `operator:`
555/// outputs are both referenced by
556/// their bare name — for `operator:` the `op/` prefix is injected later by
557/// `resolve_aliases_and_set_defaults`, so adding it here would double it up.
558///
559/// Output-side counterpart of [`node_input_maps`]: centralizes the node-kind
560/// enumeration so module output resolution stays in sync as node kinds are
561/// added or change (see #2817).
562fn node_output_refs(node: &Node) -> Vec<(String, String)> {
563    fn bare(outputs: &BTreeSet<DataId>) -> impl Iterator<Item = (String, String)> {
564        outputs.iter().map(|o| (o.to_string(), o.to_string()))
565    }
566
567    let mut refs: Vec<(String, String)> = bare(&node.outputs).collect();
568    if let Some(ref operators) = node.operators {
569        for op in &operators.operators {
570            refs.extend(
571                op.config
572                    .outputs
573                    .iter()
574                    .map(|o| (o.to_string(), format!("{}/{o}", op.id))),
575            );
576        }
577    }
578    if let Some(ref operator) = node.operator {
579        refs.extend(bare(&operator.config.outputs));
580    }
581    refs
582}
583
584/// Expand a single module node into its constituent flat nodes.
585///
586/// Returns `(expanded_nodes, output_map)`; see [`ModuleOutputMap`].
587fn expand_module_node(
588    node: &Node,
589    base_dir: &Path,
590    project_root: &Path,
591    canonical_project_root: &Path,
592    depth: u8,
593    seen: &mut HashSet<PathBuf>,
594) -> eyre::Result<(Vec<Node>, ModuleOutputMap)> {
595    if depth >= MAX_MODULE_DEPTH {
596        bail!(
597            "module nesting exceeds depth limit of {MAX_MODULE_DEPTH} \
598             (node `{}`)",
599            node.id
600        );
601    }
602
603    // Validate the module node's fields against the module whitelist. This is
604    // the single validation site for both top-level and nested module nodes, so
605    // a field that has no meaning on a module node (e.g. `outputs`,
606    // `cpu_affinity`) is rejected here rather than silently dropped during
607    // expansion, at every nesting level.
608    classify::check_module(node).with_context(|| format!("invalid module node `{}`", node.id))?;
609
610    let module_path_str = node
611        .module
612        .as_ref()
613        .expect("expand_module_node called on non-module node");
614
615    // Security: reject absolute paths and path traversal
616    if is_absolute_any_platform(module_path_str) {
617        bail!(
618            "module path `{}` must be relative (node `{}`)",
619            module_path_str,
620            node.id
621        );
622    }
623
624    // Find the canonical target of the first symlink component, if any
625    let mut current = base_dir.to_path_buf();
626    let mut symlink_target_root: Option<PathBuf> = None;
627    for component in Path::new(module_path_str).components() {
628        match component {
629            std::path::Component::Normal(c) => {
630                current.push(c);
631                if let Ok(meta) = std::fs::symlink_metadata(&current)
632                    && meta.is_symlink()
633                    && symlink_target_root.is_none()
634                {
635                    symlink_target_root = dunce::canonicalize(&current).ok();
636                }
637            }
638            std::path::Component::ParentDir => {
639                if let Ok(meta) = std::fs::symlink_metadata(&current)
640                    && meta.is_symlink()
641                {
642                    let target = dunce::canonicalize(&current).ok();
643                    let is_in_tree = target
644                        .as_ref()
645                        .is_some_and(|t| t.starts_with(canonical_project_root));
646                    if !is_in_tree {
647                        bail!(
648                            "module path `{}` escapes the project directory (node `{}`)",
649                            module_path_str,
650                            node.id
651                        );
652                    }
653                }
654                current.pop();
655            }
656            _ => {}
657        }
658    }
659
660    let module_path = base_dir.join(module_path_str);
661    let canonical = dunce::canonicalize(&module_path)
662        .with_context(|| format!("module file not found: {}", module_path.display()))?;
663
664    let absolute_module = normalize_path(dunce::simplified(
665        &std::path::absolute(&module_path).with_context(|| {
666            format!(
667                "failed to make module path absolute: {}",
668                module_path.display()
669            )
670        })?,
671    ));
672    if !absolute_module.starts_with(project_root) {
673        bail!(
674            "module path `{}` escapes the project directory (node `{}`)",
675            module_path_str,
676            node.id
677        );
678    }
679
680    // Lexical and physical resolutions must name the same file. This prevents
681    // `..` traversal over symlinks from escaping, while leaving in-tree symlinks working.
682    if dunce::canonicalize(&absolute_module).ok().as_ref() != Some(&canonical) {
683        bail!(
684            "module path `{}` escapes the project directory (node `{}`)",
685            module_path_str,
686            node.id
687        );
688    }
689
690    // Confinement: the loaded physical file must either reside within the
691    // canonical project root, or within the canonical target of a symlink
692    // located inside the project directory.
693    let in_project = canonical.starts_with(canonical_project_root);
694    let in_symlink = symlink_target_root
695        .as_ref()
696        .is_some_and(|target| canonical.starts_with(target));
697
698    if !in_project && !in_symlink {
699        bail!(
700            "module path `{}` physically escapes the project directory (node `{}`)",
701            module_path_str,
702            node.id
703        );
704    }
705
706    if !seen.insert(canonical.clone()) {
707        bail!(
708            "circular module reference detected: {} (node `{}`)\n\
709             hint: check that module files do not reference each other \
710             in a cycle",
711            module_path.display(),
712            node.id
713        );
714    }
715
716    let module_id = node.id.to_string();
717    let module_dir = absolute_module
718        .parent()
719        .expect("module file must have a parent directory");
720
721    // Builds and nodes can run from a Git checkout or a custom working directory.
722    let physical_dir = canonical
723        .parent()
724        .ok_or_else(|| eyre::eyre!("module file has no parent: {}", canonical.display()))?
725        .to_string_lossy()
726        .replace(std::path::MAIN_SEPARATOR, "/");
727    let dir = physical_dir.as_str();
728    let mut module_file = load_module_file(&canonical, dir)?;
729    validate_module_header(&module_file.module)?;
730    expand_build_dir(&mut module_file.build, dir);
731
732    // Validate: all required module inputs are provided by the node's inputs
733    for declared_input in &module_file.module.inputs {
734        if !node.inputs.contains_key(declared_input) {
735            bail!(
736                "module `{}` declares required input `{}` but node `{}` \
737                 does not provide it\n\
738                 hint: add `{}: <source_node>/<output>` to the node's inputs",
739                module_file.module.name,
740                declared_input,
741                node.id,
742                declared_input,
743            );
744        }
745    }
746    // Optional inputs: no error if missing — inner nodes referencing them
747    // will simply have their input removed during rewrite.
748
749    // Build optional input set once for fast lookup
750    let optional_inputs: BTreeSet<String> = module_file
751        .module
752        .inputs_optional
753        .iter()
754        .map(|d| d.to_string())
755        .collect();
756    let declared_inputs: BTreeSet<String> = module_file
757        .module
758        .inputs
759        .iter()
760        .chain(module_file.module.inputs_optional.iter())
761        .map(|d| d.to_string())
762        .collect();
763    for provided_input in node.inputs.keys() {
764        let provided = provided_input.to_string();
765        if !declared_inputs.contains(&provided) {
766            bail!(
767                "module `{}` does not declare input `{}` provided by node `{}`\n\
768                 hint: declared inputs are: {}",
769                module_file.module.name,
770                provided_input,
771                node.id,
772                declared_inputs
773                    .iter()
774                    .cloned()
775                    .collect::<Vec<_>>()
776                    .join(", "),
777            );
778        }
779    }
780
781    // Validate and collect params
782    let mut seen_upper: BTreeMap<String, &String> = BTreeMap::new();
783    for key in node.params.keys() {
784        if !key.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') || key.is_empty() {
785            bail!(
786                "invalid param key `{}` in node `{}`: must be non-empty and \
787                 contain only [A-Za-z0-9_]",
788                key,
789                node.id
790            );
791        }
792        // Params are injected into the node env as `PARAM_<KEY>` with the key
793        // upper-cased (see `substitute_params_in_node`). Two keys that differ
794        // only in case (e.g. `mode` and `Mode`) would both map to `PARAM_MODE`,
795        // so one would silently overwrite the other. Reject the collision
796        // instead of dropping a param.
797        let upper = key.to_uppercase();
798        if let Some(existing) = seen_upper.insert(upper.clone(), key) {
799            bail!(
800                "param keys `{}` and `{}` in node `{}` collide: both map to the \
801                 env var `PARAM_{}`. Param keys must be unique case-insensitively.",
802                existing,
803                key,
804                node.id,
805                upper
806            );
807        }
808    }
809    let params = &node.params;
810
811    // Build set of inner node IDs for cross-reference rewriting
812    let inner_node_ids: BTreeSet<String> =
813        module_file.nodes.iter().map(|n| n.id.to_string()).collect();
814    // The subset that are themselves modules: only those expand into
815    // `<sibling>.<inner>` nodes a log filter can name.
816    let module_sibling_ids: BTreeSet<String> = module_file
817        .nodes
818        .iter()
819        .filter(|n| n.module.is_some())
820        .map(|n| n.id.to_string())
821        .collect();
822
823    // Phase 1: prefix IDs, rewrite inputs, resolve paths, substitute params
824    let mut prefixed_nodes = Vec::new();
825    for mut inner_node in module_file.nodes {
826        reject_path_fallback(&inner_node, Some(&module_file.module.name))?;
827        let prefixed_id: NodeId = format!("{module_id}.{}", inner_node.id).into();
828        inner_node.id = prefixed_id;
829
830        // Rewrite inputs (None = optional input not provided, skip it).
831        // Runtime (operator) nodes and legacy custom nodes wire their inputs
832        // through config.inputs / run_config.inputs rather than the
833        // node-level `inputs` map, so `node_input_maps_mut` rewrites all of
834        // them the same way — otherwise `_mod/` references and sibling
835        // cross-references wouldn't resolve for operator/custom inner nodes
836        // (see #2441).
837        for inputs in node_input_maps_mut(&mut inner_node) {
838            *inputs = rewrite_module_inputs_map(
839                inputs,
840                &module_id,
841                &node.inputs,
842                &inner_node_ids,
843                &module_sibling_ids,
844                &optional_inputs,
845            )?;
846        }
847
848        resolve_inner_node_paths(&mut inner_node, module_dir, project_root)?;
849
850        if let Some(args) = &mut inner_node.args {
851            *args = substitute_module_vars(args, params, Some(dir));
852        }
853        expand_build_dir(&mut inner_node.build, dir);
854        if let Some(op) = &mut inner_node.operator {
855            expand_build_dir(&mut op.config.build, dir);
856        }
857        if let Some(runtime) = &mut inner_node.operators {
858            for op in &mut runtime.operators {
859                expand_build_dir(&mut op.config.build, dir);
860            }
861        }
862
863        // Propagate deploy from module node to inner nodes
864        if inner_node.deploy.is_none() {
865            inner_node.deploy = node.deploy.clone();
866        }
867
868        propagate_module_node_env(&mut inner_node, node.env.as_ref());
869
870        // Substitute params in env values
871        if !params.is_empty() {
872            substitute_params_in_node(&mut inner_node, params)
873                .wrap_err_with(|| format!("module node `{}`", node.id))?;
874        }
875
876        // Prepend module-level build command to inner node builds
877        if let Some(ref module_build) = module_file.build {
878            prepend_module_build_to_node(&mut inner_node, module_build);
879        }
880
881        prefixed_nodes.push(inner_node);
882    }
883
884    // Phase 2: recursively expand nested modules (before building output map)
885    // Collect nested output maps so sibling nodes can reference nested module
886    // outputs correctly via rewrite_external_refs.
887    let mut nested_output_maps: BTreeMap<String, ModuleOutputMap> = BTreeMap::new();
888    let mut direct_output_targets: BTreeMap<String, Vec<(String, UserInputMapping)>> =
889        BTreeMap::new();
890    let mut final_nodes = Vec::new();
891    for inner_node in prefixed_nodes {
892        if inner_node.module.is_some() {
893            let nested_id = inner_node.id.to_string();
894            let accumulated_build = inner_node.build.clone();
895            let (mut nested, nested_omap) = expand_module_node(
896                &inner_node,
897                module_dir,
898                project_root,
899                canonical_project_root,
900                depth + 1,
901                seen,
902            )?;
903            // Propagate the outer module's accumulated build to each nested leaf node,
904            // mirroring how `deploy` is propagated through recursion.
905            if let Some(ref outer_build) = accumulated_build {
906                for nested_node in &mut nested {
907                    prepend_module_build_to_node(nested_node, outer_build);
908                }
909            }
910            for (output, target) in &nested_omap {
911                direct_output_targets
912                    .entry(output.clone())
913                    .or_default()
914                    .push((format!("{nested_id}/{output}"), target.clone()));
915            }
916            nested_output_maps.insert(nested_id, nested_omap);
917            final_nodes.extend(nested);
918        } else {
919            for (name, output_ref) in node_output_refs(&inner_node) {
920                // `output_ref` may be an operator-qualified `<op_id>/<output>`
921                // form, and `OperatorId` is unvalidated, so parse fallibly
922                // instead of `output_ref.into()` — `DataId::from` panics on
923                // characters outside `[a-zA-Z0-9_./-]`, which would abort
924                // expansion on an otherwise-parseable descriptor. Mirrors
925                // `prefix_output_with_operator_id` in `descriptor/mod.rs`.
926                let output: DataId = output_ref.parse().map_err(|e| {
927                    eyre::eyre!(
928                        "node `{}` produces an invalid output id `{output_ref}`: {e}",
929                        inner_node.id
930                    )
931                })?;
932                direct_output_targets.entry(name).or_default().push((
933                    format!("{}/{output}", inner_node.id),
934                    UserInputMapping {
935                        source: inner_node.id.clone(),
936                        output,
937                    },
938                ));
939            }
940            final_nodes.push(inner_node);
941        }
942    }
943
944    // Rewrite sibling references that point to nested module outputs
945    if !nested_output_maps.is_empty() {
946        rewrite_external_refs(&mut final_nodes, &nested_output_maps)?;
947    }
948
949    // Phase 3: build output map from direct children only. A producer may
950    // be a plain node, a runtime node's operator, or a legacy custom node, so
951    // the lookup goes through `node_output_refs` — which also yields the form
952    // consumers must use to address the output (see #2817).
953    let mut output_map = ModuleOutputMap::new();
954    for declared_output in &module_file.module.outputs {
955        let declared = declared_output.to_string();
956        let target = match direct_output_targets.get(&declared).map(Vec::as_slice) {
957            None | Some([]) => {
958                bail!(
959                    "module `{}` declares output `{}` but no inner node produces it",
960                    module_file.module.name,
961                    declared_output,
962                );
963            }
964            Some([(_, target)]) => target.clone(),
965            Some(targets) => {
966                let producers = targets
967                    .iter()
968                    .map(|(producer, _)| producer.as_str())
969                    .collect::<Vec<_>>()
970                    .join(", ");
971                bail!(
972                    "module `{}` declares output `{}` but multiple inner nodes produce it: {}",
973                    module_file.module.name,
974                    declared_output,
975                    producers,
976                );
977            }
978        };
979        output_map.insert(declared, target);
980    }
981
982    // Remove from seen so the same module file can be used in different
983    // branches (multiple instances)
984    seen.remove(&canonical);
985
986    Ok((final_nodes, output_map))
987}
988
989/// `path_fallback` is internal: expansion sets it on a module's inner nodes,
990/// so a file the user writes (a dataflow file, a module file, or a node file
991/// for `dora node add`/`replace`) must not set it.
992pub fn reject_path_fallback(node: &Node, module: Option<&str>) -> eyre::Result<()> {
993    if node.path_fallback.is_some() {
994        let module = module
995            .map(|name| format!("module `{name}`: "))
996            .unwrap_or_default();
997        bail!(
998            "{module}node `{}` sets `path_fallback`, which is internal \
999             (module expansion sets it); remove it",
1000            node.id
1001        );
1002    }
1003    Ok(())
1004}
1005
1006fn resolve_inner_node_paths(
1007    node: &mut Node,
1008    module_dir: &Path,
1009    project_root: &Path,
1010) -> eyre::Result<()> {
1011    let owner = node.id.to_string();
1012    // A `git:` node's `path` is relative to its clone (the node's working dir
1013    // at build and spawn), not to the module file, so leave it untouched.
1014    if node.git.is_none()
1015        && let Some(ref mut path) = node.path
1016    {
1017        let as_written = path.clone();
1018        resolve_module_relative_path(path, module_dir, project_root, &owner)?;
1019        // A single extensionless name like `dora-echo` may also be a command
1020        // on `$PATH` rather than a file next to the module (#3826). `path`
1021        // keeps meaning the file; the name as written is what spawn falls
1022        // back to when there is none. A `hub:` node never runs from `path`
1023        // (hub resolution rejects one that has it), so it gets no fallback.
1024        if node.hub.is_none() && *path != as_written && is_bare_name(&as_written) {
1025            node.path_fallback = Some(as_written);
1026        }
1027    }
1028    if let Some(ref mut operators) = node.operators {
1029        for op in &mut operators.operators {
1030            resolve_operator_source_paths(&mut op.config, module_dir, project_root, &owner)?;
1031        }
1032    }
1033    if let Some(ref mut operator) = node.operator {
1034        resolve_operator_source_paths(&mut operator.config, module_dir, project_root, &owner)?;
1035    }
1036    Ok(())
1037}
1038
1039fn resolve_operator_source_paths(
1040    config: &mut OperatorConfig,
1041    module_dir: &Path,
1042    project_root: &Path,
1043    owner: &str,
1044) -> eyre::Result<()> {
1045    match &mut config.source {
1046        OperatorSource::SharedLibrary(path) | OperatorSource::Wasm(path) => {
1047            resolve_module_relative_path(path, module_dir, project_root, owner)
1048        }
1049        OperatorSource::Python(source) => {
1050            resolve_module_relative_path(&mut source.source, module_dir, project_root, owner)
1051        }
1052    }
1053}
1054
1055fn resolve_module_relative_path(
1056    path: &mut String,
1057    module_dir: &Path,
1058    project_root: &Path,
1059    owner: &str,
1060) -> eyre::Result<()> {
1061    // Resolve relative paths: make inner node/operator sources relative to
1062    // base_dir. Normalize lexically (collapse `..`) before the containment
1063    // check so paths like `../../evil` are detected even if the binary does
1064    // not exist yet (ruling out filesystem canonicalize).
1065    if path == DYNAMIC_SOURCE
1066        || path == SHELL_SOURCE
1067        || super::source_is_url(path)
1068        // `Path::is_absolute()` is false for a Unix-style `/foo` on Windows,
1069        // where `module_dir.join("/foo")` then rewrites it into the module
1070        // directory and the confinement check below rejects it with a
1071        // misleading "resolves outside the project directory".
1072        || is_absolute_any_platform(path)
1073    {
1074        return Ok(());
1075    }
1076
1077    let resolved = normalize_path(&module_dir.join(path.as_str()));
1078    let relative = resolved.strip_prefix(project_root).map_err(|_| {
1079        eyre::eyre!(
1080            "module node `{}` path `{}` resolves outside the project \
1081                 directory (resolved to `{}`)",
1082            owner,
1083            path,
1084            resolved.display()
1085        )
1086    })?;
1087    *path = relative.to_string_lossy().into_owned();
1088    Ok(())
1089}
1090
1091/// One plain file name without an extension, the form a command on `$PATH`
1092/// is written in (a console script, a binary). Reads only the string, so
1093/// `dora build` and `dora start` expand alike. A `:` (`C:tool` is a drive
1094/// path on Windows) or a `$` (the daemon expands variables in `path`) never
1095/// makes one. `worker.py` doesn't either: a script next to the module needs
1096/// no fallback, preserving their existing module-relative meaning.
1097/// Nor does a name made only of whitespace.
1098pub(super) fn is_bare_name(path: &str) -> bool {
1099    let name = Path::new(path);
1100    let mut components = name.components();
1101    !path.trim().is_empty()
1102        && !path.contains(['/', '\\', ':', '$'])
1103        && name.extension().is_none()
1104        && matches!(
1105            (components.next(), components.next()),
1106            (Some(std::path::Component::Normal(_)), None)
1107        )
1108}
1109
1110fn prepend_module_build_to_node(node: &mut Node, module_build: &str) {
1111    // The node-level `build` is consumed by every standard node -- `path:`,
1112    // `git:`, and `hub:` sourced -- (`build/mod.rs` reads `n.build` for all
1113    // `CoreNodeKind::Custom` nodes) and by nested `module:` nodes (which
1114    // forward it to their own leaves in Phase 2). It is *not* valid on
1115    // runtime/operator/ROS2 nodes, where the field classifier rejects it, so
1116    // for those the module build lands in the operator configs only.
1117    //
1118    // Do NOT key this off `node.path`: module expansion runs *before* git/hub
1119    // source resolution, so a `git:`/`hub:`-sourced inner node still has
1120    // `path == None` here. Keying off `path` silently dropped the module build
1121    // for those nodes (#3296). Gate on "not a runtime/operator/ROS2 node"
1122    // instead, which correctly includes git/hub standard leaves.
1123    let is_standard_or_module = node.module.is_some()
1124        || (node.operators.is_none() && node.operator.is_none() && node.ros2.is_none());
1125    if is_standard_or_module {
1126        prepend_build(&mut node.build, module_build);
1127    }
1128    if let Some(ref mut operators) = node.operators {
1129        for op in &mut operators.operators {
1130            prepend_build(&mut op.config.build, module_build);
1131        }
1132    }
1133    if let Some(ref mut operator) = node.operator {
1134        prepend_build(&mut operator.config.build, module_build);
1135    }
1136}
1137
1138fn prepend_build(build: &mut Option<String>, module_build: &str) {
1139    let existing = build.take();
1140    *build = Some(match existing {
1141        Some(existing) => format!("{module_build}\n{existing}"),
1142        None => module_build.to_string(),
1143    });
1144}
1145
1146/// Fill an inner node's `env` with entries from the module node that references
1147/// it.
1148///
1149/// The inner node's own `env` wins on conflict: the module node's entries only
1150/// fill keys the inner node did not set. This matches `merge_env`'s "per-node
1151/// entries override global ones" and the `deploy` propagation above, which also
1152/// only fills when the inner value is unset.
1153fn propagate_module_node_env(
1154    inner_node: &mut Node,
1155    module_env: Option<&BTreeMap<String, EnvValue>>,
1156) {
1157    let Some(module_env) = module_env.filter(|env| !env.is_empty()) else {
1158        return;
1159    };
1160    let env = inner_node.env.get_or_insert_with(BTreeMap::new);
1161    for (key, value) in module_env {
1162        env.entry(key.clone()).or_insert_with(|| value.clone());
1163    }
1164}
1165
1166/// Inject params into the node's env map as `EnvValue::String` entries.
1167/// A nested module node gets them in its own `params` instead.
1168///
1169/// An injected value has its `$VAR` references expanded here, as a YAML
1170/// `env:` value is when the dataflow is read: an `EnvValue` reaches the
1171/// coordinator and daemon as given and is not expanded there again (#3947).
1172fn substitute_params_in_node(
1173    node: &mut Node,
1174    params: &BTreeMap<String, String>,
1175) -> eyre::Result<()> {
1176    // A nested module node expands later with its own `params` only. Resolve
1177    // a forwarded `speed: $PARAM_SPEED` against ours and hand down the params
1178    // it does not set; its own expansion then substitutes them into its inner
1179    // nodes' args and injects them as env, as for a direct child.
1180    if node.module.is_some() {
1181        for value in node.params.values_mut() {
1182            *value = substitute_params_in_str(value, params);
1183        }
1184        for (key, value) in params {
1185            if !node.params.keys().any(|k| k.eq_ignore_ascii_case(key)) {
1186                node.params.insert(key.clone(), value.clone());
1187            }
1188        }
1189        return Ok(());
1190    }
1191
1192    // Inject params into env map (caller params override inner defaults)
1193    let env = node.env.get_or_insert_with(BTreeMap::new);
1194    for (key, value) in params {
1195        env.insert(
1196            format!("PARAM_{}", key.to_uppercase()),
1197            EnvValue::String(expand_env_references(value).wrap_err_with(|| {
1198                format!("failed to expand environment variables in param `{key}`")
1199            })?),
1200        );
1201    }
1202    Ok(())
1203}
1204
1205/// `value` with its `$VAR` / `${VAR}` references expanded, by the same rules
1206/// as a string in an `env:` block (`$$` is a literal `$`).
1207fn expand_env_references(value: &str) -> eyre::Result<String> {
1208    use serde::de::{IntoDeserializer, value::StrDeserializer};
1209    let deserializer: StrDeserializer<'_, serde::de::value::Error> = value.into_deserializer();
1210    Ok(serde_with_expand_env::with_expand_envs(deserializer)?)
1211}
1212
1213/// Replace every parameter reference with its value in a single left-to-right
1214/// pass. Two forms are accepted:
1215///
1216/// - `${_param.<key>}` -- delimited; the key is matched case-sensitively and
1217///   the closing brace terminates it.
1218/// - `$PARAM_<KEY>` -- the documented shell-style form (see `docs/modules.md`),
1219///   matched against the upper-cased key. Having no delimiter it extends over
1220///   the maximal run of `[A-Za-z0-9_]`, so `$PARAM_SPEED_LIMIT` is a single
1221///   token and never partially matches a declared `speed` (#2901).
1222///
1223/// A previous implementation looped over the params calling `String::replace`
1224/// on the accumulating result, which had two problems: the outcome depended on
1225/// `BTreeMap` key ordering, and a parameter *value* that itself contained a
1226/// `${_param.…}` token (or a literal one a user wanted to keep) was expanded
1227/// transitively. Scanning once and never re-examining substituted text makes
1228/// substitution simultaneous and order-independent. Unknown keys are left
1229/// verbatim, matching the old behavior of only replacing keys present in
1230/// `params`.
1231fn substitute_params_in_str(s: &str, params: &BTreeMap<String, String>) -> String {
1232    substitute_module_vars(s, params, None)
1233}
1234
1235fn expand_build_dir(build: &mut Option<String>, dir: &str) {
1236    if let Some(build) = build
1237        && build.contains('$')
1238    {
1239        *build = substitute_module_vars(build, &BTreeMap::new(), Some(dir));
1240    }
1241}
1242
1243fn substitute_module_vars(s: &str, params: &BTreeMap<String, String>, dir: Option<&str>) -> String {
1244    const BRACED: &str = "${_param.";
1245    const ENV_STYLE: &str = "$PARAM_";
1246
1247    // `$PARAM_<KEY>` matches against the uppercased param name, the same
1248    // mapping `substitute_params_in_node` uses for the injected env vars.
1249    // Keys that differ only in case are rejected before we get here, so this
1250    // map cannot silently drop a param.
1251    let env_style: BTreeMap<String, &String> = params
1252        .iter()
1253        .map(|(key, value)| (key.to_uppercase(), value))
1254        .collect();
1255
1256    let mut result = String::with_capacity(s.len());
1257    let mut rest = s;
1258    while let Some(start) = rest.find('$') {
1259        result.push_str(&rest[..start]);
1260        let at_token = &rest[start..];
1261
1262        if let Some(dir) = dir
1263            && let Some(tail) = at_token.strip_prefix("${MODULE_DIR}").or_else(|| {
1264                at_token.strip_prefix(MODULE_DIR_TOKEN).filter(|tail| {
1265                    !tail.starts_with(|c: char| c.is_ascii_alphanumeric() || c == '_')
1266                })
1267            })
1268        {
1269            result.push_str(dir);
1270            rest = tail;
1271        } else if let Some(after_prefix) = at_token.strip_prefix(BRACED) {
1272            match after_prefix.find('}') {
1273                Some(end) => {
1274                    let key = &after_prefix[..end];
1275                    match params.get(key) {
1276                        Some(value) => result.push_str(value),
1277                        // Unknown key: emit the token unchanged rather than dropping it.
1278                        None => {
1279                            result.push_str(BRACED);
1280                            result.push_str(key);
1281                            result.push('}');
1282                        }
1283                    }
1284                    // Continue *after* the closing brace so a substituted value is
1285                    // never re-scanned for further tokens.
1286                    rest = &after_prefix[end + 1..];
1287                }
1288                // No closing brace: emit the prefix literally and continue past it
1289                // (guarantees progress, so the loop always terminates).
1290                None => {
1291                    result.push_str(BRACED);
1292                    rest = after_prefix;
1293                }
1294            }
1295        } else if let Some(after_prefix) = at_token.strip_prefix(ENV_STYLE) {
1296            // The undelimited form ends at the first character that cannot be
1297            // part of a shell identifier, so `$PARAM_SPEED_LIMIT` is one token
1298            // and never matches a declared `speed` as a prefix (#2901).
1299            let end = after_prefix
1300                .find(|c: char| !c.is_ascii_alphanumeric() && c != '_')
1301                .unwrap_or(after_prefix.len());
1302            let key = &after_prefix[..end];
1303            match env_style.get(key) {
1304                Some(value) => result.push_str(value),
1305                // Unknown key: emit the token unchanged rather than dropping it.
1306                None => {
1307                    result.push_str(ENV_STYLE);
1308                    result.push_str(key);
1309                }
1310            }
1311            rest = &after_prefix[end..];
1312        } else {
1313            // A bare `$` that starts neither form: emit it and step past, so
1314            // the loop always makes progress.
1315            result.push('$');
1316            rest = &at_token[1..];
1317        }
1318    }
1319    result.push_str(rest);
1320    result
1321}
1322
1323/// Whether a log filter's `node` is one of `inner_node_ids`, or a node nested
1324/// under a module sibling (`<module-sibling>.<...>`, the id a nested module's
1325/// inner node gets once expanded).
1326///
1327/// Only module siblings count for the dotted form: node ids may contain `.`,
1328/// so with a plain sibling `cam`, `cam.raw` is an unrelated (top-level) node
1329/// and must be left alone.
1330fn names_sibling_or_its_inner_node(
1331    node: &str,
1332    inner_node_ids: &BTreeSet<String>,
1333    module_sibling_ids: &BTreeSet<String>,
1334) -> bool {
1335    inner_node_ids.contains(node)
1336        || node
1337            .match_indices('.')
1338            .any(|(i, _)| module_sibling_ids.contains(&node[..i]))
1339}
1340
1341/// Rewrite a single input mapping inside a module's inner node.
1342///
1343/// - `_mod/X` references are resolved to the actual source from the module
1344///   node's inputs map. Returns `None` if the port is optional and not provided.
1345/// - Internal cross-references (`sibling_node/output`) are prefixed with the
1346///   module ID.
1347/// - Timer inputs pass through unchanged.
1348fn rewrite_module_input(
1349    input: &Input,
1350    module_id: &str,
1351    module_inputs: &BTreeMap<DataId, Input>,
1352    inner_node_ids: &BTreeSet<String>,
1353    module_sibling_ids: &BTreeSet<String>,
1354    optional_inputs: &BTreeSet<String>,
1355) -> eyre::Result<Option<Input>> {
1356    match &input.mapping {
1357        // `dora/logs/<level>/<node>` naming a sibling, or an inner node of a
1358        // nested-module sibling (`<module-sibling>.<inner>`): prefix the node filter
1359        // like a sibling data source, or it would match no node after
1360        // expansion and the sink would silently receive nothing.
1361        InputMapping::Logs(LogSubscriptionFilter {
1362            min_level,
1363            node_filter: Some(node),
1364        }) if names_sibling_or_its_inner_node(
1365            node.as_ref(),
1366            inner_node_ids,
1367            module_sibling_ids,
1368        ) =>
1369        {
1370            Ok(Some(Input {
1371                mapping: InputMapping::Logs(LogSubscriptionFilter {
1372                    min_level: min_level.clone(),
1373                    node_filter: Some(format!("{module_id}.{node}").into()),
1374                }),
1375                ..input.clone()
1376            }))
1377        }
1378        InputMapping::Timer { .. } | InputMapping::Logs(_) => Ok(Some(input.clone())),
1379        InputMapping::User(user_mapping) => {
1380            let source_str = user_mapping.source.to_string();
1381
1382            if source_str == MODULE_INPUT_SOURCE {
1383                // `_mod/port_name` -> resolve from module node's inputs
1384                let port_name = user_mapping.output.to_string();
1385                match module_inputs.get(&*port_name) {
1386                    Some(bound_input) => {
1387                        // Preserve queue_size/timeout from the inner node if set,
1388                        // otherwise fall back to the module node's binding
1389                        Ok(Some(Input {
1390                            mapping: bound_input.mapping.clone(),
1391                            queue_size: input.queue_size.or(bound_input.queue_size),
1392                            input_timeout: input.input_timeout.or(bound_input.input_timeout),
1393                            queue_policy: input.queue_policy.or(bound_input.queue_policy),
1394                        }))
1395                    }
1396                    None if optional_inputs.contains(&port_name) => Ok(None),
1397                    None => bail!(
1398                        "module input reference `_mod/{}` not found in module node inputs",
1399                        port_name,
1400                    ),
1401                }
1402            } else if inner_node_ids.contains(&source_str) {
1403                // Internal cross-reference: prefix with module_id
1404                Ok(Some(Input {
1405                    mapping: InputMapping::User(UserInputMapping {
1406                        source: format!("{module_id}.{source_str}").into(),
1407                        output: user_mapping.output.clone(),
1408                    }),
1409                    queue_size: input.queue_size,
1410                    input_timeout: input.input_timeout,
1411                    queue_policy: input.queue_policy,
1412                }))
1413            } else {
1414                // External reference — pass through unchanged
1415                Ok(Some(input.clone()))
1416            }
1417        }
1418    }
1419}
1420
1421/// Rewrite every input in `inputs` via [`rewrite_module_input`], dropping
1422/// entries whose optional module input wasn't provided. Used for both the
1423/// node-level `inputs` map and the operator/custom `config.inputs` /
1424/// `run_config.inputs` maps in Phase 1 of [`expand_module_node`].
1425fn rewrite_module_inputs_map(
1426    inputs: &BTreeMap<DataId, Input>,
1427    module_id: &str,
1428    module_inputs: &BTreeMap<DataId, Input>,
1429    inner_node_ids: &BTreeSet<String>,
1430    module_sibling_ids: &BTreeSet<String>,
1431    optional_inputs: &BTreeSet<String>,
1432) -> eyre::Result<BTreeMap<DataId, Input>> {
1433    let mut new_inputs = BTreeMap::new();
1434    for (input_id, input) in inputs {
1435        if let Some(new_input) = rewrite_module_input(
1436            input,
1437            module_id,
1438            module_inputs,
1439            inner_node_ids,
1440            module_sibling_ids,
1441            optional_inputs,
1442        )? {
1443            new_inputs.insert(input_id.clone(), new_input);
1444        }
1445    }
1446    Ok(new_inputs)
1447}
1448
1449/// Rewrite inputs across all nodes that reference module outputs.
1450///
1451/// If node X has input `nav_stack/cmd_vel` and `nav_stack` was a module whose
1452/// output `cmd_vel` is produced by inner node `controller`, rewrite to
1453/// `nav_stack.controller/cmd_vel`. If the producer is an operator of a runtime
1454/// node, the rewritten output keeps the operator segment the runtime node
1455/// requires: `nav_stack.runtime/controller_op/cmd_vel`.
1456fn rewrite_external_refs(
1457    nodes: &mut [Node],
1458    output_maps: &BTreeMap<String, ModuleOutputMap>,
1459) -> eyre::Result<()> {
1460    if output_maps.is_empty() {
1461        return Ok(());
1462    }
1463
1464    for node in nodes.iter_mut() {
1465        rewrite_inputs_map(&mut node.inputs, output_maps, &node.id)?;
1466
1467        if let Some(ref mut operators) = node.operators {
1468            for op in &mut operators.operators {
1469                rewrite_inputs_map(&mut op.config.inputs, output_maps, &node.id)?;
1470            }
1471        }
1472        if let Some(ref mut operator) = node.operator {
1473            rewrite_inputs_map(&mut operator.config.inputs, output_maps, &node.id)?;
1474        }
1475    }
1476    Ok(())
1477}
1478
1479fn rewrite_inputs_map(
1480    inputs: &mut BTreeMap<DataId, Input>,
1481    output_maps: &BTreeMap<String, ModuleOutputMap>,
1482    node_id: &NodeId,
1483) -> eyre::Result<()> {
1484    let mut new_inputs = BTreeMap::new();
1485    for (input_id, input) in inputs.iter() {
1486        let new_input = match &input.mapping {
1487            InputMapping::User(user_mapping) => {
1488                let source_str = user_mapping.source.to_string();
1489                if let Some(omap) = output_maps.get(&source_str) {
1490                    let output_str = user_mapping.output.to_string();
1491                    if let Some(target) = omap.get(&output_str) {
1492                        Input {
1493                            mapping: InputMapping::User(target.clone()),
1494                            queue_size: input.queue_size,
1495                            input_timeout: input.input_timeout,
1496                            queue_policy: input.queue_policy,
1497                        }
1498                    } else {
1499                        bail!(
1500                            "node `{}` references `{}/{}` but module `{}` \
1501                             does not declare output `{}`",
1502                            node_id,
1503                            source_str,
1504                            output_str,
1505                            source_str,
1506                            output_str,
1507                        );
1508                    }
1509                } else {
1510                    input.clone()
1511                }
1512            }
1513            InputMapping::Timer { .. } | InputMapping::Logs(_) => input.clone(),
1514        };
1515        new_inputs.insert(input_id.clone(), new_input);
1516    }
1517    *inputs = new_inputs;
1518    Ok(())
1519}
1520
1521fn load_module_file(path: &Path, dir: &str) -> eyre::Result<ModuleFile> {
1522    use std::io::Read as _;
1523    // Bound the read itself, not just a `metadata().len()` pre-check: that
1524    // check reports 0 for FIFOs/character devices (e.g. `/dev/zero`) and is
1525    // racy against a file being appended to, so it would sail past the cap and
1526    // then `std::fs::read` unboundedly — exactly the "infinite files" DoS the
1527    // limit is meant to prevent. `take(MAX + 1)` caps the read regardless of
1528    // what the file claims its size is; if we hit the cap we reject. Mirrors
1529    // the manifest loader in `crate::manifest`.
1530    let file = std::fs::File::open(path)
1531        .with_context(|| format!("failed to read module file: {}", path.display()))?;
1532    let mut buf = Vec::new();
1533    file.take(MAX_MODULE_FILE_SIZE + 1)
1534        .read_to_end(&mut buf)
1535        .with_context(|| format!("failed to read module file: {}", path.display()))?;
1536    if buf.len() as u64 > MAX_MODULE_FILE_SIZE {
1537        bail!(
1538            "module file too large (limit {} bytes): {}",
1539            MAX_MODULE_FILE_SIZE,
1540            path.display()
1541        );
1542    }
1543    let module = dora_message::descriptor::deserialize_module_yaml(&buf, dir)
1544        .with_context(|| format!("failed to parse module file: {}", path.display()))?;
1545    super::reject_duplicate_keys(&buf)
1546        .with_context(|| format!("failed to parse module file: {}", path.display()))?;
1547    Ok(module)
1548}
1549
1550#[cfg(test)]
1551mod tests {
1552    use super::*;
1553    use std::io::Write;
1554    use tempfile::TempDir;
1555
1556    fn write_file(dir: &Path, name: &str, content: &str) -> PathBuf {
1557        let path = dir.join(name);
1558        if let Some(parent) = path.parent() {
1559            std::fs::create_dir_all(parent).unwrap();
1560        }
1561        let mut f = std::fs::File::create(&path).unwrap();
1562        f.write_all(content.as_bytes()).unwrap();
1563        path
1564    }
1565
1566    fn parse_descriptor(yaml: &str) -> Descriptor {
1567        serde_yaml::from_str(yaml).unwrap()
1568    }
1569
1570    /// dora-rs/dora#2920: a dataflow-level setting that expansion drops is
1571    /// silently lost for every dataflow that uses modules. The completion
1572    /// policy decides whether the graph can ever end, so losing it turns a
1573    /// batch run into a hang.
1574    ///
1575    /// Both paths now clone the source descriptor, so this is a regression
1576    /// guard rather than the primary defense. The descriptor MUST still
1577    /// contain a module: without one, `expand_modules_with_boundaries`
1578    /// short-circuits before the expansion path this exercises.
1579    #[test]
1580    fn expand_preserves_exit_when_nodes_finish() {
1581        let tmp = TempDir::new().unwrap();
1582        let base = tmp.path();
1583        write_file(
1584            base,
1585            "echo_module.yml",
1586            r#"
1587module:
1588  name: echo
1589  inputs: [data_in]
1590  outputs: [data_out]
1591
1592nodes:
1593  - id: passthrough
1594    path: echo.py
1595    inputs:
1596      incoming: _mod/data_in
1597    outputs:
1598      - data_out
1599"#,
1600        );
1601        let descriptor = parse_descriptor(
1602            r#"
1603exit_when_nodes_finish: true
1604
1605nodes:
1606  - id: source
1607    path: source.py
1608    outputs:
1609      - number
1610
1611  - id: my_echo
1612    module: echo_module.yml
1613    inputs:
1614      data_in: source/number
1615"#,
1616        );
1617        assert_eq!(descriptor.exit_when_nodes_finish, Some(true));
1618        assert!(
1619            descriptor.nodes.iter().any(|n| n.module.is_some()),
1620            "precondition: without a module, expansion clones the whole \
1621             descriptor and this test would pass even if the rebuild \
1622             dropped the field"
1623        );
1624
1625        let expanded = expand_modules(&descriptor, base).unwrap();
1626        assert_eq!(
1627            expanded.exit_when_nodes_finish,
1628            Some(true),
1629            "expansion must carry the completion policy through, or a \
1630             module-using dataflow silently loses it and never ends"
1631        );
1632    }
1633
1634    /// Absent means absent: it must not become `Some(false)`, which
1635    /// would be indistinguishable from an explicit opt out and would
1636    /// start round-tripping into serialized output.
1637    #[test]
1638    fn expand_leaves_exit_when_nodes_finish_unset() {
1639        let tmp = TempDir::new().unwrap();
1640        let descriptor = parse_descriptor(
1641            "nodes:\n  \
1642               - id: worker\n    \
1643                 path: ./worker\n",
1644        );
1645        assert_eq!(descriptor.exit_when_nodes_finish, None);
1646        let expanded = expand_modules(&descriptor, tmp.path()).unwrap();
1647        assert_eq!(expanded.exit_when_nodes_finish, None);
1648    }
1649
1650    /// A module whose inner runtime node declares an operator with an id
1651    /// containing characters outside `[a-zA-Z0-9_./-]` must surface a clean
1652    /// descriptor error, not panic. `OperatorId` is unvalidated, so its id
1653    /// flows verbatim into the `<op_id>/<output>` qualified output id, which
1654    /// used to be built with `DataId::from` (panics) rather than a fallible
1655    /// parse.
1656    #[test]
1657    fn expand_rejects_invalid_operator_output_id_without_panicking() {
1658        let tmp = TempDir::new().unwrap();
1659        let base = tmp.path();
1660        write_file(
1661            base,
1662            "bad_module.yml",
1663            r#"
1664module:
1665  name: bad
1666  outputs: [data_out]
1667
1668nodes:
1669  - id: runtime_node
1670    operators:
1671      - id: "bad id"
1672        shared-library: op
1673        outputs:
1674          - data_out
1675"#,
1676        );
1677        let descriptor = parse_descriptor(
1678            r#"
1679nodes:
1680  - id: my_mod
1681    module: bad_module.yml
1682"#,
1683        );
1684        let err = expand_modules(&descriptor, base)
1685            .expect_err("an invalid operator output id must be a clean error, not a panic");
1686        let msg = err.to_string();
1687        assert!(msg.contains("invalid output id"), "unexpected error: {msg}");
1688    }
1689
1690    #[test]
1691    fn load_module_file_rejects_oversized_file() {
1692        let tmp = TempDir::new().unwrap();
1693        // A valid module prefix followed by padding that pushes the file just
1694        // over the cap. The read is bounded, so this is rejected before the
1695        // whole (potentially unbounded) file is pulled into memory.
1696        let mut content = String::from("module:\n  name: big\n  outputs: [x]\nnodes: []\n");
1697        content.push_str("# ");
1698        content.push_str(&"a".repeat((MAX_MODULE_FILE_SIZE + 16) as usize));
1699        let path = write_file(tmp.path(), "big_module.yml", &content);
1700
1701        let err = load_module_file(&path, ".").unwrap_err().to_string();
1702        assert!(err.contains("too large"), "unexpected error: {err}");
1703    }
1704
1705    #[test]
1706    fn load_module_file_accepts_file_at_limit() {
1707        let tmp = TempDir::new().unwrap();
1708        // Exactly the cap (padding the comment out to MAX_MODULE_FILE_SIZE
1709        // bytes total) must still load — the `+ 1` in `take` is what makes the
1710        // boundary inclusive.
1711        let prefix = "module:\n  name: ok\n  outputs: [x]\nnodes: []\n# ";
1712        let pad = (MAX_MODULE_FILE_SIZE as usize) - prefix.len();
1713        let content = format!("{prefix}{}", "a".repeat(pad));
1714        assert_eq!(content.len() as u64, MAX_MODULE_FILE_SIZE);
1715        let path = write_file(tmp.path(), "ok_module.yml", &content);
1716
1717        assert!(load_module_file(&path, ".").is_ok());
1718    }
1719
1720    #[test]
1721    fn expand_flat_passthrough() {
1722        let tmp = TempDir::new().unwrap();
1723        let base = tmp.path();
1724
1725        write_file(
1726            base,
1727            "echo_module.yml",
1728            r#"
1729module:
1730  name: echo
1731  inputs: [data_in]
1732  outputs: [data_out]
1733
1734nodes:
1735  - id: passthrough
1736    path: echo.py
1737    inputs:
1738      incoming: _mod/data_in
1739    outputs:
1740      - data_out
1741"#,
1742        );
1743
1744        let desc = parse_descriptor(
1745            r#"
1746nodes:
1747  - id: source
1748    path: source.py
1749    outputs:
1750      - number
1751
1752  - id: my_echo
1753    module: echo_module.yml
1754    inputs:
1755      data_in: source/number
1756
1757  - id: sink
1758    path: sink.py
1759    inputs:
1760      result: my_echo/data_out
1761"#,
1762        );
1763
1764        let expanded = expand_modules(&desc, base).unwrap();
1765
1766        assert_eq!(expanded.nodes.len(), 3);
1767        let names: Vec<_> = expanded.nodes.iter().map(|n| n.id.to_string()).collect();
1768        assert!(names.contains(&"my_echo.passthrough".to_string()));
1769        assert!(!names.contains(&"my_echo".to_string()));
1770
1771        let passthrough = expanded
1772            .nodes
1773            .iter()
1774            .find(|n| n.id.to_string() == "my_echo.passthrough")
1775            .unwrap();
1776        let incoming = &passthrough.inputs[&DataId::from("incoming".to_string())];
1777        match &incoming.mapping {
1778            InputMapping::User(m) => {
1779                assert_eq!(m.source.to_string(), "source");
1780                assert_eq!(m.output.to_string(), "number");
1781            }
1782            _ => panic!("expected user mapping"),
1783        }
1784
1785        let sink = expanded
1786            .nodes
1787            .iter()
1788            .find(|n| n.id.to_string() == "sink")
1789            .unwrap();
1790        let result = &sink.inputs[&DataId::from("result".to_string())];
1791        match &result.mapping {
1792            InputMapping::User(m) => {
1793                assert_eq!(m.source.to_string(), "my_echo.passthrough");
1794                assert_eq!(m.output.to_string(), "data_out");
1795            }
1796            _ => panic!("expected user mapping"),
1797        }
1798    }
1799
1800    #[test]
1801    fn expand_internal_cross_ref() {
1802        let tmp = TempDir::new().unwrap();
1803        let base = tmp.path();
1804
1805        write_file(
1806            base,
1807            "pipeline_module.yml",
1808            r#"
1809module:
1810  name: pipeline
1811  inputs: [data_in]
1812  outputs: [data_out]
1813
1814nodes:
1815  - id: stage_a
1816    path: a.py
1817    inputs:
1818      raw: _mod/data_in
1819    outputs:
1820      - intermediate
1821
1822  - id: stage_b
1823    path: b.py
1824    inputs:
1825      intermediate: stage_a/intermediate
1826    outputs:
1827      - data_out
1828"#,
1829        );
1830
1831        let desc = parse_descriptor(
1832            r#"
1833nodes:
1834  - id: src
1835    path: src.py
1836    outputs: [val]
1837  - id: pipe
1838    module: pipeline_module.yml
1839    inputs:
1840      data_in: src/val
1841  - id: dst
1842    path: dst.py
1843    inputs:
1844      result: pipe/data_out
1845"#,
1846        );
1847
1848        let expanded = expand_modules(&desc, base).unwrap();
1849
1850        let stage_b = expanded
1851            .nodes
1852            .iter()
1853            .find(|n| n.id.to_string() == "pipe.stage_b")
1854            .unwrap();
1855        let inter = &stage_b.inputs[&DataId::from("intermediate".to_string())];
1856        match &inter.mapping {
1857            InputMapping::User(m) => {
1858                assert_eq!(m.source.to_string(), "pipe.stage_a");
1859                assert_eq!(m.output.to_string(), "intermediate");
1860            }
1861            _ => panic!("expected user mapping"),
1862        }
1863    }
1864
1865    #[test]
1866    fn expand_depth_limit() {
1867        let tmp = TempDir::new().unwrap();
1868        let base = tmp.path();
1869
1870        for i in 0..=MAX_MODULE_DEPTH {
1871            let next = if i < MAX_MODULE_DEPTH {
1872                format!(
1873                    "  - id: inner\n    module: level{}_module.yml\n    inputs:\n      x: _mod/x",
1874                    i + 1
1875                )
1876            } else {
1877                "  - id: inner\n    path: leaf.py\n    inputs:\n      x: _mod/x\n    outputs:\n      - y".to_string()
1878            };
1879
1880            write_file(
1881                base,
1882                &format!("level{i}_module.yml"),
1883                &format!(
1884                    r#"
1885module:
1886  name: level{i}
1887  inputs: [x]
1888  outputs: [y]
1889
1890nodes:
1891{next}
1892"#
1893                ),
1894            );
1895        }
1896
1897        let desc = parse_descriptor(
1898            r#"
1899nodes:
1900  - id: root
1901    module: level0_module.yml
1902    inputs:
1903      x: somewhere/val
1904"#,
1905        );
1906
1907        let result = expand_modules(&desc, base);
1908        assert!(result.is_err());
1909        assert!(
1910            result
1911                .unwrap_err()
1912                .to_string()
1913                .contains("nesting exceeds depth limit")
1914        );
1915    }
1916
1917    #[test]
1918    fn expand_circular_reference() {
1919        let tmp = TempDir::new().unwrap();
1920        let base = tmp.path();
1921
1922        write_file(
1923            base,
1924            "self_module.yml",
1925            r#"
1926module:
1927  name: self_ref
1928  inputs: [x]
1929  outputs: [y]
1930
1931nodes:
1932  - id: recurse
1933    module: self_module.yml
1934    inputs:
1935      x: _mod/x
1936"#,
1937        );
1938
1939        let desc = parse_descriptor(
1940            r#"
1941nodes:
1942  - id: top
1943    module: self_module.yml
1944    inputs:
1945      x: somewhere/val
1946"#,
1947        );
1948
1949        let result = expand_modules(&desc, base);
1950        assert!(result.is_err());
1951        let err_msg = result.unwrap_err().to_string();
1952        assert!(err_msg.contains("circular module reference"));
1953        // Feature 8: better error message with hint
1954        assert!(err_msg.contains("hint"));
1955    }
1956
1957    #[test]
1958    fn expand_missing_module_file() {
1959        let tmp = TempDir::new().unwrap();
1960        let base = tmp.path();
1961
1962        let desc = parse_descriptor(
1963            r#"
1964nodes:
1965  - id: broken
1966    module: nonexistent_module.yml
1967    inputs:
1968      x: somewhere/val
1969"#,
1970        );
1971
1972        let result = expand_modules(&desc, base);
1973        assert!(result.is_err());
1974        assert!(
1975            result
1976                .unwrap_err()
1977                .to_string()
1978                .contains("nonexistent_module.yml")
1979        );
1980    }
1981
1982    #[test]
1983    fn expand_undefined_input_port() {
1984        let tmp = TempDir::new().unwrap();
1985        let base = tmp.path();
1986
1987        write_file(
1988            base,
1989            "needs_input_module.yml",
1990            r#"
1991module:
1992  name: needs_input
1993  inputs: [required_port]
1994  outputs: [out]
1995
1996nodes:
1997  - id: inner
1998    path: inner.py
1999    inputs:
2000      x: _mod/required_port
2001    outputs:
2002      - out
2003"#,
2004        );
2005
2006        let desc = parse_descriptor(
2007            r#"
2008nodes:
2009  - id: mod_node
2010    module: needs_input_module.yml
2011    inputs:
2012      wrong_name: somewhere/val
2013"#,
2014        );
2015
2016        let result = expand_modules(&desc, base);
2017        assert!(result.is_err());
2018        let err_msg = result.unwrap_err().to_string();
2019        assert!(err_msg.contains("required_port"));
2020        // Feature 8: hint in error
2021        assert!(err_msg.contains("hint"));
2022    }
2023
2024    #[test]
2025    fn expand_rejects_duplicate_module_header_inputs() {
2026        let tmp = TempDir::new().unwrap();
2027        let base = tmp.path();
2028
2029        write_file(
2030            base,
2031            "dup_header_module.yml",
2032            r#"
2033module:
2034  name: dup_header
2035  inputs: [data, data]
2036  outputs: [out]
2037
2038nodes:
2039  - id: inner
2040    path: inner.py
2041    inputs:
2042      x: _mod/data
2043    outputs:
2044      - out
2045"#,
2046        );
2047
2048        let desc = parse_descriptor(
2049            r#"
2050nodes:
2051  - id: src
2052    path: src.py
2053    outputs: [val]
2054  - id: m
2055    module: dup_header_module.yml
2056    inputs:
2057      data: src/val
2058"#,
2059        );
2060
2061        let result = expand_modules(&desc, base);
2062        assert!(result.is_err());
2063        let msg = result.unwrap_err().to_string();
2064        assert!(msg.contains("duplicate"), "got: {msg}");
2065        assert!(msg.contains("inputs"), "got: {msg}");
2066        assert!(msg.contains("data"), "got: {msg}");
2067    }
2068
2069    /// A module file is YAML too: a repeated `inputs:` key inside one of its
2070    /// nodes must fail instead of silently keeping only the last mapping.
2071    #[test]
2072    fn expand_rejects_duplicate_keys_in_module_file() {
2073        let tmp = TempDir::new().unwrap();
2074        let base = tmp.path();
2075
2076        write_file(
2077            base,
2078            "dup_key_module.yml",
2079            r#"
2080module:
2081  name: dup_key
2082  inputs: [data]
2083  outputs: [out]
2084
2085nodes:
2086  - id: inner
2087    path: inner.py
2088    inputs:
2089      x: _mod/data
2090      x: dora/timer/millis/20
2091    outputs:
2092      - out
2093"#,
2094        );
2095
2096        let desc = parse_descriptor(
2097            r#"
2098nodes:
2099  - id: src
2100    path: src.py
2101    outputs: [val]
2102  - id: m
2103    module: dup_key_module.yml
2104    inputs:
2105      data: src/val
2106"#,
2107        );
2108
2109        let msg = format!("{:#}", expand_modules(&desc, base).unwrap_err());
2110        assert!(msg.contains("failed to parse module file"), "got: {msg}");
2111        assert!(msg.contains("duplicate entry with key \"x\""), "got: {msg}");
2112    }
2113
2114    #[test]
2115    fn expand_undefined_output_port() {
2116        let tmp = TempDir::new().unwrap();
2117        let base = tmp.path();
2118
2119        write_file(
2120            base,
2121            "bad_output_module.yml",
2122            r#"
2123module:
2124  name: bad_output
2125  inputs: []
2126  outputs: [nonexistent]
2127
2128nodes:
2129  - id: inner
2130    path: inner.py
2131    outputs:
2132      - something_else
2133"#,
2134        );
2135
2136        let desc = parse_descriptor(
2137            r#"
2138nodes:
2139  - id: mod_node
2140    module: bad_output_module.yml
2141"#,
2142        );
2143
2144        let result = expand_modules(&desc, base);
2145        assert!(result.is_err());
2146        assert!(result.unwrap_err().to_string().contains("nonexistent"));
2147    }
2148
2149    #[test]
2150    fn expand_no_modules_passthrough() {
2151        let desc = parse_descriptor(
2152            r#"
2153nodes:
2154  - id: a
2155    path: a.py
2156    outputs: [x]
2157  - id: b
2158    path: b.py
2159    inputs:
2160      x: a/x
2161"#,
2162        );
2163
2164        let tmp = TempDir::new().unwrap();
2165        let expanded = expand_modules(&desc, tmp.path()).unwrap();
2166        assert_eq!(expanded.nodes.len(), 2);
2167        assert_eq!(expanded.nodes[0].id.to_string(), "a");
2168        assert_eq!(expanded.nodes[1].id.to_string(), "b");
2169    }
2170
2171    #[test]
2172    fn expand_multiple_instances() {
2173        let tmp = TempDir::new().unwrap();
2174        let base = tmp.path();
2175
2176        write_file(
2177            base,
2178            "filter_module.yml",
2179            r#"
2180module:
2181  name: filter
2182  inputs: [raw]
2183  outputs: [filtered]
2184
2185nodes:
2186  - id: proc
2187    path: filter.py
2188    inputs:
2189      data: _mod/raw
2190    outputs:
2191      - filtered
2192"#,
2193        );
2194
2195        let desc = parse_descriptor(
2196            r#"
2197nodes:
2198  - id: cam1
2199    path: cam.py
2200    outputs: [frame]
2201  - id: cam2
2202    path: cam.py
2203    outputs: [frame]
2204  - id: filter1
2205    module: filter_module.yml
2206    inputs:
2207      raw: cam1/frame
2208  - id: filter2
2209    module: filter_module.yml
2210    inputs:
2211      raw: cam2/frame
2212  - id: merger
2213    path: merge.py
2214    inputs:
2215      a: filter1/filtered
2216      b: filter2/filtered
2217"#,
2218        );
2219
2220        let expanded = expand_modules(&desc, base).unwrap();
2221
2222        let names: Vec<_> = expanded.nodes.iter().map(|n| n.id.to_string()).collect();
2223        assert!(names.contains(&"filter1.proc".to_string()));
2224        assert!(names.contains(&"filter2.proc".to_string()));
2225        assert_eq!(expanded.nodes.len(), 5);
2226
2227        let merger = expanded
2228            .nodes
2229            .iter()
2230            .find(|n| n.id.to_string() == "merger")
2231            .unwrap();
2232        let a_input = &merger.inputs[&DataId::from("a".to_string())];
2233        match &a_input.mapping {
2234            InputMapping::User(m) => assert_eq!(m.source.to_string(), "filter1.proc"),
2235            _ => panic!("expected user mapping"),
2236        }
2237        let b_input = &merger.inputs[&DataId::from("b".to_string())];
2238        match &b_input.mapping {
2239            InputMapping::User(m) => assert_eq!(m.source.to_string(), "filter2.proc"),
2240            _ => panic!("expected user mapping"),
2241        }
2242    }
2243
2244    #[test]
2245    fn expand_nested_modules() {
2246        let tmp = TempDir::new().unwrap();
2247        let base = tmp.path();
2248
2249        write_file(
2250            base,
2251            "inner_module.yml",
2252            r#"
2253module:
2254  name: inner
2255  inputs: [x]
2256  outputs: [y]
2257
2258nodes:
2259  - id: leaf
2260    path: leaf.py
2261    inputs:
2262      x: _mod/x
2263    outputs:
2264      - y
2265"#,
2266        );
2267
2268        write_file(
2269            base,
2270            "outer_module.yml",
2271            r#"
2272module:
2273  name: outer
2274  inputs: [a]
2275  outputs: [y]
2276
2277nodes:
2278  - id: nested
2279    module: inner_module.yml
2280    inputs:
2281      x: _mod/a
2282"#,
2283        );
2284
2285        let desc = parse_descriptor(
2286            r#"
2287nodes:
2288  - id: src
2289    path: src.py
2290    outputs: [val]
2291  - id: wrapper
2292    module: outer_module.yml
2293    inputs:
2294      a: src/val
2295"#,
2296        );
2297
2298        let expanded = expand_modules(&desc, base).unwrap();
2299        let names: Vec<_> = expanded.nodes.iter().map(|n| n.id.to_string()).collect();
2300        assert!(names.contains(&"wrapper.nested.leaf".to_string()));
2301    }
2302
2303    // ---- Feature 3: optional inputs ----
2304
2305    #[test]
2306    fn expand_optional_input_provided() {
2307        let tmp = TempDir::new().unwrap();
2308        let base = tmp.path();
2309
2310        write_file(
2311            base,
2312            "opt_module.yml",
2313            r#"
2314module:
2315  name: opt
2316  inputs: [required]
2317  inputs_optional: [config]
2318  outputs: [out]
2319
2320nodes:
2321  - id: worker
2322    path: worker.py
2323    inputs:
2324      data: _mod/required
2325      cfg: _mod/config
2326    outputs:
2327      - out
2328"#,
2329        );
2330
2331        // Provide both required and optional
2332        let desc = parse_descriptor(
2333            r#"
2334nodes:
2335  - id: src
2336    path: src.py
2337    outputs: [data, cfg]
2338  - id: m
2339    module: opt_module.yml
2340    inputs:
2341      required: src/data
2342      config: src/cfg
2343"#,
2344        );
2345
2346        let expanded = expand_modules(&desc, base).unwrap();
2347        let worker = expanded
2348            .nodes
2349            .iter()
2350            .find(|n| n.id.to_string() == "m.worker")
2351            .unwrap();
2352        // Both inputs should be present
2353        assert_eq!(worker.inputs.len(), 2);
2354    }
2355
2356    #[test]
2357    fn expand_optional_input_omitted() {
2358        let tmp = TempDir::new().unwrap();
2359        let base = tmp.path();
2360
2361        write_file(
2362            base,
2363            "opt_module.yml",
2364            r#"
2365module:
2366  name: opt
2367  inputs: [required]
2368  inputs_optional: [config]
2369  outputs: [out]
2370
2371nodes:
2372  - id: worker
2373    path: worker.py
2374    inputs:
2375      data: _mod/required
2376      cfg: _mod/config
2377    outputs:
2378      - out
2379"#,
2380        );
2381
2382        // Only provide required, not optional
2383        let desc = parse_descriptor(
2384            r#"
2385nodes:
2386  - id: src
2387    path: src.py
2388    outputs: [data]
2389  - id: m
2390    module: opt_module.yml
2391    inputs:
2392      required: src/data
2393"#,
2394        );
2395
2396        let expanded = expand_modules(&desc, base).unwrap();
2397        let worker = expanded
2398            .nodes
2399            .iter()
2400            .find(|n| n.id.to_string() == "m.worker")
2401            .unwrap();
2402        // Only the required input should be present; optional was dropped
2403        assert_eq!(worker.inputs.len(), 1);
2404        assert!(
2405            worker
2406                .inputs
2407                .contains_key(&DataId::from("data".to_string()))
2408        );
2409    }
2410
2411    #[test]
2412    fn expand_rejects_module_input_not_declared_required_or_optional() {
2413        let tmp = TempDir::new().unwrap();
2414        let base = tmp.path();
2415
2416        write_file(
2417            base,
2418            "strict_inputs_module.yml",
2419            r#"
2420module:
2421  name: strict_inputs
2422  inputs: [required]
2423  inputs_optional: [config]
2424  outputs: [out]
2425
2426nodes:
2427  - id: worker
2428    path: worker.py
2429    inputs:
2430      data: _mod/required
2431    outputs:
2432      - out
2433"#,
2434        );
2435
2436        let desc = parse_descriptor(
2437            r#"
2438nodes:
2439  - id: src
2440    path: src.py
2441    outputs: [data, extra]
2442  - id: m
2443    module: strict_inputs_module.yml
2444    inputs:
2445      required: src/data
2446      typo: src/extra
2447"#,
2448        );
2449
2450        let result = expand_modules(&desc, base);
2451        assert!(result.is_err());
2452        let msg = result.unwrap_err().to_string();
2453        assert!(msg.contains("does not declare input"), "got: {msg}");
2454        assert!(msg.contains("typo"), "got: {msg}");
2455        assert!(msg.contains("required"), "got: {msg}");
2456        assert!(msg.contains("config"), "got: {msg}");
2457    }
2458
2459    // ---- Feature 4: params substitution ----
2460
2461    #[test]
2462    fn expand_params_in_env() {
2463        let tmp = TempDir::new().unwrap();
2464        let base = tmp.path();
2465
2466        write_file(
2467            base,
2468            "param_module.yml",
2469            r#"
2470module:
2471  name: parameterized
2472  inputs: [data]
2473  outputs: [out]
2474
2475nodes:
2476  - id: proc
2477    path: proc.py
2478    inputs:
2479      data: _mod/data
2480    outputs:
2481      - out
2482"#,
2483        );
2484
2485        let desc = parse_descriptor(
2486            r#"
2487nodes:
2488  - id: src
2489    path: src.py
2490    outputs: [val]
2491  - id: m
2492    module: param_module.yml
2493    inputs:
2494      data: src/val
2495    params:
2496      speed: "1.5"
2497      mode: turbo
2498"#,
2499        );
2500
2501        let expanded = expand_modules(&desc, base).unwrap();
2502        let proc = expanded
2503            .nodes
2504            .iter()
2505            .find(|n| n.id.to_string() == "m.proc")
2506            .unwrap();
2507        let env = proc.env.as_ref().unwrap();
2508        // Params are injected as PARAM_<UPPERCASE_KEY>
2509        assert_eq!(env["PARAM_SPEED"], EnvValue::String("1.5".to_string()));
2510        assert_eq!(env["PARAM_MODE"], EnvValue::String("turbo".to_string()));
2511    }
2512
2513    /// A param injected as env is expanded here, once, like a YAML `env:`
2514    /// value: the coordinator and daemon no longer expand what they receive
2515    /// (#3947), so `${MODEL_DIR}` in a param must not reach them unexpanded.
2516    #[test]
2517    fn expand_params_in_env_expands_variables_once() {
2518        let tmp = TempDir::new().unwrap();
2519        let base = tmp.path();
2520        write_file(
2521            base,
2522            "param_module.yml",
2523            "module:\n  name: m\n  inputs: [data]\n\
2524             nodes:\n  - id: proc\n    path: proc.py\n    inputs:\n      data: _mod/data\n",
2525        );
2526        let desc = |params: &str| {
2527            parse_descriptor(&format!(
2528                "nodes:\n  - id: src\n    path: src.py\n    outputs: [val]\n  \
2529                 - id: m\n    module: param_module.yml\n    inputs:\n      data: src/val\n    \
2530                 params:\n{params}"
2531            ))
2532        };
2533
2534        let expanded = expand_modules(
2535            &desc(
2536                "      dir: \"${DORA_TEST_PARAM_SURELY_UNSET:-/models}\"\n      \
2537                 literal: \"p$$ss\"\n",
2538            ),
2539            base,
2540        )
2541        .unwrap();
2542        let env = expanded.nodes[1].env.as_ref().unwrap();
2543        assert_eq!(env["PARAM_DIR"], EnvValue::String("/models".into()));
2544        assert_eq!(env["PARAM_LITERAL"], EnvValue::String("p$ss".into()));
2545
2546        let err = expand_modules(
2547            &desc("      dir: \"${DORA_TEST_PARAM_SURELY_UNSET}\"\n"),
2548            base,
2549        )
2550        .unwrap_err();
2551        let msg = format!("{err:#}");
2552        assert!(msg.contains("param `dir`"), "got: {msg}");
2553        assert!(msg.contains("DORA_TEST_PARAM_SURELY_UNSET"), "got: {msg}");
2554    }
2555
2556    #[test]
2557    fn expand_params_in_args() {
2558        let tmp = TempDir::new().unwrap();
2559        let base = tmp.path();
2560
2561        write_file(
2562            base,
2563            "args_module.yml",
2564            r#"
2565module:
2566  name: with_args
2567  inputs: [data]
2568  outputs: [out]
2569
2570nodes:
2571  - id: proc
2572    path: proc.py
2573    inputs:
2574      data: _mod/data
2575    outputs:
2576      - out
2577    args: --speed ${_param.speed} --verbose
2578"#,
2579        );
2580
2581        let desc = parse_descriptor(
2582            r#"
2583nodes:
2584  - id: src
2585    path: src.py
2586    outputs: [val]
2587  - id: m
2588    module: args_module.yml
2589    inputs:
2590      data: src/val
2591    params:
2592      speed: "2.0"
2593"#,
2594        );
2595
2596        let expanded = expand_modules(&desc, base).unwrap();
2597        let proc = expanded
2598            .nodes
2599            .iter()
2600            .find(|n| n.id.to_string() == "m.proc")
2601            .unwrap();
2602        assert_eq!(proc.args.as_deref(), Some("--speed 2.0 --verbose"));
2603    }
2604
2605    #[test]
2606    fn expand_params_in_documented_env_style_args() {
2607        let tmp = TempDir::new().unwrap();
2608        let base = tmp.path();
2609
2610        write_file(
2611            base,
2612            "args_module.yml",
2613            r#"
2614module:
2615  name: with_args
2616  inputs: [data]
2617  outputs: [out]
2618
2619nodes:
2620  - id: proc
2621    path: proc.py
2622    inputs:
2623      data: _mod/data
2624    outputs:
2625      - out
2626    args: --speed $PARAM_SPEED --mode $PARAM_MODE
2627"#,
2628        );
2629
2630        let desc = parse_descriptor(
2631            r#"
2632nodes:
2633  - id: src
2634    path: src.py
2635    outputs: [val]
2636  - id: m
2637    module: args_module.yml
2638    inputs:
2639      data: src/val
2640    params:
2641      speed: "2.0"
2642      mode: turbo
2643"#,
2644        );
2645
2646        let expanded = expand_modules(&desc, base).unwrap();
2647        let proc = expanded
2648            .nodes
2649            .iter()
2650            .find(|n| n.id.to_string() == "m.proc")
2651            .unwrap();
2652        assert_eq!(proc.args.as_deref(), Some("--speed 2.0 --mode turbo"));
2653    }
2654
2655    #[test]
2656    fn expand_params_in_env_style_args_distinguishes_overlapping_keys() {
2657        // `speed` and `speed_limit` overlap as prefixes. The scanner takes the
2658        // maximal `[A-Za-z0-9_]` run as the key, so each token resolves to the
2659        // key it names exactly -- no ordering between the params is involved.
2660        // (The old implementation needed a longest-first sort here.)
2661        let tmp = TempDir::new().unwrap();
2662        let base = tmp.path();
2663
2664        write_file(
2665            base,
2666            "args_module.yml",
2667            r#"
2668module:
2669  name: with_args
2670  inputs: [data]
2671  outputs: [out]
2672
2673nodes:
2674  - id: proc
2675    path: proc.py
2676    inputs:
2677      data: _mod/data
2678    outputs:
2679      - out
2680    args: --short $PARAM_SPEED --long $PARAM_SPEED_LIMIT
2681"#,
2682        );
2683
2684        let desc = parse_descriptor(
2685            r#"
2686nodes:
2687  - id: src
2688    path: src.py
2689    outputs: [val]
2690  - id: m
2691    module: args_module.yml
2692    inputs:
2693      data: src/val
2694    params:
2695      speed: "2.0"
2696      speed_limit: "4.5"
2697"#,
2698        );
2699
2700        let expanded = expand_modules(&desc, base).unwrap();
2701        let proc = expanded
2702            .nodes
2703            .iter()
2704            .find(|n| n.id.to_string() == "m.proc")
2705            .unwrap();
2706        assert_eq!(proc.args.as_deref(), Some("--short 2.0 --long 4.5"));
2707    }
2708
2709    #[test]
2710    fn substitute_params_basic_and_unknown() {
2711        let params = BTreeMap::from([
2712            ("speed".to_string(), "2.0".to_string()),
2713            ("name".to_string(), "robot".to_string()),
2714        ]);
2715        assert_eq!(
2716            substitute_params_in_str("--speed ${_param.speed} --name ${_param.name}", &params),
2717            "--speed 2.0 --name robot"
2718        );
2719        // Multiple occurrences of the same key are all replaced.
2720        assert_eq!(
2721            substitute_params_in_str("${_param.speed}/${_param.speed}", &params),
2722            "2.0/2.0"
2723        );
2724        // An unknown key is left verbatim, not dropped.
2725        assert_eq!(
2726            substitute_params_in_str("${_param.missing}", &params),
2727            "${_param.missing}"
2728        );
2729        // A dangling prefix without a closing brace is emitted literally.
2730        assert_eq!(
2731            substitute_params_in_str("prefix ${_param.speed", &params),
2732            "prefix ${_param.speed"
2733        );
2734    }
2735
2736    #[test]
2737    fn substitute_params_env_style_requires_an_identifier_boundary() {
2738        // `$PARAM_<KEY>` has no terminator, so the key must run to the end of
2739        // the shell-identifier characters. A declared param that is only a
2740        // *prefix* of the token must not match (#2901).
2741        let params = BTreeMap::from([("speed".to_string(), "2.0".to_string())]);
2742        assert_eq!(
2743            substitute_params_in_str("--flag $PARAM_SPEED_LIMIT", &params),
2744            "--flag $PARAM_SPEED_LIMIT"
2745        );
2746        // The exact token still substitutes, and a non-identifier character
2747        // terminates it.
2748        assert_eq!(
2749            substitute_params_in_str("--flag $PARAM_SPEED --x", &params),
2750            "--flag 2.0 --x"
2751        );
2752        assert_eq!(
2753            substitute_params_in_str("$PARAM_SPEED,$PARAM_SPEED", &params),
2754            "2.0,2.0"
2755        );
2756        // A bare `$` and an unknown token are both emitted verbatim.
2757        assert_eq!(
2758            substitute_params_in_str("cost $5 $PARAM_MISSING", &params),
2759            "cost $5 $PARAM_MISSING"
2760        );
2761    }
2762
2763    #[test]
2764    fn substitute_params_env_style_is_not_re_expanded() {
2765        // A value that itself looks like a token is inserted verbatim, never
2766        // re-scanned — the property the single-pass scanner exists for.
2767        let params = BTreeMap::from([
2768            ("a".to_string(), "$PARAM_B".to_string()),
2769            ("b".to_string(), "x".to_string()),
2770        ]);
2771        assert_eq!(substitute_params_in_str("$PARAM_A", &params), "$PARAM_B");
2772    }
2773
2774    #[test]
2775    fn substitute_params_is_order_independent_and_non_transitive() {
2776        // A parameter value that itself looks like a `${_param.…}` token must be
2777        // inserted verbatim, never re-expanded — and the result must not depend
2778        // on `BTreeMap` key ordering. With the old chained-`replace` approach,
2779        // `a`'s value `${_param.b}` was expanded to `x` because `a` sorts first.
2780        let params = BTreeMap::from([
2781            ("a".to_string(), "${_param.b}".to_string()),
2782            ("b".to_string(), "x".to_string()),
2783        ]);
2784        assert_eq!(
2785            substitute_params_in_str("${_param.a}", &params),
2786            "${_param.b}"
2787        );
2788        assert_eq!(substitute_params_in_str("${_param.b}", &params), "x");
2789    }
2790
2791    #[test]
2792    fn expand_module_node_env_propagates_to_inner_nodes() {
2793        let tmp = TempDir::new().unwrap();
2794        let base = tmp.path();
2795
2796        write_file(
2797            base,
2798            "env_module.yml",
2799            r#"
2800module:
2801  name: env_module
2802  inputs: [data]
2803  outputs: [out]
2804
2805nodes:
2806  - id: worker
2807    path: worker.py
2808    env:
2809      INNER_ONLY: from-inner
2810      SHARED: inner
2811    inputs:
2812      data: _mod/data
2813    outputs:
2814      - out
2815"#,
2816        );
2817
2818        let desc = parse_descriptor(
2819            r#"
2820nodes:
2821  - id: src
2822    path: src.py
2823    outputs: [val]
2824  - id: m
2825    module: env_module.yml
2826    env:
2827      WRAPPER_ONLY: from-wrapper
2828      SHARED: wrapper
2829    inputs:
2830      data: src/val
2831"#,
2832        );
2833
2834        let expanded = expand_modules(&desc, base).unwrap();
2835        let worker = expanded
2836            .nodes
2837            .iter()
2838            .find(|n| n.id.to_string() == "m.worker")
2839            .unwrap();
2840        let env = worker.env.as_ref().unwrap();
2841        assert_eq!(
2842            env["INNER_ONLY"],
2843            EnvValue::String("from-inner".to_string())
2844        );
2845        assert_eq!(
2846            env["WRAPPER_ONLY"],
2847            EnvValue::String("from-wrapper".to_string())
2848        );
2849        // The inner node's own `env` wins over the module node's, matching
2850        // `merge_env` ("per-node entries override global ones") and `deploy`.
2851        assert_eq!(env["SHARED"], EnvValue::String("inner".to_string()));
2852    }
2853
2854    #[test]
2855    fn expand_module_node_with_empty_env_leaves_inner_env_unset() {
2856        let tmp = TempDir::new().unwrap();
2857        let base = tmp.path();
2858
2859        write_file(
2860            base,
2861            "empty_env_module.yml",
2862            r#"
2863module:
2864  name: empty_env_module
2865  inputs: [data]
2866  outputs: [out]
2867
2868nodes:
2869  - id: worker
2870    path: worker.py
2871    inputs:
2872      data: _mod/data
2873    outputs:
2874      - out
2875"#,
2876        );
2877
2878        let desc = parse_descriptor(
2879            r#"
2880nodes:
2881  - id: src
2882    path: src.py
2883    outputs: [val]
2884  - id: m
2885    module: empty_env_module.yml
2886    env: {}
2887    inputs:
2888      data: src/val
2889"#,
2890        );
2891
2892        let expanded = expand_modules(&desc, base).unwrap();
2893        let worker = expanded
2894            .nodes
2895            .iter()
2896            .find(|n| n.id.to_string() == "m.worker")
2897            .unwrap();
2898        assert_eq!(worker.env, None);
2899    }
2900
2901    /// Expand `outer` (given `speed: "2.0"`) nesting `inner`, whose `worker`
2902    /// reads `$PARAM_SPEED` in its args; `nested_speed` is the nested module
2903    /// node's own `speed` param, and `worker_env_speed` the worker's own
2904    /// `env: PARAM_SPEED` default, if any.
2905    fn expand_nested_param_worker(
2906        nested_speed: Option<&str>,
2907        worker_env_speed: Option<&str>,
2908    ) -> Node {
2909        let nested_params = nested_speed
2910            .map(|speed| format!("    params:\n      speed: {speed}"))
2911            .unwrap_or_default();
2912        let worker_env = worker_env_speed
2913            .map(|speed| format!("    env:\n      PARAM_SPEED: {speed}"))
2914            .unwrap_or_default();
2915        let tmp = TempDir::new().unwrap();
2916        let base = tmp.path();
2917        write_file(
2918            base,
2919            "inner.yml",
2920            &format!(
2921                r#"
2922module:
2923  name: inner
2924  inputs: [data]
2925  outputs: [out]
2926
2927nodes:
2928  - id: worker
2929    path: worker.py
2930    args: --speed $PARAM_SPEED
2931{worker_env}
2932    inputs:
2933      data: _mod/data
2934    outputs:
2935      - out
2936"#
2937            ),
2938        );
2939        write_file(
2940            base,
2941            "outer.yml",
2942            &format!(
2943                r#"
2944module:
2945  name: outer
2946  inputs: [data]
2947  outputs: [out]
2948
2949nodes:
2950  - id: inner
2951    module: inner.yml
2952    inputs:
2953      data: _mod/data
2954{nested_params}
2955"#
2956            ),
2957        );
2958        let desc = parse_descriptor(
2959            r#"
2960nodes:
2961  - id: src
2962    path: src.py
2963    outputs: [val]
2964  - id: outer
2965    module: outer.yml
2966    inputs:
2967      data: src/val
2968    params:
2969      speed: "2.0"
2970"#,
2971        );
2972        let expanded = expand_modules(&desc, base).unwrap();
2973        expanded
2974            .nodes
2975            .into_iter()
2976            .find(|n| n.id.to_string() == "outer.inner.worker")
2977            .unwrap()
2978    }
2979
2980    /// An outer module's params reach a nested module's inner nodes as env vars
2981    /// and in `args`: the daemon does not expand `$PARAM_*` in args, so a
2982    /// left-over reference would reach the process verbatim.
2983    #[test]
2984    fn expand_outer_params_reach_nested_module_inner_nodes() {
2985        let worker = expand_nested_param_worker(None, None);
2986        assert_eq!(worker.args.as_deref(), Some("--speed 2.0"));
2987        let env = worker.env.as_ref().unwrap();
2988        assert_eq!(env["PARAM_SPEED"], EnvValue::String("2.0".to_string()));
2989    }
2990
2991    /// A nested module node forwarding a param with `$PARAM_*` gets the outer
2992    /// value, not the literal reference.
2993    #[test]
2994    fn expand_nested_module_forwarded_param_is_substituted() {
2995        let worker = expand_nested_param_worker(Some("$PARAM_SPEED"), None);
2996        assert_eq!(worker.args.as_deref(), Some("--speed 2.0"));
2997        let env = worker.env.as_ref().unwrap();
2998        assert_eq!(env["PARAM_SPEED"], EnvValue::String("2.0".to_string()));
2999    }
3000
3001    /// A nested module node's own param value wins over the outer one.
3002    #[test]
3003    fn expand_nested_module_own_param_overrides_outer() {
3004        let worker = expand_nested_param_worker(Some("\"3.0\""), None);
3005        assert_eq!(worker.args.as_deref(), Some("--speed 3.0"));
3006    }
3007
3008    /// An outer param overrides a nested module's inner node's own
3009    /// `env: PARAM_*` default, as it does for a direct child. (Before outer
3010    /// params were handed down, the inner default won here.)
3011    #[test]
3012    fn expand_outer_param_overrides_nested_inner_env_default() {
3013        let worker = expand_nested_param_worker(None, Some("\"1.0\""));
3014        let env = worker.env.as_ref().unwrap();
3015        assert_eq!(env["PARAM_SPEED"], EnvValue::String("2.0".to_string()));
3016    }
3017
3018    // ---- Feature 5: module-level build ----
3019
3020    /// Regression for #3258 (defect 1): a `build:` set on the module node itself
3021    /// (not the module file header) is accepted and propagates into the expanded
3022    /// leaf nodes, matching the documented contract and the nested behavior.
3023    #[test]
3024    fn expand_top_level_module_build_propagated() {
3025        let tmp = TempDir::new().unwrap();
3026        let base = tmp.path();
3027
3028        write_file(
3029            base,
3030            "leaf_module.yml",
3031            r#"
3032module:
3033  name: leaf
3034  inputs: [data]
3035  outputs: [out]
3036
3037nodes:
3038  - id: proc
3039    path: proc.py
3040    inputs:
3041      data: _mod/data
3042    outputs:
3043      - out
3044    build: python setup.py build
3045"#,
3046        );
3047
3048        let desc = parse_descriptor(
3049            r#"
3050nodes:
3051  - id: src
3052    path: src.py
3053    outputs: [val]
3054  - id: m
3055    module: leaf_module.yml
3056    build: pip install foo
3057    inputs:
3058      data: src/val
3059"#,
3060        );
3061
3062        let expanded = expand_modules(&desc, base).unwrap();
3063        let proc = expanded
3064            .nodes
3065            .iter()
3066            .find(|n| n.id.to_string() == "m.proc")
3067            .unwrap();
3068        let build = proc.build.as_deref().unwrap();
3069        assert!(
3070            build.starts_with("pip install foo"),
3071            "the module node's own build must be prepended; got: {build}"
3072        );
3073        assert!(build.contains("python setup.py build"), "{build}");
3074    }
3075
3076    /// Regression for #3258 (defect 2): a per-node runtime field that has no
3077    /// meaning on a module node (here `outputs`) is rejected at expansion time
3078    /// rather than silently dropped, at every nesting level.
3079    #[test]
3080    fn nested_module_node_rejects_disallowed_field() {
3081        let tmp = TempDir::new().unwrap();
3082        let base = tmp.path();
3083
3084        write_file(
3085            base,
3086            "leaf_module.yml",
3087            r#"
3088module:
3089  name: leaf
3090  inputs: [x]
3091  outputs: [y]
3092
3093nodes:
3094  - id: worker
3095    path: worker.py
3096    inputs:
3097      x: _mod/x
3098    outputs:
3099      - y
3100"#,
3101        );
3102
3103        // `outputs` on the nested module node is not part of the module
3104        // whitelist; expansion must reject it.
3105        write_file(
3106            base,
3107            "outer_module.yml",
3108            r#"
3109module:
3110  name: outer
3111  inputs: [x]
3112  outputs: [y]
3113
3114nodes:
3115  - id: inner
3116    module: leaf_module.yml
3117    inputs:
3118      x: _mod/x
3119    outputs:
3120      - y
3121"#,
3122        );
3123
3124        let desc = parse_descriptor(
3125            r#"
3126nodes:
3127  - id: src
3128    path: src.py
3129    outputs: [val]
3130  - id: top
3131    module: outer_module.yml
3132    inputs:
3133      x: src/val
3134"#,
3135        );
3136
3137        let error = format!("{:#}", expand_modules(&desc, base).unwrap_err());
3138        assert!(
3139            error.contains("outputs") && error.contains("Module"),
3140            "nested module node with `outputs` should be rejected; got: {error}"
3141        );
3142    }
3143
3144    #[test]
3145    fn expand_module_build_prepended() {
3146        let tmp = TempDir::new().unwrap();
3147        let base = tmp.path();
3148
3149        write_file(
3150            base,
3151            "build_module.yml",
3152            r#"
3153module:
3154  name: buildable
3155  inputs: [data]
3156  outputs: [out]
3157
3158build: pip install -r requirements.txt
3159
3160nodes:
3161  - id: proc
3162    path: proc.py
3163    inputs:
3164      data: _mod/data
3165    outputs:
3166      - out
3167    build: python setup.py build
3168"#,
3169        );
3170
3171        let desc = parse_descriptor(
3172            r#"
3173nodes:
3174  - id: src
3175    path: src.py
3176    outputs: [val]
3177  - id: m
3178    module: build_module.yml
3179    inputs:
3180      data: src/val
3181"#,
3182        );
3183
3184        let expanded = expand_modules(&desc, base).unwrap();
3185        let proc = expanded
3186            .nodes
3187            .iter()
3188            .find(|n| n.id.to_string() == "m.proc")
3189            .unwrap();
3190        let build = proc.build.as_deref().unwrap();
3191        assert!(build.starts_with("pip install -r requirements.txt"));
3192        assert!(build.contains("python setup.py build"));
3193    }
3194
3195    #[test]
3196    fn expand_module_build_no_inner_build() {
3197        let tmp = TempDir::new().unwrap();
3198        let base = tmp.path();
3199
3200        write_file(
3201            base,
3202            "build_only_module.yml",
3203            r#"
3204module:
3205  name: build_only
3206  inputs: [data]
3207  outputs: [out]
3208
3209build: make all
3210
3211nodes:
3212  - id: proc
3213    path: proc.py
3214    inputs:
3215      data: _mod/data
3216    outputs:
3217      - out
3218"#,
3219        );
3220
3221        let desc = parse_descriptor(
3222            r#"
3223nodes:
3224  - id: src
3225    path: src.py
3226    outputs: [val]
3227  - id: m
3228    module: build_only_module.yml
3229    inputs:
3230      data: src/val
3231"#,
3232        );
3233
3234        let expanded = expand_modules(&desc, base).unwrap();
3235        let proc = expanded
3236            .nodes
3237            .iter()
3238            .find(|n| n.id.to_string() == "m.proc")
3239            .unwrap();
3240        assert_eq!(proc.build.as_deref(), Some("make all"));
3241    }
3242
3243    /// A module-level `build:` must reach `git:`/`hub:`-sourced inner nodes,
3244    /// not just `path:`-sourced ones. Module expansion runs before git/hub
3245    /// source resolution, so these nodes still have `path == None` at this
3246    /// point; the build must be keyed off the node kind, not `node.path`
3247    /// (#3296).
3248    #[test]
3249    fn expand_module_build_prepended_to_git_and_hub_inner_nodes() {
3250        let tmp = TempDir::new().unwrap();
3251        let base = tmp.path();
3252
3253        write_file(
3254            base,
3255            "git_hub_module.yml",
3256            r#"
3257module:
3258  name: git_hub
3259  outputs: [from_git, from_hub]
3260
3261build: pip install -r requirements.txt
3262
3263nodes:
3264  - id: worker
3265    git: https://github.com/example/worker.git
3266    outputs:
3267      - from_git
3268    build: cargo build --release
3269  - id: fetched
3270    hub: example/fetched
3271    outputs:
3272      - from_hub
3273"#,
3274        );
3275
3276        let desc = parse_descriptor(
3277            r#"
3278nodes:
3279  - id: m
3280    module: git_hub_module.yml
3281"#,
3282        );
3283
3284        let expanded = expand_modules(&desc, base).unwrap();
3285
3286        // git-sourced inner node: module build prepended before its own build.
3287        let worker = expanded
3288            .nodes
3289            .iter()
3290            .find(|n| n.id.to_string() == "m.worker")
3291            .unwrap();
3292        assert_eq!(
3293            worker.build.as_deref(),
3294            Some("pip install -r requirements.txt\ncargo build --release"),
3295        );
3296
3297        // hub-sourced inner node with no own build: module build is set.
3298        let fetched = expanded
3299            .nodes
3300            .iter()
3301            .find(|n| n.id.to_string() == "m.fetched")
3302            .unwrap();
3303        assert_eq!(
3304            fetched.build.as_deref(),
3305            Some("pip install -r requirements.txt"),
3306        );
3307    }
3308
3309    /// A module-level `build:` must not make an operator inner node
3310    /// unresolvable. The expansion-only tests above stop at `expand_modules`;
3311    /// the field classifier runs at *resolution*, so the regression this pins
3312    /// lives in the seam between the two (#3070).
3313    #[test]
3314    fn module_build_keeps_operator_inner_nodes_resolvable() {
3315        let tmp = TempDir::new().unwrap();
3316        let base = tmp.path();
3317
3318        write_file(
3319            base,
3320            "kinds_module.yml",
3321            r#"
3322build: pip install shared
3323
3324module:
3325  name: kinds
3326  inputs: [data]
3327  outputs: [from_runtime, from_operator]
3328
3329nodes:
3330  - id: runtime
3331    operators:
3332      - id: proc
3333        shared-library: proc
3334        inputs:
3335          data: _mod/data
3336        outputs:
3337          - from_runtime
3338
3339  - id: single
3340    operator:
3341      python: single.py
3342      inputs:
3343        data: _mod/data
3344      outputs:
3345        - from_operator
3346"#,
3347        );
3348
3349        let desc = parse_descriptor(
3350            r#"
3351nodes:
3352  - id: src
3353    path: src.py
3354    outputs: [val]
3355  - id: m
3356    module: kinds_module.yml
3357    inputs:
3358      data: src/val
3359"#,
3360        );
3361
3362        let expanded = expand_modules(&desc, base).unwrap();
3363        // The module build must land in the operator configs, which is where
3364        // `build/mod.rs` reads it from for runtime nodes...
3365        let runtime = expanded
3366            .nodes
3367            .iter()
3368            .find(|n| n.id.to_string() == "m.runtime")
3369            .unwrap();
3370        assert_eq!(
3371            runtime.operators.as_ref().unwrap().operators[0]
3372                .config
3373                .build
3374                .as_deref(),
3375            Some("pip install shared"),
3376        );
3377        // ...and must NOT land on the node itself, where no kind but
3378        // `path:`/`module:` consumes it.
3379        assert_eq!(runtime.build, None);
3380
3381        crate::descriptor::DescriptorExt::resolve_aliases_and_set_defaults(&expanded)
3382            .expect("a module-level build must not make operator nodes unresolvable");
3383    }
3384
3385    #[test]
3386    fn expand_module_build_prepended_to_operator_and_custom_builds() {
3387        let tmp = TempDir::new().unwrap();
3388        let base = tmp.path();
3389
3390        write_file(
3391            base,
3392            "inner_kind_build_module.yml",
3393            r#"
3394module:
3395  name: inner_kind_builds
3396  inputs: [data]
3397  outputs: [from_runtime, from_operator]
3398
3399build: pip install shared
3400
3401nodes:
3402  - id: runtime
3403    operators:
3404      - id: proc
3405        shared-library: libproc.so
3406        build: make proc
3407        inputs:
3408          data: _mod/data
3409        outputs:
3410          - from_runtime
3411
3412  - id: single
3413    operator:
3414      python: single.py
3415      build: pip install single
3416      inputs:
3417        data: _mod/data
3418      outputs:
3419        - from_operator
3420"#,
3421        );
3422
3423        let desc = parse_descriptor(
3424            r#"
3425nodes:
3426  - id: src
3427    path: src.py
3428    outputs: [val]
3429  - id: m
3430    module: inner_kind_build_module.yml
3431    inputs:
3432      data: src/val
3433"#,
3434        );
3435
3436        let expanded = expand_modules(&desc, base).unwrap();
3437
3438        let runtime = expanded
3439            .nodes
3440            .iter()
3441            .find(|n| n.id.to_string() == "m.runtime")
3442            .unwrap();
3443        let runtime_build = runtime.operators.as_ref().unwrap().operators[0]
3444            .config
3445            .build
3446            .as_deref()
3447            .unwrap();
3448        assert_eq!(runtime_build, "pip install shared\nmake proc");
3449
3450        let single = expanded
3451            .nodes
3452            .iter()
3453            .find(|n| n.id.to_string() == "m.single")
3454            .unwrap();
3455        let single_build = single.operator.as_ref().unwrap().config.build.as_deref();
3456        assert_eq!(single_build, Some("pip install shared\npip install single"));
3457    }
3458
3459    // ---- Feature 1: boundaries metadata ----
3460
3461    #[test]
3462    fn expand_returns_boundaries() {
3463        let tmp = TempDir::new().unwrap();
3464        let base = tmp.path();
3465
3466        write_file(
3467            base,
3468            "simple_module.yml",
3469            r#"
3470module:
3471  name: simple
3472  inputs: [x]
3473  outputs: [y]
3474
3475nodes:
3476  - id: a
3477    path: a.py
3478    inputs:
3479      x: _mod/x
3480    outputs: [mid]
3481  - id: b
3482    path: b.py
3483    inputs:
3484      mid: a/mid
3485    outputs: [y]
3486"#,
3487        );
3488
3489        let desc = parse_descriptor(
3490            r#"
3491nodes:
3492  - id: src
3493    path: src.py
3494    outputs: [val]
3495  - id: mod1
3496    module: simple_module.yml
3497    inputs:
3498      x: src/val
3499"#,
3500        );
3501
3502        let result = expand_modules_with_boundaries(&desc, base).unwrap();
3503        assert!(result.boundaries.modules.contains_key("mod1"));
3504        let members = &result.boundaries.modules["mod1"];
3505        assert!(members.contains(&"mod1.a".to_string()));
3506        assert!(members.contains(&"mod1.b".to_string()));
3507    }
3508
3509    // ---- Feature 9: check_module_file ----
3510
3511    #[test]
3512    fn check_module_file_valid() {
3513        let tmp = TempDir::new().unwrap();
3514        let path = write_file(
3515            tmp.path(),
3516            "valid_module.yml",
3517            r#"
3518module:
3519  name: valid
3520  inputs: [x]
3521  outputs: [y]
3522
3523nodes:
3524  - id: proc
3525    path: proc.py
3526    inputs:
3527      x: _mod/x
3528    outputs:
3529      - y
3530"#,
3531        );
3532
3533        check_module_file(&path).unwrap();
3534    }
3535
3536    #[test]
3537    fn check_module_file_bad_mod_ref() {
3538        let tmp = TempDir::new().unwrap();
3539        let path = write_file(
3540            tmp.path(),
3541            "bad_ref_module.yml",
3542            r#"
3543module:
3544  name: bad_ref
3545  inputs: [x]
3546  outputs: [y]
3547
3548nodes:
3549  - id: proc
3550    path: proc.py
3551    inputs:
3552      x: _mod/nonexistent
3553    outputs:
3554      - y
3555"#,
3556        );
3557
3558        let result = check_module_file(&path);
3559        assert!(result.is_err());
3560        assert!(result.unwrap_err().to_string().contains("nonexistent"));
3561    }
3562
3563    #[test]
3564    fn check_module_file_rejects_duplicate_header_ports() {
3565        let tmp = TempDir::new().unwrap();
3566
3567        let duplicate_inputs = write_file(
3568            tmp.path(),
3569            "duplicate_inputs.yml",
3570            r#"
3571module:
3572  name: duplicate_inputs
3573  inputs: [data, data]
3574  outputs: [out]
3575
3576nodes:
3577  - id: worker
3578    path: worker.py
3579    inputs:
3580      x: _mod/data
3581    outputs:
3582      - out
3583"#,
3584        );
3585        let msg = check_module_file(&duplicate_inputs)
3586            .unwrap_err()
3587            .to_string();
3588        assert!(msg.contains("duplicate"), "got: {msg}");
3589        assert!(msg.contains("inputs"), "got: {msg}");
3590        assert!(msg.contains("data"), "got: {msg}");
3591
3592        let duplicate_optional = write_file(
3593            tmp.path(),
3594            "duplicate_optional.yml",
3595            r#"
3596module:
3597  name: duplicate_optional
3598  inputs: [data]
3599  inputs_optional: [cfg, cfg]
3600  outputs: [out]
3601
3602nodes:
3603  - id: worker
3604    path: worker.py
3605    inputs:
3606      x: _mod/data
3607    outputs:
3608      - out
3609"#,
3610        );
3611        let msg = check_module_file(&duplicate_optional)
3612            .unwrap_err()
3613            .to_string();
3614        assert!(msg.contains("duplicate"), "got: {msg}");
3615        assert!(msg.contains("inputs_optional"), "got: {msg}");
3616        assert!(msg.contains("cfg"), "got: {msg}");
3617
3618        let duplicate_outputs = write_file(
3619            tmp.path(),
3620            "duplicate_outputs.yml",
3621            r#"
3622module:
3623  name: duplicate_outputs
3624  inputs: [data]
3625  outputs: [out, out]
3626
3627nodes:
3628  - id: worker
3629    path: worker.py
3630    inputs:
3631      x: _mod/data
3632    outputs:
3633      - out
3634"#,
3635        );
3636        let msg = check_module_file(&duplicate_outputs)
3637            .unwrap_err()
3638            .to_string();
3639        assert!(msg.contains("duplicate"), "got: {msg}");
3640        assert!(msg.contains("outputs"), "got: {msg}");
3641        assert!(msg.contains("out"), "got: {msg}");
3642    }
3643
3644    #[test]
3645    fn check_module_file_bad_output() {
3646        let tmp = TempDir::new().unwrap();
3647        let path = write_file(
3648            tmp.path(),
3649            "bad_out_module.yml",
3650            r#"
3651module:
3652  name: bad_out
3653  inputs: []
3654  outputs: [missing]
3655
3656nodes:
3657  - id: proc
3658    path: proc.py
3659    outputs:
3660      - other
3661"#,
3662        );
3663
3664        let result = check_module_file(&path);
3665        assert!(result.is_err());
3666        assert!(result.unwrap_err().to_string().contains("missing"));
3667    }
3668
3669    #[test]
3670    fn check_module_file_rejects_ambiguous_declared_output() {
3671        let tmp = TempDir::new().unwrap();
3672        let path = write_file(
3673            tmp.path(),
3674            "ambiguous_output.yml",
3675            r#"
3676module:
3677  name: ambiguous
3678  inputs: []
3679  outputs: [out]
3680
3681nodes:
3682  - id: first
3683    path: first.py
3684    outputs:
3685      - out
3686  - id: second
3687    path: second.py
3688    outputs:
3689      - out
3690"#,
3691        );
3692
3693        let result = check_module_file(&path);
3694        assert!(result.is_err());
3695        let msg = result.unwrap_err().to_string();
3696        assert!(msg.contains("out"), "got: {msg}");
3697        assert!(msg.contains("multiple"), "got: {msg}");
3698        assert!(msg.contains("first"), "got: {msg}");
3699        assert!(msg.contains("second"), "got: {msg}");
3700    }
3701
3702    #[test]
3703    fn check_module_file_rejects_unknown_module_header_field() {
3704        let tmp = TempDir::new().unwrap();
3705        let path = write_file(
3706            tmp.path(),
3707            "unknown_header_field.yml",
3708            r#"
3709module:
3710  name: bad
3711  inputz: [data]
3712  outputs: [out]
3713
3714nodes:
3715  - id: worker
3716    path: worker.py
3717    outputs:
3718      - out
3719"#,
3720        );
3721
3722        let result = check_module_file(&path);
3723        assert!(result.is_err());
3724        let msg = format!("{:?}", result.unwrap_err());
3725        assert!(msg.contains("inputz"), "got: {msg}");
3726        assert!(msg.contains("unknown field"), "got: {msg}");
3727    }
3728
3729    #[test]
3730    fn check_module_file_rejects_duplicate_inner_node_ids() {
3731        let tmp = TempDir::new().unwrap();
3732        let path = write_file(
3733            tmp.path(),
3734            "duplicate_inner_nodes.yml",
3735            r#"
3736module:
3737  name: duplicate_inner_nodes
3738  inputs: []
3739  outputs: [y]
3740
3741nodes:
3742  - id: proc
3743    path: a.py
3744    outputs:
3745      - y
3746  - id: proc
3747    path: b.py
3748    outputs:
3749      - z
3750"#,
3751        );
3752
3753        let err = check_module_file(&path).unwrap_err().to_string();
3754        assert!(err.contains("duplicate node ID"), "{err}");
3755        assert!(err.contains("proc"), "{err}");
3756    }
3757
3758    #[test]
3759    fn check_module_file_rejects_invalid_internal_wiring() {
3760        let tmp = TempDir::new().unwrap();
3761        let path = write_file(
3762            tmp.path(),
3763            "bad_internal_wiring.yml",
3764            r#"
3765module:
3766  name: bad_internal_wiring
3767  inputs: []
3768  outputs: [y]
3769
3770nodes:
3771  - id: preprocessor
3772    path: preprocessor.py
3773    outputs:
3774      - cleaned
3775  - id: producer
3776    path: producer.py
3777    inputs:
3778      data: preprocessor/cleaned
3779    outputs:
3780      - y
3781  - id: valid_consumer
3782    path: valid_consumer.py
3783    inputs:
3784      data: producer/y
3785    outputs:
3786      - z
3787  - id: consumer
3788    path: consumer.py
3789    inputs:
3790      data: producer/missing
3791  - id: independent
3792    path: independent.py
3793    outputs:
3794      - side
3795"#,
3796        );
3797
3798        let err = check_module_file(&path).unwrap_err().to_string();
3799        assert!(err.contains("producer/missing"), "{err}");
3800    }
3801
3802    #[test]
3803    fn check_module_file_rejects_nested_module_missing_required_input() {
3804        let tmp = TempDir::new().unwrap();
3805
3806        write_file(
3807            tmp.path(),
3808            "leaf.yml",
3809            r#"
3810module:
3811  name: leaf
3812  inputs: [data]
3813  outputs: [out]
3814
3815nodes:
3816  - id: worker
3817    path: worker.py
3818    inputs:
3819      x: _mod/data
3820    outputs:
3821      - out
3822"#,
3823        );
3824
3825        let path = write_file(
3826            tmp.path(),
3827            "outer.yml",
3828            r#"
3829module:
3830  name: outer
3831  inputs: []
3832  outputs: [out]
3833
3834nodes:
3835  - id: nested
3836    module: leaf.yml
3837"#,
3838        );
3839
3840        let result = check_module_file(&path);
3841        assert!(result.is_err());
3842        let msg = result.unwrap_err().to_string();
3843        assert!(msg.contains("leaf"), "got: {msg}");
3844        assert!(msg.contains("data"), "got: {msg}");
3845        assert!(msg.contains("nested"), "got: {msg}");
3846    }
3847
3848    #[test]
3849    fn check_module_file_rejects_invalid_nested_module() {
3850        let tmp = TempDir::new().unwrap();
3851
3852        write_file(
3853            tmp.path(),
3854            "leaf.yml",
3855            r#"
3856module:
3857  name: leaf
3858  inputs: []
3859  outputs: [out]
3860
3861nodes:
3862  - id: worker
3863    path: worker.py
3864    outputs:
3865      - other
3866"#,
3867        );
3868
3869        let path = write_file(
3870            tmp.path(),
3871            "outer.yml",
3872            r#"
3873module:
3874  name: outer
3875  inputs: []
3876  outputs: [out]
3877
3878nodes:
3879  - id: nested
3880    module: leaf.yml
3881"#,
3882        );
3883
3884        let result = check_module_file(&path);
3885        assert!(result.is_err());
3886        let msg = format!("{:#}", result.unwrap_err());
3887        assert!(msg.contains("leaf"), "got: {msg}");
3888        assert!(msg.contains("out"), "got: {msg}");
3889        assert!(msg.contains("no inner node produces it"), "got: {msg}");
3890        // The breadcrumb must name the referencing node so a failure several
3891        // levels down is findable.
3892        assert!(msg.contains("nested"), "got: {msg}");
3893    }
3894
3895    /// The `seen` set must reject a module that includes itself. Without the
3896    /// `seen.insert` guard this recurses to the depth limit and reports a
3897    /// misleading depth error instead of naming the cycle.
3898    #[test]
3899    fn check_module_file_rejects_self_referencing_module() {
3900        let tmp = TempDir::new().unwrap();
3901        let path = write_file(
3902            tmp.path(),
3903            "self.yml",
3904            r#"
3905module:
3906  name: selfref
3907  inputs: []
3908  outputs: []
3909
3910nodes:
3911  - id: me
3912    module: self.yml
3913"#,
3914        );
3915
3916        let msg = format!("{:#}", check_module_file(&path).unwrap_err());
3917        assert!(msg.contains("circular module reference"), "got: {msg}");
3918    }
3919
3920    /// `seen.remove` on the success path must keep a diamond (`a -> b -> d`
3921    /// and `a -> c -> d`) accepted. Drop that line and every shared nested
3922    /// module starts failing as a false "circular reference".
3923    #[test]
3924    fn check_module_file_accepts_diamond_module_graph() {
3925        let tmp = TempDir::new().unwrap();
3926        let base = tmp.path();
3927
3928        write_file(
3929            base,
3930            "d.yml",
3931            r#"
3932module:
3933  name: d
3934  inputs: []
3935  outputs: [d_out]
3936
3937nodes:
3938  - id: leaf
3939    path: leaf.py
3940    outputs:
3941      - d_out
3942"#,
3943        );
3944        for name in ["b.yml", "c.yml"] {
3945            write_file(
3946                base,
3947                name,
3948                r#"
3949module:
3950  name: mid
3951  inputs: []
3952  outputs: [d_out]
3953
3954nodes:
3955  - id: node_d
3956    module: d.yml
3957"#,
3958            );
3959        }
3960        let path = write_file(
3961            base,
3962            "a.yml",
3963            r#"
3964module:
3965  name: a
3966  inputs: []
3967  outputs: []
3968
3969nodes:
3970  - id: node_b
3971    module: b.yml
3972  - id: node_c
3973    module: c.yml
3974"#,
3975        );
3976
3977        check_module_file(&path).unwrap();
3978    }
3979
3980    #[test]
3981    fn check_module_file_rejects_depth_limit() {
3982        let tmp = TempDir::new().unwrap();
3983        let base = tmp.path();
3984
3985        for i in 0..=MAX_MODULE_DEPTH {
3986            let next = if i < MAX_MODULE_DEPTH {
3987                format!("  - id: inner\n    module: level{}_module.yml", i + 1)
3988            } else {
3989                "  - id: worker\n    path: worker.py\n    outputs:\n      - out".to_string()
3990            };
3991
3992            write_file(
3993                base,
3994                &format!("level{i}_module.yml"),
3995                &format!(
3996                    r#"
3997module:
3998  name: level{i}
3999  inputs: []
4000  outputs: [out]
4001
4002nodes:
4003{next}
4004"#
4005                ),
4006            );
4007        }
4008
4009        let result = check_module_file(&base.join("level0_module.yml"));
4010        assert!(result.is_err());
4011        // `{:#}` renders the whole context chain: the nested-module breadcrumb
4012        // wraps the underlying depth-limit error.
4013        assert!(format!("{:#}", result.unwrap_err()).contains("nesting exceeds depth limit"));
4014    }
4015
4016    /// Regression test for #2851: `check_module_file` must accept a nested
4017    /// module reference that points to a sibling directory inside the same
4018    /// project (e.g. `../shared/base.yml`). The real expansion path
4019    /// (`expand_module_node`) confines nested modules to the project root, not
4020    /// to the referencing module's own directory, so such a reference is valid
4021    /// and runnable -- the standalone linter must not spuriously reject it.
4022    #[test]
4023    fn check_module_file_accepts_cross_directory_nested_ref() {
4024        let tmp = TempDir::new().unwrap();
4025
4026        // project/modules/shared/base.yml -- the nested module.
4027        write_file(
4028            tmp.path(),
4029            "modules/shared/base.yml",
4030            r#"
4031module:
4032  name: base
4033  inputs: []
4034  outputs: [y]
4035
4036nodes:
4037  - id: inner
4038    path: inner.py
4039    outputs:
4040      - y
4041"#,
4042        );
4043
4044        // project/modules/a/mod.yml -- references the sibling module via `..`.
4045        let path = write_file(
4046            tmp.path(),
4047            "modules/a/mod.yml",
4048            r#"
4049module:
4050  name: outer
4051  inputs: []
4052  outputs: [y]
4053
4054nodes:
4055  - id: nested
4056    module: ../shared/base.yml
4057"#,
4058        );
4059
4060        // Must pass: the nested reference leaves `modules/a/` but stays inside
4061        // the project, exactly what real expansion accepts.
4062        check_module_file(&path).unwrap();
4063    }
4064
4065    // ---- Security tests ----
4066
4067    #[test]
4068    fn reject_absolute_module_path() {
4069        let desc = parse_descriptor(
4070            r#"
4071nodes:
4072  - id: evil
4073    module: /etc/passwd
4074"#,
4075        );
4076        let tmp = TempDir::new().unwrap();
4077        let result = expand_modules(&desc, tmp.path());
4078        assert!(result.is_err());
4079        let msg = result.unwrap_err().to_string();
4080        assert!(msg.contains("must be relative"), "got: {msg}");
4081    }
4082
4083    #[test]
4084    fn reject_path_traversal_module() {
4085        let tmp = TempDir::new().unwrap();
4086        let base = tmp.path();
4087
4088        // Create a module outside the base dir
4089        let parent = base.parent().unwrap();
4090        write_file(parent, "escape_module.yml", "module:\n  name: x\nnodes: []");
4091
4092        let desc = parse_descriptor(
4093            r#"
4094nodes:
4095  - id: evil
4096    module: ../escape_module.yml
4097"#,
4098        );
4099        let result = expand_modules(&desc, base);
4100        assert!(result.is_err());
4101        let msg = result.unwrap_err().to_string();
4102        assert!(msg.contains("escapes"), "got: {msg}");
4103    }
4104
4105    // This test guards the fix for #3341: an in-tree module directory that is
4106    // a symlink pointing outside the project root.
4107    #[test]
4108    fn expand_modules_accepts_symlinked_module_dir() {
4109        let tmp = TempDir::new().unwrap();
4110        let shared_dir = tmp.path().join("shared_modules");
4111        std::fs::create_dir_all(&shared_dir).unwrap();
4112        write_file(
4113            &shared_dir,
4114            "shared.yml",
4115            r#"
4116module:
4117  name: shared
4118  inputs: [in_val]
4119  outputs: [out_val]
4120
4121nodes:
4122  - id: worker
4123    path: worker.py
4124    inputs:
4125      data: _mod/in_val
4126    outputs:
4127      - out_val
4128"#,
4129        );
4130
4131        let project_dir = tmp.path().join("project");
4132        std::fs::create_dir_all(&project_dir).unwrap();
4133        let symlink_path = project_dir.join("modules");
4134        #[cfg(unix)]
4135        std::os::unix::fs::symlink(&shared_dir, &symlink_path).unwrap();
4136        #[cfg(windows)]
4137        if let Err(e) = std::os::windows::fs::symlink_dir(&shared_dir, &symlink_path) {
4138            eprintln!("skipping symlink test: {e}");
4139            return;
4140        }
4141
4142        let desc = parse_descriptor(
4143            r#"
4144nodes:
4145  - id: m
4146    module: modules/shared.yml
4147    inputs:
4148      in_val: source/data
4149"#,
4150        );
4151
4152        let expanded = expand_modules(&desc, &project_dir).unwrap();
4153        assert_eq!(expanded.nodes.len(), 1);
4154        assert_eq!(expanded.nodes[0].id.to_string(), "m.worker");
4155        assert_eq!(
4156            Path::new(expanded.nodes[0].path.as_ref().unwrap()),
4157            Path::new("modules/worker.py")
4158        );
4159    }
4160
4161    #[test]
4162    fn expand_modules_accepts_in_tree_symlink_with_dotdot() {
4163        let tmp = TempDir::new().unwrap();
4164        let project_dir = tmp.path().join("project");
4165        let real_modules = project_dir.join("real_modules");
4166        std::fs::create_dir_all(&real_modules).unwrap();
4167
4168        write_file(
4169            &project_dir,
4170            "top.yml",
4171            r#"
4172module:
4173  name: top
4174  inputs: [in_val]
4175  outputs: [out_val]
4176
4177nodes:
4178  - id: worker
4179    path: worker.py
4180    inputs:
4181      data: _mod/in_val
4182    outputs:
4183      - out_val
4184"#,
4185        );
4186
4187        let symlink_path = project_dir.join("modules");
4188        #[cfg(unix)]
4189        std::os::unix::fs::symlink(&real_modules, &symlink_path).unwrap();
4190        #[cfg(windows)]
4191        if let Err(e) = std::os::windows::fs::symlink_dir(&real_modules, &symlink_path) {
4192            eprintln!("skipping symlink test: {e}");
4193            return;
4194        }
4195
4196        // `modules/../top.yml` traverses `..` over the in-tree symlink `modules`.
4197        // Lexically and physically, it resolves to `project/top.yml`, within
4198        // the project directory and must be accepted.
4199        let desc = parse_descriptor(
4200            r#"
4201nodes:
4202  - id: m
4203    module: modules/../top.yml
4204    inputs:
4205      in_val: source/data
4206"#,
4207        );
4208
4209        let expanded = expand_modules(&desc, &project_dir).unwrap();
4210        assert_eq!(expanded.nodes.len(), 1);
4211        assert_eq!(expanded.nodes[0].id.to_string(), "m.worker");
4212        assert_eq!(
4213            Path::new(expanded.nodes[0].path.as_ref().unwrap()),
4214            Path::new("worker.py")
4215        );
4216    }
4217
4218    #[test]
4219    fn reject_symlinked_module_dir_divergent_lexical_and_physical() {
4220        let tmp = TempDir::new().unwrap();
4221        let external_base = tmp.path().join("external");
4222        let external_modules = external_base.join("modules");
4223        let external_shared = external_base.join("shared");
4224        std::fs::create_dir_all(&external_modules).unwrap();
4225        std::fs::create_dir_all(&external_shared).unwrap();
4226        write_file(
4227            &external_shared,
4228            "x.yml",
4229            "module:\n  name: x\n  inputs: []\n  outputs: []\nnodes: []",
4230        );
4231
4232        let project_dir = tmp.path().join("project");
4233        std::fs::create_dir_all(&project_dir).unwrap();
4234
4235        let symlink_path = project_dir.join("modules");
4236        #[cfg(unix)]
4237        std::os::unix::fs::symlink(&external_modules, &symlink_path).unwrap();
4238        #[cfg(windows)]
4239        if let Err(e) = std::os::windows::fs::symlink_dir(&external_modules, &symlink_path) {
4240            eprintln!("skipping symlink test: {e}");
4241            return;
4242        }
4243
4244        // Also create project/shared/x.yml so lexical resolution finds a file inside project
4245        let project_shared = project_dir.join("shared");
4246        std::fs::create_dir_all(&project_shared).unwrap();
4247        write_file(
4248            &project_shared,
4249            "x.yml",
4250            "module:\n  name: project_x\n  inputs: []\n  outputs: []\nnodes: []",
4251        );
4252
4253        // `modules/../shared/x.yml`:
4254        // Lexically resolves to `project/shared/x.yml`.
4255        // Physically resolves to `external/shared/x.yml`.
4256        // Lexical and physical resolutions diverge, so this must be rejected.
4257        let desc = parse_descriptor(
4258            r#"
4259nodes:
4260  - id: m
4261    module: modules/../shared/x.yml
4262"#,
4263        );
4264
4265        let result = expand_modules(&desc, &project_dir);
4266        assert!(result.is_err(), "expected error but succeeded");
4267        let msg = result.unwrap_err().to_string();
4268        assert!(msg.contains("escapes"), "got: {msg}");
4269    }
4270
4271    #[test]
4272    fn reject_symlinked_module_dir_dotdot_escape() {
4273        let tmp = TempDir::new().unwrap();
4274        let shared_base = tmp.path().join("shared_base");
4275        let shared_dir = shared_base.join("shared_modules");
4276        std::fs::create_dir_all(&shared_dir).unwrap();
4277        write_file(
4278            &shared_dir,
4279            "shared.yml",
4280            "module:\n  name: shared\n  inputs: []\n  outputs: []\nnodes: []",
4281        );
4282
4283        // Place escape.yml outside the symlink target (in shared_base)
4284        write_file(
4285            &shared_base,
4286            "escape.yml",
4287            "module:\n  name: escape\n  inputs: []\n  outputs: []\nnodes: []",
4288        );
4289
4290        let project_dir = tmp.path().join("project");
4291        std::fs::create_dir_all(&project_dir).unwrap();
4292
4293        let symlink_path = project_dir.join("modules");
4294        #[cfg(unix)]
4295        std::os::unix::fs::symlink(&shared_dir, &symlink_path).unwrap();
4296        #[cfg(windows)]
4297        if let Err(e) = std::os::windows::fs::symlink_dir(&shared_dir, &symlink_path) {
4298            eprintln!("skipping symlink test: {e}");
4299            return;
4300        }
4301
4302        // `modules/../escape.yml` uses a single `..`.
4303        // Lexically, `project/modules/..` collapses to `project/`, which
4304        // would pass a purely lexical containment check.
4305        // Physically, `modules` dereferences to `shared_modules`, and `..`
4306        // escapes into `shared_base/escape.yml`.
4307        // This must be rejected as an escape.
4308        let desc = parse_descriptor(
4309            r#"
4310nodes:
4311  - id: m
4312    module: modules/../escape.yml
4313"#,
4314        );
4315
4316        let result = expand_modules(&desc, &project_dir);
4317        assert!(result.is_err(), "expected error but succeeded");
4318        let msg = result.unwrap_err().to_string();
4319        assert!(msg.contains("escapes"), "got: {msg}");
4320    }
4321
4322    #[test]
4323    fn expand_modules_accepts_dotdot_in_base_dir() {
4324        let tmp = TempDir::new().unwrap();
4325        let sub = tmp.path().join("sub");
4326        std::fs::create_dir_all(&sub).unwrap();
4327        let project_dir = sub.join("..").join("project");
4328        std::fs::create_dir_all(&project_dir).unwrap();
4329        write_file(
4330            &project_dir,
4331            "mod.yml",
4332            r#"
4333module:
4334  name: inner
4335  inputs: [in_val]
4336  outputs: [out_val]
4337
4338nodes:
4339  - id: worker
4340    path: worker.py
4341    inputs:
4342      data: _mod/in_val
4343    outputs:
4344      - out_val
4345"#,
4346        );
4347
4348        let desc = parse_descriptor(
4349            r#"
4350nodes:
4351  - id: m
4352    module: mod.yml
4353    inputs:
4354      in_val: source/data
4355"#,
4356        );
4357
4358        let expanded = expand_modules(&desc, &project_dir).unwrap();
4359        assert_eq!(expanded.nodes.len(), 1);
4360        assert_eq!(expanded.nodes[0].id.to_string(), "m.worker");
4361        assert_eq!(
4362            Path::new(expanded.nodes[0].path.as_ref().unwrap()),
4363            Path::new("worker.py")
4364        );
4365    }
4366
4367    /// A `git:` inner node's `path` names a file inside its clone, which is
4368    /// the node's working dir at build and spawn. Re-rooting it to the module
4369    /// directory made the daemon look for `<clone>/<module_dir>/<path>`.
4370    #[test]
4371    fn expand_keeps_git_inner_node_path_relative_to_the_clone() {
4372        let tmp = TempDir::new().unwrap();
4373        let base = tmp.path();
4374        std::fs::create_dir_all(base.join("modules")).unwrap();
4375
4376        write_file(
4377            &base.join("modules"),
4378            "git_module.yml",
4379            r#"
4380module:
4381  name: git_module
4382  outputs: [from_git, local]
4383
4384nodes:
4385  - id: fromgit
4386    git: https://github.com/example/x.git
4387    path: ../bin/x
4388    outputs:
4389      - from_git
4390  - id: sibling
4391    path: worker.py
4392    outputs:
4393      - local
4394"#,
4395        );
4396
4397        let desc = parse_descriptor(
4398            r#"
4399nodes:
4400  - id: m
4401    module: modules/git_module.yml
4402"#,
4403        );
4404
4405        let expanded = expand_modules(&desc, base).unwrap();
4406        let path_of = |id: &str| {
4407            expanded
4408                .nodes
4409                .iter()
4410                .find(|n| n.id.to_string() == id)
4411                .and_then(|n| n.path.clone())
4412                .unwrap()
4413        };
4414        assert_eq!(path_of("m.fromgit"), "../bin/x");
4415        // A plain `path:` sibling is still re-rooted to the module directory.
4416        assert_eq!(
4417            Path::new(&path_of("m.sibling")),
4418            Path::new("modules").join("worker.py")
4419        );
4420    }
4421
4422    /// #3826: a module node's `path:` that is a single extensionless name
4423    /// keeps meaning the file next to the module (`path`), and the name as
4424    /// written becomes its `path_fallback`, for a command found like a
4425    /// top-level `path:`. Any other `path:` (`worker.py` and a blank one
4426    /// too), a `git:` or `hub:` node and a module in the project root (where
4427    /// nothing is rewritten) get none.
4428    #[test]
4429    fn expand_keeps_a_bare_inner_node_path_as_its_fallback() {
4430        let tmp = TempDir::new().unwrap();
4431        let base = tmp.path();
4432        write_file(
4433            &base.join("modules"),
4434            "m.yml",
4435            r#"
4436module:
4437  name: m
4438nodes:
4439  - id: echo
4440    path: dora-echo
4441  - id: script
4442    path: worker.py
4443  - id: nested
4444    path: bin/tool
4445  - id: current
4446    path: ./tool
4447  - id: var
4448    path: $TOOL
4449  - id: fromgit
4450    git: https://github.com/example/x.git
4451    path: x
4452  - id: fromhub
4453    hub: test/x@^0.1
4454    path: tool
4455  - id: blank
4456    path: "  "
4457"#,
4458        );
4459        write_file(
4460            base,
4461            "root.yml",
4462            "module:\n  name: root\nnodes:\n  - id: echo\n    path: dora-echo\n",
4463        );
4464        let desc = parse_descriptor(
4465            "nodes:\n  - id: m\n    module: modules/m.yml\n  - id: r\n    module: root.yml\n",
4466        );
4467
4468        let expanded = expand_modules(&desc, base).unwrap();
4469        let node = |id: &str| {
4470            let node = expanded
4471                .nodes
4472                .iter()
4473                .find(|n| n.id.to_string() == id)
4474                .unwrap();
4475            (
4476                node.path.as_deref().map(PathBuf::from),
4477                node.path_fallback.as_deref(),
4478            )
4479        };
4480        let in_modules = |name: &str| Some(Path::new("modules").join(name));
4481        assert_eq!(node("m.echo"), (in_modules("dora-echo"), Some("dora-echo")));
4482        assert_eq!(node("m.script"), (in_modules("worker.py"), None));
4483        assert_eq!(node("m.nested"), (in_modules("bin/tool"), None));
4484        assert_eq!(node("m.current"), (in_modules("tool"), None));
4485        assert_eq!(node("m.var"), (in_modules("$TOOL"), None));
4486        assert_eq!(node("m.fromgit"), (Some(PathBuf::from("x")), None));
4487        assert_eq!(node("m.fromhub"), (in_modules("tool"), None));
4488        assert_eq!(node("m.blank"), (in_modules("  "), None));
4489        assert_eq!(node("r.echo"), (Some(PathBuf::from("dora-echo")), None));
4490    }
4491
4492    /// `path_fallback` is internal: only expansion sets it, so a module file
4493    /// must not set it by hand (a dataflow file is checked when it is read,
4494    /// see `a_dataflow_file_cannot_set_path_fallback`).
4495    #[test]
4496    fn a_hand_written_path_fallback_in_a_module_is_rejected() {
4497        let tmp = TempDir::new().unwrap();
4498        let base = tmp.path();
4499        let inner = "  - id: worker\n    path: worker\n    path_fallback: echo\n";
4500        write_file(
4501            base,
4502            "plain.yml",
4503            "module:\n  name: plain\nnodes:\n  - id: ok\n    path: ok\n",
4504        );
4505        write_file(
4506            base,
4507            "inner.yml",
4508            &format!("module:\n  name: inner\nnodes:\n{inner}"),
4509        );
4510        write_file(
4511            base,
4512            "outer.yml",
4513            "module:\n  name: outer\nnodes:\n  - id: sub\n    module: inner.yml\n",
4514        );
4515        let in_module = "module `inner`: node `worker` sets `path_fallback`, which is internal \
4516                         (module expansion sets it); remove it";
4517        for module in ["inner.yml", "outer.yml"] {
4518            let yaml = format!("nodes:\n  - id: m\n    module: {module}\n");
4519            let err = expand_modules(&parse_descriptor(&yaml), base).unwrap_err();
4520            assert_eq!(err.to_string(), in_module, "{yaml}");
4521        }
4522
4523        // `dora expand --module` checks a module file the same way.
4524        let err = check_module_file(&base.join("inner.yml")).unwrap_err();
4525        assert_eq!(err.to_string(), in_module);
4526        let err = check_module_file(&base.join("outer.yml")).unwrap_err();
4527        assert_eq!(err.root_cause().to_string(), in_module);
4528
4529        // Expansion doesn't judge the dataflow's own nodes: a descriptor that
4530        // was expanded already (`dora build`'s session, which the daemon
4531        // expands again) keeps the `path_fallback` expansion set, next to a
4532        // module or not.
4533        let flat = parse_descriptor(&format!(
4534            "nodes:\n  - id: m\n    module: plain.yml\n{inner}"
4535        ));
4536        let expanded = expand_modules(&flat, base).unwrap();
4537        let worker = expanded.nodes.iter().find(|n| n.id.to_string() == "worker");
4538        assert_eq!(worker.unwrap().path_fallback.as_deref(), Some("echo"));
4539    }
4540
4541    #[test]
4542    fn reject_inner_node_path_traversal_via_dotdot() {
4543        let tmp = TempDir::new().unwrap();
4544        let base = tmp.path();
4545
4546        // Module file that declares an inner node with a `..`-escaping path.
4547        // The binary doesn't need to exist — the check is purely lexical.
4548        write_file(
4549            base,
4550            "escape_node_module.yml",
4551            r#"
4552module:
4553  name: escape_node
4554  inputs: []
4555  outputs: []
4556
4557nodes:
4558  - id: evil
4559    path: ../../etc/evil-binary
4560"#,
4561        );
4562
4563        let desc = parse_descriptor(
4564            r#"
4565nodes:
4566  - id: m
4567    module: escape_node_module.yml
4568"#,
4569        );
4570
4571        let result = expand_modules(&desc, base);
4572        assert!(result.is_err(), "expected error but got success");
4573        let msg = result.unwrap_err().to_string();
4574        assert!(
4575            msg.contains("resolves outside the project directory"),
4576            "got: {msg}"
4577        );
4578    }
4579
4580    /// A `dora/logs/<level>/<node>` input naming a sibling inside a module must
4581    /// follow the sibling's prefixed id, or the daemon's exact node-id filter
4582    /// matches nothing and the sink silently receives no logs.
4583    #[test]
4584    fn expand_prefixes_sibling_log_filter() {
4585        let tmp = TempDir::new().unwrap();
4586        let base = tmp.path();
4587
4588        write_file(
4589            base,
4590            "logs_module.yml",
4591            r#"
4592module:
4593  name: logs_module
4594  outputs: []
4595
4596nodes:
4597  - id: worker
4598    path: worker.py
4599  - id: sink
4600    path: sink.py
4601    inputs:
4602      sibling: dora/logs/info/worker
4603      external: dora/logs/warn/outside
4604      all: dora/logs/info
4605"#,
4606        );
4607
4608        let desc = parse_descriptor(
4609            r#"
4610nodes:
4611  - id: m
4612    module: logs_module.yml
4613  - id: outside
4614    path: outside.py
4615"#,
4616        );
4617
4618        let expanded = expand_modules(&desc, base).unwrap();
4619        let sink = expanded
4620            .nodes
4621            .iter()
4622            .find(|n| n.id.to_string() == "m.sink")
4623            .unwrap();
4624        let filter_of = |input: &str| match &sink.inputs[&DataId::from(input.to_string())].mapping {
4625            InputMapping::Logs(filter) => filter.clone(),
4626            other => panic!("expected a logs mapping, got {other:?}"),
4627        };
4628
4629        let sibling = filter_of("sibling");
4630        assert_eq!(sibling.node_filter.unwrap().to_string(), "m.worker");
4631        assert!(sibling.min_level.is_some(), "level must be preserved");
4632        // A node outside the module and an unfiltered subscription are left as is.
4633        assert_eq!(
4634            filter_of("external").node_filter.unwrap().to_string(),
4635            "outside"
4636        );
4637        assert!(filter_of("all").node_filter.is_none());
4638    }
4639
4640    /// A log filter naming a module node (or a nested module inside it) names
4641    /// no node once expanded, so wiring validation must reject it rather than
4642    /// let the sink silently receive nothing. Inside a module, a filter naming
4643    /// an inner node of a nested-module sibling (`inner.worker`) is prefixed
4644    /// with the module id like any sibling reference.
4645    #[test]
4646    fn log_filters_naming_modules_and_nested_module_nodes() {
4647        let tmp = TempDir::new().unwrap();
4648        let base = tmp.path();
4649
4650        write_file(
4651            base,
4652            "leaf_module.yml",
4653            r#"
4654module:
4655  name: leaf_module
4656  outputs: []
4657
4658nodes:
4659  - id: worker
4660    path: worker.py
4661"#,
4662        );
4663        write_file(
4664            base,
4665            "outer_module.yml",
4666            r#"
4667module:
4668  name: outer_module
4669  outputs: []
4670
4671nodes:
4672  - id: inner
4673    module: leaf_module.yml
4674  - id: inner_sink
4675    path: sink.py
4676    inputs:
4677      logs: dora/logs/info/inner.worker
4678"#,
4679        );
4680
4681        for (filter, accepted) in [
4682            ("outer", false),
4683            ("outer.inner", false),
4684            ("outer.inner.worker", true),
4685        ] {
4686            let desc = parse_descriptor(&format!(
4687                r#"
4688nodes:
4689  - id: outer
4690    module: outer_module.yml
4691  - id: sink
4692    path: sink.py
4693    inputs:
4694      logs: dora/logs/info/{filter}
4695"#
4696            ));
4697            let expanded = expand_modules(&desc, base).unwrap();
4698            let result = crate::descriptor::validate::check_wiring(&expanded);
4699            assert_eq!(result.is_ok(), accepted, "{filter}: {result:?}");
4700
4701            let inner_sink = expanded
4702                .nodes
4703                .iter()
4704                .find(|n| n.id.to_string() == "outer.inner_sink")
4705                .unwrap();
4706            let InputMapping::Logs(inner_filter) =
4707                &inner_sink.inputs[&DataId::from("logs".to_string())].mapping
4708            else {
4709                panic!("expected a logs mapping");
4710            };
4711            assert_eq!(
4712                inner_filter.node_filter.as_ref().unwrap().to_string(),
4713                "outer.inner.worker"
4714            );
4715        }
4716    }
4717
4718    /// A module-internal log filter naming a dotted top-level node whose
4719    /// first segment equals a plain (non-module) sibling must not be
4720    /// prefixed: `cam.raw` is that top-level node, not a child of `cam`.
4721    #[test]
4722    fn log_filter_naming_dotted_top_level_node_is_not_prefixed() {
4723        let tmp = TempDir::new().unwrap();
4724        let base = tmp.path();
4725
4726        write_file(
4727            base,
4728            "cam_module.yml",
4729            r#"
4730module:
4731  name: cam_module
4732  outputs: []
4733
4734nodes:
4735  - id: cam
4736    path: cam.py
4737  - id: sink
4738    path: sink.py
4739    inputs:
4740      logs: dora/logs/info/cam.raw
4741"#,
4742        );
4743
4744        let desc = parse_descriptor(
4745            r#"
4746nodes:
4747  - id: m
4748    module: cam_module.yml
4749  - id: cam.raw
4750    path: raw.py
4751"#,
4752        );
4753        let expanded = expand_modules(&desc, base).unwrap();
4754        let sink = expanded
4755            .nodes
4756            .iter()
4757            .find(|n| n.id.to_string() == "m.sink")
4758            .unwrap();
4759        let InputMapping::Logs(filter) = &sink.inputs[&DataId::from("logs".to_string())].mapping
4760        else {
4761            panic!("expected a logs mapping");
4762        };
4763        assert_eq!(filter.node_filter.as_ref().unwrap().to_string(), "cam.raw");
4764        crate::descriptor::validate::check_wiring(&expanded).unwrap();
4765    }
4766
4767    #[test]
4768    fn names_sibling_or_its_inner_node_matches_whole_segments_only() {
4769        let ids = BTreeSet::from([
4770            "inner".to_string(),
4771            "node.v2".to_string(),
4772            "cam".to_string(),
4773        ]);
4774        let modules = BTreeSet::from(["inner".to_string(), "node.v2".to_string()]);
4775        let names = |node| names_sibling_or_its_inner_node(node, &ids, &modules);
4776        assert!(names("inner"));
4777        assert!(names("inner.worker"));
4778        assert!(names("node.v2"));
4779        assert!(names("node.v2.worker"));
4780        assert!(names("cam"));
4781        // `cam` is a plain node, so `cam.raw` is some other node, not one of
4782        // its children.
4783        assert!(!names("cam.raw"));
4784        assert!(!names("innerx"));
4785        assert!(!names("node"));
4786        assert!(!names("outside"));
4787    }
4788
4789    #[test]
4790    fn reject_inner_operator_source_path_traversal_via_dotdot() {
4791        let tmp = TempDir::new().unwrap();
4792        let base = tmp.path();
4793
4794        write_file(
4795            base,
4796            "escape_operator_module.yml",
4797            r#"
4798module:
4799  name: escape_operator
4800  inputs: []
4801  outputs: []
4802
4803nodes:
4804  - id: runtime
4805    operators:
4806      - id: evil
4807        shared-library: ../../etc/evil-operator
4808"#,
4809        );
4810
4811        let desc = parse_descriptor(
4812            r#"
4813nodes:
4814  - id: m
4815    module: escape_operator_module.yml
4816"#,
4817        );
4818
4819        let result = expand_modules(&desc, base);
4820        assert!(result.is_err(), "expected error but got success");
4821        let msg = result.unwrap_err().to_string();
4822        assert!(
4823            msg.contains("resolves outside the project directory"),
4824            "got: {msg}"
4825        );
4826    }
4827
4828    #[test]
4829    fn reject_invalid_param_key() {
4830        let tmp = TempDir::new().unwrap();
4831        let base = tmp.path();
4832
4833        write_file(
4834            base,
4835            "param_mod.yml",
4836            r#"
4837module:
4838  name: p
4839  inputs: [x]
4840  outputs: [y]
4841
4842nodes:
4843  - id: n
4844    path: n.py
4845    inputs:
4846      x: _mod/x
4847    outputs: [y]
4848"#,
4849        );
4850
4851        let desc = parse_descriptor(
4852            r#"
4853nodes:
4854  - id: src
4855    path: src.py
4856    outputs: [v]
4857  - id: m
4858    module: param_mod.yml
4859    inputs:
4860      x: src/v
4861    params:
4862      "bad}key": value
4863"#,
4864        );
4865        let result = expand_modules(&desc, base);
4866        assert!(result.is_err());
4867        let msg = result.unwrap_err().to_string();
4868        assert!(msg.contains("invalid param key"), "got: {msg}");
4869    }
4870
4871    #[test]
4872    fn reject_case_colliding_param_keys() {
4873        let tmp = TempDir::new().unwrap();
4874        let base = tmp.path();
4875
4876        write_file(
4877            base,
4878            "param_mod.yml",
4879            r#"
4880module:
4881  name: p
4882  inputs: [x]
4883  outputs: [y]
4884
4885nodes:
4886  - id: n
4887    path: n.py
4888    inputs:
4889      x: _mod/x
4890    outputs: [y]
4891"#,
4892        );
4893
4894        // `mode` and `Mode` are both valid keys but both map to `PARAM_MODE`,
4895        // so one would silently overwrite the other in the node env.
4896        let desc = parse_descriptor(
4897            r#"
4898nodes:
4899  - id: src
4900    path: src.py
4901    outputs: [v]
4902  - id: m
4903    module: param_mod.yml
4904    inputs:
4905      x: src/v
4906    params:
4907      mode: safe
4908      Mode: turbo
4909"#,
4910        );
4911        let result = expand_modules(&desc, base);
4912        assert!(result.is_err());
4913        let msg = result.unwrap_err().to_string();
4914        assert!(msg.contains("PARAM_MODE"), "got: {msg}");
4915    }
4916
4917    #[test]
4918    fn reject_duplicate_node_ids() {
4919        let tmp = TempDir::new().unwrap();
4920        let base = tmp.path();
4921
4922        write_file(
4923            base,
4924            "dup_module.yml",
4925            r#"
4926module:
4927  name: dup
4928  inputs: []
4929  outputs: [y]
4930
4931nodes:
4932  - id: inner
4933    path: inner.py
4934    outputs: [y]
4935"#,
4936        );
4937
4938        // Top-level node named "m.inner" collides with module expansion
4939        let desc = parse_descriptor(
4940            r#"
4941nodes:
4942  - id: m.inner
4943    path: other.py
4944    outputs: [z]
4945  - id: m
4946    module: dup_module.yml
4947"#,
4948        );
4949        let result = expand_modules(&desc, base);
4950        assert!(result.is_err());
4951        let msg = result.unwrap_err().to_string();
4952        assert!(msg.contains("duplicate node ID"), "got: {msg}");
4953    }
4954
4955    #[test]
4956    fn expand_nested_module_build_propagated() {
4957        let tmp = TempDir::new().unwrap();
4958        let base = tmp.path();
4959
4960        write_file(
4961            base,
4962            "leaf_module.yml",
4963            r#"
4964module:
4965  name: leaf
4966  inputs: [x]
4967  outputs: [y]
4968
4969nodes:
4970  - id: worker
4971    path: worker.py
4972    inputs:
4973      x: _mod/x
4974    outputs:
4975      - y
4976"#,
4977        );
4978
4979        write_file(
4980            base,
4981            "outer_module.yml",
4982            r#"
4983module:
4984  name: outer
4985  inputs: [x]
4986  outputs: [y]
4987
4988build: pip install outer-deps
4989
4990nodes:
4991  - id: inner
4992    module: leaf_module.yml
4993    inputs:
4994      x: _mod/x
4995"#,
4996        );
4997
4998        let desc = parse_descriptor(
4999            r#"
5000nodes:
5001  - id: src
5002    path: src.py
5003    outputs: [val]
5004  - id: top
5005    module: outer_module.yml
5006    inputs:
5007      x: src/val
5008"#,
5009        );
5010
5011        let expanded = expand_modules(&desc, base).unwrap();
5012        let worker = expanded
5013            .nodes
5014            .iter()
5015            .find(|n| n.id.to_string() == "top.inner.worker")
5016            .unwrap();
5017        let build = worker.build.as_deref().unwrap();
5018        assert!(
5019            build.contains("pip install outer-deps"),
5020            "outer module build must propagate through nested modules; got: {build}"
5021        );
5022    }
5023
5024    #[test]
5025    fn param_override_precedence() {
5026        let tmp = TempDir::new().unwrap();
5027        let base = tmp.path();
5028
5029        write_file(
5030            base,
5031            "override_mod.yml",
5032            r#"
5033module:
5034  name: override
5035  inputs: [x]
5036  outputs: [y]
5037
5038nodes:
5039  - id: proc
5040    path: proc.py
5041    inputs:
5042      x: _mod/x
5043    outputs: [y]
5044    env:
5045      PARAM_SPEED: "default_value"
5046"#,
5047        );
5048
5049        let desc = parse_descriptor(
5050            r#"
5051nodes:
5052  - id: src
5053    path: src.py
5054    outputs: [v]
5055  - id: m
5056    module: override_mod.yml
5057    inputs:
5058      x: src/v
5059    params:
5060      speed: "caller_value"
5061"#,
5062        );
5063
5064        let expanded = expand_modules(&desc, base).unwrap();
5065        let proc = expanded
5066            .nodes
5067            .iter()
5068            .find(|n| n.id.to_string() == "m.proc")
5069            .unwrap();
5070        let env = proc.env.as_ref().unwrap();
5071        // Caller params should override inner default
5072        assert_eq!(
5073            env["PARAM_SPEED"],
5074            EnvValue::String("caller_value".to_string())
5075        );
5076    }
5077
5078    /// Regression test for #2441: operator (runtime) inner nodes wire their
5079    /// inputs through `config.inputs`, not the node-level `inputs` map, so
5080    /// `_mod/` and sibling references inside an operator input must be
5081    /// rewritten the same way as node-level inputs.
5082    #[test]
5083    fn expand_rewrites_operator_inputs() {
5084        let tmp = TempDir::new().unwrap();
5085        let base = tmp.path();
5086
5087        write_file(
5088            base,
5089            "runtime_module.yml",
5090            r#"
5091module:
5092  name: rt
5093  inputs: [data]
5094
5095nodes:
5096  - id: stage_a
5097    path: a.py
5098    outputs: [aux]
5099
5100  - id: runtime
5101    operators:
5102      - id: proc
5103        shared-library: proc.so
5104        inputs:
5105          x: _mod/data
5106          y: stage_a/aux
5107        outputs:
5108          - result
5109"#,
5110        );
5111
5112        let desc = parse_descriptor(
5113            r#"
5114nodes:
5115  - id: src
5116    path: src.py
5117    outputs: [val]
5118  - id: m
5119    module: runtime_module.yml
5120    inputs:
5121      data: src/val
5122"#,
5123        );
5124
5125        let expanded = expand_modules(&desc, base).unwrap();
5126
5127        let runtime = expanded
5128            .nodes
5129            .iter()
5130            .find(|n| n.id.to_string() == "m.runtime")
5131            .unwrap();
5132        let proc = runtime
5133            .operators
5134            .as_ref()
5135            .unwrap()
5136            .operators
5137            .iter()
5138            .find(|op| op.id.to_string() == "proc")
5139            .unwrap();
5140
5141        let x = &proc.config.inputs[&DataId::from("x".to_string())];
5142        match &x.mapping {
5143            InputMapping::User(m) => {
5144                assert_eq!(m.source.to_string(), "src");
5145                assert_eq!(m.output.to_string(), "val");
5146            }
5147            _ => panic!("expected user mapping"),
5148        }
5149
5150        let y = &proc.config.inputs[&DataId::from("y".to_string())];
5151        match &y.mapping {
5152            InputMapping::User(m) => {
5153                assert_eq!(m.source.to_string(), "m.stage_a");
5154                assert_eq!(m.output.to_string(), "aux");
5155            }
5156            _ => panic!("expected user mapping"),
5157        }
5158    }
5159
5160    /// Regression test for #2441: `check_module_file` must catch an invalid
5161    /// `_mod/` reference inside an operator input, not just node-level inputs.
5162    #[test]
5163    fn check_module_file_rejects_invalid_mod_ref_in_operator_input() {
5164        let tmp = TempDir::new().unwrap();
5165        let base = tmp.path();
5166
5167        let path = write_file(
5168            base,
5169            "bad_operator_module.yml",
5170            r#"
5171module:
5172  name: bad
5173  inputs: [data]
5174  outputs: [result]
5175
5176nodes:
5177  - id: runtime
5178    operators:
5179      - id: proc
5180        shared-library: proc.so
5181        inputs:
5182          x: _mod/nonexistent
5183        outputs:
5184          - result
5185"#,
5186        );
5187
5188        let err = check_module_file(&path).unwrap_err();
5189        assert!(err.to_string().contains("_mod/nonexistent"));
5190    }
5191
5192    #[test]
5193    fn expand_resolves_inner_operator_and_node_sources_relative_to_module_file() {
5194        let tmp = TempDir::new().unwrap();
5195        let base = tmp.path();
5196
5197        write_file(
5198            base,
5199            "modules/nested/source_paths.yml",
5200            r#"
5201module:
5202  name: source_paths
5203  inputs: [data]
5204  outputs: [from_runtime, from_operator, from_path]
5205
5206nodes:
5207  - id: runtime
5208    operators:
5209      - id: proc
5210        shared-library: libproc.so
5211        inputs:
5212          x: _mod/data
5213        outputs:
5214          - from_runtime
5215
5216  - id: single
5217    operator:
5218      python: single.py
5219      inputs:
5220        x: _mod/data
5221      outputs:
5222        - from_operator
5223
5224  - id: runner
5225    path: runner.py
5226    inputs:
5227      x: _mod/data
5228    outputs:
5229      - from_path
5230"#,
5231        );
5232
5233        let desc = parse_descriptor(
5234            r#"
5235nodes:
5236  - id: src
5237    path: src.py
5238    outputs: [val]
5239  - id: m
5240    module: modules/nested/source_paths.yml
5241    inputs:
5242      data: src/val
5243"#,
5244        );
5245
5246        let expanded = expand_modules(&desc, base).unwrap();
5247        let runtime = expanded
5248            .nodes
5249            .iter()
5250            .find(|n| n.id.to_string() == "m.runtime")
5251            .unwrap();
5252        let proc_source = &runtime
5253            .operators
5254            .as_ref()
5255            .unwrap()
5256            .operators
5257            .first()
5258            .unwrap()
5259            .config
5260            .source;
5261        // `normalize_path` builds the rewritten path with `MAIN_SEPARATOR`,
5262        // so on Windows these come back as `modules\\nested\\...`. Compare on a
5263        // normalized form -- CI runs this suite on windows-latest nightly.
5264        assert!(
5265            matches!(proc_source, dora_message::descriptor::OperatorSource::SharedLibrary(path) if path.replace('\\', "/") == "modules/nested/libproc.so"),
5266            "unexpected runtime operator source: {proc_source:?}"
5267        );
5268
5269        let single = expanded
5270            .nodes
5271            .iter()
5272            .find(|n| n.id.to_string() == "m.single")
5273            .unwrap();
5274        let single_source = &single.operator.as_ref().unwrap().config.source;
5275        assert!(
5276            matches!(single_source, dora_message::descriptor::OperatorSource::Python(source) if source.source.replace('\\', "/") == "modules/nested/single.py"),
5277            "unexpected single operator source: {single_source:?}"
5278        );
5279
5280        let runner = expanded
5281            .nodes
5282            .iter()
5283            .find(|n| n.id.to_string() == "m.runner")
5284            .unwrap();
5285        assert_eq!(
5286            runner
5287                .path
5288                .as_deref()
5289                .map(|p| p.replace('\\', "/"))
5290                .as_deref(),
5291            Some("modules/nested/runner.py")
5292        );
5293    }
5294
5295    /// `path: dynamic` is a sentinel, not a file: the daemon matches it
5296    /// verbatim to decide a node is externally spawned. Module expansion must
5297    /// leave it alone, or a module in a subdirectory turns it into
5298    /// `modules/nested/dynamic` and the node is spawned as a binary instead.
5299    #[test]
5300    fn expand_preserves_dynamic_source_sentinel() {
5301        let tmp = TempDir::new().unwrap();
5302        let base = tmp.path();
5303
5304        write_file(
5305            base,
5306            "modules/nested/dynamic_source.yml",
5307            r#"
5308module:
5309  name: dynamic_source
5310  inputs: [data]
5311  outputs: [result]
5312
5313nodes:
5314  - id: dyn
5315    path: dynamic
5316    inputs:
5317      x: _mod/data
5318    outputs:
5319      - result
5320"#,
5321        );
5322
5323        let desc = parse_descriptor(
5324            r#"
5325nodes:
5326  - id: src
5327    path: src.py
5328    outputs: [val]
5329  - id: m
5330    module: modules/nested/dynamic_source.yml
5331    inputs:
5332      data: src/val
5333"#,
5334        );
5335
5336        let expanded = expand_modules(&desc, base).unwrap();
5337        let dyn_node = expanded
5338            .nodes
5339            .iter()
5340            .find(|n| n.id.to_string() == "m.dyn")
5341            .unwrap();
5342
5343        assert_eq!(dyn_node.path.as_deref(), Some("dynamic"));
5344    }
5345
5346    /// Same as the `dynamic` case: `path: shell` tells the daemon to run
5347    /// `args` through a shell, so expansion must not rewrite it into a path.
5348    #[test]
5349    fn expand_preserves_shell_source_sentinel() {
5350        let tmp = TempDir::new().unwrap();
5351        let base = tmp.path();
5352
5353        write_file(
5354            base,
5355            "modules/nested/shell_source.yml",
5356            r#"
5357module:
5358  name: shell_source
5359  inputs: [data]
5360  outputs: [result]
5361
5362nodes:
5363  - id: shell
5364    path: shell
5365    args: echo hi
5366    inputs:
5367      x: _mod/data
5368    outputs:
5369      - result
5370"#,
5371        );
5372
5373        let desc = parse_descriptor(
5374            r#"
5375nodes:
5376  - id: src
5377    path: src.py
5378    outputs: [val]
5379  - id: m
5380    module: modules/nested/shell_source.yml
5381    inputs:
5382      data: src/val
5383"#,
5384        );
5385
5386        let expanded = expand_modules(&desc, base).unwrap();
5387        let shell_node = expanded
5388            .nodes
5389            .iter()
5390            .find(|n| n.id.to_string() == "m.shell")
5391            .unwrap();
5392
5393        assert_eq!(shell_node.path.as_deref(), Some("shell"));
5394    }
5395
5396    /// Expand a dataflow whose single module node `m` re-exports `result`, and
5397    /// return the mapping the downstream `sink` node ends up with. Also asserts
5398    /// that the expanded dataflow passes wiring validation, which is what
5399    /// catches a producer reference that is syntactically plausible but wrong
5400    /// for the producer's node kind (e.g. a missing operator segment).
5401    fn expand_and_resolve_sink_input(base: &Path) -> UserInputMapping {
5402        let desc = parse_descriptor(
5403            r#"
5404nodes:
5405  - id: src
5406    path: src.py
5407    outputs: [val]
5408  - id: m
5409    module: mod.yml
5410    inputs:
5411      data: src/val
5412  - id: sink
5413    path: sink.py
5414    inputs:
5415      r: m/result
5416"#,
5417        );
5418
5419        let expanded = expand_modules(&desc, base).unwrap();
5420        crate::descriptor::validate::check_wiring(&expanded).unwrap();
5421
5422        let sink = expanded
5423            .nodes
5424            .iter()
5425            .find(|n| n.id.to_string() == "sink")
5426            .unwrap();
5427        match &sink.inputs[&DataId::from("r".to_string())].mapping {
5428            InputMapping::User(m) => m.clone(),
5429            _ => panic!("expected user mapping"),
5430        }
5431    }
5432
5433    /// Regression test for #2817: a module output produced by an operator of a
5434    /// multi-operator runtime node must resolve. Consumers of a runtime node
5435    /// address outputs as `<node>/<operator>/<output>`, so the rewritten
5436    /// reference has to keep the `proc/` segment.
5437    #[test]
5438    fn expand_resolves_operator_produced_module_output() {
5439        let tmp = TempDir::new().unwrap();
5440        let base = tmp.path();
5441
5442        write_file(
5443            base,
5444            "mod.yml",
5445            r#"
5446module:
5447  name: rt
5448  inputs: [data]
5449  outputs: [result]
5450
5451nodes:
5452  - id: runtime
5453    operators:
5454      - id: proc
5455        shared-library: proc.so
5456        inputs:
5457          x: _mod/data
5458        outputs:
5459          - result
5460"#,
5461        );
5462
5463        let mapping = expand_and_resolve_sink_input(base);
5464        assert_eq!(mapping.source.to_string(), "m.runtime");
5465        assert_eq!(mapping.output.to_string(), "proc/result");
5466    }
5467
5468    /// Regression test for #2817: same for a single `operator:` node. Here the
5469    /// output stays bare — `resolve_aliases_and_set_defaults` injects the `op/`
5470    /// prefix afterwards, so adding it during expansion would double it up.
5471    #[test]
5472    fn expand_resolves_single_operator_produced_module_output() {
5473        let tmp = TempDir::new().unwrap();
5474        let base = tmp.path();
5475
5476        write_file(
5477            base,
5478            "mod.yml",
5479            r#"
5480module:
5481  name: rt
5482  inputs: [data]
5483  outputs: [result]
5484
5485nodes:
5486  - id: runtime
5487    operator:
5488      shared-library: proc.so
5489      inputs:
5490        x: _mod/data
5491      outputs:
5492        - result
5493"#,
5494        );
5495
5496        let mapping = expand_and_resolve_sink_input(base);
5497        assert_eq!(mapping.source.to_string(), "m.runtime");
5498        assert_eq!(mapping.output.to_string(), "result");
5499    }
5500
5501    #[test]
5502    fn expand_rejects_ambiguous_module_output() {
5503        let tmp = TempDir::new().unwrap();
5504        let base = tmp.path();
5505
5506        write_file(
5507            base,
5508            "mod.yml",
5509            r#"
5510module:
5511  name: ambiguous
5512  inputs: []
5513  outputs: [out]
5514
5515nodes:
5516  - id: first
5517    path: first.py
5518    outputs:
5519      - out
5520  - id: second
5521    path: second.py
5522    outputs:
5523      - out
5524"#,
5525        );
5526
5527        let desc = parse_descriptor(
5528            r#"
5529nodes:
5530  - id: m
5531    module: mod.yml
5532  - id: sink
5533    path: sink.py
5534    inputs:
5535      value: m/out
5536"#,
5537        );
5538
5539        let result = expand_modules(&desc, base);
5540        assert!(result.is_err());
5541        let msg = result.unwrap_err().to_string();
5542        assert!(msg.contains("out"), "got: {msg}");
5543        assert!(msg.contains("multiple"), "got: {msg}");
5544        assert!(msg.contains("m.first"), "got: {msg}");
5545        assert!(msg.contains("m.second"), "got: {msg}");
5546    }
5547
5548    #[test]
5549    fn expand_rejects_nested_module_private_output_export() {
5550        let tmp = TempDir::new().unwrap();
5551        let base = tmp.path();
5552
5553        write_file(
5554            base,
5555            "leaf.yml",
5556            r#"
5557module:
5558  name: leaf
5559  inputs: []
5560  outputs: [public]
5561
5562nodes:
5563  - id: worker
5564    path: worker.py
5565    outputs:
5566      - public
5567      - private
5568"#,
5569        );
5570
5571        write_file(
5572            base,
5573            "outer.yml",
5574            r#"
5575module:
5576  name: outer
5577  inputs: []
5578  outputs: [private]
5579
5580nodes:
5581  - id: nested
5582    module: leaf.yml
5583"#,
5584        );
5585
5586        let desc = parse_descriptor(
5587            r#"
5588nodes:
5589  - id: m
5590    module: outer.yml
5591  - id: sink
5592    path: sink.py
5593    inputs:
5594      value: m/private
5595"#,
5596        );
5597
5598        let result = expand_modules(&desc, base);
5599        assert!(result.is_err());
5600        let msg = result.unwrap_err().to_string();
5601        assert!(msg.contains("private"), "got: {msg}");
5602        assert!(msg.contains("no inner node produces it"), "got: {msg}");
5603    }
5604
5605    /// Regression test for #2817: `check_module_file` must accept a declared
5606    /// output produced by an operator inner node, and still reject one nothing
5607    /// produces.
5608    #[test]
5609    fn check_module_file_accepts_operator_produced_outputs() {
5610        let tmp = TempDir::new().unwrap();
5611        let base = tmp.path();
5612
5613        let path = write_file(
5614            base,
5615            "mixed_module.yml",
5616            r#"
5617module:
5618  name: mixed
5619  inputs: [data]
5620  outputs: [from_operator]
5621
5622nodes:
5623  - id: runtime
5624    operators:
5625      - id: proc
5626        shared-library: proc.so
5627        inputs:
5628          x: _mod/data
5629        outputs:
5630          - from_operator
5631"#,
5632        );
5633        check_module_file(&path).unwrap();
5634
5635        let missing = write_file(
5636            base,
5637            "missing_module.yml",
5638            r#"
5639module:
5640  name: missing
5641  outputs: [nobody_produces_this]
5642
5643nodes:
5644  - id: runtime
5645    operators:
5646      - id: proc
5647        shared-library: proc.so
5648        outputs:
5649          - something_else
5650"#,
5651        );
5652        let err = check_module_file(&missing).unwrap_err().to_string();
5653        assert!(err.contains("no inner node produces it"), "{err}");
5654    }
5655}