Skip to main content

dora_core/descriptor/
mod.rs

1use dora_message::{
2    config::{Input, InputMapping},
3    descriptor::{EnvValue, derive_port_id, single_topic_port_id},
4    id::{DataId, NodeId, OperatorId},
5};
6use eyre::{Context, OptionExt, Result, bail};
7use std::{
8    borrow::Cow,
9    collections::{BTreeMap, BTreeSet, HashMap},
10    env::consts::EXE_EXTENSION,
11    path::{Component, Path, PathBuf},
12    process::Command,
13};
14
15// reexport for compatibility
16pub use dora_message::descriptor::{
17    CoreNodeKind, CustomNode, DYNAMIC_SOURCE, Descriptor, Node, OperatorConfig, OperatorDefinition,
18    OperatorSource, PythonSource, RUNTIME_PYTHON, RUNTIME_SHARED_LIBRARY, RUNTIME_WASM,
19    ResolvedNode, RmwZenohCompatibility, Ros2BridgeConfig, Ros2Direction, Ros2QosConfig,
20    Ros2TopicConfig, Ros2TransportConfig, RuntimeNode, SHELL_SOURCE, SingleOperatorDefinition,
21    descriptor_for_display,
22};
23pub use validate::ResolvedNodeExt;
24pub use visualize::collect_dora_timers;
25
26mod classify;
27/// Lexically normalize a path (collapse `.` and resolve `..`) without touching
28/// the filesystem — the executable may not be built yet when this is called.
29///
30/// Used to sanitize untrusted node paths before a containment check, so the
31/// two callers (module expansion and manifest injection) must collapse `..`
32/// identically; keeping a single implementation prevents them from drifting.
33pub(crate) fn normalize_path(path: &Path) -> PathBuf {
34    let mut out = PathBuf::new();
35    for component in path.components() {
36        match component {
37            Component::CurDir => {}
38            Component::ParentDir => {
39                out.pop();
40            }
41            other => out.push(other),
42        }
43    }
44    out
45}
46
47mod expand;
48pub mod validate;
49mod visualize;
50
51pub use expand::{
52    ExpandedDescriptor, ModuleBoundaries, check_module_file, expand_modules,
53    expand_modules_with_boundaries, reject_path_fallback,
54};
55
56/// Operations on a parsed [`Descriptor`].
57///
58/// These live on an extension trait rather than inherent methods because
59/// [`Descriptor`] is defined in `dora-message` (the wire-format crate), while
60/// the parsing, validation, resolution, and visualization logic belongs to
61/// `dora-core`. Import the trait to turn a descriptor into the resolved node
62/// map dora runs, validate it, or render it as a mermaid graph.
63///
64/// # Example
65///
66/// ```
67/// use dora_core::descriptor::{Descriptor, DescriptorExt};
68///
69/// let yaml = b"
70/// nodes:
71///   - id: source
72///     path: ./source
73///     outputs: [data]
74///   - id: sink
75///     path: ./sink
76///     inputs:
77///       value: source/data
78/// ";
79///
80/// // Parse the YAML into a descriptor...
81/// let descriptor = Descriptor::parse(yaml.to_vec())?;
82/// assert_eq!(descriptor.nodes.len(), 2);
83///
84/// // ...then resolve aliases and fill in defaults to get the node map dora runs.
85/// let resolved = descriptor.resolve_aliases_and_set_defaults()?;
86/// assert_eq!(resolved.len(), 2);
87/// # Ok::<(), eyre::Report>(())
88/// ```
89pub trait DescriptorExt {
90    /// Resolve the descriptor into the map of nodes dora runs.
91    ///
92    /// Fills in defaults, rewrites single-operator input references to the
93    /// operator-qualified output name, and returns the nodes keyed by id. The
94    /// descriptor must already be module-expanded (see [`expand`](Self::expand))
95    /// if it contains `module:` references.
96    fn resolve_aliases_and_set_defaults(&self) -> eyre::Result<BTreeMap<NodeId, ResolvedNode>>;
97    /// Render the resolved dataflow as a mermaid `flowchart`, annotated with the
98    /// given module `boundaries` (from [`expand_with_boundaries`](Self::expand_with_boundaries)).
99    fn visualize_as_mermaid_with_boundaries(
100        &self,
101        boundaries: &ModuleBoundaries,
102    ) -> eyre::Result<String>;
103    /// Apply a command-line override to the dataflow's completion policy.
104    ///
105    /// `None` leaves the descriptor's own `exit_when_nodes_finish`
106    /// alone, so a setting written in the YAML stands; `Some(v)`
107    /// overrides it in either direction, so `--exit-when-nodes-finish`
108    /// can force the policy on and `=false` can force it off for a
109    /// descriptor that asks for it (dora-rs/dora#2920).
110    ///
111    /// Shared rather than spelled out at each call site: `dora run`,
112    /// `dora start` and the daemon all have to agree, and three copies
113    /// of the same three lines is how one of them ends up not being
114    /// updated.
115    fn apply_exit_when_nodes_finish(&mut self, over: Option<bool>);
116
117    /// Read a descriptor from a YAML file at `path` and [`parse`](Self::parse) it.
118    fn blocking_read(path: &Path) -> eyre::Result<Descriptor>;
119    /// Parse a descriptor from raw YAML bytes.
120    ///
121    /// This only deserializes; it does not expand modules or validate the
122    /// dataflow — use [`check`](Self::check) for that.
123    fn parse(buf: Vec<u8>) -> eyre::Result<Descriptor>;
124    /// Expand modules and validate the whole dataflow (node ids, input wiring,
125    /// field combinations, …), resolving relative paths against `working_dir`.
126    fn check(&self, working_dir: &Path) -> eyre::Result<()>;
127    /// Expand all module references into flat nodes.
128    ///
129    /// Module nodes are replaced by the inner nodes defined in their module
130    /// file. Internal IDs are prefixed with `{module_id}.` and input/output
131    /// wiring is rewritten accordingly.
132    fn expand(&self, working_dir: &Path) -> eyre::Result<Descriptor>;
133    /// Like [`expand`](Self::expand) but also returns module boundary metadata
134    /// for visualization.
135    fn expand_with_boundaries(
136        &self,
137        working_dir: &Path,
138    ) -> eyre::Result<(Descriptor, ModuleBoundaries)>;
139}
140
141pub const SINGLE_OPERATOR_DEFAULT_ID: &str = "op";
142
143/// Prefixes a single-operator node's output id with the operator id
144/// (e.g. `result` -> `op/result`) so downstream references resolve to the
145/// operator-qualified output.
146///
147/// Operator ids are *not* validated against the `DataId` character set when a
148/// descriptor is parsed (`OperatorId` stores its string verbatim), so build the
149/// qualified id fallibly: `DataId::from` panics on characters outside
150/// `[a-zA-Z0-9_./-]`, which would abort `dora check`/`graph`/`build` on an
151/// otherwise-parseable descriptor. Returning an `Err` surfaces it as a clean
152/// descriptor error instead.
153fn prefix_output_with_operator_id(op_name: &OperatorId, output: &DataId) -> eyre::Result<DataId> {
154    format!("{op_name}/{output}")
155        .parse::<DataId>()
156        .map_err(|e| {
157            eyre::eyre!(
158                "operator id `{op_name}` produces an invalid output id `{op_name}/{output}`: {e}"
159            )
160        })
161}
162
163/// Like [`DescriptorExt::resolve_aliases_and_set_defaults`], but resolves
164/// `desc` as a node (or nodes) being added to an already-running dataflow
165/// whose current node set is `topology_nodes`.
166///
167/// Whole-descriptor resolution rewrites an input that references a
168/// single-`operator:` producer from the bare output name to the
169/// operator-qualified one (`result` -> `op/result`). The dynamic-topology
170/// `AddNode` path resolves the new node in isolation, so that producer is not
171/// present in the descriptor being resolved and the rewrite is skipped —
172/// leaving the added node subscribed to an output name nobody publishes
173/// (silent data loss, #2877). Supplying the surrounding `topology_nodes` makes
174/// those producers visible so the prefixing is applied.
175///
176/// `topology_nodes` contribute *only* to the single-operator output-prefixing
177/// lookup — they are never themselves resolved or emitted, and nothing else on
178/// the surrounding descriptor (`env`, `deploy`, …) is consulted. Callers that
179/// want the running dataflow's `env` merged in must set it on `desc` (the
180/// `AddNode` handler does, see #2919). `desc`'s own nodes take precedence in
181/// the lookup, so a node id present in both resolves against the copy being
182/// added.
183pub fn resolve_aliases_and_set_defaults_in_topology(
184    desc: &Descriptor,
185    topology_nodes: &[Node],
186) -> eyre::Result<BTreeMap<NodeId, ResolvedNode>> {
187    let default_op_id = OperatorId::from(SINGLE_OPERATOR_DEFAULT_ID.to_string());
188
189    let single_operator_nodes: HashMap<_, _> = topology_nodes
190        .iter()
191        .chain(desc.nodes.iter())
192        .filter_map(|n| {
193            n.operator
194                .as_ref()
195                .map(|op| (&n.id, op.id.as_ref().unwrap_or(&default_op_id)))
196        })
197        .collect();
198
199    let mut resolved = BTreeMap::new();
200    for mut node in desc.nodes.clone() {
201        // classify node: determine kind + validate fields against whitelist
202        let node_class = classify::classify(&node)?;
203
204        // adjust ROS2 bridge input mappings early
205        if node.ros2.is_some() {
206            for input in node.inputs.values_mut() {
207                if let InputMapping::User(m) = &mut input.mapping
208                    && let Some(op_name) = single_operator_nodes.get(&m.source).copied()
209                {
210                    m.output = prefix_output_with_operator_id(op_name, &m.output)?;
211                }
212            }
213        }
214
215        // adjust input mappings
216        let input_mappings: Vec<_> = match &node_class {
217            classify::NodeClass::Standard { .. } => node.inputs.values_mut().collect(),
218            classify::NodeClass::Runtime => node
219                .operators
220                .as_mut()
221                .ok_or_eyre("no operators")?
222                .operators
223                .iter_mut()
224                .flat_map(|op| op.config.inputs.values_mut())
225                .collect(),
226            classify::NodeClass::Operator => node
227                .operator
228                .as_mut()
229                .ok_or_eyre("no operator")?
230                .config
231                .inputs
232                .values_mut()
233                .collect(),
234            classify::NodeClass::Ros2Bridge => vec![],
235        };
236        for mapping in input_mappings
237            .into_iter()
238            .filter_map(|i| match &mut i.mapping {
239                InputMapping::Timer { .. } | InputMapping::Logs(_) => None,
240                InputMapping::User(m) => Some(m),
241            })
242        {
243            if let Some(op_name) = single_operator_nodes.get(&mapping.source).copied() {
244                mapping.output = prefix_output_with_operator_id(op_name, &mapping.output)?;
245            }
246        }
247
248        // resolve nodes. The two custom-node arms drain the custom-node keys
249        // out of `node` with `CustomNode::from_node`; the node-level keys stay
250        // behind for `ResolvedNode::from_node` below.
251        let kind = match node_class {
252            classify::NodeClass::Standard { source } => {
253                let path = node.path.take().ok_or_eyre("missing `path` attribute")?;
254                let mut custom = CustomNode::from_node(&mut node, path);
255                custom.source = source;
256                CoreNodeKind::Custom(custom)
257            }
258            classify::NodeClass::Runtime => {
259                // `node` is already an owned copy (see `desc.nodes.clone()`
260                // above) and `ResolvedNode::from_node` never reads
261                // `operators`, so move the operator subtree out instead of
262                // deep-cloning it a second time.
263                let runtime = node.operators.take().ok_or_eyre("no operators")?;
264                CoreNodeKind::Runtime(runtime)
265            }
266            classify::NodeClass::Operator => {
267                // Move the operator out of the owned `node` rather than
268                // cloning its (potentially large) config; `from_node` does
269                // not read `operator`.
270                let op = node.operator.take().ok_or_eyre("no operator")?;
271                CoreNodeKind::Runtime(RuntimeNode {
272                    operators: vec![OperatorDefinition {
273                        id: op.id.unwrap_or_else(|| default_op_id.clone()),
274                        config: op.config,
275                    }],
276                })
277            }
278            classify::NodeClass::Ros2Bridge => {
279                let config = node.ros2.as_ref().ok_or_eyre("no ros2")?;
280                let config =
281                    resolve_ros2_single_topic(&node.id, config, &node.inputs, &node.outputs)?;
282                // `resolve_ros2_single_topic` checks single-topic port mappings
283                // and rewrites them into a one-entry `topics:` list; a config
284                // that already uses `topics:` passes through unchanged. Either
285                // way, verify every resolved topic maps to a declared port here
286                // on the resolution path, so the coordinator's `dora start` path
287                // — which resolves without running the validator — rejects an
288                // undeclared multi-topic mapping instead of silently dropping
289                // every message at runtime (dora-rs/dora#3484). Service/action
290                // configs leave `topics` unset and are skipped.
291                if let Some(topics) = &config.topics {
292                    validate_ros2_topic_ports(&node.id, topics, &node.inputs, &node.outputs)?;
293                }
294                let bridge_config_json = serde_json::to_string(&config)
295                    .context("failed to serialize ROS2 bridge config")?;
296
297                let mut envs = BTreeMap::new();
298                envs.insert(
299                    "DORA_ROS2_BRIDGE_CONFIG".to_string(),
300                    EnvValue::String(bridge_config_json),
301                );
302
303                // The bridge binary is fixed, so `path` is a constant and
304                // `source` stays at its default. `path_sha256`,
305                // `path_fallback` and `build` are not accepted on a `ros2:`
306                // node (classification rejects them), so `from_node` finds
307                // them unset.
308                let mut custom =
309                    CustomNode::from_node(&mut node, "dora-ros2-bridge-node".to_string());
310                custom.envs = Some(envs);
311                CoreNodeKind::Custom(custom)
312            }
313        };
314
315        if resolved.contains_key(&node.id) {
316            eyre::bail!(
317                "duplicate node ID `{}` — each node must have a unique `id`",
318                node.id
319            );
320        }
321        let mut resolved_node = ResolvedNode::from_node(node, kind);
322        // Checked here on the resolution path rather than in `validate` alone:
323        // the coordinator's `dora start`, `dora node add/replace` and recovery
324        // paths resolve without validating, and an invalid operator id makes
325        // `DataId::from` panic in the coordinator and the daemon.
326        validate::check_operator_ids(&resolved_node)?;
327        validate::check_runtime_operator_count(&resolved_node)?;
328        // Merge the dataflow-level `env` into the per-node `env`. Per-node keys
329        // win on conflict so a node can override a shared default (e.g. global
330        // `RUST_LOG=info` with one verbose node setting `RUST_LOG=debug`).
331        resolved_node.env = merge_env(desc.env.as_ref(), resolved_node.env.take());
332        resolved.insert(resolved_node.id.clone(), resolved_node);
333    }
334
335    Ok(resolved)
336}
337
338/// Fill a single-topic (`topic:`) ros2 bridge config's port mapping in, by
339/// rewriting it into the equivalent one-entry `topics:` form.
340///
341/// Single-topic mode has no `output:`/`input:` field, so without this the
342/// bridge falls back to the topic-derived id and binds to a port the node never
343/// declared — `/turtle1/pose` to `turtle1_pose` rather than to the documented
344/// `pose` (`docs/ros2-bridge.md`: "the node's declared `outputs` or `inputs` are
345/// used directly"), silently dropping every message.
346///
347/// This is also where an unresolvable mapping is *reported*, rather than in
348/// [`validate`] alone: `dora run` and `dora check` validate first, but the
349/// coordinator's `dora start` path resolves without validating, and there the
350/// only alternative to an error is the silent drop.
351pub(crate) fn resolve_ros2_single_topic<'a>(
352    node_id: &NodeId,
353    config: &'a Ros2BridgeConfig,
354    node_inputs: &BTreeMap<DataId, Input>,
355    node_outputs: &BTreeSet<DataId>,
356) -> eyre::Result<Cow<'a, Ros2BridgeConfig>> {
357    // A config that also sets `topics:` is rejected by the bridge itself
358    // ("exactly one of `topic` or `topics`"); overwriting the list here would
359    // turn that loud failure into a silent one.
360    let (Some(topic), Some(message_type), None) =
361        (&config.topic, &config.message_type, &config.topics)
362    else {
363        return Ok(Cow::Borrowed(config));
364    };
365    let (direction, port_kind, declared) = match config.direction {
366        Ros2Direction::Subscribe => (
367            "subscribe",
368            "output",
369            node_outputs
370                .iter()
371                .map(|id| id.as_str())
372                .collect::<Vec<_>>(),
373        ),
374        Ros2Direction::Publish => (
375            "publish",
376            "input",
377            node_inputs.keys().map(|id| id.as_str()).collect(),
378        ),
379    };
380    let Some(port) = single_topic_port_id(topic, &declared) else {
381        if declared.is_empty() {
382            bail!("node `{node_id}`: ros2 {direction} bridge requires at least one {port_kind}");
383        }
384        bail!(
385            "node `{node_id}`: ros2 {direction} topic `{topic}` has no unambiguous {port_kind} \
386             — single-topic mode binds to the node's declared {port_kind}, but it declares \
387             several: {}. Declare a single {port_kind}, name one of them after the topic \
388             (`{}`), or use `topics:` with an explicit `{port_kind}:`",
389            declared
390                .iter()
391                .map(|port| format!("`{port}`"))
392                .collect::<Vec<_>>()
393                .join(", "),
394            derive_port_id(topic),
395        );
396    };
397    let (output, input) = match config.direction {
398        Ros2Direction::Subscribe => (Some(port), None),
399        Ros2Direction::Publish => (None, Some(port)),
400    };
401    let mut resolved = config.clone();
402    resolved.topic = None;
403    resolved.message_type = None;
404    resolved.topics = Some(vec![Ros2TopicConfig {
405        topic: topic.clone(),
406        message_type: message_type.clone(),
407        direction: config.direction.clone(),
408        output,
409        input,
410        // Per-topic QoS unset, so the topic inherits the bridge-level `qos`
411        // the single-topic form already carries.
412        qos: None,
413    }]);
414    Ok(Cow::Owned(resolved))
415}
416
417/// Verify that every entry of a multi-topic (`topics:`) ros2 bridge config maps
418/// to a port the node actually declares.
419///
420/// The bridge routes each topic to a dora port: a subscribe topic feeds an
421/// output, a publish topic consumes an input. When the mapping is not set
422/// explicitly the id is derived from the topic name
423/// ([`Ros2TopicConfig::output_port_id`] / [`input_port_id`]). Either way, the
424/// resulting id must be a declared port — otherwise data is silently dropped at
425/// runtime with no diagnostic: a subscribe `send_output` to an unknown id is
426/// ignored, and a publish topic bound to an unknown input never receives any
427/// data to publish.
428///
429/// Like [`resolve_ros2_single_topic`], this lives on the *resolution* path (and
430/// is delegated to from [`validate`]) rather than in the validator alone: `dora
431/// run` and `dora check` validate first, but the coordinator's `dora start` path
432/// resolves without validating, so a validator-only guard would still drop
433/// silently there (dora-rs/dora#3484).
434///
435/// [`input_port_id`]: Ros2TopicConfig::input_port_id
436pub(crate) fn validate_ros2_topic_ports(
437    node_id: &NodeId,
438    topics: &[Ros2TopicConfig],
439    node_inputs: &BTreeMap<DataId, Input>,
440    node_outputs: &BTreeSet<DataId>,
441) -> eyre::Result<()> {
442    for t in topics {
443        match &t.direction {
444            Ros2Direction::Subscribe => {
445                let output = t.output_port_id();
446                if !node_outputs.contains(output.as_str()) {
447                    bail!(
448                        "node `{node_id}`: ros2 subscribe topic `{}` maps to output \
449                         `{output}`, which is not declared in the node's `outputs`",
450                        t.topic
451                    );
452                }
453            }
454            Ros2Direction::Publish => {
455                let input = t.input_port_id();
456                if !node_inputs.contains_key(input.as_str()) {
457                    bail!(
458                        "node `{node_id}`: ros2 publish topic `{}` maps to input \
459                         `{input}`, which is not declared in the node's `inputs`",
460                        t.topic
461                    );
462                }
463            }
464        }
465    }
466    Ok(())
467}
468
469impl DescriptorExt for Descriptor {
470    fn resolve_aliases_and_set_defaults(&self) -> eyre::Result<BTreeMap<NodeId, ResolvedNode>> {
471        resolve_aliases_and_set_defaults_in_topology(self, &[])
472    }
473
474    fn visualize_as_mermaid_with_boundaries(
475        &self,
476        boundaries: &ModuleBoundaries,
477    ) -> eyre::Result<String> {
478        let resolved = self.resolve_aliases_and_set_defaults()?;
479        let flowchart = visualize::visualize_nodes_with_boundaries(&resolved, boundaries);
480        Ok(flowchart)
481    }
482
483    fn apply_exit_when_nodes_finish(&mut self, over: Option<bool>) {
484        if let Some(over) = over {
485            self.exit_when_nodes_finish = Some(over);
486        }
487    }
488
489    fn blocking_read(path: &Path) -> eyre::Result<Descriptor> {
490        let buf = std::fs::read(path).context("failed to open given file")?;
491        Descriptor::parse(buf)
492    }
493
494    fn parse(buf: Vec<u8>) -> eyre::Result<Descriptor> {
495        let descriptor: Descriptor =
496            serde_yaml::from_slice(&buf).context("failed to parse given descriptor")?;
497        reject_duplicate_keys(&buf).context("failed to parse given descriptor")?;
498        // A dataflow file must not set the internal `path_fallback`. Checked
499        // here, not in expansion: the daemon also expands a descriptor that
500        // was expanded already (`dora build`'s session), which carries it.
501        for node in &descriptor.nodes {
502            expand::reject_path_fallback(node, None)?;
503        }
504        Ok(descriptor)
505    }
506
507    fn check(&self, working_dir: &Path) -> eyre::Result<()> {
508        let expanded = self.expand(working_dir)?;
509        validate::check_dataflow(&expanded, working_dir)
510            .wrap_err("Dataflow could not be validated.")
511    }
512
513    fn expand(&self, working_dir: &Path) -> eyre::Result<Descriptor> {
514        expand::expand_modules(self, working_dir)
515    }
516
517    fn expand_with_boundaries(
518        &self,
519        working_dir: &Path,
520    ) -> eyre::Result<(Descriptor, ModuleBoundaries)> {
521        let expanded = expand::expand_modules_with_boundaries(self, working_dir)?;
522        Ok((expanded.descriptor, expanded.boundaries))
523    }
524}
525
526/// Merge dataflow-level `env` into a node's `env`, with per-node keys winning
527/// on conflict. Returns `None` when the merged result is empty so the resolved
528/// node serializes cleanly (no empty `env: {}` map) whenever no env vars are
529/// effectively set — regardless of whether the emptiness comes from the global
530/// map, the node map, or both (e.g. a node that declares `env: {}` with no
531/// dataflow-level env).
532fn merge_env(
533    global: Option<&BTreeMap<String, EnvValue>>,
534    node: Option<BTreeMap<String, EnvValue>>,
535) -> Option<BTreeMap<String, EnvValue>> {
536    let merged = match (global, node) {
537        (None, None) => return None,
538        (None, Some(node)) => node,
539        (Some(global), None) => global.clone(),
540        (Some(global), Some(node)) => {
541            let mut merged = global.clone();
542            // Per-node entries override global ones on key conflict.
543            merged.extend(node);
544            merged
545        }
546    };
547    // Normalize an empty result to `None` regardless of which side was empty.
548    (!merged.is_empty()).then_some(merged)
549}
550
551/// Fail if any YAML mapping in `buf` repeats a key.
552///
553/// YAML forbids duplicate keys, but `serde_yaml`'s typed deserializer hands a
554/// repeated key to a map field (`inputs`, `env`, ...) as a second insert, so
555/// the last entry silently wins: a copy-pasted `image:` input line would drop
556/// the first subscription without any error. `serde_yaml::Value` does reject
557/// them, naming the key and its location, so parse `buf` into it as a check.
558/// Struct fields already reject duplicates on their own, so this only adds
559/// errors for map-valued fields.
560///
561/// [`DescriptorExt::parse`], module loading, node manifests and user type
562/// files call this already; call it when deserializing other YAML that users
563/// write (such as a single node) directly.
564///
565/// ```
566/// use dora_core::descriptor::reject_duplicate_keys;
567///
568/// let yaml = b"id: sink\npath: ./sink\ninputs:\n  image: cam/img\n  image: dora/timer/millis/20\n";
569/// let err = reject_duplicate_keys(yaml).unwrap_err();
570/// assert!(err.to_string().contains(r#"duplicate entry with key "image""#));
571///
572/// reject_duplicate_keys(b"id: sink\npath: ./sink\n").unwrap();
573/// ```
574pub fn reject_duplicate_keys(buf: &[u8]) -> eyre::Result<()> {
575    serde_yaml::from_slice::<serde_yaml::Value>(buf)?;
576    Ok(())
577}
578
579/// Async counterpart of [`DescriptorExt::blocking_read`]: read a descriptor
580/// from the YAML file at `path` and [`parse`](DescriptorExt::parse) it.
581///
582/// Like `blocking_read`, this only reads and deserializes — it neither expands
583/// modules nor validates the dataflow (use [`DescriptorExt::check`] for that).
584pub async fn read_as_descriptor(path: &Path) -> eyre::Result<Descriptor> {
585    let buf = tokio::fs::read(path)
586        .await
587        .context("failed to open given file")?;
588    Descriptor::parse(buf)
589}
590
591/// Returns `true` if `source` is an `http://` or `https://` URL.
592///
593/// This is the trust boundary that decides whether a node `path` is fetched as
594/// a remote download (and, for hub artifacts, checksum-verified) versus
595/// resolved as a local filesystem path. The match is on the literal scheme
596/// prefix and is **case-sensitive**: an upper-cased scheme such as `HTTPS://`
597/// is treated as a path, not a URL. Schemes other than HTTP(S) (e.g. `ftp://`,
598/// `s3://`, `file://`) are likewise not considered URLs here.
599///
600/// ```
601/// use dora_core::descriptor::source_is_url;
602///
603/// assert!(source_is_url("https://example.com/node"));
604/// assert!(source_is_url("http://example.com/node"));
605///
606/// assert!(!source_is_url("./build/my_node"));
607/// assert!(!source_is_url("/usr/bin/my_node"));
608/// assert!(!source_is_url("s3://bucket/key"));
609/// assert!(!source_is_url("HTTPS://example.com/node")); // case-sensitive
610/// ```
611pub fn source_is_url(source: &str) -> bool {
612    source.starts_with("https://") || source.starts_with("http://")
613}
614
615/// Resolve a node's executable `source` to an absolute path.
616///
617/// An extensionless `source` gets the platform executable extension. The path
618/// is then searched, in order:
619///
620/// 1. under `working_dir` (the dataflow's directory),
621/// 2. the `uv`-managed environment, when `uv` is on the host,
622/// 3. the ambient system `$PATH`.
623///
624/// The resolved path is absolutized but symlinks are **not** resolved (the
625/// binary is spawned at the path it was found). Unlike
626/// [`resolve_path_confined`], this has an ambient-`$PATH` fallback and does not
627/// confine the result to any root — it is the resolution used for local,
628/// trusted dataflow files, whereas confined resolution is for untrusted `hub:`
629/// nodes.
630pub fn resolve_path(source: &str, working_dir: &Path) -> Result<PathBuf> {
631    let path = with_exe_extension(source);
632
633    // Search path within current working directory. A folder that cannot be
634    // spawned must not shadow the uv/`$PATH` lookup (see `is_spawnable`).
635    let joined = working_dir.join(&path);
636    if is_spawnable(&joined) {
637        absolutize_preserving_symlinks(&joined)
638    // Otherwise resolve against the `uv`-managed environment first (when `uv`
639    // is available), then fall back to the system `$PATH`.
640    } else if which::which("uv").is_ok() {
641        or_on_system_path(resolve_path_via_uv(&path), &path)
642    } else if let Ok(abs_path) = which::which(&path) {
643        Ok(abs_path)
644    } else {
645        bail!("Could not find source path {}", path.display())
646    }
647}
648
649/// Whether a node path found on disk can be spawned.
650///
651/// A folder named like the executable (often a Python package's source, next
652/// to the console script that `pip install -e` puts on `$PATH`) cannot be, so
653/// it must not count as found. The exception is a folder with a
654/// `__main__.py`: under `--uv` it is spawned as `uv run <folder>`, which runs
655/// that file.
656fn is_spawnable(path: &Path) -> bool {
657    path.is_file() || path.join("__main__.py").is_file()
658}
659
660/// `source` with the platform's executable extension when it has none.
661fn with_exe_extension(source: &str) -> PathBuf {
662    let path = Path::new(source);
663    if path.extension().is_none() {
664        path.with_extension(EXE_EXTENSION)
665    } else {
666        path.to_owned()
667    }
668}
669
670/// [`resolve_path`] for a node's `path`. A node with a `path_fallback` (module
671/// expansion sets it to the name a bare module node `path:` was written as,
672/// #3826) runs the file at `path` if there is one, so a file next to the
673/// module wins, and else the fallback, looked up like a top-level `path`. A
674/// folder at `path` (often a Python package's source, named like its console
675/// script) is not a file, so the fallback is used. `path` itself is not looked
676/// up in uv or on `$PATH` then, where a relative `modules/tool` would be found
677/// from the current directory instead.
678pub fn resolve_node_path(
679    path: &str,
680    fallback: Option<&str>,
681    working_dir: &Path,
682) -> Result<PathBuf> {
683    let Some(fallback) = fallback else {
684        return resolve_path(path, working_dir);
685    };
686    let local = working_dir.join(with_exe_extension(path));
687    if local.is_file() {
688        return absolutize_preserving_symlinks(&local);
689    }
690    resolve_path(fallback, working_dir).wrap_err_with(|| {
691        format!("Could not find source path {path}, nor its `path_fallback` `{fallback}`")
692    })
693}
694
695/// Returns `descriptor` as nodes and the CLI receive it (`NodeConfig`,
696/// `DataflowInfo`): without `path_fallback`, which they never read, and which
697/// a node or CLI built with an older dora rejects as an unknown field.
698pub fn without_path_fallback(descriptor: &Descriptor) -> Descriptor {
699    let mut descriptor = descriptor.clone();
700    for node in &mut descriptor.nodes {
701        node.path_fallback = None;
702    }
703    descriptor
704}
705
706/// Fall back to the ambient `$PATH` when the `uv` lookup failed. If the binary
707/// is not on `$PATH` either, the error names both searches, with the `uv`
708/// failure as its cause.
709///
710/// `uv run` fails for reasons unrelated to the binary (a project whose
711/// dependencies do not resolve, no network, no `which` binary on the host),
712/// and none of those should hide a binary that `$PATH` provides.
713fn or_on_system_path(uv_result: Result<PathBuf>, path: &Path) -> Result<PathBuf> {
714    uv_result.or_else(|uv_err| {
715        which::which(path).map_err(|_| {
716            uv_err.wrap_err(format!(
717                "Could not find source path {} in the uv environment or on $PATH",
718                path.display()
719            ))
720        })
721    })
722}
723
724/// Resolve a hub node's entrypoint under **confined** rules (spec §11): the
725/// executable may only come from the node's own working directory
726/// (`<clone>/<subdir>`) or its managed Python environment. There is no
727/// ambient-`$PATH` fallback — a typo or missing console script fails loudly
728/// instead of silently running a host binary — and the resolved path is
729/// canonicalized and checked to stay inside those roots, so a symlink
730/// escaping the working dir is rejected rather than followed.
731pub fn resolve_path_confined(
732    source: &str,
733    working_dir: &Path,
734    python_env_dir: Option<&Path>,
735) -> Result<PathBuf> {
736    let path = Path::new(&source);
737    let path = if path.extension().is_none() {
738        path.with_extension(EXE_EXTENSION)
739    } else {
740        path.to_owned()
741    };
742
743    // a console script installed into the node's managed env
744    if let Some(env_dir) = python_env_dir {
745        let bin_dir = env_dir.join(if cfg!(windows) { "Scripts" } else { "bin" });
746        let candidate = bin_dir.join(&path);
747        if candidate.is_file() {
748            return confine(&candidate, &bin_dir);
749        }
750    }
751
752    // a file within the node's working dir (e.g. target/release/<bin>)
753    let candidate = working_dir.join(&path);
754    if is_spawnable(&candidate) {
755        return confine(&candidate, working_dir);
756    }
757
758    bail!(
759        "could not find `{}` in the node's working directory `{}`{} — \
760         hub nodes resolve only within their own package (no $PATH fallback)",
761        path.display(),
762        working_dir.display(),
763        python_env_dir
764            .map(|env| format!(" or its managed environment `{}`", env.display()))
765            .unwrap_or_default(),
766    )
767}
768
769/// Canonicalize `candidate` and require it to stay under `root`.
770fn confine(candidate: &Path, root: &Path) -> Result<PathBuf> {
771    let resolved = candidate
772        .canonicalize()
773        .with_context(|| format!("failed to canonicalize `{}`", candidate.display()))?;
774    let root = root
775        .canonicalize()
776        .with_context(|| format!("failed to canonicalize `{}`", root.display()))?;
777    if !resolved.starts_with(&root) {
778        bail!(
779            "entrypoint `{}` resolves outside the node's directory `{}` \
780             (symlink escape?) — refusing to run it",
781            resolved.display(),
782            root.display()
783        );
784    }
785    Ok(resolved)
786}
787
788/// Make an existing executable path absolute WITHOUT following symlinks.
789///
790/// Deliberately not `canonicalize()`: that resolves symlinks, and a
791/// virtualenv's `bin/python` is a symlink whose *location* is what
792/// CPython uses to discover `pyvenv.cfg`. Resolving it before exec runs
793/// the base interpreter with no venv, so imports that work in a shell
794/// fail under dora (dora-rs/dora#2918). `path::absolute` only prepends
795/// the cwd and drops `.` components; symlinks and `..` are left for the
796/// kernel to resolve at exec time, which matches shell behavior.
797///
798/// Errors if the path does not exist (`exists()` traverses symlinks, so
799/// a dangling link counts as missing — same outcome canonicalize gave).
800/// Shared by every [`resolve_path`] branch so the no-symlink-resolution
801/// contract cannot regress in one branch while the tests exercise
802/// another.
803fn absolutize_preserving_symlinks(path: &Path) -> Result<PathBuf> {
804    if !path.exists() {
805        bail!("path {} does not exist", path.display());
806    }
807    std::path::absolute(path)
808        .with_context(|| format!("failed to make path {} absolute", path.display()))
809}
810
811/// Resolve `path` against the `uv`-managed environment by running
812/// `uv run which <path>`, returning an absolute path.
813///
814/// Unlike a fire-and-forget spawn, this waits for the child, checks its
815/// exit status (so a missing binary surfaces as an error), and verifies
816/// the captured location exists — without resolving symlinks, which
817/// would reintroduce the venv bypass fixed for the working-dir branch
818/// (dora-rs/dora#2918).
819fn resolve_path_via_uv(path: &Path) -> Result<PathBuf> {
820    let which = if cfg!(windows) { "where" } else { "which" };
821    let output = Command::new("uv")
822        .arg("run")
823        .arg(which)
824        .arg(path)
825        .output()
826        .with_context(|| format!("failed to run `uv run {which}`"))?;
827    if !output.status.success() {
828        bail!("Could not find source path {} within uv", path.display());
829    }
830    // `which`/`where` may emit multiple matches; the first line is the
831    // resolved binary.
832    let stdout = String::from_utf8_lossy(&output.stdout);
833    let resolved = stdout
834        .lines()
835        .map(str::trim)
836        .find(|line| !line.is_empty())
837        .ok_or_else(|| eyre::eyre!("`uv run {which} {}` produced no output", path.display()))?;
838    absolutize_preserving_symlinks(Path::new(resolved))
839        .with_context(|| format!("uv-resolved path {resolved} is not usable"))
840}
841
842/// Canonicalize the working dir for a dataflow, preferring an explicit
843/// override over the dataflow file's parent directory.
844///
845/// When falling back to the dataflow's parent directory, returns the lexical parent
846/// directory of the dataflow path as given, canonicalized — symlinks in the file
847/// are not resolved, so the project root matches where the entrypoint was invoked
848/// rather than the target's location.
849pub fn canonicalize_working_dir(
850    override_: Option<&Path>,
851    dataflow_path: &Path,
852) -> eyre::Result<PathBuf> {
853    match override_ {
854        Some(p) => dunce::canonicalize(p)
855            .with_context(|| format!("failed to canonicalize working_dir `{}`", p.display())),
856        None => {
857            let parent = dataflow_path
858                .parent()
859                .filter(|p| !p.as_os_str().is_empty())
860                .unwrap_or_else(|| Path::new("."));
861            dunce::canonicalize(parent).with_context(|| {
862                format!(
863                    "failed to canonicalize dataflow parent directory `{}`",
864                    parent.display()
865                )
866            })
867        }
868    }
869}
870
871/// Classification of a [`Node`] by which of its mutually exclusive
872/// implementation fields is set.
873pub trait NodeExt {
874    /// Determine the node's [`NodeKind`].
875    ///
876    /// A node must set **exactly one** of `path`, `operators`, `operator`,
877    /// `ros2`, or `module`; this returns an error if none or more than one is
878    /// set. A node carrying an unresolved `hub:` reference is also rejected —
879    /// `hub:` is desugared into a concrete node earlier in the build, so
880    /// reaching `kind` with one still present means resolution was skipped.
881    fn kind(&self) -> eyre::Result<NodeKind<'_>>;
882}
883
884impl NodeExt for Node {
885    fn kind(&self) -> eyre::Result<NodeKind<'_>> {
886        if self.hub.is_some() && self.path.is_none() {
887            // `hub:` is desugared into a concrete git node by `dora build` /
888            // `dora run` / `dora validate` before any kind dispatch — an
889            // unresolved reference reaching this point means a flow that
890            // skipped resolution
891            eyre::bail!(
892                "node `{}` uses an unresolved `hub:` reference — run `dora build` \
893                 first (`dora start` requires a prior build for hub nodes)",
894                self.id
895            );
896        }
897        match (
898            &self.path,
899            &self.operators,
900            &self.operator,
901            &self.ros2,
902            &self.module,
903        ) {
904            (None, None, None, None, None) => {
905                eyre::bail!(
906                    "node `{}` requires a `path`, `operators`, `operator`, `ros2`, or `module` field",
907                    self.id
908                )
909            }
910            (None, None, Some(operator), None, None) => Ok(NodeKind::Operator(operator)),
911            (None, Some(runtime), None, None, None) => Ok(NodeKind::Runtime(runtime)),
912            (Some(path), None, None, None, None) => Ok(NodeKind::Standard(path)),
913            (None, None, None, Some(ros2), None) => Ok(NodeKind::Ros2Bridge(ros2)),
914            (None, None, None, None, Some(module)) => Ok(NodeKind::Module(module)),
915            _ => {
916                eyre::bail!(
917                    "node `{}` has multiple exclusive fields set, only one of `path`, `operators`, `operator`, `ros2`, and `module` is allowed",
918                    self.id
919                )
920            }
921        }
922    }
923}
924
925/// The implementation kind of a [`Node`], returned by [`NodeExt::kind`].
926///
927/// Each variant borrows the one exclusive field that was set on the node.
928#[derive(Debug)]
929pub enum NodeKind<'a> {
930    /// A custom node run from an executable `path`.
931    Standard(&'a String),
932    /// A dora runtime node hosting one or more in-process `operators`.
933    Runtime(&'a RuntimeNode),
934    /// A node defined by a single inline `operator`.
935    Operator(&'a SingleOperatorDefinition),
936    /// A ROS2 bridge node.
937    Ros2Bridge(&'a Ros2BridgeConfig),
938    /// A `module` (sub-dataflow) reference — must be expanded before resolution.
939    Module(&'a String),
940}
941
942#[cfg(test)]
943mod tests {
944    /// The `DORA_ROS2_BRIDGE_CONFIG` a resolved bridge node is spawned with.
945    fn resolved_bridge_config(yaml: &str) -> Ros2BridgeConfig {
946        let descriptor: Descriptor = serde_yaml::from_str(yaml).expect("parse");
947        let resolved = descriptor
948            .resolve_aliases_and_set_defaults()
949            .expect("resolve");
950        let node = resolved.values().next().expect("one node");
951        let CoreNodeKind::Custom(custom) = &node.kind else {
952            panic!("ros2 bridge must resolve to a custom node");
953        };
954        let Some(EnvValue::String(json)) = custom
955            .envs
956            .as_ref()
957            .and_then(|envs| envs.get("DORA_ROS2_BRIDGE_CONFIG"))
958        else {
959            panic!("bridge node must carry DORA_ROS2_BRIDGE_CONFIG");
960        };
961        serde_json::from_str(json).expect("bridge config round-trips")
962    }
963
964    /// A single-topic subscribe bridge must bind to the declared `pose`, not to
965    /// the topic-derived `turtle1_pose` the bridge would otherwise fall back to
966    /// — nothing is wired to that id, so every message would be dropped.
967    #[test]
968    fn single_topic_subscribe_binds_the_declared_output() {
969        let config = resolved_bridge_config(
970            "\
971nodes:
972  - id: pose_bridge
973    ros2:
974      topic: /turtle1/pose
975      message_type: turtlesim/Pose
976      direction: subscribe
977    outputs:
978      - pose
979",
980        );
981        let topics = config
982            .topics
983            .expect("single topic is resolved to a mapping");
984        assert_eq!(topics.len(), 1);
985        assert_eq!(topics[0].topic, "/turtle1/pose");
986        assert_eq!(topics[0].output.as_deref(), Some("pose"));
987        assert_eq!(config.topic, None, "the unresolved form must not survive");
988    }
989
990    #[test]
991    fn single_topic_publish_binds_the_declared_input() {
992        let config = resolved_bridge_config(
993            "\
994nodes:
995  - id: cmd_bridge
996    ros2:
997      topic: /turtle1/cmd_vel
998      message_type: geometry_msgs/Twist
999      direction: publish
1000    inputs:
1001      cmd_vel: planner/cmd_vel
1002",
1003        );
1004        let topics = config
1005            .topics
1006            .expect("single topic is resolved to a mapping");
1007        assert_eq!(topics[0].input.as_deref(), Some("cmd_vel"));
1008    }
1009
1010    /// Multi-topic configs already carry their mapping and must pass through.
1011    #[test]
1012    fn multi_topic_config_is_left_alone() {
1013        let config = resolved_bridge_config(
1014            "\
1015nodes:
1016  - id: turtle_bridge
1017    ros2:
1018      topics:
1019        - topic: /turtle1/pose
1020          message_type: turtlesim/Pose
1021          direction: subscribe
1022          output: pose
1023    outputs:
1024      - pose
1025",
1026        );
1027        let topics = config.topics.expect("topics survive resolution");
1028        assert_eq!(topics[0].output.as_deref(), Some("pose"));
1029    }
1030
1031    /// Resolution, not just validation, has to reject an unresolvable mapping:
1032    /// `dora start` resolves through the coordinator without running
1033    /// `check_dataflow`, so a guard that lives only in the validator would let
1034    /// the bridge bind to a port nothing is wired to.
1035    #[test]
1036    fn ambiguous_single_topic_is_rejected_during_resolution() {
1037        let descriptor: Descriptor = serde_yaml::from_str(
1038            "\
1039nodes:
1040  - id: pose_bridge
1041    ros2:
1042      topic: /turtle1/pose
1043      message_type: turtlesim/Pose
1044      direction: subscribe
1045    outputs:
1046      - pose
1047      - log
1048",
1049        )
1050        .expect("parse");
1051        let err = descriptor
1052            .resolve_aliases_and_set_defaults()
1053            .expect_err("an ambiguous port mapping must not resolve")
1054            .to_string();
1055        assert!(
1056            err.contains("no unambiguous output") && err.contains("turtle1_pose"),
1057            "error should explain the ambiguity, got: {err}"
1058        );
1059    }
1060
1061    /// Setting both `topic:` and `topics:` is rejected downstream by the bridge
1062    /// ("exactly one of `topic` or `topics`"). Resolution must leave the list
1063    /// alone rather than overwrite it and turn that into a silent drop.
1064    #[test]
1065    fn single_topic_rewrite_never_overwrites_an_explicit_topics_list() {
1066        let config = resolved_bridge_config(
1067            "\
1068nodes:
1069  - id: bridge
1070    ros2:
1071      topic: /turtle1/pose
1072      message_type: turtlesim/Pose
1073      direction: subscribe
1074      topics:
1075        - topic: /turtle1/other
1076          message_type: turtlesim/Pose
1077          direction: subscribe
1078          output: pose
1079    outputs:
1080      - pose
1081",
1082        );
1083        assert_eq!(config.topic.as_deref(), Some("/turtle1/pose"));
1084        let topics = config.topics.expect("the explicit list survives");
1085        assert_eq!(topics.len(), 1);
1086        assert_eq!(topics[0].topic, "/turtle1/other");
1087    }
1088
1089    /// dora-rs/dora#2920: the command-line flag beats the descriptor in
1090    /// BOTH directions, and its absence beats neither.
1091    ///
1092    /// The third state matters: if "flag omitted" meant `false`, a YAML
1093    /// `exit_when_nodes_finish: true` would be overridden on every
1094    /// invocation, and since `dora run` and `dora start` are the only
1095    /// ways to start a dataflow, the descriptor field could never take
1096    /// effect at all.
1097    #[test]
1098    fn exit_when_nodes_finish_override_semantics() {
1099        use super::DescriptorExt;
1100
1101        let parse = |yaml: &str| -> Descriptor { serde_yaml::from_str(yaml).expect("parse") };
1102        let with_setting = "exit_when_nodes_finish: true\nnodes:\n  - id: a\n    path: ./a\n";
1103        let without = "nodes:\n  - id: a\n    path: ./a\n";
1104
1105        // Omitted: the descriptor decides, either way.
1106        let mut d = parse(with_setting);
1107        d.apply_exit_when_nodes_finish(None);
1108        assert_eq!(
1109            d.exit_when_nodes_finish,
1110            Some(true),
1111            "omitting the flag must not silently disable a policy the \
1112             dataflow file asked for"
1113        );
1114
1115        let mut d = parse(without);
1116        d.apply_exit_when_nodes_finish(None);
1117        assert_eq!(d.exit_when_nodes_finish, None, "and must not invent one");
1118
1119        // Given: it wins, including against an opposite descriptor value.
1120        let mut d = parse(with_setting);
1121        d.apply_exit_when_nodes_finish(Some(false));
1122        assert_eq!(
1123            d.exit_when_nodes_finish,
1124            Some(false),
1125            "`--exit-when-nodes-finish=false` must be able to turn OFF a \
1126             policy the dataflow file turned on"
1127        );
1128
1129        let mut d = parse(without);
1130        d.apply_exit_when_nodes_finish(Some(true));
1131        assert_eq!(d.exit_when_nodes_finish, Some(true));
1132    }
1133
1134    use super::*;
1135    use dora_message::descriptor::{GitRepoRev, NodeSource};
1136    use std::collections::BTreeSet;
1137
1138    fn env(pairs: &[(&str, &str)]) -> BTreeMap<String, EnvValue> {
1139        pairs
1140            .iter()
1141            .map(|(k, v)| (k.to_string(), EnvValue::String(v.to_string())))
1142            .collect()
1143    }
1144
1145    #[test]
1146    fn merge_env_returns_none_when_both_absent() {
1147        assert!(merge_env(None, None).is_none());
1148    }
1149
1150    #[test]
1151    fn merge_env_keeps_per_node_when_no_global() {
1152        let node_env = env(&[("A", "1")]);
1153        let merged = merge_env(None, Some(node_env.clone())).unwrap();
1154        assert_eq!(merged, node_env);
1155    }
1156
1157    #[test]
1158    fn merge_env_keeps_global_when_no_per_node() {
1159        let global = env(&[("A", "1")]);
1160        let merged = merge_env(Some(&global), None).unwrap();
1161        assert_eq!(merged, global);
1162    }
1163
1164    #[test]
1165    fn merge_env_normalizes_empty_node_map_to_none() {
1166        // A node that declares `env: {}` with no dataflow-level env must
1167        // resolve to `None`, not `Some({})`, matching the documented contract
1168        // (and the `(Some(empty), None)` arm) so the resolved node serializes
1169        // without an empty `env:` map.
1170        assert!(merge_env(None, Some(env(&[]))).is_none());
1171    }
1172
1173    #[test]
1174    fn merge_env_normalizes_empty_global_and_node_maps_to_none() {
1175        assert!(merge_env(Some(&env(&[])), Some(env(&[]))).is_none());
1176        assert!(merge_env(Some(&env(&[])), None).is_none());
1177    }
1178
1179    #[test]
1180    fn merge_env_per_node_overrides_global_on_conflict() {
1181        let global = env(&[("A", "global"), ("B", "global")]);
1182        let node_env = env(&[("A", "node"), ("C", "node")]);
1183        let merged = merge_env(Some(&global), Some(node_env)).unwrap();
1184        assert_eq!(merged.get("A"), Some(&EnvValue::String("node".into())));
1185        assert_eq!(merged.get("B"), Some(&EnvValue::String("global".into())));
1186        assert_eq!(merged.get("C"), Some(&EnvValue::String("node".into())));
1187    }
1188
1189    fn resolved_input_mapping<'a>(
1190        resolved: &'a BTreeMap<NodeId, ResolvedNode>,
1191        node: &str,
1192        input: &str,
1193    ) -> &'a InputMapping {
1194        let node = resolved
1195            .get(&NodeId::from(node.to_string()))
1196            .expect("node resolved");
1197        let inputs = match &node.kind {
1198            CoreNodeKind::Custom(n) => &n.run_config.inputs,
1199            CoreNodeKind::Runtime(_) => panic!("expected custom node"),
1200        };
1201        &inputs
1202            .get(&DataId::from(input.to_string()))
1203            .expect("input present")
1204            .mapping
1205    }
1206
1207    #[test]
1208    fn add_node_prefixes_single_operator_producer_input_via_topology() {
1209        // A node added to a running dataflow via `AddNode` is resolved against a
1210        // single-node descriptor. If its input references an existing
1211        // single-`operator:` producer, the `op/` output prefix that
1212        // whole-descriptor resolution applies must still be added — sourced
1213        // from the surrounding topology — or the node subscribes to an output
1214        // name nobody publishes and silently receives no data (#2877).
1215        let topology: Descriptor = serde_yaml::from_str(
1216            "\
1217nodes:
1218  - id: producer
1219    operator:
1220      python: producer.py
1221      outputs:
1222        - result
1223",
1224        )
1225        .expect("parse topology");
1226
1227        let added: Descriptor = serde_yaml::from_str(
1228            "\
1229nodes:
1230  - id: consumer
1231    path: consumer
1232    inputs:
1233      reading: producer/result
1234",
1235        )
1236        .expect("parse added node");
1237
1238        // With the topology the input is prefixed to the operator-qualified
1239        // output name the runtime actually publishes under (`op/result`).
1240        let resolved = resolve_aliases_and_set_defaults_in_topology(&added, &topology.nodes)
1241            .expect("resolve in topology");
1242        match resolved_input_mapping(&resolved, "consumer", "reading") {
1243            InputMapping::User(m) => {
1244                assert_eq!(m.source, NodeId::from("producer".to_string()));
1245                assert_eq!(m.output, DataId::from("op/result".to_string()));
1246            }
1247            other => panic!("expected user mapping, got {other:?}"),
1248        }
1249
1250        // Contrast: with no topology the producer is not in scope at all, so
1251        // there is nothing to key the rewrite off and the name stays bare.
1252        // That is the correct answer for the inputs given — which is exactly
1253        // why the `AddNode` path had to stop resolving in isolation.
1254        let resolved_isolated = added
1255            .resolve_aliases_and_set_defaults()
1256            .expect("resolve isolated");
1257        match resolved_input_mapping(&resolved_isolated, "consumer", "reading") {
1258            InputMapping::User(m) => {
1259                assert_eq!(m.output, DataId::from("result".to_string()));
1260            }
1261            other => panic!("expected user mapping, got {other:?}"),
1262        }
1263    }
1264
1265    /// The operator subtree must survive resolution. The `Runtime`/`Operator`
1266    /// arms move `node.operators` / `node.operator` out with `take()`, which
1267    /// is only sound because `ResolvedNode::from_node` never reads those
1268    /// fields. Pin that invariant: a regression that consumed the subtree
1269    /// before building the `CoreNodeKind`, or a new `ResolvedNode` field
1270    /// sourced from `node.operator` after the take (which would compile and
1271    /// silently read `None`), surfaces here as a missing operator.
1272    #[test]
1273    fn resolve_preserves_operator_subtree() {
1274        let desc: Descriptor = serde_yaml::from_str(
1275            "\
1276nodes:
1277  - id: runtime_node
1278    operators:
1279      - id: op_a
1280        python: a.py
1281        outputs:
1282          - out_a
1283  - id: operator_node
1284    operator:
1285      python: b.py
1286      outputs:
1287        - out_b
1288",
1289        )
1290        .expect("parse");
1291
1292        let resolved = desc.resolve_aliases_and_set_defaults().expect("resolve");
1293
1294        // A `runtime:` (operators) node keeps every declared operator.
1295        match &resolved[&NodeId::from("runtime_node".to_string())].kind {
1296            CoreNodeKind::Runtime(rt) => {
1297                let ids: Vec<_> = rt.operators.iter().map(|o| o.id.to_string()).collect();
1298                assert_eq!(ids, ["op_a"], "runtime operators must survive resolution");
1299            }
1300            other => panic!("expected Runtime kind, got {other:?}"),
1301        }
1302
1303        // A single-`operator:` node resolves to a one-operator runtime,
1304        // defaulting the operator id to `op`.
1305        match &resolved[&NodeId::from("operator_node".to_string())].kind {
1306            CoreNodeKind::Runtime(rt) => {
1307                assert_eq!(
1308                    rt.operators.len(),
1309                    1,
1310                    "the operator must survive resolution"
1311                );
1312                assert_eq!(rt.operators[0].id.to_string(), SINGLE_OPERATOR_DEFAULT_ID);
1313            }
1314            other => panic!("expected Runtime kind, got {other:?}"),
1315        }
1316    }
1317
1318    #[test]
1319    fn topology_lookup_prefers_the_node_being_added_over_a_same_id_topology_entry() {
1320        // The lookup chains topology nodes *before* `desc`'s own, so a node id
1321        // present in both resolves against the copy being added rather than a
1322        // stale topology entry. Unreachable through `AddNode` today (duplicate
1323        // ids are rejected up front and `RemoveNode` prunes the stored
1324        // descriptor), but the precedence should not depend on that.
1325        let topology: Descriptor = serde_yaml::from_str(
1326            "\
1327nodes:
1328  - id: producer
1329    operator:
1330      id: stale
1331      python: producer.py
1332      outputs:
1333        - result
1334",
1335        )
1336        .expect("parse topology");
1337
1338        let added: Descriptor = serde_yaml::from_str(
1339            "\
1340nodes:
1341  - id: producer
1342    operator:
1343      id: fresh
1344      python: producer.py
1345      outputs:
1346        - result
1347  - id: consumer
1348    path: consumer
1349    inputs:
1350      reading: producer/result
1351",
1352        )
1353        .expect("parse added nodes");
1354
1355        let resolved = resolve_aliases_and_set_defaults_in_topology(&added, &topology.nodes)
1356            .expect("resolve in topology");
1357        match resolved_input_mapping(&resolved, "consumer", "reading") {
1358            InputMapping::User(m) => {
1359                assert_eq!(m.output, DataId::from("fresh/result".to_string()));
1360            }
1361            other => panic!("expected user mapping, got {other:?}"),
1362        }
1363    }
1364
1365    #[test]
1366    fn descriptor_global_env_parses_from_yaml() {
1367        // Verify the new top-level `env:` field parses and the resolver
1368        // hands merged envs to every node with per-node keys winning.
1369        let yaml = r#"
1370env:
1371  RUST_LOG: info
1372  OTEL_ENDPOINT: http://collector:4317
1373nodes:
1374  - id: a
1375    path: ./a
1376    env:
1377      RUST_LOG: debug
1378  - id: b
1379    path: ./b
1380"#;
1381        let desc: Descriptor = serde_yaml::from_str(yaml).expect("parse");
1382        let resolved = desc.resolve_aliases_and_set_defaults().expect("resolve");
1383
1384        let a = resolved.get(&NodeId::from("a".to_string())).unwrap();
1385        let a_env = a.env.as_ref().expect("node a inherits env");
1386        // Per-node RUST_LOG=debug wins over global RUST_LOG=info.
1387        assert_eq!(
1388            a_env.get("RUST_LOG"),
1389            Some(&EnvValue::String("debug".into()))
1390        );
1391        // Global key not overridden on node a is still visible.
1392        assert_eq!(
1393            a_env.get("OTEL_ENDPOINT"),
1394            Some(&EnvValue::String("http://collector:4317".into()))
1395        );
1396
1397        let b = resolved.get(&NodeId::from("b".to_string())).unwrap();
1398        let b_env = b.env.as_ref().expect("node b inherits global env");
1399        assert_eq!(
1400            b_env.get("RUST_LOG"),
1401            Some(&EnvValue::String("info".into()))
1402        );
1403        assert_eq!(
1404            b_env.get("OTEL_ENDPOINT"),
1405            Some(&EnvValue::String("http://collector:4317".into()))
1406        );
1407    }
1408
1409    #[test]
1410    fn invalid_operator_id_prefix_errors_instead_of_panicking() {
1411        // A single-operator node whose `operator.id` contains a character
1412        // outside the `DataId` set (here a space) is accepted at parse time
1413        // (`OperatorId` is unvalidated). When another node references its
1414        // output, the resolver prefixes the output with the operator id. That
1415        // used to build the qualified id via `DataId::from`, which panics on
1416        // invalid characters and aborted `dora check`/`graph`/`build`. It must
1417        // now surface as a clean `Err` instead.
1418        let yaml = r#"
1419nodes:
1420  - id: producer
1421    operator:
1422      id: "bad id"
1423      python: op.py
1424      outputs: [result]
1425  - id: consumer
1426    path: ./consumer
1427    inputs:
1428      x: producer/result
1429"#;
1430        let desc: Descriptor = serde_yaml::from_str(yaml).expect("parse");
1431        let result = desc.resolve_aliases_and_set_defaults();
1432        assert!(result.is_err(), "expected a clean descriptor error, got Ok");
1433    }
1434
1435    #[test]
1436    fn resolve_path_errors_for_nonexistent_binary() {
1437        // Regression for #2016: the `uv` fallback previously spawned
1438        // `uv run which <path>` fire-and-forget and returned the original
1439        // (relative) path even when the binary did not exist. A missing
1440        // binary must surface as an `Err`, and any successful resolution
1441        // must be an absolute path.
1442        let working_dir = std::env::current_dir().expect("cwd");
1443        let result = resolve_path("dora_nonexistent_binary_2016_regression", &working_dir);
1444        assert!(
1445            result.is_err(),
1446            "expected Err for a binary that exists nowhere, got {result:?}"
1447        );
1448    }
1449
1450    /// dora-rs/dora#2918: resolving a node path must NOT follow symlinks.
1451    ///
1452    /// A virtualenv's `bin/python` is a symlink to the base interpreter,
1453    /// and CPython's venv discovery hinges on that: it looks for
1454    /// `pyvenv.cfg` relative to the path it was *invoked* as, not the
1455    /// symlink's target. Canonicalizing before exec therefore runs the
1456    /// base interpreter with no venv — imports that work in a shell
1457    /// (`.venv/bin/python -c "import numpy"`) fail under dora with
1458    /// `ModuleNotFoundError`.
1459    #[test]
1460    #[cfg(unix)]
1461    fn resolve_path_preserves_symlinks() {
1462        let tmp = tempfile::tempdir().expect("tempdir");
1463        let target = tmp.path().join("base-interpreter.bin");
1464        std::fs::write(&target, b"x").unwrap();
1465        let link = tmp.path().join("venv-python.bin");
1466        std::os::unix::fs::symlink(&target, &link).unwrap();
1467
1468        // relative source resolved against the working dir
1469        let resolved = resolve_path("venv-python.bin", tmp.path()).unwrap();
1470        assert!(resolved.is_absolute());
1471        assert!(
1472            resolved.ends_with("venv-python.bin"),
1473            "resolve_path followed the symlink: {} — venv discovery \
1474             (pyvenv.cfg) is keyed off the symlink location, so execing \
1475             the target bypasses the venv",
1476            resolved.display()
1477        );
1478
1479        // absolute source (the shape from the issue: `path: /…/.venv/bin/python`)
1480        let resolved = resolve_path(link.to_str().unwrap(), Path::new("/")).unwrap();
1481        assert!(
1482            resolved.ends_with("venv-python.bin"),
1483            "absolute symlink path was canonicalized: {}",
1484            resolved.display()
1485        );
1486
1487        // `..` components survive too: they are resolved by the kernel at
1488        // exec time, AFTER any symlinked directories — which is the
1489        // shell-matching semantic. A lexical "cleanup" that collapses
1490        // them would resolve differently through symlinked dirs.
1491        std::fs::create_dir(tmp.path().join("sub")).unwrap();
1492        let resolved = resolve_path("sub/../venv-python.bin", tmp.path()).unwrap();
1493        assert!(
1494            resolved.ends_with("sub/../venv-python.bin"),
1495            "`..` was normalized away: {}",
1496            resolved.display()
1497        );
1498    }
1499
1500    /// A dangling symlink is "missing": `exists()` traverses the link, so
1501    /// resolution falls through to the uv/$PATH branches and ultimately
1502    /// errors — the same outcome the old `canonicalize()` failure gave.
1503    /// Pins the branch boundary so a switch to `symlink_metadata()`
1504    /// (which would treat the dangling link as present and exec a
1505    /// guaranteed-ENOENT path) doesn't slip in silently.
1506    #[test]
1507    #[cfg(unix)]
1508    fn resolve_path_treats_dangling_symlink_as_missing() {
1509        let tmp = tempfile::tempdir().expect("tempdir");
1510        let link = tmp.path().join("dangling-2918-regression.bin");
1511        std::os::unix::fs::symlink(tmp.path().join("no-such-target"), &link).unwrap();
1512
1513        let result = resolve_path("dangling-2918-regression.bin", tmp.path());
1514        assert!(
1515            result.is_err(),
1516            "a dangling symlink must not resolve (nothing on uv/$PATH matches \
1517             this name either), got {result:?}"
1518        );
1519    }
1520
1521    /// A folder named like the executable is not the executable: on Unix
1522    /// (`EXE_EXTENSION` is empty) the source folder `talker` of a package
1523    /// whose console script is `talker` used to resolve to the folder, and
1524    /// spawn then failed with EACCES instead of finding the script.
1525    #[test]
1526    fn resolve_path_skips_a_directory_with_the_executable_name() {
1527        let tmp = tempfile::tempdir().expect("tempdir");
1528        let name = format!(
1529            "dora-dir-not-exe-regression{}",
1530            std::env::consts::EXE_SUFFIX
1531        );
1532        std::fs::create_dir(tmp.path().join(&name)).unwrap();
1533
1534        let result = resolve_path(&name, tmp.path());
1535        assert!(
1536            result.is_err(),
1537            "a directory must not resolve (nothing on uv/$PATH matches this \
1538             name either), got {result:?}"
1539        );
1540    }
1541
1542    /// A folder with a `__main__.py` is still a node path: under `--uv` it is
1543    /// spawned as `uv run <folder>`, which runs that file.
1544    #[test]
1545    fn resolve_path_keeps_a_directory_with_a_main_py() {
1546        let tmp = tempfile::tempdir().expect("tempdir");
1547        let name = format!("dora-main-py-dir{}", std::env::consts::EXE_SUFFIX);
1548        let dir = tmp.path().join(&name);
1549        std::fs::create_dir(&dir).unwrap();
1550        std::fs::write(dir.join("__main__.py"), "").unwrap();
1551
1552        let resolved = resolve_path(&name, tmp.path()).unwrap();
1553        assert_eq!(resolved, absolutize_preserving_symlinks(&dir).unwrap());
1554    }
1555
1556    /// `path_fallback` is internal, so a dataflow file must not set it, with
1557    /// or without modules. Only reading a file checks this: a descriptor that
1558    /// expansion already filled in (`dora build`'s session) keeps it.
1559    #[test]
1560    fn a_dataflow_file_cannot_set_path_fallback() {
1561        for yaml in [
1562            "nodes:\n  - id: x\n    path: tool\n    path_fallback: tool\n",
1563            "nodes:\n  - id: m\n    module: m.yml\n  - id: x\n    path: ./x\n    path_fallback: x\n",
1564        ] {
1565            let err = Descriptor::parse(yaml.as_bytes().to_vec()).unwrap_err();
1566            assert_eq!(
1567                format!("{err:#}"),
1568                "node `x` sets `path_fallback`, which is internal \
1569                 (module expansion sets it); remove it",
1570                "{yaml}"
1571            );
1572        }
1573        Descriptor::parse(b"nodes:\n  - id: x\n    path: tool\n".to_vec()).unwrap();
1574    }
1575
1576    /// A repeated key in a map-valued field (`inputs`, `env`) must be an
1577    /// error. The typed deserializer would keep only the last entry, so a
1578    /// copy-pasted input line silently dropped the first subscription.
1579    #[test]
1580    fn a_dataflow_file_cannot_repeat_a_map_key() {
1581        for (yaml, key) in [
1582            (
1583                "nodes:\n  - id: x\n    path: tool\n    inputs:\n      image: cam/img\n      image: dora/timer/millis/20\n",
1584                "image",
1585            ),
1586            (
1587                "nodes:\n  - id: x\n    path: tool\n    env:\n      A: \"1\"\n      A: \"2\"\n",
1588                "A",
1589            ),
1590        ] {
1591            let err = Descriptor::parse(yaml.as_bytes().to_vec()).unwrap_err();
1592            let msg = format!("{err:#}");
1593            assert!(
1594                msg.contains(&format!("duplicate entry with key \"{key}\"")),
1595                "{yaml}: {msg}"
1596            );
1597        }
1598        let ok = Descriptor::parse(
1599            b"nodes:\n  - id: x\n    path: tool\n    inputs:\n      a: dora/timer/millis/20\n      b: dora/timer/millis/30\n"
1600                .to_vec(),
1601        )
1602        .unwrap();
1603        assert_eq!(ok.nodes[0].inputs.len(), 2);
1604    }
1605
1606    #[test]
1607    fn path_fallbacks_survive_persistence_and_resolution() {
1608        let mut descriptor: Descriptor = serde_yaml::from_str(
1609            "nodes:\n  - id: module.worker\n    path: modules/worker\n    args: --keep\n",
1610        )
1611        .unwrap();
1612        let fallbacks = BTreeMap::from([("module.worker".parse().unwrap(), "worker".into())]);
1613        descriptor.nodes[0].path_fallback = Some("worker".into());
1614        let persisted = serde_json::to_vec(&descriptor).unwrap();
1615        let restored: Descriptor = serde_json::from_slice(&persisted).unwrap();
1616        assert_eq!(restored.path_fallbacks(), fallbacks);
1617        let nodes = restored.resolve_aliases_and_set_defaults().unwrap();
1618        let CoreNodeKind::Custom(node) = &nodes[&NodeId::from("module.worker".to_owned())].kind
1619        else {
1620            panic!("expected a custom node");
1621        };
1622        assert_eq!(node.path_fallback.as_deref(), Some("worker"));
1623        assert_eq!(node.args.as_deref(), Some("--keep"));
1624    }
1625
1626    #[test]
1627    fn without_path_fallback_clears_it_on_every_node_only() {
1628        let nodes =
1629            "nodes:\n  - id: a\n    path: modules/a\n  - id: b\n    path: sub/b\n    args: --x\n";
1630        let with: Descriptor = serde_yaml::from_str(
1631            &nodes
1632                .replace(
1633                    "path: modules/a\n",
1634                    "path: modules/a\n    path_fallback: a\n",
1635                )
1636                .replace("path: sub/b\n", "path: sub/b\n    path_fallback: b\n"),
1637        )
1638        .unwrap();
1639        assert!(with.nodes.iter().all(|node| node.path_fallback.is_some()));
1640        let without: Descriptor = serde_yaml::from_str(nodes).unwrap();
1641
1642        assert_eq!(
1643            serde_yaml::to_value(without_path_fallback(&with)).unwrap(),
1644            serde_yaml::to_value(&without).unwrap()
1645        );
1646    }
1647
1648    /// #3826: inside a module in a subdirectory, a bare `path:` names either a
1649    /// file next to the module or, like a top-level `path:`, something found
1650    /// from the working directory, uv or `$PATH`. Expansion still points
1651    /// `path` at the module directory; the name as written is the fallback
1652    /// when no file is there.
1653    #[test]
1654    fn a_bare_module_node_path_falls_back_to_a_top_level_lookup() {
1655        let tmp = tempfile::tempdir().expect("tempdir");
1656        let dir = tmp.path();
1657        std::fs::create_dir_all(dir.join("modules")).unwrap();
1658        std::fs::write(
1659            dir.join("modules/m.yml"),
1660            "module:\n  name: m\nnodes:\n  - id: worker\n    path: worker-3826\n",
1661        )
1662        .unwrap();
1663        let desc: Descriptor =
1664            serde_yaml::from_str("nodes:\n  - id: m\n    module: modules/m.yml\n").unwrap();
1665        // `resolve_path` appends `.exe` to an extensionless name on Windows.
1666        let file = format!("worker-3826{}", std::env::consts::EXE_SUFFIX);
1667
1668        let missing = desc.check(dir).expect_err("no file anywhere");
1669        let missing = format!("{missing:?}");
1670        assert!(
1671            missing.contains("nor its `path_fallback` `worker-3826`"),
1672            "{missing}"
1673        );
1674
1675        // Only the top-level lookup finds it: the node runs this file.
1676        std::fs::write(dir.join(&file), "").unwrap();
1677        desc.check(dir).unwrap();
1678        let expanded = desc.expand(dir).unwrap();
1679        let path = expanded.nodes[0].path.clone().unwrap();
1680        let fallback = expanded.nodes[0].path_fallback.as_deref();
1681        assert_eq!(Path::new(&path), Path::new("modules").join("worker-3826"));
1682        assert_eq!(fallback, Some("worker-3826"));
1683        assert_eq!(
1684            resolve_node_path(&path, fallback, dir).unwrap(),
1685            dir.join(&file)
1686        );
1687
1688        // A file next to the module still wins, as on main.
1689        std::fs::write(dir.join("modules").join(&file), "").unwrap();
1690        assert_eq!(
1691            resolve_node_path(&path, fallback, dir).unwrap(),
1692            dir.join("modules").join(&file)
1693        );
1694    }
1695
1696    /// A Python package shipped with a module often has a source folder named
1697    /// like its console script (`modules/my-node/`). A folder can't be run, so
1698    /// it must not stop the fallback lookup.
1699    #[test]
1700    fn a_folder_next_to_the_module_does_not_block_the_fallback() {
1701        let tmp = tempfile::tempdir().expect("tempdir");
1702        let dir = tmp.path();
1703        let file = format!("my-node{}", std::env::consts::EXE_SUFFIX);
1704        std::fs::create_dir_all(dir.join("modules").join(&file)).unwrap();
1705        std::fs::write(dir.join(&file), "").unwrap();
1706
1707        let path = Path::new("modules").join("my-node");
1708        assert_eq!(
1709            resolve_node_path(path.to_str().unwrap(), Some("my-node"), dir).unwrap(),
1710            dir.join(&file)
1711        );
1712    }
1713
1714    #[test]
1715    fn resolve_path_confined_has_no_path_fallback() {
1716        let tmp = tempfile::tempdir().expect("tempdir");
1717        // `sh` exists on $PATH everywhere on unix — confined resolution must
1718        // NOT find it (spec §11: a typo or missing console script fails, it
1719        // never silently runs a host binary)
1720        let result = resolve_path_confined("sh", tmp.path(), None);
1721        assert!(result.is_err(), "expected Err, got {result:?}");
1722
1723        // a real file in the working dir resolves
1724        let exe = if cfg!(windows) {
1725            "node.exe"
1726        } else {
1727            "node.bin"
1728        };
1729        std::fs::write(tmp.path().join(exe), b"x").unwrap();
1730        let resolved = resolve_path_confined(exe, tmp.path(), None).unwrap();
1731        assert!(resolved.is_absolute());
1732
1733        // a managed-env console script resolves through the env's bin dir
1734        let env_dir = tmp.path().join("env");
1735        let bin_dir = env_dir.join(if cfg!(windows) { "Scripts" } else { "bin" });
1736        std::fs::create_dir_all(&bin_dir).unwrap();
1737        std::fs::write(bin_dir.join(exe), b"x").unwrap();
1738        let resolved =
1739            resolve_path_confined(exe, tmp.path().join("empty").as_path(), Some(&env_dir));
1740        assert!(resolved.is_ok(), "{resolved:?}");
1741    }
1742
1743    /// Like [`resolve_path`], a folder named like the entrypoint (often the
1744    /// package source next to its console script) cannot be spawned, so it
1745    /// must fail resolution with the "could not find" error instead of
1746    /// resolving and failing at spawn with `Permission denied`.
1747    #[test]
1748    fn resolve_path_confined_skips_a_directory_with_the_entrypoint_name() {
1749        let tmp = tempfile::tempdir().expect("tempdir");
1750        let name = format!("talker{}", std::env::consts::EXE_SUFFIX);
1751        std::fs::create_dir(tmp.path().join(&name)).unwrap();
1752        let env_dir = tmp.path().join("env");
1753        std::fs::create_dir_all(env_dir.join(if cfg!(windows) { "Scripts" } else { "bin" }))
1754            .unwrap();
1755
1756        let err = resolve_path_confined(&name, tmp.path(), Some(&env_dir)).unwrap_err();
1757        assert!(
1758            format!("{err:#}").contains("could not find"),
1759            "unexpected error: {err:#}"
1760        );
1761    }
1762
1763    /// A folder with a `__main__.py` still resolves, as it does for
1764    /// [`resolve_path`]: under `--uv` it is spawned as `uv run <folder>`.
1765    #[test]
1766    fn resolve_path_confined_keeps_a_directory_with_a_main_py() {
1767        let tmp = tempfile::tempdir().expect("tempdir");
1768        let name = format!("talker{}", std::env::consts::EXE_SUFFIX);
1769        let dir = tmp.path().join(&name);
1770        std::fs::create_dir(&dir).unwrap();
1771        std::fs::write(dir.join("__main__.py"), "").unwrap();
1772
1773        let resolved = resolve_path_confined(&name, tmp.path(), None).unwrap();
1774        assert_eq!(resolved, dir.canonicalize().unwrap());
1775    }
1776
1777    #[cfg(unix)]
1778    #[test]
1779    fn resolve_path_confined_rejects_symlink_escape() {
1780        let tmp = tempfile::tempdir().expect("tempdir");
1781        let working_dir = tmp.path().join("work");
1782        std::fs::create_dir_all(&working_dir).unwrap();
1783        let outside = tmp.path().join("outside.bin");
1784        std::fs::write(&outside, b"x").unwrap();
1785        std::os::unix::fs::symlink(&outside, working_dir.join("escape.bin")).unwrap();
1786        let result = resolve_path_confined("escape.bin", &working_dir, None);
1787        assert!(
1788            result.is_err(),
1789            "a symlink pointing outside the working dir must be rejected, got {result:?}"
1790        );
1791        let msg = format!("{:#}", result.unwrap_err());
1792        assert!(msg.contains("outside"), "{msg}");
1793    }
1794
1795    #[test]
1796    fn unresolved_hub_node_has_clear_kind_error() {
1797        let node: Node = serde_yaml::from_str("id: x\nhub: dora-yolo@^0.5\n").unwrap();
1798        let err = node.kind().unwrap_err();
1799        assert!(format!("{err}").contains("dora build"), "{err}");
1800    }
1801
1802    #[test]
1803    fn resolve_path_via_uv_errors_for_nonexistent_binary() {
1804        // Pins the #2016 root cause directly on the `uv` branch. The buggy
1805        // code spawned `uv run which <path>` fire-and-forget and returned
1806        // `Ok(<relative path>)` regardless of the child's exit status, so a
1807        // missing binary was silently accepted. This branch only runs when
1808        // `uv` is installed (the only environment where the bug manifested),
1809        // so guard on its presence to keep the test meaningful where it can
1810        // actually discriminate the fix.
1811        if which::which("uv").is_err() {
1812            return;
1813        }
1814        let path = Path::new("dora_nonexistent_binary_2016_regression");
1815        let result = resolve_path_via_uv(path);
1816        assert!(
1817            result.is_err(),
1818            "expected Err from `uv run which` for a missing binary, got {result:?}"
1819        );
1820    }
1821
1822    /// A failed `uv` lookup must not hide a binary that is on `$PATH`: with
1823    /// `uv` installed, `resolve_path` used to return the `uv` error as-is.
1824    #[test]
1825    #[cfg(unix)]
1826    fn failed_uv_lookup_falls_back_to_system_path() {
1827        let resolved = or_on_system_path(Err(eyre::eyre!("uv failed")), Path::new("sh"))
1828            .expect("`sh` is on $PATH");
1829        assert!(resolved.is_absolute(), "{}", resolved.display());
1830
1831        let missing = Path::new("dora_nonexistent_binary_2016_regression");
1832        let err = or_on_system_path(Err(eyre::eyre!("uv failed")), missing).unwrap_err();
1833        assert!(err.to_string().contains("or on $PATH"), "{err:?}");
1834        assert_eq!(err.root_cause().to_string(), "uv failed");
1835    }
1836
1837    #[test]
1838    fn descriptor_without_global_env_preserves_per_node_env() {
1839        // Regression guard: no top-level `env:` must leave per-node env
1840        // semantics unchanged.
1841        let yaml = r#"
1842nodes:
1843  - id: a
1844    path: ./a
1845    env:
1846      FOO: bar
1847  - id: b
1848    path: ./b
1849"#;
1850        let desc: Descriptor = serde_yaml::from_str(yaml).expect("parse");
1851        let resolved = desc.resolve_aliases_and_set_defaults().expect("resolve");
1852        let a = resolved.get(&NodeId::from("a".to_string())).unwrap();
1853        assert_eq!(
1854            a.env.as_ref().and_then(|e| e.get("FOO")),
1855            Some(&EnvValue::String("bar".into()))
1856        );
1857        let b = resolved.get(&NodeId::from("b".to_string())).unwrap();
1858        assert!(b.env.is_none(), "node b has no env anywhere");
1859    }
1860
1861    #[test]
1862    fn duplicate_node_id_is_rejected() {
1863        // Regression for #2393: a plain dataflow with two nodes sharing the
1864        // same `id` must return an error instead of silently discarding one.
1865        let yaml = r#"
1866nodes:
1867  - id: my-node
1868    path: ./a
1869  - id: my-node
1870    path: ./b
1871"#;
1872        let desc: Descriptor = serde_yaml::from_str(yaml).expect("parse");
1873        let err = desc
1874            .resolve_aliases_and_set_defaults()
1875            .expect_err("duplicate node ID must be rejected");
1876        let msg = format!("{err:#}");
1877        assert!(
1878            msg.contains("duplicate node ID") && msg.contains("my-node"),
1879            "unexpected error message: {msg}"
1880        );
1881    }
1882
1883    /// Every `CustomNode` field name, taken from its JSON schema.
1884    ///
1885    /// A field marked `#[schemars(skip)]` would never appear in `properties`
1886    /// and would slip past the carried-through tests below; if `CustomNode` ever
1887    /// gains one, add it here by hand.
1888    fn custom_node_field_names() -> BTreeSet<String> {
1889        let schema = schemars::schema_for!(dora_message::descriptor::CustomNode);
1890        let schema = serde_json::to_value(schema).expect("schema should serialize");
1891        schema
1892            .pointer("/$defs/CustomNode/properties")
1893            .or_else(|| schema.pointer("/definitions/CustomNode/properties"))
1894            .or_else(|| schema.pointer("/properties"))
1895            .and_then(serde_json::Value::as_object)
1896            .expect("CustomNode schema should expose properties")
1897            .keys()
1898            .cloned()
1899            .collect()
1900    }
1901
1902    /// The per-node keys every custom-node kind resolves identically, each set
1903    /// to a value that differs from `CustomNode::new`'s default — a YAML
1904    /// fragment to append to a `- id:` entry.
1905    const SHARED_CUSTOM_NODE_KEYS: &str = r#"
1906    args: --verbose
1907    send_stdout_as: stdout-topic
1908    send_logs_as: logs-topic
1909    min_log_level: debug
1910    max_log_size: 4MB
1911    max_rotated_files: 3
1912    restart_policy: always
1913    max_restarts: 7
1914    restart_delay: 1.5
1915    max_restart_delay: 9.5
1916    restart_window: 60.0
1917    health_check_timeout: 2.5
1918    startup_timeout: 4.5
1919    finish_grace_secs: 3.5
1920    shared_memory_pool_size: 8MB
1921    inputs:
1922      tick: dora/timer/millis/100
1923    outputs:
1924      - out
1925    output_types:
1926      out: arrow.int32
1927    output_framing:
1928      out: arrow-ipc
1929    input_types:
1930      tick: arrow.uint64
1931"#;
1932
1933    /// Resolve the single node in `yaml` and assert that every `CustomNode`
1934    /// key outside `kind_specific` arrived carrying the value the YAML
1935    /// declared — and that the YAML did set it to something other than
1936    /// `CustomNode::new`'s default, so the comparison is never a trivial
1937    /// `None == None`. Returns the resolved node for the kind-specific checks.
1938    ///
1939    /// `CustomNode::from_node` is a struct literal inside `dora-message`, so a
1940    /// key added to `CustomNode` is already a compile error there. This is the
1941    /// value-level half: it catches a key wired to the wrong `Node` field, or
1942    /// left at its default. When it fails for a newly added key, carry the key
1943    /// in `from_node` and give it a non-default value in
1944    /// `SHARED_CUSTOM_NODE_KEYS`.
1945    fn resolve_and_check_carried_through(yaml: &str, kind_specific: &[&str]) -> CustomNode {
1946        let desc: Descriptor = serde_yaml::from_str(yaml).expect("parse");
1947        let declared = serde_json::to_value(&desc.nodes[0]).expect("serialize declared");
1948        let resolved = desc.resolve_aliases_and_set_defaults().expect("resolve");
1949        let node = resolved.values().next().expect("one node");
1950        let CoreNodeKind::Custom(custom) = &node.kind else {
1951            panic!("expected a custom node, got {:?}", node.kind);
1952        };
1953
1954        let actual = serde_json::to_value(custom).expect("serialize resolved");
1955        // A sentinel `path` that no YAML here uses, so `path` itself is checked
1956        // like every other field rather than comparing equal to it.
1957        let default =
1958            serde_json::to_value(CustomNode::new("<unset>".to_owned())).expect("serialize default");
1959
1960        for field in custom_node_field_names() {
1961            if kind_specific.contains(&field.as_str()) {
1962                continue;
1963            }
1964            assert_ne!(
1965                actual.get(&field),
1966                default.get(&field),
1967                "`{field}` is still at its `CustomNode::new` default after \
1968                 resolution — either the YAML does not set it (add it to \
1969                 `SHARED_CUSTOM_NODE_KEYS`) or the key is parsed and then \
1970                 dropped (carry it in `CustomNode::from_node`)."
1971            );
1972            assert_eq!(
1973                actual.get(&field),
1974                declared.get(&field),
1975                "`{field}` resolved to a different value than the YAML declared \
1976                 — `CustomNode::from_node` copies it from the wrong `Node` field."
1977            );
1978        }
1979        custom.clone()
1980    }
1981
1982    /// A `path:` node: every shared key and the standard-only `path_sha256` /
1983    /// `path_fallback` / `build` arrive. `source` resolves to `Local`, which is already the
1984    /// default, and `envs` is set only by the ROS2-bridge arm — the two tests
1985    /// below cover those.
1986    #[test]
1987    fn every_custom_node_field_is_carried_through() {
1988        let yaml = format!(
1989            "nodes:\n  - id: full\n    path: ./full-node\n    path_sha256: abc123\n    \
1990             path_fallback: full-node\n    build: cargo build{SHARED_CUSTOM_NODE_KEYS}"
1991        );
1992        let custom = resolve_and_check_carried_through(&yaml, &["source", "envs"]);
1993        assert!(
1994            matches!(custom.source, NodeSource::Local),
1995            "{:?}",
1996            custom.source
1997        );
1998        assert!(custom.envs.is_none(), "{:?}", custom.envs);
1999    }
2000
2001    /// The `source` a `git:` node classifies to must reach the resolved node:
2002    /// it is the one assignment in the standard arm that `from_node` does not
2003    /// cover, and dropping it would turn every git node into a local one.
2004    #[test]
2005    fn git_source_is_carried_through() {
2006        let yaml = format!(
2007            "nodes:\n  - id: full\n    path: node\n    path_sha256: abc123\n    \
2008             path_fallback: full-node\n    build: cargo build\n    git: https://github.com/example/node.git\n    \
2009             branch: main{SHARED_CUSTOM_NODE_KEYS}"
2010        );
2011        let custom = resolve_and_check_carried_through(&yaml, &["source", "envs"]);
2012        assert!(
2013            matches!(
2014                &custom.source,
2015                NodeSource::GitBranch { repo, rev: Some(GitRepoRev::Branch(branch)) }
2016                    if repo == "https://github.com/example/node.git" && branch == "main"
2017            ),
2018            "{:?}",
2019            custom.source
2020        );
2021        assert!(custom.envs.is_none(), "{:?}", custom.envs);
2022    }
2023
2024    /// The ROS2-bridge arm: `path` is the bridge binary, `envs` carries the
2025    /// bridge config the binary reads at startup, and every shared key still
2026    /// arrives. `path_sha256`, `path_fallback` and `build` are rejected on a
2027    /// `ros2:` node by classification, so they must stay unset.
2028    #[test]
2029    fn ros2_bridge_node_is_carried_through() {
2030        let yaml = format!(
2031            "nodes:\n  - id: bridge\n    ros2:\n      topic: /odom\n      \
2032             message_type: nav_msgs/msg/Odometry\n      direction: subscribe\
2033             {SHARED_CUSTOM_NODE_KEYS}"
2034        );
2035        let custom = resolve_and_check_carried_through(
2036            &yaml,
2037            &[
2038                "path",
2039                "source",
2040                "path_sha256",
2041                "path_fallback",
2042                "build",
2043                "envs",
2044            ],
2045        );
2046        assert_eq!(custom.path, "dora-ros2-bridge-node");
2047        assert!(
2048            matches!(custom.source, NodeSource::Local),
2049            "{:?}",
2050            custom.source
2051        );
2052        assert!(custom.path_sha256.is_none(), "{:?}", custom.path_sha256);
2053        assert!(custom.path_fallback.is_none(), "{:?}", custom.path_fallback);
2054        assert!(custom.build.is_none(), "{:?}", custom.build);
2055        let envs = custom
2056            .envs
2057            .expect("the bridge is configured through its environment");
2058        let Some(EnvValue::String(config)) = envs.get("DORA_ROS2_BRIDGE_CONFIG") else {
2059            panic!("DORA_ROS2_BRIDGE_CONFIG missing from {envs:?}");
2060        };
2061        assert!(config.contains("/odom"), "{config}");
2062    }
2063
2064    /// The node-level keys — the ones `ResolvedNode::from_node` consumes once
2065    /// `CustomNode::from_node` has drained the rest — must reach the resolved
2066    /// node. `from_node` is a struct literal inside `dora-message`, so a new
2067    /// `ResolvedNode` field is a compile error there; this checks the values,
2068    /// including that the dataflow-level `env` is merged in with the per-node
2069    /// key winning.
2070    #[test]
2071    fn node_level_keys_are_carried_through() {
2072        let yaml = r#"
2073env:
2074  RUST_LOG: info
2075  SHARED: global
2076nodes:
2077  - id: full
2078    name: Full Node
2079    description: Sets every node-level key
2080    path: ./full-node
2081    env:
2082      SHARED: per-node
2083    cpu_affinity: [0, 1]
2084    deploy:
2085      machine: gpu-box
2086"#;
2087        let desc: Descriptor = serde_yaml::from_str(yaml).expect("parse");
2088        let resolved = desc.resolve_aliases_and_set_defaults().expect("resolve");
2089        let node = resolved.values().next().expect("one node");
2090
2091        assert_eq!(node.id.to_string(), "full");
2092        assert_eq!(node.name.as_deref(), Some("Full Node"));
2093        assert_eq!(
2094            node.description.as_deref(),
2095            Some("Sets every node-level key")
2096        );
2097        assert_eq!(
2098            node.env,
2099            Some(env(&[("RUST_LOG", "info"), ("SHARED", "per-node")]))
2100        );
2101        assert_eq!(node.cpu_affinity, Some(vec![0, 1]));
2102        assert_eq!(
2103            node.deploy.as_ref().and_then(|d| d.machine.as_deref()),
2104            Some("gpu-box")
2105        );
2106    }
2107
2108    /// A multi-operator runtime node whose id contains a `.` must emit a
2109    /// Mermaid `subgraph` with a sanitized id (dots are invalid in subgraph
2110    /// ids), mirroring the module-subgraph path. Node ids legally contain `.`,
2111    /// and module expansion prefixes inner node ids with `{module_id}.`, so the
2112    /// unsanitized `subgraph camera.front` this used to emit was an invalid
2113    /// Mermaid document.
2114    #[test]
2115    fn runtime_node_subgraph_id_is_sanitized_for_dotted_ids() {
2116        let yaml = r#"
2117nodes:
2118  - id: camera.front
2119    operators:
2120      - id: detect
2121        python: detect.py
2122        inputs:
2123          tick: dora/timer/millis/100
2124        outputs:
2125          - bbox
2126"#;
2127        let desc: Descriptor = serde_yaml::from_str(yaml).expect("parse");
2128        let resolved = desc.resolve_aliases_and_set_defaults().expect("resolve");
2129        let flowchart =
2130            visualize::visualize_nodes_with_boundaries(&resolved, &ModuleBoundaries::default());
2131
2132        assert!(
2133            flowchart.contains("subgraph camera_front [camera.front]"),
2134            "runtime-node subgraph id must be sanitized and labelled; got:\n{flowchart}"
2135        );
2136        assert!(
2137            !flowchart.contains("subgraph camera.front"),
2138            "an unsanitized dotted subgraph id is invalid Mermaid; got:\n{flowchart}"
2139        );
2140    }
2141
2142    /// A multi-topic (`topics:`) ros2 bridge that maps a topic to an undeclared
2143    /// port must be rejected on the *resolution* path, not just by the
2144    /// validator. The coordinator's `dora start` path resolves without running
2145    /// the validator, so before dora-rs/dora#3484 an undeclared multi-topic
2146    /// mapping passed here and silently dropped every message at runtime.
2147    #[test]
2148    fn resolve_rejects_undeclared_multi_topic_subscribe_output() {
2149        let yaml = r#"
2150nodes:
2151  - id: lidar_bridge
2152    outputs: [scan]
2153    ros2:
2154      topics:
2155        - topic: /scan
2156          message_type: sensor_msgs/LaserScan
2157          direction: subscribe
2158          output: scna
2159"#;
2160        let desc: Descriptor = serde_yaml::from_str(yaml).expect("parse");
2161        let err = desc
2162            .resolve_aliases_and_set_defaults()
2163            .expect_err("resolution must reject a topic mapped to an undeclared output")
2164            .to_string();
2165        assert!(
2166            err.contains("scna") && err.contains("not declared"),
2167            "error should name the undeclared output, got: {err}"
2168        );
2169    }
2170
2171    /// The publish counterpart: a topic bound to an undeclared input is rejected
2172    /// on the resolution path too.
2173    #[test]
2174    fn resolve_rejects_undeclared_multi_topic_publish_input() {
2175        let yaml = r#"
2176nodes:
2177  - id: source
2178    path: ./source
2179    outputs: [cmd]
2180  - id: cmd_bridge
2181    inputs:
2182      cmd: source/cmd
2183    ros2:
2184      topics:
2185        - topic: /cmd_vel
2186          message_type: geometry_msgs/Twist
2187          direction: publish
2188          input: typo_in
2189"#;
2190        let desc: Descriptor = serde_yaml::from_str(yaml).expect("parse");
2191        let err = desc
2192            .resolve_aliases_and_set_defaults()
2193            .expect_err("resolution must reject a topic mapped to an undeclared input")
2194            .to_string();
2195        assert!(
2196            err.contains("typo_in") && err.contains("not declared"),
2197            "error should name the undeclared input, got: {err}"
2198        );
2199    }
2200
2201    /// Guard the other way: a multi-topic config whose mappings all reference
2202    /// declared ports (explicit and topic-derived) still resolves.
2203    #[test]
2204    fn resolve_accepts_declared_multi_topic_ports() {
2205        let yaml = r#"
2206nodes:
2207  - id: bridge
2208    outputs: [scan, laser]
2209    ros2:
2210      topics:
2211        - topic: /scan
2212          message_type: sensor_msgs/LaserScan
2213          direction: subscribe
2214          output: scan
2215        - topic: /laser
2216          message_type: sensor_msgs/LaserScan
2217          direction: subscribe
2218"#;
2219        let desc: Descriptor = serde_yaml::from_str(yaml).expect("parse");
2220        desc.resolve_aliases_and_set_defaults().expect(
2221            "a multi-topic config mapping declared ports (explicit and derived) must resolve",
2222        );
2223    }
2224
2225    /// A node that sets none of its mutually exclusive implementation fields is
2226    /// rejected, and the error must list every valid kind — including the
2227    /// single-`operator` form. The message previously named only `path`,
2228    /// `operators`, `ros2`, and `module`, silently omitting `operator` and so
2229    /// steering a user who mistyped an `operator:` key away from the correct
2230    /// fix (the sibling "multiple fields" error and the trait doc both list it).
2231    #[test]
2232    fn node_kind_error_lists_the_operator_field() {
2233        let descriptor: Descriptor =
2234            serde_yaml::from_str("nodes:\n  - id: lonely\n").expect("parse");
2235        let node = descriptor.nodes.first().expect("one node");
2236        let err = node
2237            .kind()
2238            .expect_err("a node with no implementation field must be rejected");
2239        let msg = format!("{err}");
2240        assert!(
2241            msg.contains("`operator`"),
2242            "the error must list the single-`operator` kind, got: {msg}"
2243        );
2244    }
2245}