Skip to main content

dora_core/descriptor/
validate.rs

1use crate::{
2    adjust_shared_library_path,
3    descriptor::{self, source_is_url},
4    get_python_path,
5};
6
7use dora_message::{
8    config::{Input, InputMapping, LogSubscriptionFilter, UserInputMapping, parse_byte_count},
9    descriptor::{CoreNodeKind, DYNAMIC_SOURCE, OperatorSource, ResolvedNode, SHELL_SOURCE},
10    id::{DataId, NodeId, OperatorId},
11    versions_compatible,
12};
13use eyre::{Context, bail, eyre};
14use std::{
15    collections::{BTreeMap, BTreeSet},
16    path::Path,
17    process::{Command, Stdio},
18};
19use tracing::info;
20
21use super::{Descriptor, DescriptorExt, resolve_node_path};
22const VERSION: &str = env!("CARGO_PKG_VERSION");
23
24/// Validate input/output wiring without checking path existence.
25///
26/// This is safe to run before building nodes. It verifies every input
27/// reference points to a declared output on the source node.
28pub fn check_wiring(dataflow: &Descriptor) -> eyre::Result<()> {
29    let nodes = dataflow.resolve_aliases_and_set_defaults()?;
30    check_wiring_resolved(&nodes)
31}
32
33/// [`check_wiring`] on an already-resolved node map, so callers that have
34/// resolved the descriptor can avoid re-resolving it.
35fn check_wiring_resolved(nodes: &BTreeMap<NodeId, ResolvedNode>) -> eyre::Result<()> {
36    for node in nodes.values() {
37        match &node.kind {
38            descriptor::CoreNodeKind::Custom(custom_node) => {
39                for (input_id, input) in &custom_node.run_config.inputs {
40                    check_input(input, nodes, &format!("{}/{input_id}", node.id))?;
41                }
42            }
43            descriptor::CoreNodeKind::Runtime(runtime_node) => {
44                for operator_definition in &runtime_node.operators {
45                    for (input_id, input) in &operator_definition.config.inputs {
46                        check_input(
47                            input,
48                            nodes,
49                            &format!("{}/{}/{input_id}", node.id, operator_definition.id),
50                        )?;
51                    }
52                }
53            }
54        };
55    }
56
57    Ok(())
58}
59
60/// Static (filesystem-independent) descriptor checks: ROS2 bridge configs,
61/// timing fields, input/output wiring, and log-output configuration.
62///
63/// This is the subset of [`check_dataflow`] that `dora validate` can run
64/// before any build has happened. [`check_dataflow`] runs it as its first
65/// step and adds source-path existence and Python runtime checks on top.
66pub fn check_dataflow_static(dataflow: &Descriptor) -> eyre::Result<()> {
67    // validate ROS2 bridge configs before resolution
68    validate_ros2_configs(dataflow)?;
69
70    let nodes = dataflow.resolve_aliases_and_set_defaults()?;
71    check_dataflow_static_resolved(dataflow, &nodes)
72}
73
74/// Check every local `shared-library:` operator path against the runtime's
75/// file-name rules (no `lib` prefix, no extension; see
76/// [`adjust_shared_library_path`]).
77///
78/// The rules need no filesystem access, so this runs in the static pass —
79/// before any build, and also for operators whose `build:` command will
80/// produce the file later. Without it a misnamed path validated, the build
81/// ran, and the node only failed at spawn.
82fn check_shared_library_names(nodes: &BTreeMap<NodeId, ResolvedNode>) -> eyre::Result<()> {
83    for node in nodes.values() {
84        let CoreNodeKind::Runtime(runtime) = &node.kind else {
85            continue;
86        };
87        for operator in &runtime.operators {
88            if let OperatorSource::SharedLibrary(path) = &operator.config.source
89                && !source_is_url(path)
90            {
91                adjust_shared_library_path(Path::new(path)).wrap_err_with(|| {
92                    format!(
93                        "invalid shared-library path for operator `{}/{}`",
94                        node.id, operator.id
95                    )
96                })?;
97            }
98        }
99    }
100    Ok(())
101}
102
103/// Validate all ROS2 bridge configs on the *unresolved* descriptor.
104///
105/// Run before [`Descriptor::resolve_aliases_and_set_defaults`] so a ROS2
106/// misconfiguration is reported ahead of any alias-resolution error.
107fn validate_ros2_configs(dataflow: &Descriptor) -> eyre::Result<()> {
108    for node in &dataflow.nodes {
109        if let Some(ros2) = &node.ros2 {
110            validate_ros2_config(&node.id, ros2, &node.inputs, &node.outputs)?;
111        }
112    }
113    Ok(())
114}
115
116/// The resolution-dependent part of [`check_dataflow_static`], operating on an
117/// already-resolved node map so callers don't re-resolve the descriptor.
118fn check_dataflow_static_resolved(
119    dataflow: &Descriptor,
120    nodes: &BTreeMap<NodeId, ResolvedNode>,
121) -> eyre::Result<()> {
122    for node in nodes.values() {
123        check_node_timing(node)?;
124    }
125    // dataflow-level `health_check_interval` reaches `Duration::from_secs_f64`
126    // in the same way (`binaries/daemon/src/lib.rs`). A zero interval must also
127    // be rejected: it is fed to `tokio::time::interval`, which panics on a zero
128    // period.
129    check_seconds_field(
130        "dataflow",
131        "health_check_interval",
132        dataflow.health_check_interval,
133        false,
134    )?;
135
136    // check that all inputs mappings point to an existing output
137    check_wiring_resolved(nodes)?;
138
139    check_shared_library_names(nodes)?;
140
141    // Check that nodes can resolve `send_stdout_as`, `send_logs_as`, `min_log_level`
142    for node in nodes.values() {
143        node.send_stdout_as()
144            .context("Could not resolve `send_stdout_as` configuration")?;
145        node.send_logs_as()
146            .context("Could not resolve `send_logs_as` configuration")?;
147        node.min_log_level()
148            .context("Could not resolve `min_log_level` configuration")?;
149        node.max_log_size()
150            .context("Could not resolve `max_log_size` configuration")?;
151        node.max_rotated_files()
152            .context("Could not resolve `max_rotated_files` configuration")?;
153    }
154
155    Ok(())
156}
157
158pub fn check_dataflow(dataflow: &Descriptor, working_dir: &Path) -> eyre::Result<()> {
159    // Resolve the descriptor once and share the result across every check
160    // (static validation + path/runtime existence) instead of re-resolving it
161    // for each, which clones the whole node topology on every call.
162    validate_ros2_configs(dataflow)?;
163    let nodes = dataflow.resolve_aliases_and_set_defaults()?;
164    check_dataflow_static_resolved(dataflow, &nodes)?;
165
166    let mut has_python_operator = false;
167
168    // check that nodes and operators exist
169    for node in nodes.values() {
170        match &node.kind {
171            descriptor::CoreNodeKind::Custom(custom) => match &custom.source {
172                dora_message::descriptor::NodeSource::Local => match custom.path.as_str() {
173                    SHELL_SOURCE => (),
174                    DYNAMIC_SOURCE => (),
175                    source => {
176                        if source_is_url(source) {
177                            info!("{source} is a URL."); // TODO: Implement url check.
178                        } else if custom.build.is_some() {
179                            info!("skipping path check for node with build command");
180                        } else {
181                            resolve_node_path(source, custom.path_fallback.as_deref(), working_dir)
182                                .wrap_err_with(|| {
183                                    format!("Could not find source path `{source}`")
184                                })?;
185                        };
186                    }
187                },
188                dora_message::descriptor::NodeSource::GitBranch { .. } => {
189                    info!("skipping check for node with git source");
190                }
191            },
192            descriptor::CoreNodeKind::Runtime(runtime) => {
193                for operator_definition in &runtime.operators {
194                    match &operator_definition.config.source {
195                        OperatorSource::SharedLibrary(path) => {
196                            if source_is_url(path) {
197                                info!("{path} is a URL."); // TODO: Implement url check.
198                            } else if operator_definition.config.build.is_some() {
199                                info!("skipping path check for operator with build command");
200                            } else {
201                                // The file-name rules were already checked by the
202                                // static pass above.
203                                let path = adjust_shared_library_path(Path::new(&path))?;
204                                if !working_dir.join(&path).exists() {
205                                    bail!("no shared library at `{}`", path.display());
206                                }
207                            }
208                        }
209                        OperatorSource::Python(python_source) => {
210                            has_python_operator = true;
211                            let path = &python_source.source;
212                            if source_is_url(path) {
213                                info!("{path} is a URL."); // TODO: Implement url check.
214                            } else if operator_definition.config.build.is_some() {
215                                info!("skipping path check for operator with build command");
216                            } else if !working_dir.join(path).exists() {
217                                bail!("no Python library at `{path}`");
218                            }
219                        }
220                        OperatorSource::Wasm(path) => {
221                            if source_is_url(path) {
222                                info!("{path} is a URL."); // TODO: Implement url check.
223                            } else if operator_definition.config.build.is_some() {
224                                info!("skipping path check for operator with build command");
225                            } else if !working_dir.join(path).exists() {
226                                bail!("no WASM library at `{path}`");
227                            }
228                        }
229                    }
230                }
231            }
232        }
233    }
234
235    if has_python_operator {
236        check_python_runtime()?;
237    }
238
239    Ok(())
240}
241
242/// Validate the second-valued timing fields of one resolved node: the custom
243/// node's own timeouts and restart delays, plus every input's
244/// `input_timeout`.
245///
246/// The daemon feeds these to `Duration::from_secs_f64`, which panics on
247/// negative, non-finite, or overflowing values. [`check_dataflow_static`]
248/// runs this for every node; call it directly for a node that joins a running
249/// dataflow (`dora node add` / `dora node replace`), which never goes through
250/// whole-dataflow validation.
251///
252/// This also enforces the `startup_timeout` rule for dynamic nodes, which is
253/// a descriptor-policy check rather than a panic guard. The spawn path of an
254/// existing dataflow (`dora start`) must not apply that rule to a descriptor
255/// that started fine before, so it calls [`check_node_timing_values`] instead.
256pub fn check_node_timing(node: &ResolvedNode) -> eyre::Result<()> {
257    check_node_timing_values(node)?;
258    if let descriptor::CoreNodeKind::Custom(custom) = &node.kind
259        && custom.path.as_str() == DYNAMIC_SOURCE
260        && custom.startup_timeout.is_some()
261    {
262        bail!(
263            "dynamic node `{}` cannot specify `startup_timeout` (dynamic nodes connect out-of-band and are not managed by the startup watchdog)",
264            node.id
265        );
266    }
267    Ok(())
268}
269
270/// A runtime node must hold exactly one operator: the operator runtime
271/// (`dora_runtime_api::main`, shared by the shared-library and Python
272/// backends) refuses to start with zero or several. Without this check such a
273/// descriptor passes validation and only fails when the runtime process
274/// starts.
275///
276/// Like [`check_operator_ids`], descriptor resolution runs this for every
277/// node, so `dora start`, `dora node add/replace` and recovery are covered.
278pub fn check_runtime_operator_count(node: &ResolvedNode) -> eyre::Result<()> {
279    if let descriptor::CoreNodeKind::Runtime(runtime) = &node.kind
280        && runtime.operators.len() != 1
281    {
282        bail!(
283            "runtime node `{}` has {} operators, but a runtime node runs exactly one \
284             operator; split them into one node per operator",
285            node.id,
286            runtime.operators.len()
287        );
288    }
289    Ok(())
290}
291
292/// The panic-guard half of [`check_node_timing`]: reject only the values the
293/// daemon would panic on in `Duration::from_secs_f64`, with no
294/// descriptor-policy rules on top.
295///
296/// `dora start` never ran whole-dataflow validation before, so applying a
297/// policy rule there would reject descriptors that start fine on 1.0.x and
298/// never panicked -- a dynamic node carrying an (ignored) `startup_timeout`,
299/// for one. The spawn path therefore guards against the panic only, and
300/// leaves the policy rules to `dora run` / `dora validate`
301/// ([`check_dataflow_static`]) and to the node-join path
302/// ([`check_node_timing`]).
303pub fn check_node_timing_values(node: &ResolvedNode) -> eyre::Result<()> {
304    if let descriptor::CoreNodeKind::Custom(custom) = &node.kind {
305        check_timing_fields(&node.id, custom)?;
306    }
307    // `input_timeout` is a second-valued `f64` that the daemon also feeds
308    // to `Duration::from_secs_f64`, on both the initial-spawn and the
309    // reconnect paths.
310    for (input_id, input) in node_inputs(node) {
311        check_seconds_field(
312            &format!("input `{input_id}` of node `{}`", node.id),
313            "input_timeout",
314            input.input_timeout,
315            true,
316        )?;
317    }
318    Ok(())
319}
320
321/// Reject negative / non-finite / overflowing second-valued timing fields on a
322/// custom node.
323///
324/// The daemon converts these to `Duration` via `Duration::from_secs_f64`, which
325/// panics on negative, NaN, infinite, or overflowing (> `Duration::MAX`) input.
326/// Catching them here surfaces a clean descriptor error instead of crashing the
327/// daemon on node spawn.
328fn check_timing_fields(
329    node_id: &NodeId,
330    custom: &dora_message::descriptor::CustomNode,
331) -> eyre::Result<()> {
332    let owner = format!("node `{node_id}`");
333    for (field, value) in [
334        ("finish_grace_secs", custom.finish_grace_secs),
335        ("health_check_timeout", custom.health_check_timeout),
336        ("startup_timeout", custom.startup_timeout),
337        ("restart_delay", custom.restart_delay),
338        ("max_restart_delay", custom.max_restart_delay),
339        ("restart_window", custom.restart_window),
340    ] {
341        check_seconds_field(&owner, field, value, true)?;
342    }
343    Ok(())
344}
345
346/// Reject a negative / non-finite / overflowing second-valued field before it
347/// reaches the daemon, where `Duration::from_secs_f64` would panic on such
348/// input.
349///
350/// `Duration::from_secs_f64` panics on negative, NaN, infinite, *and* finite
351/// values too large to fit in a `Duration` (> `Duration::MAX`, ≈ 1.8e19 s). We
352/// probe the exact same boundary with its non-panicking twin
353/// `try_from_secs_f64`, so a value accepted here can never panic the daemon.
354///
355/// When `allow_zero` is `false`, any value that produces a zero-length
356/// `Duration` is also rejected. This is required for fields that reach
357/// `tokio::time::interval` (e.g. `health_check_interval`), which panics on a
358/// zero period. Checking the resulting `Duration` -- not just the literal
359/// `0.0` -- also rejects a tiny-but-positive value such as `1e-10`, which
360/// `Duration::from_secs_f64` rounds down to `Duration::ZERO`. This mirrors the
361/// timer parser's `interval.is_zero()` guard in `dora-message`.
362fn check_seconds_field(
363    owner: &str,
364    field: &str,
365    value: Option<f64>,
366    allow_zero: bool,
367) -> eyre::Result<()> {
368    if let Some(value) = value {
369        // A negative / non-finite / overflowing value fails to convert; a
370        // tiny-but-positive value (e.g. `1e-10`) converts to `Duration::ZERO`,
371        // which must also be rejected for interval fields (`allow_zero ==
372        // false`). Inspect the resulting `Duration`, not the literal `0.0`.
373        let duration = std::time::Duration::try_from_secs_f64(value);
374        let is_zero = duration.as_ref().is_ok_and(|d| d.is_zero());
375        if !allow_zero && is_zero {
376            // Distinct message: a value like `1e-10` *is* positive, so calling it
377            // "not positive" would misdirect the user -- the real reason is that
378            // it rounds down to a zero-length duration.
379            bail!(
380                "{owner} has invalid `{field}`: {value} \
381                 (must be a positive number of seconds; this value is zero or \
382                 rounds down to a zero-length duration)"
383            );
384        }
385        if duration.is_err() {
386            let requirement = if allow_zero {
387                "non-negative"
388            } else {
389                "positive"
390            };
391            bail!(
392                "{owner} has invalid `{field}`: {value} \
393                 (must be a finite, {requirement} number of seconds smaller than {})",
394                std::time::Duration::MAX.as_secs_f64()
395            );
396        }
397    }
398    Ok(())
399}
400
401/// Reject a runtime operator id that cannot prefix a `DataId`.
402///
403/// The daemon and the operator runtime expose each operator input/output as
404/// the `DataId` `{operator_id}/{id}`, built with `DataId::from`, which panics
405/// on an invalid id. `OperatorId` itself accepts any string (its `FromStr` is
406/// infallible), so an id such as `my op` or `""` would otherwise pass
407/// validation and crash the daemon when it spawns the node. The id must also
408/// be a single path segment, or the `{operator_id}/{id}` split is ambiguous.
409///
410/// Descriptor resolution (`resolve_aliases_and_set_defaults`) runs this for
411/// every node, so every coordinator path is covered. The daemon also calls it
412/// on the nodes it is asked to spawn, so an older coordinator cannot crash it.
413pub fn check_operator_ids(node: &ResolvedNode) -> eyre::Result<()> {
414    let CoreNodeKind::Runtime(runtime) = &node.kind else {
415        return Ok(());
416    };
417    for operator in &runtime.operators {
418        let id: &str = operator.id.as_ref();
419        if id.contains('/') {
420            bail!(
421                "node `{}`: invalid operator id `{id}`: must not contain `/`",
422                node.id
423            );
424        }
425        if let Err(err) = id.parse::<DataId>() {
426            bail!("node `{}`: invalid operator id `{id}`: {err}", node.id);
427        }
428    }
429    Ok(())
430}
431
432/// All `(input_id, input)` pairs declared on a resolved node: a custom node's
433/// own inputs, or the merged inputs of every operator of a runtime node.
434fn node_inputs(node: &ResolvedNode) -> Vec<(&DataId, &Input)> {
435    match &node.kind {
436        CoreNodeKind::Custom(custom) => custom.run_config.inputs.iter().collect(),
437        CoreNodeKind::Runtime(runtime) => runtime
438            .operators
439            .iter()
440            .flat_map(|op| op.config.inputs.iter())
441            .collect(),
442    }
443}
444
445pub trait ResolvedNodeExt {
446    fn send_stdout_as(&self) -> eyre::Result<Option<String>>;
447    fn send_logs_as(&self) -> eyre::Result<Option<String>>;
448    fn min_log_level(&self) -> eyre::Result<Option<dora_message::common::LogLevelOrStdout>>;
449    fn max_log_size(&self) -> eyre::Result<Option<u64>>;
450    fn max_rotated_files(&self) -> eyre::Result<Option<u32>>;
451}
452
453/// Check that a resolved `send_stdout_as` / `send_logs_as` name is a valid
454/// [`DataId`]. The daemon's per-node log task turns it into one for every log
455/// line, and an invalid name (empty, a space, `op/` from an empty operator
456/// entry, ...) would otherwise panic that task on the node's first line and
457/// silently drop all of the node's later logs.
458fn checked_output_name(field: &str, name: String) -> eyre::Result<String> {
459    name.parse::<DataId>()
460        .map_err(|err| eyre!("`{field}: {name}` is not a valid output id: {err}"))?;
461    Ok(name)
462}
463
464impl ResolvedNodeExt for ResolvedNode {
465    fn send_stdout_as(&self) -> eyre::Result<Option<String>> {
466        let name = match &self.kind {
467            // TODO: Split stdout between operators
468            CoreNodeKind::Runtime(n) => {
469                let count = n
470                    .operators
471                    .iter()
472                    .filter(|op| op.config.send_stdout_as.is_some())
473                    .count();
474                if count == 1 && n.operators.len() > 1 {
475                    tracing::warn!(
476                        "All stdout from all operators of a runtime are going to be sent in the selected `send_stdout_as` operator."
477                    )
478                } else if count > 1 {
479                    return Err(eyre!(
480                        "More than one `send_stdout_as` entries for a runtime node. Please only use one `send_stdout_as` per runtime."
481                    ));
482                }
483                n.operators.iter().find_map(|op| {
484                    op.config
485                        .send_stdout_as
486                        .as_ref()
487                        .map(|stdout| format!("{}/{}", op.id, stdout))
488                })
489            }
490            CoreNodeKind::Custom(n) => n.send_stdout_as.clone(),
491        };
492        name.map(|name| checked_output_name("send_stdout_as", name))
493            .transpose()
494    }
495
496    fn send_logs_as(&self) -> eyre::Result<Option<String>> {
497        let name = match &self.kind {
498            CoreNodeKind::Runtime(n) => {
499                let count = n
500                    .operators
501                    .iter()
502                    .filter(|op| op.config.send_logs_as.is_some())
503                    .count();
504                if count > 1 {
505                    return Err(eyre!(
506                        "More than one `send_logs_as` entries for a runtime node. Please only use one `send_logs_as` per runtime."
507                    ));
508                }
509                n.operators.iter().find_map(|op| {
510                    op.config
511                        .send_logs_as
512                        .as_ref()
513                        .map(|logs| format!("{}/{}", op.id, logs))
514                })
515            }
516            CoreNodeKind::Custom(n) => n.send_logs_as.clone(),
517        };
518        name.map(|name| checked_output_name("send_logs_as", name))
519            .transpose()
520    }
521
522    fn min_log_level(&self) -> eyre::Result<Option<dora_message::common::LogLevelOrStdout>> {
523        let level_str = match &self.kind {
524            CoreNodeKind::Runtime(n) => {
525                // Use the first operator's min_log_level (only one allowed)
526                let levels: Vec<_> = n
527                    .operators
528                    .iter()
529                    .filter_map(|op| op.config.min_log_level.as_deref())
530                    .collect();
531                if levels.len() > 1 {
532                    return Err(eyre!(
533                        "More than one `min_log_level` entries for a runtime node. Please only use one `min_log_level` per runtime."
534                    ));
535                }
536                levels.first().map(|s| s.to_string())
537            }
538            CoreNodeKind::Custom(n) => n.min_log_level.clone(),
539        };
540        match level_str {
541            None => Ok(None),
542            Some(s) => {
543                let level = parse_log_level(&s)?;
544                Ok(Some(level))
545            }
546        }
547    }
548
549    fn max_log_size(&self) -> eyre::Result<Option<u64>> {
550        let size_str = match &self.kind {
551            CoreNodeKind::Runtime(n) => {
552                let sizes: Vec<_> = n
553                    .operators
554                    .iter()
555                    .filter_map(|op| op.config.max_log_size.as_deref())
556                    .collect();
557                if sizes.len() > 1 {
558                    return Err(eyre!(
559                        "More than one `max_log_size` entries for a runtime node. Please only use one `max_log_size` per runtime."
560                    ));
561                }
562                sizes.first().map(|s| s.to_string())
563            }
564            CoreNodeKind::Custom(n) => n.max_log_size.clone(),
565        };
566        match size_str {
567            None => Ok(None),
568            Some(s) => {
569                let bytes = parse_byte_size(&s)?;
570                Ok(Some(bytes))
571            }
572        }
573    }
574
575    fn max_rotated_files(&self) -> eyre::Result<Option<u32>> {
576        let value = match &self.kind {
577            CoreNodeKind::Runtime(n) => {
578                let values: Vec<_> = n
579                    .operators
580                    .iter()
581                    .filter_map(|op| op.config.max_rotated_files)
582                    .collect();
583                if values.len() > 1 {
584                    return Err(eyre!(
585                        "More than one `max_rotated_files` entries for a runtime node. Please only use one `max_rotated_files` per runtime."
586                    ));
587                }
588                values.first().copied()
589            }
590            CoreNodeKind::Custom(n) => n.max_rotated_files,
591        };
592        if let Some(n) = value {
593            // 0 is meaningful: keep the active log only, rotating the previous
594            // one away rather than retaining it. That matches the documented
595            // disk bound `max_log_size * (1 + max_rotated_files)`, which at 0
596            // is one active file.
597            if n > 100 {
598                bail!("`max_rotated_files` must not exceed 100");
599            }
600        }
601        Ok(value)
602    }
603}
604
605fn parse_byte_size(s: &str) -> eyre::Result<u64> {
606    // Share `dora_message::config::ByteSize`'s grammar, but parse in `u64`:
607    // `ByteSize` is `usize`-based, which would reject log sizes of 4 GiB and
608    // above on 32-bit targets (#3604).
609    parse_byte_count(s).map_err(|e| eyre!("{e}"))
610}
611
612fn parse_log_level(s: &str) -> eyre::Result<dora_message::common::LogLevelOrStdout> {
613    match s.to_lowercase().as_str() {
614        "error" => Ok(dora_message::common::LogLevelOrStdout::LogLevel(
615            log::Level::Error,
616        )),
617        "warn" => Ok(dora_message::common::LogLevelOrStdout::LogLevel(
618            log::Level::Warn,
619        )),
620        "info" => Ok(dora_message::common::LogLevelOrStdout::LogLevel(
621            log::Level::Info,
622        )),
623        "debug" => Ok(dora_message::common::LogLevelOrStdout::LogLevel(
624            log::Level::Debug,
625        )),
626        "trace" => Ok(dora_message::common::LogLevelOrStdout::LogLevel(
627            log::Level::Trace,
628        )),
629        "stdout" => Ok(dora_message::common::LogLevelOrStdout::Stdout),
630        _ => bail!(
631            "invalid min_log_level: '{s}', expected one of: error, warn, info, debug, trace, stdout"
632        ),
633    }
634}
635
636fn check_input(
637    input: &Input,
638    nodes: &BTreeMap<NodeId, super::ResolvedNode>,
639    input_id_str: &str,
640) -> Result<(), eyre::ErrReport> {
641    match &input.mapping {
642        // The daemon matches a log filter's node id exactly. A filter naming
643        // a module node can never match: expansion replaced that node with
644        // its prefixed `<module>.<inner>` nodes. Any other unknown id may
645        // still be a node added later with `dora node add`, so only warn.
646        InputMapping::Logs(LogSubscriptionFilter {
647            node_filter: Some(node),
648            ..
649        }) if !nodes.contains_key(node) => {
650            let module_prefix = format!("{node}.");
651            if let Some(inner) = nodes
652                .keys()
653                .find(|id| id.as_ref().starts_with(&module_prefix))
654            {
655                bail!(
656                    "log filter on input `{input_id_str}` names `{node}`, which is not a node \
657                     but the prefix of node `{inner}`; a module's nodes are named \
658                     `<module>.<inner-node>`, so name one of them instead"
659                );
660            }
661            tracing::warn!(
662                "log filter on input `{input_id_str}` names node `{node}`, which is not in \
663                 the dataflow; it delivers nothing unless a node with that id is added later"
664            );
665        }
666        InputMapping::Timer { interval: _ } | InputMapping::Logs(_) => {}
667        InputMapping::User(UserInputMapping { source, output }) => {
668            // `nodes` is keyed by each node's own id (see
669            // `resolve_aliases_and_set_defaults`), so look the source up
670            // directly instead of scanning every node — this runs once per
671            // input of every node, so a linear scan makes wiring validation
672            // quadratic in the node count.
673            let source_node = nodes.get(source).ok_or_else(|| {
674                eyre!("source node `{source}` mapped to input `{input_id_str}` does not exist",)
675            })?;
676            match &source_node.kind {
677                CoreNodeKind::Custom(custom_node) => {
678                    if !custom_node.run_config.outputs.contains(output) {
679                        bail!(
680                            "output `{source}/{output}` mapped to \
681                            input `{input_id_str}` does not exist",
682                        );
683                    }
684                }
685                CoreNodeKind::Runtime(runtime) => {
686                    // Outputs of runtime nodes are referenced as
687                    // `<node>/<operator>/<output>`. Without the operator
688                    // segment, falling back to an empty operator id would
689                    // produce a misleading "operator `` does not exist" error.
690                    let Some((operator_id, output)) = output.split_once('/') else {
691                        bail!(
692                            "input `{input_id_str}` references output `{output}` of node \
693                            `{source}`, which is a runtime node; runtime node outputs \
694                            must include the operator id \
695                            (expected format: `{source}/<operator_id>/<output_id>`)"
696                        );
697                    };
698                    let operator_id = OperatorId::from(operator_id.to_owned());
699                    let output = DataId::from(output.to_owned());
700
701                    let operator = runtime
702                        .operators
703                        .iter()
704                        .find(|o| o.id == operator_id)
705                        .ok_or_else(|| {
706                            eyre!(
707                                "source operator `{source}/{operator_id}` used \
708                                for input `{input_id_str}` does not exist",
709                            )
710                        })?;
711
712                    if !operator.config.outputs.contains(&output) {
713                        bail!(
714                            "output `{source}/{operator_id}/{output}` mapped to \
715                            input `{input_id_str}` does not exist",
716                        );
717                    }
718                }
719            }
720        }
721    };
722    Ok(())
723}
724
725fn check_python_runtime() -> eyre::Result<()> {
726    let mut command = Command::new(get_python_path().context("Could not get python binary")?);
727    command
728        .args(["-c", "import dora; print(dora.__version__)"])
729        // Only the version is captured, so that import errors stay visible.
730        .stderr(Stdio::inherit());
731    let output = command
732        .output()
733        .wrap_err("Could not run python dora-rs command.")?;
734
735    if !output.status.success() {
736        bail!(
737            "Something went wrong with Python dora-rs. {}",
738            python_reinstall_hint()
739        )
740    }
741
742    check_python_dora_version(&String::from_utf8_lossy(&output.stdout))
743}
744
745fn python_reinstall_hint() -> String {
746    format!("Please reinstall it with: `pip install dora-rs=={VERSION} --force`")
747}
748
749/// Check the installed Python `dora-rs` version, as printed on the last line of
750/// `stdout`, with the same rule as the version handshakes. An exact match would
751/// reject wheels that the daemon accepts, e.g. a stable wheel with a release
752/// candidate CLI.
753fn check_python_dora_version(stdout: &str) -> eyre::Result<()> {
754    // Importing a package can print to stdout, so only the last line counts.
755    let installed = stdout.trim().lines().last().unwrap_or_default().trim();
756    let installed = semver::Version::parse(installed).wrap_err_with(|| {
757        format!(
758            "Could not read the Python dora-rs version from `{installed}`. {}",
759            python_reinstall_hint()
760        )
761    })?;
762    let own = semver::Version::parse(VERSION).wrap_err("invalid dora version")?;
763
764    if !versions_compatible(&own, &installed).map_err(|error| eyre!(error))? {
765        bail!(
766            "Python dora-rs {installed} is not compatible with dora {VERSION}. {}",
767            python_reinstall_hint()
768        )
769    }
770
771    Ok(())
772}
773
774fn validate_ros2_config(
775    node_id: &NodeId,
776    config: &dora_message::descriptor::Ros2BridgeConfig,
777    node_inputs: &BTreeMap<DataId, Input>,
778    node_outputs: &BTreeSet<DataId>,
779) -> eyre::Result<()> {
780    use dora_message::descriptor::{Ros2Role, Ros2TransportConfig};
781
782    if let Ros2TransportConfig::Zenoh {
783        config_uri: Some(uri),
784        ..
785    } = &config.transport
786        && uri.as_os_str().is_empty()
787    {
788        bail!("node `{node_id}`: ros2 Zenoh config_uri must not be empty");
789    }
790
791    // Exactly one of topic, topics, service, action must be set
792    let mode_count = [
793        config.topic.is_some(),
794        config.topics.is_some(),
795        config.service.is_some(),
796        config.action.is_some(),
797    ]
798    .iter()
799    .filter(|&&v| v)
800    .count();
801    if mode_count == 0 {
802        bail!(
803            "node `{node_id}`: ros2 config requires one of \
804             `topic`, `topics`, `service`, or `action`"
805        );
806    }
807    if mode_count > 1 {
808        bail!(
809            "node `{node_id}`: ros2 config has multiple of \
810             `topic`, `topics`, `service`, `action` - only one is allowed"
811        );
812    }
813
814    if let Some(topic) = &config.topic {
815        validate_ros2_name(node_id, "topic", topic)?;
816        let message_type = config.message_type.as_ref().ok_or_else(|| {
817            eyre!("node `{node_id}`: ros2 config with `topic` requires `message_type`")
818        })?;
819        validate_ros2_type_format(node_id, topic, message_type)?;
820
821        // Single-topic mode has no explicit `output:`/`input:` field, so the
822        // bridge binds to the node's declared port. Resolution is what picks
823        // that port and what rejects a node whose declarations leave the choice
824        // ambiguous, so call it here rather than restating the rule: the two
825        // must not be able to disagree.
826        super::resolve_ros2_single_topic(node_id, config, node_inputs, node_outputs)?;
827    } else if let Some(topics) = &config.topics {
828        if topics.is_empty() {
829            bail!("node `{node_id}`: ros2 `topics` list must not be empty");
830        }
831        if topics.len() > 64 {
832            bail!(
833                "node `{node_id}`: ros2 `topics` list has {} entries, maximum is 64",
834                topics.len()
835            );
836        }
837        for t in topics {
838            validate_ros2_name(node_id, "topic", &t.topic)?;
839            validate_ros2_type_format(node_id, &t.topic, &t.message_type)?;
840        }
841        // The per-topic port-existence check lives on the resolution path
842        // (`validate_ros2_topic_ports`) so the coordinator's `dora start` path,
843        // which resolves without validating, enforces it too. Delegate here
844        // rather than restating the rule, keeping validation and `dora start` in
845        // lockstep by construction (dora-rs/dora#3484).
846        super::validate_ros2_topic_ports(node_id, topics, node_inputs, node_outputs)?;
847    } else if let Some(service) = &config.service {
848        validate_ros2_name(node_id, "service", service)?;
849        let service_type = config.service_type.as_ref().ok_or_else(|| {
850            eyre!("node `{node_id}`: ros2 config with `service` requires `service_type`")
851        })?;
852        validate_ros2_type_format(node_id, service, service_type)?;
853        let role = config.role.as_ref().ok_or_else(|| {
854            eyre!("node `{node_id}`: ros2 service bridge requires `role` (client or server)")
855        })?;
856        match role {
857            Ros2Role::Client => {
858                if node_inputs.is_empty() {
859                    bail!(
860                        "node `{node_id}`: ros2 service client requires at least one input (request)"
861                    );
862                }
863                if node_outputs.is_empty() {
864                    bail!(
865                        "node `{node_id}`: ros2 service client requires at least one output (response)"
866                    );
867                }
868            }
869            Ros2Role::Server => {
870                if node_inputs.is_empty() {
871                    bail!(
872                        "node `{node_id}`: ros2 service server requires at least one input (response)"
873                    );
874                }
875                if node_outputs.is_empty() {
876                    bail!(
877                        "node `{node_id}`: ros2 service server requires at least one output (request)"
878                    );
879                }
880            }
881        }
882    } else if let Some(action) = &config.action {
883        validate_ros2_name(node_id, "action", action)?;
884        let action_type = config.action_type.as_ref().ok_or_else(|| {
885            eyre!("node `{node_id}`: ros2 config with `action` requires `action_type`")
886        })?;
887        validate_ros2_type_format(node_id, action, action_type)?;
888        let role = config
889            .role
890            .as_ref()
891            .ok_or_else(|| eyre!("node `{node_id}`: ros2 action bridge requires `role`"))?;
892        match role {
893            Ros2Role::Client => {
894                if node_inputs.is_empty() {
895                    bail!(
896                        "node `{node_id}`: ros2 action client requires at least one input (goal)"
897                    );
898                }
899                if node_outputs.is_empty() {
900                    bail!(
901                        "node `{node_id}`: ros2 action client requires at least one output \
902                         (feedback/result)"
903                    );
904                }
905            }
906            Ros2Role::Server => {
907                if node_inputs.is_empty() {
908                    bail!(
909                        "node `{node_id}`: ros2 action server requires at least one input \
910                         (feedback/result)"
911                    );
912                }
913                if node_outputs.is_empty() {
914                    bail!(
915                        "node `{node_id}`: ros2 action server requires at least one output (goal)"
916                    );
917                }
918            }
919        }
920    }
921
922    // Validate QoS config
923    validate_ros2_qos(node_id, &config.qos)?;
924    if let Some(topics) = &config.topics {
925        for t in topics {
926            if let Some(qos) = &t.qos {
927                validate_ros2_qos(node_id, qos)?;
928            }
929        }
930    }
931
932    Ok(())
933}
934
935fn validate_ros2_qos(
936    node_id: &NodeId,
937    qos: &dora_message::descriptor::Ros2QosConfig,
938) -> eyre::Result<()> {
939    if let Some(d) = &qos.durability {
940        match d.as_str() {
941            "volatile" | "transient_local" => {}
942            _ => bail!(
943                "node `{node_id}`: invalid QoS durability `{d}`, \
944                 expected \"volatile\" or \"transient_local\""
945            ),
946        }
947    }
948    if let Some(l) = &qos.liveliness {
949        match l.as_str() {
950            "automatic" | "manual_by_participant" | "manual_by_topic" => {}
951            _ => bail!(
952                "node `{node_id}`: invalid QoS liveliness `{l}`, \
953                 expected \"automatic\", \"manual_by_participant\", or \"manual_by_topic\""
954            ),
955        }
956    }
957    if let Some(depth) = qos.keep_last
958        && !(1..=10_000).contains(&depth)
959    {
960        bail!(
961            "node `{node_id}`: QoS keep_last depth {depth} out of range, \
962                 must be between 1 and 10000"
963        );
964    }
965    // Both fields reach `Duration::from_secs_f64` in the ROS2 bridge QoS
966    // conversion and panic on a finite-but-overflowing value (e.g. `1e300`),
967    // not just on NaN/infinite/negative. `check_seconds_field` probes that
968    // exact boundary with `try_from_secs_f64`, matching every other
969    // second-valued field here, and keeps validating both fields whenever set
970    // (as the prior check did). `allow_zero = true`: `max_blocking_time`
971    // defaults to `0.0` and a zero lease is harmless.
972    let owner = format!("node `{node_id}`");
973    check_seconds_field(&owner, "QoS max_blocking_time", qos.max_blocking_time, true)?;
974    check_seconds_field(&owner, "QoS lease_duration", qos.lease_duration, true)?;
975    Ok(())
976}
977
978/// Validate a ROS2 name (topic, service, or action) follows ROS2 naming rules.
979///
980/// ROS2 names allow ASCII alphanumeric, underscore, and forward slash characters,
981/// and must additionally be structurally valid: no consecutive slashes, no trailing
982/// slash, not a bare `/`, and each `/`-delimited token must not start with a digit.
983/// Tokens may begin with an underscore (hidden topic/service convention in ROS2).
984/// See <https://design.ros2.org/articles/topic_and_service_names.html>.
985fn validate_ros2_name(node_id: &NodeId, field: &str, name: &str) -> eyre::Result<()> {
986    if name.is_empty() {
987        bail!("node `{node_id}`: `{field}` must not be empty");
988    }
989    if !name
990        .chars()
991        .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '/')
992    {
993        bail!(
994            "node `{node_id}`: invalid `{field}` name `{name}`, \
995             only ASCII alphanumeric, underscore, and '/' characters allowed"
996        );
997    }
998    if name == "/" {
999        bail!("node `{node_id}`: invalid `{field}` name, must not be a bare '/'");
1000    }
1001    if name.contains("//") {
1002        bail!(
1003            "node `{node_id}`: invalid `{field}` name `{name}`, \
1004             consecutive slashes ('//') are not allowed"
1005        );
1006    }
1007    if name.ends_with('/') {
1008        bail!(
1009            "node `{node_id}`: invalid `{field}` name `{name}`, \
1010             name must not end with '/'"
1011        );
1012    }
1013    // Each '/'-delimited token must not start with a digit. A leading '/'
1014    // (absolute name) produces an empty first token, which is allowed and skipped.
1015    // Leading underscores are valid — they denote hidden topics/services in ROS2.
1016    for (i, token) in name.split('/').enumerate() {
1017        if i == 0 && token.is_empty() {
1018            continue;
1019        }
1020        if token.starts_with(|c: char| c.is_ascii_digit()) {
1021            bail!(
1022                "node `{node_id}`: invalid `{field}` name `{name}`, \
1023                 a token must not start with a digit (offending token `{token}`)"
1024            );
1025        }
1026    }
1027    Ok(())
1028}
1029
1030/// A non-fatal warning about type annotations in the dataflow.
1031#[derive(Debug)]
1032pub struct TypeWarning {
1033    /// Node that produced the warning.
1034    pub node_id: String,
1035    /// Human-readable warning message.
1036    pub message: String,
1037}
1038
1039impl std::fmt::Display for TypeWarning {
1040    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1041        write!(f, "node \"{}\": {}", self.node_id, self.message)
1042    }
1043}
1044
1045/// A type inferred from an upstream annotated output (Phase 3).
1046#[derive(Debug)]
1047pub struct TypeInference {
1048    /// Node that received the inferred type.
1049    pub node_id: String,
1050    /// Port that received the inferred type.
1051    pub port_id: String,
1052    /// The inferred type URN.
1053    pub inferred_urn: String,
1054    /// Source of the inference (e.g. "sensor/reading").
1055    pub source: String,
1056}
1057
1058impl std::fmt::Display for TypeInference {
1059    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1060        write!(
1061            f,
1062            "inferred {} on {}/{} (from {})",
1063            self.inferred_urn, self.node_id, self.port_id, self.source
1064        )
1065    }
1066}
1067
1068/// Result of type checking a dataflow.
1069pub struct TypeCheckResult {
1070    /// Type warnings found.
1071    pub warnings: Vec<TypeWarning>,
1072    /// Types inferred from upstream annotations (Phase 3).
1073    pub inferences: Vec<TypeInference>,
1074}
1075
1076/// Timer nodes auto-inject this type.
1077const TIMER_TYPE: &str = "std/core/v1/UInt64";
1078
1079/// Register one declared output type under `key` (a `(node_id, output_ref)`
1080/// pair). The port is *always* recorded in `annotated` so a typo'd or
1081/// otherwise unresolvable URN still suppresses the strict-mode "upstream has
1082/// no type annotation" warning; it is additionally recorded in
1083/// `output_type_map` (the map used for cross-edge type matching) only when its
1084/// URN resolves. Keeping both writes behind one call makes the two structures
1085/// impossible to desync — the invariant the strict-mode check relies on.
1086fn register_output_type(
1087    output_type_map: &mut BTreeMap<(String, String), String>,
1088    annotated: &mut BTreeSet<(String, String)>,
1089    key: (String, String),
1090    urn: &str,
1091    registry: &crate::types::TypeRegistry,
1092) {
1093    annotated.insert(key.clone());
1094    if registry.resolve(urn).is_some() {
1095        output_type_map.insert(key, urn.to_string());
1096    }
1097}
1098
1099/// Check type annotations in a dataflow, with strict mode support.
1100///
1101/// Returns the collected warnings plus any inferred edge types.
1102///
1103/// Checks:
1104/// 1. `output_types` keys exist in `outputs`
1105/// 2. `input_types` keys exist in `inputs`
1106/// 3. All type URNs resolve in the registry
1107/// 4. Connected edges have compatible types (using compatibility graph)
1108/// 5. Type inference across edges (Phase 3)
1109/// 6. Metadata annotation validation (Phase 5)
1110/// 7. Arrow schema validation (Phase 6)
1111/// 8. Strict mode: warn on unannotated ports connected to annotated ports
1112pub fn check_type_annotations_full(
1113    dataflow: &super::Descriptor,
1114    registry: &crate::types::TypeRegistry,
1115    strict: bool,
1116) -> TypeCheckResult {
1117    use crate::types::{CompatibilityGraph, TypeRule};
1118
1119    let mut warnings = Vec::new();
1120    let mut inferences = Vec::new();
1121
1122    // Build compatibility graph from user rules
1123    let user_rules: Vec<TypeRule> = dataflow
1124        .type_rules
1125        .iter()
1126        .map(|r| TypeRule {
1127            from: r.from.clone(),
1128            to: r.to.clone(),
1129        })
1130        .collect();
1131    let compat = CompatibilityGraph::new(&user_rules);
1132
1133    // Map of (source_node_id, output_ref) -> type_urn for cross-edge checking.
1134    // Only outputs whose declared URN *resolves* are registered here.
1135    let mut output_type_map: BTreeMap<(String, String), String> = BTreeMap::new();
1136
1137    // Every (source_node_id, output_ref) that carries *some* output-type
1138    // annotation, including one whose URN does not resolve (a typo). Used to
1139    // suppress the strict-mode "upstream has no type annotation" warning on a
1140    // port that *is* annotated but with an unknown URN — that URN is already
1141    // reported by `check_port_types`, so the extra "no annotation" warning
1142    // would be factually wrong and misdirect the user.
1143    let mut annotated_output_ports: BTreeSet<(String, String)> = BTreeSet::new();
1144
1145    for node in &dataflow.nodes {
1146        let nid = node.id.to_string();
1147
1148        // Check node-level output_types
1149        check_port_types(
1150            &nid,
1151            &node.output_types,
1152            |id| node.outputs.contains(id),
1153            "output",
1154            registry,
1155            &mut warnings,
1156        );
1157        // Register node outputs for cross-edge checking
1158        for (output_id, urn) in &node.output_types {
1159            register_output_type(
1160                &mut output_type_map,
1161                &mut annotated_output_ports,
1162                (nid.clone(), output_id.to_string()),
1163                urn,
1164                registry,
1165            );
1166        }
1167
1168        // Check node-level input_types
1169        check_port_types(
1170            &nid,
1171            &node.input_types,
1172            |id| node.inputs.contains_key(id),
1173            "input",
1174            registry,
1175            &mut warnings,
1176        );
1177
1178        // Check metadata annotations (Phase 5)
1179        check_metadata_annotations(
1180            &nid,
1181            &node.output_metadata,
1182            &node.pattern,
1183            &node.outputs,
1184            &mut warnings,
1185        );
1186
1187        // Check operator output/input types
1188        if let Some(op) = &node.operator {
1189            let op_id = op
1190                .id
1191                .as_ref()
1192                .map(|id| id.to_string())
1193                .unwrap_or_else(|| super::SINGLE_OPERATOR_DEFAULT_ID.to_string());
1194            check_port_types(
1195                &nid,
1196                &op.config.output_types,
1197                |id| op.config.outputs.contains(id),
1198                "output",
1199                registry,
1200                &mut warnings,
1201            );
1202            for (output_id, urn) in &op.config.output_types {
1203                // A consumer of a single-`operator:` node references its output
1204                // in short form (`node/output`) in the source YAML; the `op/`
1205                // prefix is only injected later by
1206                // `resolve_aliases_and_set_defaults`, which this pre-build check
1207                // never runs. Register both the prefixed key and the bare
1208                // `output_id` so short-form edges resolve here too — otherwise
1209                // the upstream type is invisible, silently dropping genuine
1210                // mismatches and, under `strict`, emitting a false "upstream has
1211                // no type annotation" warning.
1212                register_output_type(
1213                    &mut output_type_map,
1214                    &mut annotated_output_ports,
1215                    (nid.clone(), format!("{op_id}/{output_id}")),
1216                    urn,
1217                    registry,
1218                );
1219                register_output_type(
1220                    &mut output_type_map,
1221                    &mut annotated_output_ports,
1222                    (nid.clone(), output_id.to_string()),
1223                    urn,
1224                    registry,
1225                );
1226            }
1227            check_port_types(
1228                &nid,
1229                &op.config.input_types,
1230                |id| op.config.inputs.contains_key(id),
1231                "input",
1232                registry,
1233                &mut warnings,
1234            );
1235            check_metadata_annotations(
1236                &nid,
1237                &op.config.output_metadata,
1238                &op.config.pattern,
1239                &op.config.outputs,
1240                &mut warnings,
1241            );
1242        }
1243        if let Some(runtime) = &node.operators {
1244            for op in &runtime.operators {
1245                let label = format!("{nid}/{}", op.id);
1246                check_port_types(
1247                    &label,
1248                    &op.config.output_types,
1249                    |id| op.config.outputs.contains(id),
1250                    "output",
1251                    registry,
1252                    &mut warnings,
1253                );
1254                for (output_id, urn) in &op.config.output_types {
1255                    register_output_type(
1256                        &mut output_type_map,
1257                        &mut annotated_output_ports,
1258                        (nid.clone(), format!("{}/{output_id}", op.id)),
1259                        urn,
1260                        registry,
1261                    );
1262                }
1263                check_port_types(
1264                    &label,
1265                    &op.config.input_types,
1266                    |id| op.config.inputs.contains_key(id),
1267                    "input",
1268                    registry,
1269                    &mut warnings,
1270                );
1271                check_metadata_annotations(
1272                    &label,
1273                    &op.config.output_metadata,
1274                    &op.config.pattern,
1275                    &op.config.outputs,
1276                    &mut warnings,
1277                );
1278            }
1279        }
1280    }
1281
1282    // Cross-edge type checking + inference (Phase 3 + 4)
1283    // Also check timer inputs against input_types annotations.
1284    for node in &dataflow.nodes {
1285        let nid = node.id.to_string();
1286        let timer_types = timer_input_types(&node.inputs);
1287        check_edge_mismatches_with_compat(
1288            &nid,
1289            &node.input_types,
1290            &node.inputs,
1291            &output_type_map,
1292            &annotated_output_ports,
1293            &timer_types,
1294            &compat,
1295            registry,
1296            strict,
1297            &mut warnings,
1298            &mut inferences,
1299        );
1300
1301        if let Some(op) = &node.operator {
1302            let op_timer = timer_input_types(&op.config.inputs);
1303            check_edge_mismatches_with_compat(
1304                &nid,
1305                &op.config.input_types,
1306                &op.config.inputs,
1307                &output_type_map,
1308                &annotated_output_ports,
1309                &op_timer,
1310                &compat,
1311                registry,
1312                strict,
1313                &mut warnings,
1314                &mut inferences,
1315            );
1316        }
1317        if let Some(runtime) = &node.operators {
1318            for op in &runtime.operators {
1319                let label = format!("{nid}/{}", op.id);
1320                let op_timer = timer_input_types(&op.config.inputs);
1321                check_edge_mismatches_with_compat(
1322                    &label,
1323                    &op.config.input_types,
1324                    &op.config.inputs,
1325                    &output_type_map,
1326                    &annotated_output_ports,
1327                    &op_timer,
1328                    &compat,
1329                    registry,
1330                    strict,
1331                    &mut warnings,
1332                    &mut inferences,
1333                );
1334            }
1335        }
1336    }
1337
1338    TypeCheckResult {
1339        warnings,
1340        inferences,
1341    }
1342}
1343
1344/// Build a map of (input_id -> timer_type) for Timer-mapped inputs.
1345fn timer_input_types(inputs: &BTreeMap<DataId, Input>) -> BTreeMap<DataId, String> {
1346    // Quick check: skip allocation if no timer inputs
1347    if !inputs
1348        .values()
1349        .any(|i| matches!(i.mapping, InputMapping::Timer { .. }))
1350    {
1351        return BTreeMap::new();
1352    }
1353    let mut result = BTreeMap::new();
1354    for (input_id, input) in inputs {
1355        if matches!(input.mapping, InputMapping::Timer { .. }) {
1356            result.insert(input_id.clone(), TIMER_TYPE.to_string());
1357        }
1358    }
1359    result
1360}
1361
1362/// Validate that port type keys exist in the port list and URNs resolve.
1363fn check_port_types(
1364    node_id: &str,
1365    type_map: &BTreeMap<DataId, String>,
1366    contains: impl Fn(&DataId) -> bool,
1367    port_kind: &str,
1368    registry: &crate::types::TypeRegistry,
1369    warnings: &mut Vec<TypeWarning>,
1370) {
1371    for (port_id, urn) in type_map {
1372        if !contains(port_id) {
1373            warnings.push(TypeWarning {
1374                node_id: node_id.to_string(),
1375                message: format!(
1376                    "{port_kind}_types key \"{port_id}\" not found in {port_kind}s list"
1377                ),
1378            });
1379        }
1380        if registry.resolve(urn).is_none() {
1381            let hint = registry
1382                .suggest(urn)
1383                .map(|s| format!(" (did you mean \"{s}\"?)"))
1384                .unwrap_or_default();
1385            warnings.push(TypeWarning {
1386                node_id: node_id.to_string(),
1387                message: format!("unknown type \"{urn}\" on {port_kind} \"{port_id}\"{hint}"),
1388            });
1389        }
1390    }
1391}
1392
1393/// Check metadata annotations on outputs (Phase 5).
1394fn check_metadata_annotations(
1395    node_id: &str,
1396    output_metadata: &BTreeMap<DataId, Vec<String>>,
1397    pattern: &Option<String>,
1398    outputs: &BTreeSet<DataId>,
1399    warnings: &mut Vec<TypeWarning>,
1400) {
1401    // Check explicit output_metadata keys exist in outputs
1402    for output_id in output_metadata.keys() {
1403        if !outputs.contains(output_id) {
1404            warnings.push(TypeWarning {
1405                node_id: node_id.to_string(),
1406                message: format!("output_metadata key \"{output_id}\" not found in outputs list"),
1407            });
1408        }
1409    }
1410
1411    // Validate pattern shorthand
1412    if let Some(pat) = pattern
1413        && crate::types::pattern_metadata_keys(pat).is_none()
1414    {
1415        warnings.push(TypeWarning {
1416            node_id: node_id.to_string(),
1417            message: format!(
1418                "unknown pattern \"{pat}\", expected one of: \
1419                     service-server, service-client, action-server, action-client"
1420            ),
1421        });
1422    }
1423}
1424
1425/// Check cross-edge type mismatches using compatibility graph.
1426///
1427/// Also performs type inference (Phase 3) and strict-mode unannotated checks.
1428/// `timer_types` maps input IDs to auto-injected timer type URNs.
1429#[allow(clippy::too_many_arguments)]
1430fn check_edge_mismatches_with_compat(
1431    node_id: &str,
1432    input_types: &BTreeMap<DataId, String>,
1433    inputs: &BTreeMap<DataId, Input>,
1434    output_type_map: &BTreeMap<(String, String), String>,
1435    annotated_output_ports: &BTreeSet<(String, String)>,
1436    timer_types: &BTreeMap<DataId, String>,
1437    compat: &crate::types::CompatibilityGraph,
1438    registry: &crate::types::TypeRegistry,
1439    strict: bool,
1440    warnings: &mut Vec<TypeWarning>,
1441    inferences: &mut Vec<TypeInference>,
1442) {
1443    for (input_id, input) in inputs {
1444        match &input.mapping {
1445            InputMapping::User(mapping) => {
1446                let key = (mapping.source.to_string(), mapping.output.to_string());
1447                let upstream_urn = output_type_map.get(&key);
1448                let downstream_urn = input_types.get(input_id);
1449
1450                match (upstream_urn, downstream_urn) {
1451                    (Some(out_urn), Some(in_urn)) if !compat.is_compatible(out_urn, in_urn) => {
1452                        let schema_detail = check_schema_compat(out_urn, in_urn, registry);
1453                        let detail = schema_detail.map(|d| format!(" ({d})")).unwrap_or_default();
1454                        warnings.push(TypeWarning {
1455                            node_id: node_id.to_string(),
1456                            message: format!(
1457                                "type mismatch on input \"{input_id}\": \
1458                                 upstream {}/{} declares \"{out_urn}\", \
1459                                 but expected \"{in_urn}\"{detail}",
1460                                mapping.source, mapping.output,
1461                            ),
1462                        });
1463                    }
1464                    (Some(out_urn), None) => {
1465                        inferences.push(TypeInference {
1466                            node_id: node_id.to_string(),
1467                            port_id: input_id.to_string(),
1468                            inferred_urn: out_urn.clone(),
1469                            source: format!("{}/{}", mapping.source, mapping.output),
1470                        });
1471                    }
1472                    // Strict mode, and the upstream has no *resolvable* type.
1473                    // The guard also excludes an upstream that *is* annotated
1474                    // but with an unresolvable URN (a typo): such a port is
1475                    // absent from `output_type_map` yet present in
1476                    // `annotated_output_ports`, so it falls through to `_` with
1477                    // no warning here. `check_port_types` already reports the
1478                    // unknown URN, so a second "has no type annotation" warning
1479                    // would be factually wrong and send the user chasing a
1480                    // missing annotation instead of the typo.
1481                    (None, Some(in_urn)) if strict && !annotated_output_ports.contains(&key) => {
1482                        warnings.push(TypeWarning {
1483                            node_id: node_id.to_string(),
1484                            message: format!(
1485                                "input \"{input_id}\" expects type \"{in_urn}\" but upstream \
1486                                 {}/{} has no type annotation",
1487                                mapping.source, mapping.output,
1488                            ),
1489                        });
1490                    }
1491                    _ => {}
1492                }
1493            }
1494            InputMapping::Timer { .. } => {
1495                // Timer inputs auto-inject std/core/v1/UInt64
1496                if let Some(expected_urn) = input_types.get(input_id) {
1497                    let timer_urn = timer_types
1498                        .get(input_id)
1499                        .map(|s| s.as_str())
1500                        .unwrap_or(TIMER_TYPE);
1501                    if !compat.is_compatible(timer_urn, expected_urn) {
1502                        warnings.push(TypeWarning {
1503                            node_id: node_id.to_string(),
1504                            message: format!(
1505                                "type mismatch on input \"{input_id}\": \
1506                                 timer provides \"{timer_urn}\", \
1507                                 but expected \"{expected_urn}\"",
1508                            ),
1509                        });
1510                    }
1511                }
1512            }
1513            // Log subscriptions deliver JSON strings — skip type checking.
1514            InputMapping::Logs(_) => {}
1515        }
1516    }
1517}
1518
1519/// Check schema-level compatibility for struct types (Phase 6).
1520/// Returns an optional detail string for the error message.
1521fn check_schema_compat(
1522    out_urn: &str,
1523    in_urn: &str,
1524    registry: &crate::types::TypeRegistry,
1525) -> Option<String> {
1526    let out_def = registry.resolve(out_urn)?;
1527    let in_def = registry.resolve(in_urn)?;
1528    let out_schema = out_def.to_arrow_schema_with_registry(registry)?;
1529    let in_schema = in_def.to_arrow_schema_with_registry(registry)?;
1530    // in_schema = expected (consumer), out_schema = actual (producer)
1531    match crate::types::schema_compatible(&in_schema, &out_schema) {
1532        Ok(()) => None,
1533        Err(e) => Some(e.to_string()),
1534    }
1535}
1536
1537fn validate_ros2_type_format(node_id: &NodeId, name: &str, type_str: &str) -> eyre::Result<()> {
1538    // type must be "package/TypeName" format with alphanumeric+underscore parts
1539    let parts: Vec<&str> = type_str.split('/').collect();
1540    if parts.len() != 2 || parts[0].is_empty() || parts[1].is_empty() {
1541        bail!(
1542            "node `{node_id}`: invalid type `{type_str}` for `{name}`, \
1543             expected format `package/TypeName` (e.g. `sensor_msgs/Image`)"
1544        );
1545    }
1546    for (label, part) in [("package", parts[0]), ("type name", parts[1])] {
1547        if !part.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') {
1548            bail!(
1549                "node `{node_id}`: invalid {label} `{part}` in type `{type_str}` for `{name}`, \
1550                 only ASCII alphanumeric and underscore characters allowed"
1551            );
1552        }
1553    }
1554    Ok(())
1555}
1556
1557#[cfg(test)]
1558mod tests {
1559    use super::*;
1560    use crate::types::TypeRegistry;
1561    use dora_message::config::{Input, InputMapping};
1562    use dora_message::descriptor::{
1563        Descriptor, RmwZenohCompatibility, Ros2BridgeConfig, Ros2Direction, Ros2Role,
1564        Ros2TopicConfig, Ros2TransportConfig,
1565    };
1566    use std::{path::PathBuf, time::Duration};
1567
1568    fn dummy_input() -> Input {
1569        Input {
1570            mapping: InputMapping::Timer {
1571                interval: Duration::from_secs(1),
1572            },
1573            queue_size: None,
1574            input_timeout: None,
1575            queue_policy: None,
1576        }
1577    }
1578
1579    fn service_config(role: Ros2Role) -> Ros2BridgeConfig {
1580        Ros2BridgeConfig {
1581            service: Some("/add_two_ints".into()),
1582            service_type: Some("example_interfaces/AddTwoInts".into()),
1583            role: Some(role),
1584            ..Default::default()
1585        }
1586    }
1587
1588    fn action_config(role: Ros2Role) -> Ros2BridgeConfig {
1589        Ros2BridgeConfig {
1590            action: Some("/navigate".into()),
1591            action_type: Some("nav2_msgs/NavigateToPose".into()),
1592            role: Some(role),
1593            ..Default::default()
1594        }
1595    }
1596
1597    fn runtime_node() -> ResolvedNode {
1598        serde_yaml::from_str(
1599            r#"
1600id: runtime-node
1601operators:
1602  - id: op1
1603    python: op.py
1604    outputs:
1605      - out
1606"#,
1607        )
1608        .unwrap()
1609    }
1610
1611    #[test]
1612    fn runtime_node_with_several_operators_is_rejected() {
1613        let descriptor: Descriptor = serde_yaml::from_str(
1614            r#"
1615nodes:
1616  - id: runtime-node
1617    operators:
1618      - id: op1
1619        shared-library: op1
1620      - id: op2
1621        shared-library: op2
1622"#,
1623        )
1624        .unwrap();
1625        let err = check_dataflow_static(&descriptor).unwrap_err().to_string();
1626        assert!(
1627            err.contains("runtime-node") && err.contains("2 operators"),
1628            "error should name the node and the operator count, got: {err}"
1629        );
1630    }
1631
1632    #[test]
1633    fn runtime_node_with_no_operators_is_rejected() {
1634        let descriptor: Descriptor = serde_yaml::from_str(
1635            r#"
1636nodes:
1637  - id: runtime-node
1638    operators: []
1639"#,
1640        )
1641        .unwrap();
1642        let err = check_dataflow_static(&descriptor).unwrap_err().to_string();
1643        assert!(
1644            err.contains("runtime-node") && err.contains("0 operators"),
1645            "error should name the node and the operator count, got: {err}"
1646        );
1647    }
1648
1649    /// `dora start`, `dora node add/replace` and recovery resolve the
1650    /// descriptor without running `check_dataflow_static`, so the count must
1651    /// be enforced by resolution itself.
1652    #[test]
1653    fn resolution_rejects_a_runtime_node_with_several_operators() {
1654        let descriptor: Descriptor = serde_yaml::from_str(
1655            r#"
1656nodes:
1657  - id: runtime-node
1658    operators:
1659      - id: op1
1660        shared-library: op1
1661      - id: op2
1662        shared-library: op2
1663"#,
1664        )
1665        .unwrap();
1666        let err = descriptor
1667            .resolve_aliases_and_set_defaults()
1668            .unwrap_err()
1669            .to_string();
1670        assert!(err.contains("2 operators"), "got: {err}");
1671    }
1672
1673    #[test]
1674    fn runtime_node_with_one_operator_passes_the_operator_count_check() {
1675        check_runtime_operator_count(&runtime_node()).unwrap();
1676    }
1677
1678    fn custom_node() -> dora_message::descriptor::CustomNode {
1679        dora_message::descriptor::CustomNode::new("node".to_string())
1680    }
1681
1682    #[test]
1683    fn timing_fields_accept_finite_non_negative_and_none() {
1684        let id = NodeId::from("n".to_owned());
1685        let mut node = custom_node();
1686        // unset is fine
1687        check_timing_fields(&id, &node).unwrap();
1688        // a large finite grace is fine
1689        node.finish_grace_secs = Some(3600.0);
1690        node.health_check_timeout = Some(0.0);
1691        node.startup_timeout = Some(5.0);
1692        check_timing_fields(&id, &node).unwrap();
1693    }
1694
1695    #[test]
1696    fn timing_fields_reject_negative_finish_grace_secs() {
1697        let id = NodeId::from("n".to_owned());
1698        let mut node = custom_node();
1699        node.finish_grace_secs = Some(-1.0);
1700        let err = check_timing_fields(&id, &node).unwrap_err().to_string();
1701        assert!(
1702            err.contains("finish_grace_secs") && err.contains("non-negative"),
1703            "error should name the field and the constraint, got: {err}"
1704        );
1705    }
1706
1707    #[test]
1708    fn timing_fields_reject_negative_startup_timeout() {
1709        let id = NodeId::from("n".to_owned());
1710        let mut node = custom_node();
1711        node.startup_timeout = Some(-0.5);
1712        let err = check_timing_fields(&id, &node).unwrap_err().to_string();
1713        assert!(
1714            err.contains("startup_timeout") && err.contains("non-negative"),
1715            "error should name the field and the constraint, got: {err}"
1716        );
1717    }
1718
1719    /// The daemon and the runtime join each operator id with its input and
1720    /// output ids into `DataId`s (`{operator}/{id}`), and `DataId::from`
1721    /// panics on an invalid one. An operator id that is not itself a valid,
1722    /// slash-free `DataId` must therefore be rejected up front, not crash the
1723    /// daemon at spawn.
1724    #[test]
1725    fn invalid_operator_id_is_rejected() {
1726        for (form, id) in [
1727            ("operators", "my op"),
1728            ("operators", "a/b"),
1729            ("operators", "\"\""),
1730            ("operator", "my op"),
1731        ] {
1732            let yaml = if form == "operators" {
1733                format!(
1734                    "nodes:\n  - id: rt\n    operators:\n      - id: {id}\n        \
1735                     python: op.py\n        outputs:\n          - out\n"
1736                )
1737            } else {
1738                format!(
1739                    "nodes:\n  - id: rt\n    operator:\n      id: {id}\n      \
1740                     python: op.py\n      outputs:\n        - out\n"
1741                )
1742            };
1743            let descriptor: Descriptor = serde_yaml::from_str(&yaml).unwrap();
1744            let err = check_dataflow_static(&descriptor)
1745                .expect_err(&format!("operator id {id:?} ({form}) must be rejected"))
1746                .to_string();
1747            assert!(
1748                err.contains("invalid operator id"),
1749                "error should name the operator id problem, got: {err}"
1750            );
1751        }
1752
1753        let ok: Descriptor = serde_yaml::from_str(
1754            "nodes:\n  - id: rt\n    operators:\n      - id: my-op.v2\n        \
1755             python: op.py\n        outputs:\n          - out\n",
1756        )
1757        .unwrap();
1758        check_dataflow_static(&ok).unwrap();
1759    }
1760
1761    #[test]
1762    fn dynamic_node_rejects_startup_timeout() {
1763        let descriptor: Descriptor = serde_yaml::from_str(
1764            r#"
1765nodes:
1766  - id: dyn
1767    path: dynamic
1768    startup_timeout: 5.0
1769"#,
1770        )
1771        .unwrap();
1772        let err = check_dataflow_static(&descriptor).unwrap_err().to_string();
1773        assert!(
1774            err.contains("dynamic node `dyn` cannot specify `startup_timeout`"),
1775            "error should explain dynamic node startup_timeout rejection, got: {err}"
1776        );
1777    }
1778
1779    /// `check_node_timing_values` is the panic guard the `dora start` path
1780    /// uses, so it must stop at the values `Duration::from_secs_f64` panics
1781    /// on and leave the dynamic-node `startup_timeout` policy rule to
1782    /// `check_node_timing` (`dora node add` / `replace`) and
1783    /// `check_dataflow_static` (`dora run` / `validate`). Were the policy
1784    /// rule in both, `dora start` would reject a descriptor that starts fine
1785    /// on 1.0.x.
1786    #[test]
1787    fn timing_values_check_skips_the_dynamic_node_policy_rule() {
1788        let descriptor: Descriptor = serde_yaml::from_str(
1789            r#"
1790nodes:
1791  - id: dyn
1792    path: dynamic
1793    startup_timeout: 5.0
1794"#,
1795        )
1796        .unwrap();
1797        let nodes = descriptor.resolve_aliases_and_set_defaults().unwrap();
1798        let node = nodes.values().next().unwrap();
1799
1800        check_node_timing_values(node)
1801            .expect("an ignored startup_timeout is not a panic risk, so the spawn path allows it");
1802        let err = check_node_timing(node).unwrap_err().to_string();
1803        assert!(
1804            err.contains("dynamic node `dyn` cannot specify `startup_timeout`"),
1805            "the node-join path keeps the policy rule, got: {err}"
1806        );
1807
1808        // The panic guard itself is unchanged by the split.
1809        let bad: Descriptor = serde_yaml::from_str(
1810            r#"
1811nodes:
1812  - id: dyn
1813    path: dynamic
1814    restart_delay: -1.0
1815"#,
1816        )
1817        .unwrap();
1818        let bad_nodes = bad.resolve_aliases_and_set_defaults().unwrap();
1819        let err = check_node_timing_values(bad_nodes.values().next().unwrap())
1820            .unwrap_err()
1821            .to_string();
1822        assert!(
1823            err.contains("restart_delay"),
1824            "the spawn path still rejects a panicking value, got: {err}"
1825        );
1826    }
1827
1828    #[test]
1829    fn timing_fields_reject_non_finite_values() {
1830        let id = NodeId::from("n".to_owned());
1831        for bad in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
1832            let mut node = custom_node();
1833            node.health_check_timeout = Some(bad);
1834            let err = check_timing_fields(&id, &node).unwrap_err().to_string();
1835            assert!(
1836                err.contains("health_check_timeout"),
1837                "non-finite {bad} should be rejected, got: {err}"
1838            );
1839        }
1840    }
1841
1842    #[test]
1843    fn seconds_field_accepts_none_zero_and_positive() {
1844        check_seconds_field("owner", "field", None, true).unwrap();
1845        check_seconds_field("owner", "field", Some(0.0), true).unwrap();
1846        check_seconds_field("owner", "field", Some(3600.0), true).unwrap();
1847    }
1848
1849    #[test]
1850    fn seconds_field_rejects_negative_and_non_finite() {
1851        for bad in [-1.0, f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
1852            let err = check_seconds_field("owner", "field", Some(bad), true)
1853                .unwrap_err()
1854                .to_string();
1855            assert!(
1856                err.contains("field") && err.contains("non-negative"),
1857                "{bad} should be rejected with a field/constraint message, got: {err}"
1858            );
1859        }
1860    }
1861
1862    // Finite, non-negative, but too large for `Duration::from_secs_f64`, which
1863    // would otherwise panic on daemon node spawn (see #2470). `Duration::MAX`'s
1864    // own `as_secs_f64()` rounds *up* past the representable max, so the exact
1865    // boundary value must be rejected too — a `value > MAX` guard would wrongly
1866    // let it through.
1867    #[test]
1868    fn seconds_field_rejects_values_that_overflow_duration() {
1869        for bad in [1e20, Duration::MAX.as_secs_f64()] {
1870            // Confirms the value genuinely trips the daemon's conversion.
1871            assert!(Duration::try_from_secs_f64(bad).is_err());
1872            let err = check_seconds_field("owner", "field", Some(bad), true)
1873                .unwrap_err()
1874                .to_string();
1875            assert!(
1876                err.contains("field") && err.contains("smaller than"),
1877                "overflowing {bad} should be rejected with a field/bound message, got: {err}"
1878            );
1879        }
1880    }
1881
1882    // A large but representable value (well under `Duration::MAX`) stays valid.
1883    #[test]
1884    fn seconds_field_accepts_large_representable_value() {
1885        assert!(Duration::try_from_secs_f64(1e18).is_ok());
1886        check_seconds_field("owner", "field", Some(1e18), true).unwrap();
1887    }
1888
1889    // With `allow_zero: false`, `0.0` must be rejected (in addition to the
1890    // negative / non-finite cases) because such a field reaches
1891    // `tokio::time::interval`, which panics on a zero period.
1892    #[test]
1893    fn seconds_field_rejects_zero_when_positive_required() {
1894        check_seconds_field("owner", "field", None, false).unwrap();
1895        check_seconds_field("owner", "field", Some(3600.0), false).unwrap();
1896        // `1e-10` is finite and positive but `Duration::from_secs_f64` rounds
1897        // it down to `Duration::ZERO`, which would panic `tokio::time::interval`
1898        // just like a literal `0.0`, so it must be rejected too.
1899        for bad in [0.0, 1e-10, -1.0, f64::NAN, f64::INFINITY] {
1900            let err = check_seconds_field("owner", "field", Some(bad), false)
1901                .unwrap_err()
1902                .to_string();
1903            assert!(
1904                err.contains("field") && err.contains("positive"),
1905                "{bad} should be rejected with a field/constraint message, got: {err}"
1906            );
1907        }
1908        // A tiny-but-positive value is fine when zero is allowed (it does not
1909        // reach `tokio::time::interval`).
1910        check_seconds_field("owner", "field", Some(1e-10), true).unwrap();
1911    }
1912
1913    // `health_check_interval` (dataflow-level) reaches `Duration::from_secs_f64`
1914    // and then `tokio::time::interval` in the daemon, so `check_dataflow` must
1915    // reject a non-finite / negative / zero value rather than let the daemon
1916    // panic. A zero interval additionally panics `tokio::time::interval`, so it
1917    // is rejected with a `positive` constraint.
1918    #[test]
1919    fn check_dataflow_rejects_negative_health_check_interval() {
1920        let dataflow = parse_dataflow(
1921            "\
1922health_check_interval: -1.0
1923nodes:
1924  - id: a
1925    path: node_a
1926    build: cargo build
1927    outputs:
1928      - out
1929",
1930        );
1931        let err = check_dataflow(&dataflow, Path::new("/nonexistent-dora-validate-test"))
1932            .unwrap_err()
1933            .to_string();
1934        assert!(
1935            err.contains("health_check_interval") && err.contains("positive"),
1936            "error should name the field and constraint, got: {err}"
1937        );
1938    }
1939
1940    // A zero `health_check_interval` passes `Duration::from_secs_f64` (yielding
1941    // `Duration::ZERO`) but then panics `tokio::time::interval`, so it must be
1942    // rejected up front (regression test for #2752).
1943    #[test]
1944    fn check_dataflow_rejects_zero_health_check_interval() {
1945        let dataflow = parse_dataflow(
1946            "\
1947health_check_interval: 0.0
1948nodes:
1949  - id: a
1950    path: node_a
1951    build: cargo build
1952    outputs:
1953      - out
1954",
1955        );
1956        let err = check_dataflow(&dataflow, Path::new("/nonexistent-dora-validate-test"))
1957            .unwrap_err()
1958            .to_string();
1959        assert!(
1960            err.contains("health_check_interval") && err.contains("positive"),
1961            "error should name the field and constraint, got: {err}"
1962        );
1963    }
1964
1965    // A tiny-but-positive `health_check_interval` (e.g. `1e-10`) is finite and
1966    // non-zero as an `f64`, so a literal `value == 0.0` check would let it
1967    // through -- but `Duration::from_secs_f64` rounds it down to
1968    // `Duration::ZERO`, which panics `tokio::time::interval`. It must be
1969    // rejected up front just like `0.0`.
1970    #[test]
1971    fn check_dataflow_rejects_subnanosecond_health_check_interval() {
1972        let dataflow = parse_dataflow(
1973            "\
1974health_check_interval: 0.0000000001
1975nodes:
1976  - id: a
1977    path: node_a
1978    build: cargo build
1979    outputs:
1980      - out
1981",
1982        );
1983        let err = check_dataflow(&dataflow, Path::new("/nonexistent-dora-validate-test"))
1984            .unwrap_err()
1985            .to_string();
1986        assert!(
1987            err.contains("health_check_interval") && err.contains("positive"),
1988            "error should name the field and constraint, got: {err}"
1989        );
1990    }
1991
1992    // Same guarantee for the per-input `input_timeout`, which the daemon feeds
1993    // to `Duration::from_secs_f64` on both the spawn and reconnect paths.
1994    #[test]
1995    fn check_dataflow_rejects_non_finite_input_timeout() {
1996        let dataflow = parse_dataflow(
1997            "\
1998nodes:
1999  - id: a
2000    path: node_a
2001    build: cargo build
2002    outputs:
2003      - out
2004  - id: b
2005    path: node_b
2006    build: cargo build
2007    inputs:
2008      x:
2009        source: a/out
2010        input_timeout: .inf
2011",
2012        );
2013        let err = check_dataflow(&dataflow, Path::new("/nonexistent-dora-validate-test"))
2014            .unwrap_err()
2015            .to_string();
2016        assert!(
2017            err.contains("input_timeout") && err.contains('x'),
2018            "error should name the offending input and field, got: {err}"
2019        );
2020    }
2021
2022    // A finite `input_timeout` too large for `Duration` must be rejected too:
2023    // `Duration::from_secs_f64` panics on overflow just as it does on `.inf`.
2024    #[test]
2025    fn check_dataflow_rejects_overflowing_input_timeout() {
2026        let dataflow = parse_dataflow(
2027            "\
2028nodes:
2029  - id: a
2030    path: node_a
2031    build: cargo build
2032    outputs:
2033      - out
2034  - id: b
2035    path: node_b
2036    build: cargo build
2037    inputs:
2038      x:
2039        source: a/out
2040        input_timeout: 1e20
2041",
2042        );
2043        let err = check_dataflow(&dataflow, Path::new("/nonexistent-dora-validate-test"))
2044            .unwrap_err()
2045            .to_string();
2046        assert!(
2047            err.contains("input_timeout") && err.contains('x'),
2048            "error should name the offending input and field, got: {err}"
2049        );
2050    }
2051
2052    #[test]
2053    fn check_dataflow_accepts_valid_interval_and_timeout() {
2054        let dataflow = parse_dataflow(
2055            "\
2056health_check_interval: 2.5
2057nodes:
2058  - id: a
2059    path: node_a
2060    build: cargo build
2061    outputs:
2062      - out
2063  - id: b
2064    path: node_b
2065    build: cargo build
2066    inputs:
2067      x:
2068        source: a/out
2069        input_timeout: 0.5
2070",
2071        );
2072        check_dataflow(&dataflow, Path::new("/nonexistent-dora-validate-test")).unwrap();
2073    }
2074
2075    fn user_input(source: &str, output: &str) -> Input {
2076        Input {
2077            mapping: InputMapping::User(UserInputMapping {
2078                source: NodeId::from(source.to_owned()),
2079                output: DataId::from(output.to_owned()),
2080            }),
2081            queue_size: None,
2082            input_timeout: None,
2083            queue_policy: None,
2084        }
2085    }
2086
2087    #[test]
2088    fn runtime_input_with_operator_segment_is_accepted() {
2089        let node = runtime_node();
2090        let nodes = BTreeMap::from([(node.id.clone(), node)]);
2091        check_input(&user_input("runtime-node", "op1/out"), &nodes, "sink/in").unwrap();
2092    }
2093
2094    #[test]
2095    fn runtime_input_without_operator_segment_reports_expected_format() {
2096        // Mapping `runtime-node/out` (instead of `runtime-node/op1/out`) used
2097        // to fall back to an empty operator id and report that operator ``
2098        // does not exist, hiding the actual mistake.
2099        let node = runtime_node();
2100        let nodes = BTreeMap::from([(node.id.clone(), node)]);
2101        let err = check_input(&user_input("runtime-node", "out"), &nodes, "sink/in")
2102            .unwrap_err()
2103            .to_string();
2104        assert!(
2105            err.contains("runtime-node/<operator_id>/<output_id>"),
2106            "error should explain the expected format, got: {err}"
2107        );
2108    }
2109
2110    // A runtime operator whose artifact is produced by a `build:` command must
2111    // not fail the on-disk source check before the build has run — mirroring the
2112    // custom-node and shared-library behavior. Exercised via the WASM arm so the
2113    // test does not require a Python `dora-rs` runtime (the Python arm carries an
2114    // identical guard).
2115    #[test]
2116    fn operator_with_build_command_skips_missing_source_check() {
2117        let dataflow = parse_dataflow(
2118            "\
2119nodes:
2120  - id: runtime-node
2121    operators:
2122      - id: op1
2123        wasm: does/not/exist.wasm
2124        build: cargo build
2125        outputs:
2126          - out
2127",
2128        );
2129        check_dataflow(&dataflow, Path::new("/nonexistent-dora-validate-test")).unwrap();
2130    }
2131
2132    // The shared-library naming rules are checked without touching the
2133    // filesystem, so a `build:` command must not exempt a path the runtime will
2134    // refuse at spawn (`lib` prefix or a file extension).
2135    #[test]
2136    fn shared_library_with_build_command_still_checks_file_name() {
2137        for bad in ["target/debug/libop", "target/debug/op.so"] {
2138            let dataflow = parse_dataflow(&format!(
2139                "\
2140nodes:
2141  - id: runtime-node
2142    operators:
2143      - id: op1
2144        shared-library: {bad}
2145        build: cargo build -p op
2146        outputs:
2147          - out
2148"
2149            ));
2150            // `dora validate` runs only the static pass; `dora build`/`start`
2151            // run the full check. Both must refuse the name.
2152            for err in [
2153                check_dataflow_static(&dataflow).unwrap_err(),
2154                check_dataflow(&dataflow, Path::new("/nonexistent-dora-validate-test"))
2155                    .unwrap_err(),
2156            ] {
2157                let msg = format!("{err:#}");
2158                assert!(
2159                    msg.contains("runtime-node/op1") && msg.contains("Shared library file name"),
2160                    "`{bad}` should be rejected with the naming rule, got: {msg}"
2161                );
2162            }
2163        }
2164    }
2165
2166    #[test]
2167    fn shared_library_with_build_command_skips_missing_file_check() {
2168        let dataflow = parse_dataflow(
2169            "\
2170nodes:
2171  - id: runtime-node
2172    operators:
2173      - id: op1
2174        shared-library: target/debug/op
2175        build: cargo build -p op
2176        outputs:
2177          - out
2178",
2179        );
2180        check_dataflow(&dataflow, Path::new("/nonexistent-dora-validate-test")).unwrap();
2181    }
2182
2183    #[test]
2184    fn operator_without_build_command_rejects_missing_source() {
2185        let dataflow = parse_dataflow(
2186            "\
2187nodes:
2188  - id: runtime-node
2189    operators:
2190      - id: op1
2191        wasm: does/not/exist.wasm
2192        outputs:
2193          - out
2194",
2195        );
2196        let err = check_dataflow(&dataflow, Path::new("/nonexistent-dora-validate-test"))
2197            .unwrap_err()
2198            .to_string();
2199        assert!(
2200            err.contains("no WASM library"),
2201            "missing source without a build command should still be rejected, got: {err}"
2202        );
2203    }
2204
2205    #[test]
2206    fn validate_no_mode_set() {
2207        let config = Ros2BridgeConfig::default();
2208        let err = validate_ros2_config(
2209            &NodeId::from("n".to_owned()),
2210            &config,
2211            &BTreeMap::new(),
2212            &BTreeSet::new(),
2213        )
2214        .unwrap_err();
2215        assert!(err.to_string().contains("requires one of"));
2216    }
2217
2218    #[test]
2219    fn validate_rejects_empty_ros2_zenoh_config_uri() {
2220        let config = Ros2BridgeConfig {
2221            transport: Ros2TransportConfig::Zenoh {
2222                compatibility: RmwZenohCompatibility::Humble,
2223                config_uri: Some(PathBuf::new()),
2224            },
2225            topic: Some("/t".into()),
2226            message_type: Some("a/B".into()),
2227            ..Default::default()
2228        };
2229        let err = validate_ros2_config(
2230            &NodeId::from("n".to_owned()),
2231            &config,
2232            &BTreeMap::new(),
2233            &BTreeSet::from([DataId::from("out".to_owned())]),
2234        )
2235        .unwrap_err();
2236        assert!(err.to_string().contains("config_uri must not be empty"));
2237    }
2238
2239    fn single_topic_config(topic: &str, direction: Ros2Direction) -> Ros2BridgeConfig {
2240        Ros2BridgeConfig {
2241            topic: Some(topic.into()),
2242            message_type: Some("turtlesim/Pose".into()),
2243            direction,
2244            ..Default::default()
2245        }
2246    }
2247
2248    /// Single-topic mode binds to the node's declared port, so a name that has
2249    /// nothing to do with the topic is correct and must be accepted.
2250    #[test]
2251    fn validate_single_topic_accepts_the_sole_declared_port() {
2252        let config = single_topic_config("/turtle1/pose", Ros2Direction::Subscribe);
2253        validate_ros2_config(
2254            &NodeId::from("n".to_owned()),
2255            &config,
2256            &BTreeMap::new(),
2257            &BTreeSet::from([DataId::from("pose".to_owned())]),
2258        )
2259        .unwrap();
2260    }
2261
2262    /// Several declared outputs leave the binding ambiguous, which the bridge
2263    /// would resolve by silently dropping every message.
2264    #[test]
2265    fn validate_single_topic_rejects_ambiguous_subscribe_output() {
2266        let config = single_topic_config("/turtle1/pose", Ros2Direction::Subscribe);
2267        let err = validate_ros2_config(
2268            &NodeId::from("n".to_owned()),
2269            &config,
2270            &BTreeMap::new(),
2271            &BTreeSet::from([
2272                DataId::from("pose".to_owned()),
2273                DataId::from("log".to_owned()),
2274            ]),
2275        )
2276        .unwrap_err()
2277        .to_string();
2278        assert!(
2279            err.contains("no unambiguous output")
2280                && err.contains("`pose`")
2281                && err.contains("`log`")
2282                && err.contains("turtle1_pose"),
2283            "error should list the candidates and the topic-derived id, got: {err}"
2284        );
2285    }
2286
2287    #[test]
2288    fn validate_multi_topic_rejects_undeclared_subscribe_output() {
2289        // A subscribe topic mapped to an output the node never declares would
2290        // pass validation and then silently drop every message at runtime
2291        // (`DoraNode::send_output` ignores unknown output ids).
2292        let config = Ros2BridgeConfig {
2293            topics: Some(vec![Ros2TopicConfig {
2294                topic: "/scan".into(),
2295                message_type: "sensor_msgs/LaserScan".into(),
2296                direction: Ros2Direction::Subscribe,
2297                output: Some("typo_out".into()),
2298                input: None,
2299                qos: None,
2300            }]),
2301            ..Default::default()
2302        };
2303        let err = validate_ros2_config(
2304            &NodeId::from("n".to_owned()),
2305            &config,
2306            &BTreeMap::new(),
2307            &BTreeSet::from([DataId::from("scan".to_owned())]),
2308        )
2309        .unwrap_err()
2310        .to_string();
2311        assert!(
2312            err.contains("typo_out") && err.contains("not declared"),
2313            "error should name the undeclared output, got: {err}"
2314        );
2315    }
2316
2317    #[test]
2318    fn validate_multi_topic_rejects_undeclared_publish_input() {
2319        let config = Ros2BridgeConfig {
2320            topics: Some(vec![Ros2TopicConfig {
2321                topic: "/cmd_vel".into(),
2322                message_type: "geometry_msgs/Twist".into(),
2323                direction: Ros2Direction::Publish,
2324                output: None,
2325                input: Some("typo_in".into()),
2326                qos: None,
2327            }]),
2328            ..Default::default()
2329        };
2330        let err = validate_ros2_config(
2331            &NodeId::from("n".to_owned()),
2332            &config,
2333            &BTreeMap::from([(DataId::from("cmd".to_owned()), dummy_input())]),
2334            &BTreeSet::new(),
2335        )
2336        .unwrap_err()
2337        .to_string();
2338        assert!(
2339            err.contains("typo_in") && err.contains("not declared"),
2340            "error should name the undeclared input, got: {err}"
2341        );
2342    }
2343
2344    #[test]
2345    fn validate_multi_topic_rejects_undeclared_derived_output() {
2346        // No explicit `output:` — the bridge derives the output id from the
2347        // topic name (`/scan` -> `scan`). A derived id that is not a declared
2348        // output silently drops every message, so validation must reject it.
2349        let config = Ros2BridgeConfig {
2350            topics: Some(vec![Ros2TopicConfig {
2351                topic: "/scan".into(),
2352                message_type: "sensor_msgs/LaserScan".into(),
2353                direction: Ros2Direction::Subscribe,
2354                output: None,
2355                input: None,
2356                qos: None,
2357            }]),
2358            ..Default::default()
2359        };
2360        let err = validate_ros2_config(
2361            &NodeId::from("n".to_owned()),
2362            &config,
2363            &BTreeMap::new(),
2364            &BTreeSet::from([DataId::from("laser".to_owned())]),
2365        )
2366        .unwrap_err()
2367        .to_string();
2368        assert!(
2369            err.contains("scan") && err.contains("not declared"),
2370            "error should name the derived output, got: {err}"
2371        );
2372    }
2373
2374    #[test]
2375    fn validate_multi_topic_accepts_derived_output() {
2376        // The topic-derived id (`/scan` -> `scan`) matches a declared output.
2377        let config = Ros2BridgeConfig {
2378            topics: Some(vec![Ros2TopicConfig {
2379                topic: "/scan".into(),
2380                message_type: "sensor_msgs/LaserScan".into(),
2381                direction: Ros2Direction::Subscribe,
2382                output: None,
2383                input: None,
2384                qos: None,
2385            }]),
2386            ..Default::default()
2387        };
2388        validate_ros2_config(
2389            &NodeId::from("n".to_owned()),
2390            &config,
2391            &BTreeMap::new(),
2392            &BTreeSet::from([DataId::from("scan".to_owned())]),
2393        )
2394        .expect("a topic-derived output matching a declared output should validate");
2395    }
2396
2397    #[test]
2398    fn validate_multi_topic_accepts_declared_ports() {
2399        let config = Ros2BridgeConfig {
2400            topics: Some(vec![
2401                Ros2TopicConfig {
2402                    topic: "/scan".into(),
2403                    message_type: "sensor_msgs/LaserScan".into(),
2404                    direction: Ros2Direction::Subscribe,
2405                    output: Some("scan".into()),
2406                    input: None,
2407                    qos: None,
2408                },
2409                Ros2TopicConfig {
2410                    topic: "/cmd_vel".into(),
2411                    message_type: "geometry_msgs/Twist".into(),
2412                    direction: Ros2Direction::Publish,
2413                    output: None,
2414                    input: Some("cmd".into()),
2415                    qos: None,
2416                },
2417            ]),
2418            ..Default::default()
2419        };
2420        validate_ros2_config(
2421            &NodeId::from("n".to_owned()),
2422            &config,
2423            &BTreeMap::from([(DataId::from("cmd".to_owned()), dummy_input())]),
2424            &BTreeSet::from([DataId::from("scan".to_owned())]),
2425        )
2426        .expect("multi-topic config mapping declared ports should validate");
2427    }
2428
2429    #[test]
2430    fn validate_multiple_modes() {
2431        let config = Ros2BridgeConfig {
2432            topic: Some("/t".into()),
2433            service: Some("/s".into()),
2434            message_type: Some("a/B".into()),
2435            service_type: Some("a/B".into()),
2436            role: Some(Ros2Role::Client),
2437            ..Default::default()
2438        };
2439        let err = validate_ros2_config(
2440            &NodeId::from("n".to_owned()),
2441            &config,
2442            &BTreeMap::new(),
2443            &BTreeSet::new(),
2444        )
2445        .unwrap_err();
2446        assert!(err.to_string().contains("multiple of"));
2447    }
2448
2449    #[test]
2450    fn validate_service_client_ok() {
2451        let config = service_config(Ros2Role::Client);
2452        let mut inputs = BTreeMap::new();
2453        inputs.insert(DataId::from("request".to_owned()), dummy_input());
2454        let mut outputs = BTreeSet::new();
2455        outputs.insert(DataId::from("response".to_owned()));
2456        validate_ros2_config(&NodeId::from("n".to_owned()), &config, &inputs, &outputs).unwrap();
2457    }
2458
2459    #[test]
2460    fn validate_service_client_missing_service_type() {
2461        let config = Ros2BridgeConfig {
2462            service: Some("/svc".into()),
2463            role: Some(Ros2Role::Client),
2464            ..Default::default()
2465        };
2466        let mut inputs = BTreeMap::new();
2467        inputs.insert(DataId::from("request".to_owned()), dummy_input());
2468        let mut outputs = BTreeSet::new();
2469        outputs.insert(DataId::from("response".to_owned()));
2470        let err = validate_ros2_config(&NodeId::from("n".to_owned()), &config, &inputs, &outputs)
2471            .unwrap_err();
2472        assert!(err.to_string().contains("service_type"));
2473    }
2474
2475    #[test]
2476    fn validate_service_client_missing_role() {
2477        let config = Ros2BridgeConfig {
2478            service: Some("/svc".into()),
2479            service_type: Some("a/B".into()),
2480            ..Default::default()
2481        };
2482        let mut inputs = BTreeMap::new();
2483        inputs.insert(DataId::from("request".to_owned()), dummy_input());
2484        let mut outputs = BTreeSet::new();
2485        outputs.insert(DataId::from("response".to_owned()));
2486        let err = validate_ros2_config(&NodeId::from("n".to_owned()), &config, &inputs, &outputs)
2487            .unwrap_err();
2488        assert!(err.to_string().contains("role"));
2489    }
2490
2491    #[test]
2492    fn validate_service_client_no_inputs() {
2493        let config = service_config(Ros2Role::Client);
2494        let mut outputs = BTreeSet::new();
2495        outputs.insert(DataId::from("response".to_owned()));
2496        let err = validate_ros2_config(
2497            &NodeId::from("n".to_owned()),
2498            &config,
2499            &BTreeMap::new(),
2500            &outputs,
2501        )
2502        .unwrap_err();
2503        assert!(err.to_string().contains("input"));
2504    }
2505
2506    #[test]
2507    fn validate_service_client_no_outputs() {
2508        let config = service_config(Ros2Role::Client);
2509        let mut inputs = BTreeMap::new();
2510        inputs.insert(DataId::from("request".to_owned()), dummy_input());
2511        let err = validate_ros2_config(
2512            &NodeId::from("n".to_owned()),
2513            &config,
2514            &inputs,
2515            &BTreeSet::new(),
2516        )
2517        .unwrap_err();
2518        assert!(err.to_string().contains("output"));
2519    }
2520
2521    #[test]
2522    fn validate_service_server_ok() {
2523        let config = service_config(Ros2Role::Server);
2524        let mut inputs = BTreeMap::new();
2525        inputs.insert(DataId::from("response".to_owned()), dummy_input());
2526        let mut outputs = BTreeSet::new();
2527        outputs.insert(DataId::from("request".to_owned()));
2528        validate_ros2_config(&NodeId::from("n".to_owned()), &config, &inputs, &outputs).unwrap();
2529    }
2530
2531    #[test]
2532    fn validate_service_server_no_inputs() {
2533        let config = service_config(Ros2Role::Server);
2534        let mut outputs = BTreeSet::new();
2535        outputs.insert(DataId::from("request".to_owned()));
2536        let err = validate_ros2_config(
2537            &NodeId::from("n".to_owned()),
2538            &config,
2539            &BTreeMap::new(),
2540            &outputs,
2541        )
2542        .unwrap_err();
2543        assert!(err.to_string().contains("input"));
2544    }
2545
2546    #[test]
2547    fn validate_service_server_no_outputs() {
2548        let config = service_config(Ros2Role::Server);
2549        let mut inputs = BTreeMap::new();
2550        inputs.insert(DataId::from("response".to_owned()), dummy_input());
2551        let err = validate_ros2_config(
2552            &NodeId::from("n".to_owned()),
2553            &config,
2554            &inputs,
2555            &BTreeSet::new(),
2556        )
2557        .unwrap_err();
2558        assert!(err.to_string().contains("output"));
2559    }
2560
2561    #[test]
2562    fn validate_action_client_ok() {
2563        let config = action_config(Ros2Role::Client);
2564        let mut inputs = BTreeMap::new();
2565        inputs.insert(DataId::from("goal".to_owned()), dummy_input());
2566        let mut outputs = BTreeSet::new();
2567        outputs.insert(DataId::from("feedback".to_owned()));
2568        outputs.insert(DataId::from("result".to_owned()));
2569        validate_ros2_config(&NodeId::from("n".to_owned()), &config, &inputs, &outputs).unwrap();
2570    }
2571
2572    #[test]
2573    fn validate_action_client_missing_action_type() {
2574        let config = Ros2BridgeConfig {
2575            action: Some("/nav".into()),
2576            role: Some(Ros2Role::Client),
2577            ..Default::default()
2578        };
2579        let mut inputs = BTreeMap::new();
2580        inputs.insert(DataId::from("goal".to_owned()), dummy_input());
2581        let mut outputs = BTreeSet::new();
2582        outputs.insert(DataId::from("feedback".to_owned()));
2583        let err = validate_ros2_config(&NodeId::from("n".to_owned()), &config, &inputs, &outputs)
2584            .unwrap_err();
2585        assert!(err.to_string().contains("action_type"));
2586    }
2587
2588    #[test]
2589    fn validate_action_client_no_inputs() {
2590        let config = action_config(Ros2Role::Client);
2591        let mut outputs = BTreeSet::new();
2592        outputs.insert(DataId::from("feedback".to_owned()));
2593        let err = validate_ros2_config(
2594            &NodeId::from("n".to_owned()),
2595            &config,
2596            &BTreeMap::new(),
2597            &outputs,
2598        )
2599        .unwrap_err();
2600        assert!(err.to_string().contains("input"));
2601    }
2602
2603    #[test]
2604    fn validate_action_client_no_outputs() {
2605        let config = action_config(Ros2Role::Client);
2606        let mut inputs = BTreeMap::new();
2607        inputs.insert(DataId::from("goal".to_owned()), dummy_input());
2608        let err = validate_ros2_config(
2609            &NodeId::from("n".to_owned()),
2610            &config,
2611            &inputs,
2612            &BTreeSet::new(),
2613        )
2614        .unwrap_err();
2615        assert!(err.to_string().contains("output"));
2616    }
2617
2618    #[test]
2619    fn validate_action_server_ok() {
2620        let config = action_config(Ros2Role::Server);
2621        let mut inputs = BTreeMap::new();
2622        inputs.insert(DataId::from("feedback".to_owned()), dummy_input());
2623        let mut outputs = BTreeSet::new();
2624        outputs.insert(DataId::from("goal".to_owned()));
2625        validate_ros2_config(&NodeId::from("n".to_owned()), &config, &inputs, &outputs).unwrap();
2626    }
2627
2628    #[test]
2629    fn validate_action_server_no_inputs() {
2630        let config = action_config(Ros2Role::Server);
2631        let mut outputs = BTreeSet::new();
2632        outputs.insert(DataId::from("goal".to_owned()));
2633        let err = validate_ros2_config(
2634            &NodeId::from("n".to_owned()),
2635            &config,
2636            &BTreeMap::new(),
2637            &outputs,
2638        )
2639        .unwrap_err();
2640        assert!(err.to_string().contains("input"));
2641    }
2642
2643    #[test]
2644    fn validate_action_server_no_outputs() {
2645        let config = action_config(Ros2Role::Server);
2646        let mut inputs = BTreeMap::new();
2647        inputs.insert(DataId::from("feedback".to_owned()), dummy_input());
2648        let err = validate_ros2_config(
2649            &NodeId::from("n".to_owned()),
2650            &config,
2651            &inputs,
2652            &BTreeSet::new(),
2653        )
2654        .unwrap_err();
2655        assert!(err.to_string().contains("output"));
2656    }
2657
2658    #[test]
2659    fn validate_bad_type_format() {
2660        let config = Ros2BridgeConfig {
2661            service: Some("/svc".into()),
2662            service_type: Some("invalid_no_slash".into()),
2663            role: Some(Ros2Role::Client),
2664            ..Default::default()
2665        };
2666        let mut inputs = BTreeMap::new();
2667        inputs.insert(DataId::from("request".to_owned()), dummy_input());
2668        let mut outputs = BTreeSet::new();
2669        outputs.insert(DataId::from("response".to_owned()));
2670        let err = validate_ros2_config(&NodeId::from("n".to_owned()), &config, &inputs, &outputs)
2671            .unwrap_err();
2672        assert!(err.to_string().contains("package/TypeName"));
2673    }
2674
2675    #[test]
2676    fn validate_type_rejects_special_chars() {
2677        let config = Ros2BridgeConfig {
2678            service: Some("/svc".into()),
2679            service_type: Some("pkg-bad/Evil".into()),
2680            role: Some(Ros2Role::Client),
2681            ..Default::default()
2682        };
2683        let mut inputs = BTreeMap::new();
2684        inputs.insert(DataId::from("request".to_owned()), dummy_input());
2685        let mut outputs = BTreeSet::new();
2686        outputs.insert(DataId::from("response".to_owned()));
2687        let err = validate_ros2_config(&NodeId::from("n".to_owned()), &config, &inputs, &outputs)
2688            .unwrap_err();
2689        assert!(err.to_string().contains("alphanumeric"));
2690    }
2691
2692    #[test]
2693    fn ros2_name_accepts_valid() {
2694        let node = NodeId::from("n".to_owned());
2695        for name in [
2696            "topic",
2697            "/topic",
2698            "/a/b/c",
2699            "/add_two_ints",
2700            "ns/sub_topic",
2701            "/navigate",
2702            "_hidden",
2703            "/_internal/state",
2704            "/_ros2cli_node",
2705        ] {
2706            validate_ros2_name(&node, "topic", name)
2707                .unwrap_or_else(|e| panic!("`{name}` should be valid: {e}"));
2708        }
2709    }
2710
2711    #[test]
2712    fn ros2_name_rejects_double_leading_slash() {
2713        let node = NodeId::from("n".to_owned());
2714        let err = validate_ros2_name(&node, "topic", "//topic").unwrap_err();
2715        assert!(err.to_string().contains("consecutive slashes"));
2716    }
2717
2718    #[test]
2719    fn ros2_name_rejects_trailing_slash() {
2720        let node = NodeId::from("n".to_owned());
2721        let err = validate_ros2_name(&node, "topic", "topic/").unwrap_err();
2722        assert!(err.to_string().contains("end with"));
2723    }
2724
2725    #[test]
2726    fn ros2_name_rejects_consecutive_interior_slashes() {
2727        let node = NodeId::from("n".to_owned());
2728        let err = validate_ros2_name(&node, "topic", "topic//sub").unwrap_err();
2729        assert!(err.to_string().contains("consecutive slashes"));
2730    }
2731
2732    #[test]
2733    fn ros2_name_rejects_bare_slash() {
2734        let node = NodeId::from("n".to_owned());
2735        let err = validate_ros2_name(&node, "topic", "/").unwrap_err();
2736        assert!(err.to_string().contains("bare"));
2737    }
2738
2739    #[test]
2740    fn ros2_name_accepts_leading_underscore() {
2741        let node = NodeId::from("n".to_owned());
2742        for name in ["_hidden", "/_internal/state", "/_ros2cli_node"] {
2743            validate_ros2_name(&node, "topic", name)
2744                .unwrap_or_else(|e| panic!("`{name}` should be valid (hidden topic): {e}"));
2745        }
2746    }
2747
2748    #[test]
2749    fn ros2_name_rejects_token_starting_with_digit() {
2750        let node = NodeId::from("n".to_owned());
2751        let err = validate_ros2_name(&node, "topic", "/2bad").unwrap_err();
2752        assert!(err.to_string().contains("digit"));
2753    }
2754
2755    #[test]
2756    fn validate_qos_bad_durability() {
2757        let config = Ros2BridgeConfig {
2758            service: Some("/svc".into()),
2759            service_type: Some("a/B".into()),
2760            role: Some(Ros2Role::Client),
2761            qos: dora_message::descriptor::Ros2QosConfig {
2762                durability: Some("persistent".into()),
2763                ..Default::default()
2764            },
2765            ..Default::default()
2766        };
2767        let mut inputs = BTreeMap::new();
2768        inputs.insert(DataId::from("request".to_owned()), dummy_input());
2769        let mut outputs = BTreeSet::new();
2770        outputs.insert(DataId::from("response".to_owned()));
2771        let err = validate_ros2_config(&NodeId::from("n".to_owned()), &config, &inputs, &outputs)
2772            .unwrap_err();
2773        assert!(err.to_string().contains("durability"));
2774    }
2775
2776    #[test]
2777    fn validate_qos_keep_last_out_of_range() {
2778        let config = Ros2BridgeConfig {
2779            service: Some("/svc".into()),
2780            service_type: Some("a/B".into()),
2781            role: Some(Ros2Role::Client),
2782            qos: dora_message::descriptor::Ros2QosConfig {
2783                keep_last: Some(100_000),
2784                ..Default::default()
2785            },
2786            ..Default::default()
2787        };
2788        let mut inputs = BTreeMap::new();
2789        inputs.insert(DataId::from("request".to_owned()), dummy_input());
2790        let mut outputs = BTreeSet::new();
2791        outputs.insert(DataId::from("response".to_owned()));
2792        let err = validate_ros2_config(&NodeId::from("n".to_owned()), &config, &inputs, &outputs)
2793            .unwrap_err();
2794        assert!(err.to_string().contains("keep_last"));
2795    }
2796
2797    // --- Type annotation tests ---
2798
2799    fn parse_dataflow(yaml: &str) -> Descriptor {
2800        serde_yaml::from_str(yaml).expect("test YAML should parse")
2801    }
2802
2803    #[test]
2804    fn type_check_no_annotations_no_warnings() {
2805        let dataflow = parse_dataflow("nodes:\n  - id: a\n");
2806        let reg = TypeRegistry::new();
2807        let warnings = check_type_annotations_full(&dataflow, &reg, false).warnings;
2808        assert!(warnings.is_empty());
2809    }
2810
2811    #[test]
2812    fn type_check_valid_output_type() {
2813        let dataflow = parse_dataflow(
2814            "nodes:\n  - id: camera\n    outputs:\n      - image\n    output_types:\n      image: std/media/v1/Image\n",
2815        );
2816        let reg = TypeRegistry::new();
2817        let warnings = check_type_annotations_full(&dataflow, &reg, false).warnings;
2818        assert!(warnings.is_empty());
2819    }
2820
2821    #[test]
2822    fn type_check_output_types_key_not_in_outputs() {
2823        let dataflow = parse_dataflow(
2824            "nodes:\n  - id: camera\n    output_types:\n      image: std/media/v1/Image\n",
2825        );
2826        let reg = TypeRegistry::new();
2827        let warnings = check_type_annotations_full(&dataflow, &reg, false).warnings;
2828        assert_eq!(warnings.len(), 1);
2829        assert!(warnings[0].message.contains("not found in outputs"));
2830    }
2831
2832    #[test]
2833    fn type_check_unknown_urn_with_suggestion() {
2834        let dataflow = parse_dataflow(
2835            "nodes:\n  - id: camera\n    outputs:\n      - image\n    output_types:\n      image: std/media/v1/Imag\n",
2836        );
2837        let reg = TypeRegistry::new();
2838        let warnings = check_type_annotations_full(&dataflow, &reg, false).warnings;
2839        assert_eq!(warnings.len(), 1);
2840        assert!(warnings[0].message.contains("unknown type"));
2841        assert!(warnings[0].message.contains("did you mean"));
2842    }
2843
2844    #[test]
2845    fn type_check_matching_edge_types() {
2846        let dataflow = parse_dataflow(
2847            "\
2848nodes:
2849  - id: sender
2850    outputs:
2851      - data
2852    output_types:
2853      data: std/core/v1/Float32
2854  - id: receiver
2855    inputs:
2856      data: sender/data
2857    input_types:
2858      data: std/core/v1/Float32
2859",
2860        );
2861        let reg = TypeRegistry::new();
2862        let warnings = check_type_annotations_full(&dataflow, &reg, false).warnings;
2863        assert!(warnings.is_empty());
2864    }
2865
2866    #[test]
2867    fn type_check_mismatched_edge_types() {
2868        let dataflow = parse_dataflow(
2869            "\
2870nodes:
2871  - id: sender
2872    outputs:
2873      - data
2874    output_types:
2875      data: std/core/v1/Float32
2876  - id: receiver
2877    inputs:
2878      data: sender/data
2879    input_types:
2880      data: std/media/v1/Image
2881",
2882        );
2883        let reg = TypeRegistry::new();
2884        let warnings = check_type_annotations_full(&dataflow, &reg, false).warnings;
2885        assert_eq!(warnings.len(), 1);
2886        assert!(warnings[0].message.contains("type mismatch"));
2887        assert!(warnings[0].message.contains("Float32"));
2888        assert!(warnings[0].message.contains("Image"));
2889    }
2890
2891    // --- Phase 1: strict mode tests ---
2892
2893    #[test]
2894    fn strict_types_parses_in_yaml() {
2895        let dataflow = parse_dataflow("nodes:\n  - id: a\nstrict_types: true\n");
2896        assert_eq!(dataflow.strict_types, Some(true));
2897    }
2898
2899    #[test]
2900    fn strict_mode_warns_on_unannotated_upstream() {
2901        let dataflow = parse_dataflow(
2902            "\
2903nodes:
2904  - id: sender
2905    outputs:
2906      - data
2907  - id: receiver
2908    inputs:
2909      data: sender/data
2910    input_types:
2911      data: std/core/v1/Float32
2912",
2913        );
2914        let reg = TypeRegistry::new();
2915        let result = check_type_annotations_full(&dataflow, &reg, true);
2916        assert!(!result.warnings.is_empty());
2917        assert!(result.warnings[0].message.contains("no type annotation"));
2918    }
2919
2920    /// Regression: an upstream output that *is* annotated but with an
2921    /// unresolvable URN (a typo) must not trigger the strict-mode "upstream
2922    /// has no type annotation" warning. The unknown URN is already reported by
2923    /// the port-type check; a second "no annotation" warning would be
2924    /// factually wrong and send the user chasing a missing annotation instead
2925    /// of the typo.
2926    #[test]
2927    fn strict_mode_no_missing_annotation_warning_for_typoed_upstream() {
2928        let dataflow = parse_dataflow(
2929            "\
2930nodes:
2931  - id: sender
2932    outputs:
2933      - image
2934    output_types:
2935      image: std/media/v1/Imag
2936  - id: receiver
2937    inputs:
2938      image: sender/image
2939    input_types:
2940      image: std/media/v1/Image
2941",
2942        );
2943        let reg = TypeRegistry::new();
2944        let result = check_type_annotations_full(&dataflow, &reg, true);
2945        // The typo itself is still reported...
2946        assert!(
2947            result
2948                .warnings
2949                .iter()
2950                .any(|w| w.message.contains("unknown type")),
2951            "expected an unknown-type warning for the typo, got: {:?}",
2952            result.warnings
2953        );
2954        // ...but the misleading "no type annotation" warning must not appear:
2955        // the upstream *is* annotated, just misspelled.
2956        assert!(
2957            !result
2958                .warnings
2959                .iter()
2960                .any(|w| w.message.contains("no type annotation")),
2961            "must not claim the annotated-but-typoed upstream has no annotation, got: {:?}",
2962            result.warnings
2963        );
2964    }
2965
2966    #[test]
2967    fn non_strict_no_warning_on_unannotated_upstream() {
2968        let dataflow = parse_dataflow(
2969            "\
2970nodes:
2971  - id: sender
2972    outputs:
2973      - data
2974  - id: receiver
2975    inputs:
2976      data: sender/data
2977    input_types:
2978      data: std/core/v1/Float32
2979",
2980        );
2981        let reg = TypeRegistry::new();
2982        let result = check_type_annotations_full(&dataflow, &reg, false);
2983        assert!(result.warnings.is_empty());
2984    }
2985
2986    // --- Phase 3: type inference tests ---
2987
2988    #[test]
2989    fn inference_from_annotated_upstream() {
2990        let dataflow = parse_dataflow(
2991            "\
2992nodes:
2993  - id: sensor
2994    outputs:
2995      - reading
2996    output_types:
2997      reading: std/core/v1/Float64
2998  - id: processor
2999    inputs:
3000      reading: sensor/reading
3001",
3002        );
3003        let reg = TypeRegistry::new();
3004        let result = check_type_annotations_full(&dataflow, &reg, false);
3005        assert!(result.warnings.is_empty());
3006        assert_eq!(result.inferences.len(), 1);
3007        assert_eq!(result.inferences[0].inferred_urn, "std/core/v1/Float64");
3008        assert_eq!(result.inferences[0].port_id, "reading");
3009    }
3010
3011    #[test]
3012    fn no_inference_when_both_annotated() {
3013        let dataflow = parse_dataflow(
3014            "\
3015nodes:
3016  - id: sender
3017    outputs:
3018      - data
3019    output_types:
3020      data: std/core/v1/Float32
3021  - id: receiver
3022    inputs:
3023      data: sender/data
3024    input_types:
3025      data: std/core/v1/Float32
3026",
3027        );
3028        let reg = TypeRegistry::new();
3029        let result = check_type_annotations_full(&dataflow, &reg, false);
3030        assert!(result.inferences.is_empty());
3031    }
3032
3033    #[test]
3034    fn no_inference_when_neither_annotated() {
3035        let dataflow = parse_dataflow(
3036            "\
3037nodes:
3038  - id: sender
3039    outputs:
3040      - data
3041  - id: receiver
3042    inputs:
3043      data: sender/data
3044",
3045        );
3046        let reg = TypeRegistry::new();
3047        let result = check_type_annotations_full(&dataflow, &reg, false);
3048        assert!(result.inferences.is_empty());
3049    }
3050
3051    // --- Phase 4: compatibility tests ---
3052
3053    #[test]
3054    fn compat_uint8_to_uint32_edge() {
3055        let dataflow = parse_dataflow(
3056            "\
3057nodes:
3058  - id: sender
3059    outputs:
3060      - data
3061    output_types:
3062      data: std/core/v1/UInt8
3063  - id: receiver
3064    inputs:
3065      data: sender/data
3066    input_types:
3067      data: std/core/v1/UInt32
3068",
3069        );
3070        let reg = TypeRegistry::new();
3071        let warnings = check_type_annotations_full(&dataflow, &reg, false).warnings;
3072        assert!(warnings.is_empty(), "UInt8 -> UInt32 should be compatible");
3073    }
3074
3075    #[test]
3076    fn compat_any_to_bytes_edge() {
3077        let dataflow = parse_dataflow(
3078            "\
3079nodes:
3080  - id: sender
3081    outputs:
3082      - data
3083    output_types:
3084      data: std/media/v1/Image
3085  - id: receiver
3086    inputs:
3087      data: sender/data
3088    input_types:
3089      data: std/core/v1/Bytes
3090",
3091        );
3092        let reg = TypeRegistry::new();
3093        let warnings = check_type_annotations_full(&dataflow, &reg, false).warnings;
3094        assert!(
3095            warnings.is_empty(),
3096            "anything -> Bytes should be compatible"
3097        );
3098    }
3099
3100    #[test]
3101    fn compat_user_defined_rule_in_yaml() {
3102        let dataflow = parse_dataflow(
3103            "\
3104type_rules:
3105  - from: std/core/v1/UInt8
3106    to: std/core/v1/String
3107nodes:
3108  - id: sender
3109    outputs:
3110      - data
3111    output_types:
3112      data: std/core/v1/UInt8
3113  - id: receiver
3114    inputs:
3115      data: sender/data
3116    input_types:
3117      data: std/core/v1/String
3118",
3119        );
3120        let reg = TypeRegistry::new();
3121        let warnings = check_type_annotations_full(&dataflow, &reg, false).warnings;
3122        assert!(
3123            warnings.is_empty(),
3124            "user-defined rule should make this compatible"
3125        );
3126    }
3127
3128    // --- Phase 5: metadata tests ---
3129
3130    #[test]
3131    fn metadata_pattern_resolves() {
3132        let dataflow = parse_dataflow(
3133            "\
3134nodes:
3135  - id: srv
3136    pattern: service-server
3137    outputs:
3138      - response
3139",
3140        );
3141        let reg = TypeRegistry::new();
3142        let warnings = check_type_annotations_full(&dataflow, &reg, false).warnings;
3143        assert!(warnings.is_empty());
3144    }
3145
3146    #[test]
3147    fn metadata_unknown_pattern() {
3148        let dataflow = parse_dataflow(
3149            "\
3150nodes:
3151  - id: srv
3152    pattern: unknown-pattern
3153    outputs:
3154      - response
3155",
3156        );
3157        let reg = TypeRegistry::new();
3158        let warnings = check_type_annotations_full(&dataflow, &reg, false).warnings;
3159        assert_eq!(warnings.len(), 1);
3160        assert!(warnings[0].message.contains("unknown pattern"));
3161    }
3162
3163    #[test]
3164    fn metadata_output_key_not_in_outputs() {
3165        let dataflow = parse_dataflow(
3166            "\
3167nodes:
3168  - id: srv
3169    output_metadata:
3170      missing_port: [request_id]
3171    outputs:
3172      - response
3173",
3174        );
3175        let reg = TypeRegistry::new();
3176        let warnings = check_type_annotations_full(&dataflow, &reg, false).warnings;
3177        assert_eq!(warnings.len(), 1);
3178        assert!(warnings[0].message.contains("output_metadata key"));
3179    }
3180
3181    // --- Timer auto-inject test ---
3182
3183    #[test]
3184    fn timer_input_type_mismatch() {
3185        let dataflow = parse_dataflow(
3186            "\
3187nodes:
3188  - id: node
3189    inputs:
3190      tick: dora/timer/millis/100
3191    input_types:
3192      tick: std/media/v1/Image
3193",
3194        );
3195        let reg = TypeRegistry::new();
3196        let warnings = check_type_annotations_full(&dataflow, &reg, false).warnings;
3197        assert!(!warnings.is_empty());
3198        assert!(warnings[0].message.contains("type mismatch"));
3199    }
3200
3201    #[test]
3202    fn validate_qos_negative_lease_duration() {
3203        let config = Ros2BridgeConfig {
3204            service: Some("/svc".into()),
3205            service_type: Some("a/B".into()),
3206            role: Some(Ros2Role::Client),
3207            qos: dora_message::descriptor::Ros2QosConfig {
3208                lease_duration: Some(-1.0),
3209                ..Default::default()
3210            },
3211            ..Default::default()
3212        };
3213        let mut inputs = BTreeMap::new();
3214        inputs.insert(DataId::from("request".to_owned()), dummy_input());
3215        let mut outputs = BTreeSet::new();
3216        outputs.insert(DataId::from("response".to_owned()));
3217        let err = validate_ros2_config(&NodeId::from("n".to_owned()), &config, &inputs, &outputs)
3218            .unwrap_err();
3219        assert!(err.to_string().contains("lease_duration"));
3220    }
3221
3222    /// A finite but enormous QoS duration passes the old
3223    /// `is_finite()` / `>= 0` check yet overflows `Duration`, which panics
3224    /// `Duration::from_secs_f64` in the ROS2 bridge QoS conversion. Both
3225    /// fields must be rejected at descriptor validation instead.
3226    #[test]
3227    fn validate_qos_overflowing_durations_are_rejected() {
3228        let base = Ros2BridgeConfig {
3229            service: Some("/svc".into()),
3230            service_type: Some("a/B".into()),
3231            role: Some(Ros2Role::Client),
3232            ..Default::default()
3233        };
3234        let mut inputs = BTreeMap::new();
3235        inputs.insert(DataId::from("request".to_owned()), dummy_input());
3236        let mut outputs = BTreeSet::new();
3237        outputs.insert(DataId::from("response".to_owned()));
3238
3239        // `1e300` seconds is finite and positive but far beyond `Duration::MAX`.
3240        for (field, qos) in [
3241            (
3242                "lease_duration",
3243                dora_message::descriptor::Ros2QosConfig {
3244                    lease_duration: Some(1e300),
3245                    ..Default::default()
3246                },
3247            ),
3248            (
3249                "max_blocking_time",
3250                dora_message::descriptor::Ros2QosConfig {
3251                    reliable: true,
3252                    max_blocking_time: Some(1e300),
3253                    ..Default::default()
3254                },
3255            ),
3256        ] {
3257            let config = Ros2BridgeConfig {
3258                qos,
3259                ..base.clone()
3260            };
3261            let err =
3262                validate_ros2_config(&NodeId::from("n".to_owned()), &config, &inputs, &outputs)
3263                    .unwrap_err();
3264            assert!(
3265                err.to_string().contains(field),
3266                "expected error naming `{field}`, got: {err}"
3267            );
3268        }
3269    }
3270
3271    // --- Wiring validation tests ---
3272
3273    #[test]
3274    fn wiring_valid_dataflow() {
3275        let yaml = r#"
3276nodes:
3277  - id: source
3278    path: source.py
3279    outputs:
3280      - data
3281  - id: sink
3282    path: sink.py
3283    inputs:
3284      data: source/data
3285"#;
3286        let descriptor: Descriptor = serde_yaml::from_str(yaml).unwrap();
3287        check_wiring(&descriptor).unwrap();
3288    }
3289
3290    /// Every shipped `ros2:` example must satisfy the port-mapping rule the
3291    /// bridge binds by. The docs present these as working dataflows, and a
3292    /// mismatch is silent data loss at runtime rather than a startup error, so
3293    /// parsing them is not enough — they have to be validated.
3294    #[test]
3295    fn ros2_example_dataflows_have_valid_port_mappings() {
3296        let examples = [
3297            "examples/ros2-bridge/yaml-bridge/dataflow.yml",
3298            "examples/ros2-bridge/yaml-bridge/dataflow-zenoh.yml",
3299            "examples/ros2-bridge/yaml-bridge-service/dataflow-client.yml",
3300            "examples/ros2-bridge/yaml-bridge-service/dataflow-client-zenoh.yml",
3301            "examples/ros2-bridge/yaml-bridge-service/dataflow-server.yml",
3302            "examples/ros2-bridge/yaml-bridge-service/dataflow-server-zenoh.yml",
3303            "examples/ros2-bridge/yaml-bridge-action/dataflow.yml",
3304            "examples/ros2-bridge/yaml-bridge-action/dataflow-zenoh.yml",
3305            "examples/ros2-bridge/yaml-bridge-action-server/dataflow.yml",
3306            "examples/ros2-bridge/yaml-bridge-action-server/dataflow-zenoh.yml",
3307            "examples/ros2-bridge/yaml-bridge-action-server/dataflow-accept.yml",
3308        ];
3309        for relative in examples {
3310            let Some(yaml) = repo_fixture(relative) else {
3311                continue; // packaged crate: the examples tree is not shipped
3312            };
3313            let descriptor: Descriptor = serde_yaml::from_str(&yaml).unwrap();
3314            if let Err(err) = validate_ros2_configs(&descriptor) {
3315                panic!("shipped example `{relative}` has an invalid ros2 config: {err}");
3316            }
3317        }
3318    }
3319
3320    /// Reads a fixture that lives outside this crate, or `None` when this is
3321    /// not a repository checkout. `include_str!` would be the obvious choice,
3322    /// but a path that leaves the crate directory is not in the published
3323    /// `.crate`, so the crate would fail to *compile* its tests for anyone
3324    /// building from crates.io (#3400).
3325    ///
3326    /// The workspace manifest is the marker for "we are in the repo". Only
3327    /// its absence skips: inside a checkout a missing fixture is a stale
3328    /// path and panics, so this keeps the one property `include_str!` had
3329    /// that a plain `.ok()` would throw away.
3330    fn repo_fixture(relative: &str) -> Option<String> {
3331        let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
3332        if !root.join("Cargo.toml").is_file() {
3333            return None;
3334        }
3335        let path = root.join(relative);
3336        Some(
3337            std::fs::read_to_string(&path)
3338                .unwrap_or_else(|e| panic!("fixture {} is missing: {e}", path.display())),
3339        )
3340    }
3341
3342    #[test]
3343    fn ros2_zenoh_documentation_examples_parse_with_explicit_profiles() {
3344        let examples = [
3345            "examples/ros2-bridge/yaml-bridge/dataflow-zenoh.yml",
3346            "examples/ros2-bridge/yaml-bridge-service/dataflow-client-zenoh.yml",
3347            "examples/ros2-bridge/yaml-bridge-action/dataflow-zenoh.yml",
3348        ];
3349        for relative in examples {
3350            let Some(yaml) = repo_fixture(relative) else {
3351                continue; // packaged crate: the examples tree is not shipped
3352            };
3353            let descriptor: Descriptor = serde_yaml::from_str(&yaml).unwrap();
3354            let ros2 = descriptor
3355                .nodes
3356                .iter()
3357                .find_map(|node| node.ros2.as_ref())
3358                .unwrap();
3359            assert!(matches!(
3360                ros2.transport,
3361                Ros2TransportConfig::Zenoh {
3362                    compatibility: RmwZenohCompatibility::Humble,
3363                    ..
3364                }
3365            ));
3366        }
3367    }
3368
3369    #[test]
3370    fn ros2_zenoh_documentation_links_upstream_wire_contract() {
3371        let Some(guide) = repo_fixture("guide/src/advanced/ros2-bridge.md") else {
3372            return; // packaged crate: the guide is not shipped
3373        };
3374        assert!(guide.contains("https://github.com/ros2/rmw_zenoh/blob/rolling/docs/design.md"));
3375        assert!(guide.contains("https://www.ros.org/reps/rep-2016.html"));
3376    }
3377
3378    #[test]
3379    fn wiring_rejects_nonexistent_source_node() {
3380        let yaml = r#"
3381nodes:
3382  - id: sink
3383    path: sink.py
3384    inputs:
3385      data: nonexistent/data
3386"#;
3387        let descriptor: Descriptor = serde_yaml::from_str(yaml).unwrap();
3388        let err = check_wiring(&descriptor).unwrap_err();
3389        assert!(
3390            err.to_string().contains("nonexistent"),
3391            "expected error about missing node, got: {err}"
3392        );
3393    }
3394
3395    #[test]
3396    fn wiring_log_filter_rejects_a_module_but_allows_a_later_node() {
3397        // `nav.worker` is what a module node `nav` expands to.
3398        let yaml = r#"
3399nodes:
3400  - id: nav.worker
3401    path: worker.py
3402  - id: sink
3403    path: sink.py
3404    inputs:
3405      ok: dora/logs/info/nav.worker
3406      all: dora/logs/info
3407      later: dora/logs/info/plugin
3408"#;
3409        let descriptor: Descriptor = serde_yaml::from_str(yaml).unwrap();
3410        // A node that may still be added with `dora node add` is only warned about.
3411        check_wiring(&descriptor).unwrap();
3412
3413        let descriptor: Descriptor =
3414            serde_yaml::from_str(&format!("{yaml}      module: dora/logs/info/nav\n")).unwrap();
3415        let err = check_wiring(&descriptor).unwrap_err().to_string();
3416        assert!(
3417            err.contains("`sink/module`") && err.contains("prefix of node `nav.worker`"),
3418            "got: {err}"
3419        );
3420    }
3421
3422    #[test]
3423    fn wiring_rejects_nonexistent_output() {
3424        let yaml = r#"
3425nodes:
3426  - id: source
3427    path: source.py
3428    outputs:
3429      - data
3430  - id: sink
3431    path: sink.py
3432    inputs:
3433      data: source/typo
3434"#;
3435        let descriptor: Descriptor = serde_yaml::from_str(yaml).unwrap();
3436        let err = check_wiring(&descriptor).unwrap_err();
3437        assert!(
3438            err.to_string().contains("typo"),
3439            "expected error about missing output, got: {err}"
3440        );
3441    }
3442
3443    #[test]
3444    fn wiring_runtime_input_id_order() {
3445        // A runtime node's operator input that references a missing source
3446        // must report the input in the conventional
3447        // `{node_id}/{operator_id}/{input_id}` order (see #2019).
3448        let yaml = r#"
3449nodes:
3450  - id: runtime-node
3451    operators:
3452      - id: my-operator
3453        shared-library: op
3454        inputs:
3455          tick: nonexistent/data
3456        outputs:
3457          - status
3458"#;
3459        let descriptor: Descriptor = serde_yaml::from_str(yaml).unwrap();
3460        let err = check_wiring(&descriptor).unwrap_err();
3461        let msg = err.to_string();
3462        assert!(
3463            msg.contains("runtime-node/my-operator/tick"),
3464            "expected node/operator/input order, got: {msg}"
3465        );
3466        assert!(
3467            !msg.contains("my-operator/runtime-node/tick"),
3468            "input id should not use reversed operator/node order, got: {msg}"
3469        );
3470    }
3471
3472    // --- Single-`operator:` producer edges (short-form references) ---
3473    //
3474    // A consumer of a single-`operator:` node references its output in short
3475    // form (`node/output`) in the source YAML. The `op/` prefix is only
3476    // injected later by `resolve_aliases_and_set_defaults`, which the
3477    // pre-build type check does not run. These tests guard that the type
3478    // check still sees the upstream type across such an edge.
3479
3480    #[test]
3481    fn infers_type_across_single_operator_edge() {
3482        let dataflow = parse_dataflow(
3483            "\
3484nodes:
3485  - id: producer
3486    operator:
3487      python: producer.py
3488      outputs:
3489        - result
3490      output_types:
3491        result: std/core/v1/Float64
3492  - id: consumer
3493    inputs:
3494      reading: producer/result
3495",
3496        );
3497        let reg = TypeRegistry::new();
3498        let result = check_type_annotations_full(&dataflow, &reg, false);
3499        assert!(
3500            result.warnings.is_empty(),
3501            "unexpected: {:?}",
3502            result.warnings
3503        );
3504        assert_eq!(
3505            result.inferences.len(),
3506            1,
3507            "should infer from the operator output"
3508        );
3509        assert_eq!(result.inferences[0].inferred_urn, "std/core/v1/Float64");
3510        assert_eq!(result.inferences[0].port_id, "reading");
3511    }
3512
3513    #[test]
3514    fn detects_mismatch_across_single_operator_edge() {
3515        let dataflow = parse_dataflow(
3516            "\
3517nodes:
3518  - id: producer
3519    operator:
3520      python: producer.py
3521      outputs:
3522        - result
3523      output_types:
3524        result: std/core/v1/Float64
3525  - id: consumer
3526    inputs:
3527      reading: producer/result
3528    input_types:
3529      reading: std/core/v1/Int32
3530",
3531        );
3532        let reg = TypeRegistry::new();
3533        let result = check_type_annotations_full(&dataflow, &reg, false);
3534        assert!(
3535            result
3536                .warnings
3537                .iter()
3538                .any(|w| w.message.contains("type mismatch")),
3539            "expected a type mismatch warning, got: {:?}",
3540            result.warnings
3541        );
3542    }
3543
3544    #[test]
3545    fn strict_mode_no_false_positive_across_single_operator_edge() {
3546        // Upstream single-operator output IS annotated, so strict mode must
3547        // not claim it has "no type annotation".
3548        let dataflow = parse_dataflow(
3549            "\
3550nodes:
3551  - id: producer
3552    operator:
3553      python: producer.py
3554      outputs:
3555        - result
3556      output_types:
3557        result: std/core/v1/Float64
3558  - id: consumer
3559    inputs:
3560      reading: producer/result
3561    input_types:
3562      reading: std/core/v1/Float64
3563",
3564        );
3565        let reg = TypeRegistry::new();
3566        let result = check_type_annotations_full(&dataflow, &reg, true);
3567        assert!(
3568            !result
3569                .warnings
3570                .iter()
3571                .any(|w| w.message.contains("no type annotation")),
3572            "annotated upstream must not trigger a strict no-annotation warning, got: {:?}",
3573            result.warnings
3574        );
3575    }
3576
3577    // --- Focused unit tests for parse_byte_size and parse_log_level ---
3578    //
3579    // Added 2026-04-08 to close the biggest mutation-score gap in
3580    // dora-core: 14 escaped mutants in parse_byte_size and 6 in
3581    // parse_log_level (20 of the 91 missed mutants in validate.rs).
3582    // See docs/qa-baseline-2026-04-07.md.
3583    //
3584    // These tests exercise every match arm and every boundary case by
3585    // construction, so any mutation that deletes an arm, flips a
3586    // comparison, or changes a multiplier is caught.
3587
3588    // parse_byte_size: every unit produces the exact byte count ----
3589
3590    #[test]
3591    fn parse_byte_size_bare_number() {
3592        assert_eq!(parse_byte_size("0").unwrap(), 0);
3593        assert_eq!(parse_byte_size("1").unwrap(), 1);
3594        assert_eq!(parse_byte_size("100").unwrap(), 100);
3595        assert_eq!(parse_byte_size("1000000").unwrap(), 1_000_000);
3596    }
3597
3598    #[test]
3599    fn parse_byte_size_bytes_unit() {
3600        assert_eq!(parse_byte_size("0B").unwrap(), 0);
3601        assert_eq!(parse_byte_size("1B").unwrap(), 1);
3602        assert_eq!(parse_byte_size("42B").unwrap(), 42);
3603        // case insensitive
3604        assert_eq!(parse_byte_size("42b").unwrap(), 42);
3605    }
3606
3607    #[test]
3608    fn parse_byte_size_kilobyte_units() {
3609        assert_eq!(parse_byte_size("1KB").unwrap(), 1024);
3610        assert_eq!(parse_byte_size("1K").unwrap(), 1024);
3611        assert_eq!(parse_byte_size("2KB").unwrap(), 2048);
3612        assert_eq!(parse_byte_size("4K").unwrap(), 4096);
3613        // case insensitive
3614        assert_eq!(parse_byte_size("1kb").unwrap(), 1024);
3615        assert_eq!(parse_byte_size("1k").unwrap(), 1024);
3616    }
3617
3618    #[test]
3619    fn parse_byte_size_megabyte_units() {
3620        assert_eq!(parse_byte_size("1MB").unwrap(), 1024 * 1024);
3621        assert_eq!(parse_byte_size("1M").unwrap(), 1024 * 1024);
3622        assert_eq!(parse_byte_size("10MB").unwrap(), 10 * 1024 * 1024);
3623        // distinct from KB: pins the multiplier ratio
3624        assert_eq!(
3625            parse_byte_size("1MB").unwrap(),
3626            1024 * parse_byte_size("1KB").unwrap()
3627        );
3628    }
3629
3630    #[test]
3631    fn parse_byte_size_gigabyte_units() {
3632        assert_eq!(parse_byte_size("1GB").unwrap(), 1024 * 1024 * 1024);
3633        assert_eq!(parse_byte_size("1G").unwrap(), 1024 * 1024 * 1024);
3634        // distinct from MB: pins the multiplier ratio
3635        assert_eq!(
3636            parse_byte_size("1GB").unwrap(),
3637            1024 * parse_byte_size("1MB").unwrap()
3638        );
3639    }
3640
3641    #[test]
3642    fn parse_byte_size_all_units_are_distinct() {
3643        // Pins each unit's multiplier to catch mutations that swap arms
3644        // (e.g., KB → MB would make "1KB" and "1MB" equal).
3645        let b = parse_byte_size("1B").unwrap();
3646        let kb = parse_byte_size("1KB").unwrap();
3647        let mb = parse_byte_size("1MB").unwrap();
3648        let gb = parse_byte_size("1GB").unwrap();
3649        assert_eq!(b, 1);
3650        assert_eq!(kb, 1024);
3651        assert_eq!(mb, 1024 * kb);
3652        assert_eq!(gb, 1024 * mb);
3653        // And strict ordering
3654        assert!(b < kb);
3655        assert!(kb < mb);
3656        assert!(mb < gb);
3657    }
3658
3659    #[test]
3660    fn parse_byte_size_accepts_sizes_above_4gib() {
3661        // `usize` is 32 bits on i686/armv7; the log size limit must not be
3662        // bounded by it (#3604).
3663        assert_eq!(parse_byte_size("8GB").unwrap(), 8 << 30);
3664        assert_eq!(parse_byte_size("5000MB").unwrap(), 5000 << 20);
3665        assert_eq!(parse_byte_size("4294967296").unwrap(), 1 << 32);
3666        assert_eq!(parse_byte_size("4.5GB").unwrap(), 9 << 29);
3667    }
3668
3669    #[test]
3670    fn parse_byte_size_float_path() {
3671        // When the integer parse fails, fall back to float.
3672        assert_eq!(parse_byte_size("1.5KB").unwrap(), 1536);
3673        assert_eq!(parse_byte_size("0.5MB").unwrap(), 512 * 1024);
3674        assert_eq!(parse_byte_size("2.25KB").unwrap(), 2304);
3675    }
3676
3677    #[test]
3678    fn parse_byte_size_whitespace_tolerated() {
3679        assert_eq!(parse_byte_size(" 1KB ").unwrap(), 1024);
3680        assert_eq!(parse_byte_size("1 KB").unwrap(), 1024);
3681        assert_eq!(parse_byte_size("  1  KB  ").unwrap(), 1024);
3682    }
3683
3684    #[test]
3685    fn parse_byte_size_rejects_negative() {
3686        // A negative f64 cast to u64 saturates to 0, which would silently
3687        // disable a limit instead of being rejected (issue #2018).
3688        assert!(parse_byte_size("-1KB").is_err());
3689        assert!(parse_byte_size("-0.5MB").is_err());
3690        assert!(parse_byte_size("-1").is_err());
3691        assert!(parse_byte_size("-100").is_err());
3692    }
3693
3694    #[test]
3695    fn parse_byte_size_rejects_non_finite() {
3696        // inf/nan cast to u64 saturate (to u64::MAX / 0) rather than erroring.
3697        assert!(parse_byte_size("infKB").is_err());
3698        assert!(parse_byte_size("nanMB").is_err());
3699    }
3700
3701    #[test]
3702    fn parse_byte_size_rejects_unknown_unit() {
3703        assert!(parse_byte_size("1TB").is_err());
3704        assert!(parse_byte_size("1XB").is_err());
3705        assert!(parse_byte_size("1foo").is_err());
3706    }
3707
3708    #[test]
3709    fn parse_byte_size_rejects_integer_overflow() {
3710        // num fits in u64 but num * multiplier overflows; must not panic
3711        // (debug) or silently wrap (release).
3712        assert!(parse_byte_size("20000000000GB").is_err());
3713        assert!(parse_byte_size("18446744073709551615GB").is_err());
3714    }
3715
3716    #[test]
3717    fn parse_byte_size_rejects_float_overflow() {
3718        // num does not fit in u64 (so it takes the f64 path) and is finite and
3719        // positive, but num * multiplier exceeds u64::MAX. Casting the result
3720        // to u64 saturates to u64::MAX instead of erroring, so it must be
3721        // rejected up front rather than silently clamped.
3722        assert!(parse_byte_size("99999999999999999999GB").is_err());
3723        assert!(parse_byte_size("99999999999999999999.0GB").is_err());
3724        assert!(parse_byte_size("184467440737095516160B").is_err());
3725    }
3726
3727    #[test]
3728    fn parse_byte_size_rejects_invalid_number() {
3729        assert!(parse_byte_size("abc").is_err());
3730        assert!(parse_byte_size("abcKB").is_err());
3731        assert!(parse_byte_size("1.2.3KB").is_err());
3732    }
3733
3734    #[test]
3735    fn send_as_rejects_names_that_are_not_valid_output_ids() {
3736        for (field, value) in [
3737            ("send_stdout_as", "std out"),
3738            ("send_stdout_as", "out/"),
3739            ("send_logs_as", "\"\""),
3740            ("send_logs_as", "a//b"),
3741        ] {
3742            let yaml = format!(
3743                "nodes:\n  - id: talker\n    path: talker\n    {field}: {value}\n    outputs: [out]\n"
3744            );
3745            let descriptor: Descriptor = serde_yaml::from_str(&yaml).unwrap();
3746            let err = check_dataflow_static(&descriptor)
3747                .expect_err(&format!("`{field}: {value}` must be rejected"));
3748            assert!(
3749                format!("{err:?}").contains("is not a valid output id"),
3750                "unexpected error for `{field}: {value}`: {err:?}"
3751            );
3752        }
3753    }
3754
3755    #[test]
3756    fn send_as_rejects_empty_operator_entry() {
3757        let yaml = r#"
3758nodes:
3759  - id: rt
3760    operators:
3761      - id: op1
3762        python: op.py
3763        send_stdout_as: ""
3764        send_logs_as: ""
3765        outputs: [out]
3766"#;
3767        let descriptor: Descriptor = serde_yaml::from_str(yaml).unwrap();
3768        let nodes = descriptor.resolve_aliases_and_set_defaults().unwrap();
3769        let node = &nodes[&NodeId::from("rt".to_string())];
3770        assert!(node.send_stdout_as().is_err());
3771        assert!(node.send_logs_as().is_err());
3772    }
3773
3774    #[test]
3775    fn send_as_accepts_valid_names() {
3776        let yaml = r#"
3777nodes:
3778  - id: rt
3779    operators:
3780      - id: op1
3781        python: op.py
3782        send_stdout_as: stdout
3783        send_logs_as: logs
3784        outputs: [stdout, logs]
3785  - id: talker
3786    path: talker
3787    send_stdout_as: stdout
3788    send_logs_as: logs
3789    outputs: [stdout, logs]
3790"#;
3791        let descriptor: Descriptor = serde_yaml::from_str(yaml).unwrap();
3792        let nodes = descriptor.resolve_aliases_and_set_defaults().unwrap();
3793        let rt = &nodes[&NodeId::from("rt".to_string())];
3794        assert_eq!(rt.send_stdout_as().unwrap().as_deref(), Some("op1/stdout"));
3795        assert_eq!(rt.send_logs_as().unwrap().as_deref(), Some("op1/logs"));
3796        let talker = &nodes[&NodeId::from("talker".to_string())];
3797        assert_eq!(talker.send_stdout_as().unwrap().as_deref(), Some("stdout"));
3798        assert_eq!(talker.send_logs_as().unwrap().as_deref(), Some("logs"));
3799    }
3800
3801    // parse_log_level: every level variant ----
3802
3803    #[test]
3804    fn parse_log_level_all_levels() {
3805        use dora_message::common::LogLevelOrStdout;
3806
3807        assert!(matches!(
3808            parse_log_level("error").unwrap(),
3809            LogLevelOrStdout::LogLevel(log::Level::Error)
3810        ));
3811        assert!(matches!(
3812            parse_log_level("warn").unwrap(),
3813            LogLevelOrStdout::LogLevel(log::Level::Warn)
3814        ));
3815        assert!(matches!(
3816            parse_log_level("info").unwrap(),
3817            LogLevelOrStdout::LogLevel(log::Level::Info)
3818        ));
3819        assert!(matches!(
3820            parse_log_level("debug").unwrap(),
3821            LogLevelOrStdout::LogLevel(log::Level::Debug)
3822        ));
3823        assert!(matches!(
3824            parse_log_level("trace").unwrap(),
3825            LogLevelOrStdout::LogLevel(log::Level::Trace)
3826        ));
3827        assert!(matches!(
3828            parse_log_level("stdout").unwrap(),
3829            LogLevelOrStdout::Stdout
3830        ));
3831    }
3832
3833    #[test]
3834    fn parse_log_level_case_insensitive() {
3835        use dora_message::common::LogLevelOrStdout;
3836
3837        for variant in ["ERROR", "Error", "error", "ErRoR"] {
3838            assert!(matches!(
3839                parse_log_level(variant).unwrap(),
3840                LogLevelOrStdout::LogLevel(log::Level::Error)
3841            ));
3842        }
3843        for variant in ["STDOUT", "Stdout", "stdout"] {
3844            assert!(matches!(
3845                parse_log_level(variant).unwrap(),
3846                LogLevelOrStdout::Stdout
3847            ));
3848        }
3849    }
3850
3851    #[test]
3852    fn parse_log_level_rejects_unknown() {
3853        assert!(parse_log_level("").is_err());
3854        assert!(parse_log_level("INVALID").is_err());
3855        assert!(parse_log_level("fatal").is_err());
3856        assert!(parse_log_level("log").is_err());
3857    }
3858
3859    #[test]
3860    fn parse_log_level_error_message_lists_options() {
3861        let err = parse_log_level("bogus").unwrap_err().to_string();
3862        // The error message should name at least the valid options so
3863        // users can fix typos. Pinning this so the fmt::Display impl
3864        // used in the bail! macro stays informative.
3865        for expected in ["error", "warn", "info", "debug", "trace", "stdout"] {
3866            assert!(
3867                err.contains(expected),
3868                "expected '{expected}' to be mentioned in error, got: {err}"
3869            );
3870        }
3871    }
3872
3873    #[test]
3874    fn max_rotated_files_accepts_zero_and_still_caps_at_100() {
3875        let node = |n: u32| -> ResolvedNode {
3876            let mut custom = custom_node();
3877            custom.max_rotated_files = Some(n);
3878            ResolvedNode::new(NodeId::from("n".to_owned()), CoreNodeKind::Custom(custom))
3879        };
3880
3881        // 0 is a real configuration: keep the active log only, rotating the
3882        // previous one away. The documented disk bound
3883        // `max_log_size * (1 + max_rotated_files)` is one file at 0.
3884        assert_eq!(node(0).max_rotated_files().unwrap(), Some(0));
3885        // The upper bound is unchanged.
3886        assert_eq!(node(100).max_rotated_files().unwrap(), Some(100));
3887        assert!(node(101).max_rotated_files().is_err());
3888    }
3889}
3890
3891#[cfg(test)]
3892mod python_version_tests {
3893    use super::{VERSION, check_python_dora_version};
3894
3895    fn own() -> semver::Version {
3896        semver::Version::parse(VERSION).unwrap()
3897    }
3898
3899    #[test]
3900    fn accepts_the_wheels_that_the_handshake_accepts() {
3901        let own = own();
3902        let stable = format!("{}.{}.{}", own.major, own.minor, own.patch);
3903        for wheel in [
3904            VERSION.to_string(),
3905            stable.clone(),
3906            format!("{stable}-rc.99"),
3907            format!("{}.0.0", own.major),
3908            format!("{}.{}.0", own.major, own.minor + 1),
3909        ] {
3910            check_python_dora_version(&format!("{wheel}\n"))
3911                .unwrap_or_else(|error| panic!("{wheel} must be accepted: {error}"));
3912        }
3913    }
3914
3915    #[test]
3916    fn rejects_another_major_version() {
3917        for wheel in ["0.4.1".to_string(), format!("{}.0.0", own().major + 1)] {
3918            let error = check_python_dora_version(&wheel).unwrap_err().to_string();
3919            assert!(error.contains("is not compatible"), "{error}");
3920            assert!(error.contains("pip install dora-rs=="), "{error}");
3921        }
3922    }
3923
3924    #[test]
3925    fn reads_the_last_line_of_the_output() {
3926        let output = format!("printed while importing\r\n{VERSION}\r\n");
3927        check_python_dora_version(&output).unwrap();
3928    }
3929
3930    #[test]
3931    fn rejects_output_without_a_version() {
3932        for output in ["", "unknown"] {
3933            let error = format!("{:#}", check_python_dora_version(output).unwrap_err());
3934            assert!(error.contains("Could not read"), "{error}");
3935        }
3936    }
3937}
3938
3939/// Property-based tests for the pure parsing/validation helpers. These
3940/// complement the Kani proofs in `crate::metadata` — see
3941/// `docs/formal-verification.md` for how the tiers fit together.
3942#[cfg(test)]
3943mod proptest_properties {
3944    use super::{parse_byte_size, validate_ros2_name};
3945    use dora_message::id::NodeId;
3946    use proptest::prelude::*;
3947
3948    fn node_id() -> NodeId {
3949        NodeId::from("prop".to_owned())
3950    }
3951
3952    /// Strategy for ROS2 names that are valid by construction: optional
3953    /// leading '/', then '/'-separated tokens matching `[A-Za-z_][A-Za-z0-9_]*`.
3954    fn valid_ros2_name() -> impl Strategy<Value = String> {
3955        (
3956            any::<bool>(),
3957            prop::collection::vec("[A-Za-z_][A-Za-z0-9_]{0,8}", 1..4),
3958        )
3959            .prop_map(|(absolute, tokens)| {
3960                let joined = tokens.join("/");
3961                if absolute {
3962                    format!("/{joined}")
3963                } else {
3964                    joined
3965                }
3966            })
3967    }
3968
3969    proptest! {
3970        /// Total: never panics, whatever the input.
3971        #[test]
3972        fn ros2_name_validation_never_panics(name in ".{0,32}") {
3973            let _ = validate_ros2_name(&node_id(), "topic", &name);
3974        }
3975
3976        /// Completeness: structurally valid names are always accepted.
3977        #[test]
3978        fn ros2_name_accepts_valid_names(name in valid_ros2_name()) {
3979            prop_assert!(validate_ros2_name(&node_id(), "topic", &name).is_ok());
3980        }
3981
3982        /// Soundness: every accepted name satisfies all documented rules.
3983        ///
3984        /// The strategy samples from the valid alphabet plus a few
3985        /// near-miss characters ('.', '-', ' ') so that *accepted* names
3986        /// are common — a fully random unicode strategy would virtually
3987        /// never enter the accepted branch, making the property vacuous.
3988        #[test]
3989        fn ros2_name_accepted_implies_well_formed(name in "[a-zA-Z0-9_/. -]{0,16}") {
3990            if validate_ros2_name(&node_id(), "topic", &name).is_ok() {
3991                prop_assert!(!name.is_empty());
3992                prop_assert!(name.chars().all(|c| c.is_ascii_alphanumeric()
3993                    || c == '_'
3994                    || c == '/'));
3995                prop_assert!(!name.contains("//"));
3996                prop_assert!(!name.ends_with('/'));
3997                for (i, token) in name.split('/').enumerate() {
3998                    if i == 0 && token.is_empty() {
3999                        continue;
4000                    }
4001                    prop_assert!(!token.starts_with(|c: char| c.is_ascii_digit()));
4002                }
4003            }
4004        }
4005
4006        /// Total: never panics, whatever the input.
4007        #[test]
4008        fn byte_size_parsing_never_panics(s in ".{0,24}") {
4009            let _ = parse_byte_size(&s);
4010        }
4011
4012        /// Integer inputs with units multiply exactly (no float rounding)
4013        /// and overflow is reported as an error, never wrapped.
4014        #[test]
4015        fn byte_size_integer_units_are_exact(
4016            num in any::<u64>(),
4017            unit_idx in 0usize..7,
4018            lowercase in any::<bool>(),
4019        ) {
4020            // All unit spellings accepted by `parse_byte_size` (which also
4021            // uppercases, so lowercase forms must behave identically).
4022            let (unit, multiplier) =
4023                [("B", 1u64), ("KB", 1 << 10), ("K", 1 << 10), ("MB", 1 << 20),
4024                 ("M", 1 << 20), ("GB", 1 << 30), ("G", 1 << 30)][unit_idx];
4025            let unit = if lowercase { unit.to_lowercase() } else { unit.to_string() };
4026            match parse_byte_size(&format!("{num}{unit}")) {
4027                Ok(bytes) => prop_assert_eq!(Some(bytes), num.checked_mul(multiplier)),
4028                Err(_) => prop_assert!(num.checked_mul(multiplier).is_none()),
4029            }
4030        }
4031
4032        /// Bare integers parse to themselves.
4033        #[test]
4034        fn byte_size_bare_integer_is_identity(num in any::<u64>()) {
4035            prop_assert_eq!(parse_byte_size(&num.to_string()).unwrap(), num);
4036        }
4037
4038        /// The float fallback path is total for ordinary decimals: any
4039        /// simple non-negative decimal with a valid unit parses Ok.
4040        #[test]
4041        fn byte_size_fractional_inputs_parse(
4042            int_part in 0u32..1_000_000,
4043            frac in 0u32..100,
4044            unit_idx in 0usize..7,
4045        ) {
4046            let unit = ["B", "KB", "K", "MB", "M", "GB", "G"][unit_idx];
4047            let input = format!("{int_part}.{frac:02}{unit}");
4048            prop_assert!(parse_byte_size(&input).is_ok(), "failed to parse '{input}'");
4049        }
4050    }
4051}