dora-message 1.1.0

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

use aligned_vec::{AVec, ConstAlign};
use chrono::{DateTime, Utc};
use eyre::Context as _;
use serde::Deserialize;
use uuid::Uuid;

use crate::{BuildId, DataflowId, daemon_to_daemon::InterDaemonEvent, id::NodeId};

pub use log::Level as LogLevel;

/// A single log record delivered to `dora/logs` subscribers.
///
/// One of these is produced for every captured log line — a `tracing` event
/// from a dora component or a line a node wrote to stdout/stderr — and carries
/// both the message and the routing/provenance context a log consumer needs to
/// attribute it (which dataflow, node, and daemon it came from).
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq)]
#[must_use]
pub struct LogMessage {
    /// The build this record belongs to, when it originated during a build.
    pub build_id: Option<BuildId>,
    /// The dataflow the emitting component was part of, if any.
    pub dataflow_id: Option<DataflowId>,
    /// The node that emitted the record, if it came from a node.
    pub node_id: Option<NodeId>,
    /// The daemon that captured and forwarded the record.
    pub daemon_id: Option<DaemonId>,
    /// The severity, or [`LogLevelOrStdout::Stdout`] for a captured stdout line.
    pub level: LogLevelOrStdout,
    /// The `tracing` target (typically the emitting module path), when known.
    pub target: Option<String>,
    /// Source module path of the emitting code, when known.
    pub module_path: Option<String>,
    /// Source file of the emitting code, when known.
    pub file: Option<String>,
    /// Line within [`file`](Self::file) of the emitting code, when known.
    pub line: Option<u32>,
    /// The log text itself.
    pub message: String,
    /// When the record was produced.
    pub timestamp: DateTime<Utc>,
    /// Structured key/value fields attached to a `tracing` event, if any.
    pub fields: Option<BTreeMap<String, String>>,
}

#[derive(Deserialize)]
pub struct LogMessageHelper {
    build_id: Option<BuildId>,
    dataflow_id: Option<DataflowId>,
    node_id: Option<NodeId>,
    daemon_id: Option<DaemonId>,
    level: LogLevelOrStdout,
    target: Option<String>,
    module_path: Option<String>,
    file: Option<String>,
    line: Option<u32>,
    message: Option<String>,
    timestamp: DateTime<Utc>,
    fields: Option<BTreeMap<String, String>>,
}

impl From<LogMessageHelper> for LogMessage {
    fn from(helper: LogMessageHelper) -> Self {
        let fields = helper.fields.as_ref();
        // Use `or_else` throughout so each fallback (a `BTreeMap` lookup plus a
        // `String` clone, and sometimes a parse) is computed only when the
        // typed field is absent. `or` would evaluate every fallback eagerly and
        // discard it whenever the typed field is already `Some`.
        LogMessage {
            build_id: helper.build_id.or_else(|| {
                fields
                    .and_then(|f| f.get("build_id").cloned())
                    .and_then(|id| BuildId::from_display_str(&id))
            }),
            dataflow_id: helper.dataflow_id.or_else(|| {
                fields
                    .and_then(|f| f.get("dataflow_id").cloned())
                    .and_then(|id| Uuid::parse_str(&id).ok())
            }),
            node_id: helper.node_id.or_else(|| {
                fields
                    .and_then(|f| f.get("node_id").cloned())
                    .and_then(|id| id.parse::<NodeId>().ok())
            }),
            daemon_id: helper.daemon_id.or_else(|| {
                fields
                    .and_then(|f| f.get("daemon_id").cloned())
                    .and_then(|id| DaemonId::from_display_str(&id))
            }),
            level: helper.level,
            target: helper
                .target
                .or_else(|| fields.and_then(|f| f.get("target").cloned())),
            module_path: helper
                .module_path
                .or_else(|| fields.and_then(|f| f.get("module_path").cloned())),
            file: helper
                .file
                .or_else(|| fields.and_then(|f| f.get("file").cloned())),
            line: helper.line.or_else(|| {
                fields
                    .and_then(|f| f.get("line").cloned())
                    .and_then(|s| s.parse().ok())
            }),
            message: helper
                .message
                .or_else(|| fields.and_then(|f| f.get("message").cloned()))
                .unwrap_or_default(),
            fields: helper.fields,
            timestamp: helper.timestamp,
        }
    }
}

#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq, PartialOrd, Ord)]
#[serde(rename_all = "UPPERCASE")]
pub enum LogLevelOrStdout {
    #[serde(rename = "stdout")]
    Stdout,
    #[serde(untagged)]
    LogLevel(LogLevel),
}

impl LogLevelOrStdout {
    /// Returns true if a message at this level passes the given minimum level filter.
    ///
    /// `Stdout` is treated as a distinct channel rather than a severity, so it
    /// does not participate in the `Error < Warn < Info < Debug < Trace`
    /// ordering (where `Error` is the most severe and `Trace` the least):
    ///
    /// - A `Stdout` message passes only a `Stdout` filter; it is never
    ///   delivered to a severity filter.
    /// - A `LogLevel` message always passes a `Stdout` filter (the most
    ///   permissive), and passes a `LogLevel` filter `min` when its severity is
    ///   at least as severe as `min` (`msg <= min` in log-crate ordering).
    ///
    /// ```
    /// use dora_message::common::{LogLevel, LogLevelOrStdout};
    ///
    /// let stdout = LogLevelOrStdout::Stdout;
    /// let info = LogLevelOrStdout::LogLevel(LogLevel::Info);
    /// let error = LogLevelOrStdout::LogLevel(LogLevel::Error);
    ///
    /// // Severity: `Error` is more severe than `Info`, so it passes an `Info` filter...
    /// assert!(error.passes(&info));
    /// // ...while a less severe message is filtered out.
    /// assert!(!info.passes(&error));
    /// // A message passes a filter at its own level.
    /// assert!(info.passes(&info));
    ///
    /// // A `LogLevel` message always passes the (most permissive) `Stdout` filter,
    /// // but a `Stdout` message passes only a `Stdout` filter, never a severity one.
    /// assert!(info.passes(&stdout));
    /// assert!(stdout.passes(&stdout));
    /// assert!(!stdout.passes(&info));
    /// ```
    pub fn passes(&self, min: &LogLevelOrStdout) -> bool {
        match (self, min) {
            (LogLevelOrStdout::Stdout, LogLevelOrStdout::Stdout) => true,
            (LogLevelOrStdout::Stdout, _) => false,
            (LogLevelOrStdout::LogLevel(_), LogLevelOrStdout::Stdout) => true,
            (LogLevelOrStdout::LogLevel(msg), LogLevelOrStdout::LogLevel(max)) => msg <= max,
        }
    }
}

impl From<LogLevel> for LogLevelOrStdout {
    fn from(level: LogLevel) -> Self {
        Self::LogLevel(level)
    }
}

#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
pub struct NodeError {
    pub timestamp: uhlc::Timestamp,
    pub cause: NodeErrorCause,
    pub exit_status: NodeExitStatus,
}

impl std::fmt::Display for NodeError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if let NodeErrorCause::FailedToSpawn(err) = &self.cause {
            return write!(f, "failed to spawn node: {err}");
        }
        match &self.exit_status {
            NodeExitStatus::Success => write!(f, "<success>"),
            NodeExitStatus::IoError(err) => write!(f, "I/O error while reading exit status: {err}"),
            NodeExitStatus::ExitCode(code) => write!(f, "exited with code {code}"),
            NodeExitStatus::Signal(signal) => {
                let signal_str: Cow<_> = match signal {
                    1 => "SIGHUP".into(),
                    2 => "SIGINT".into(),
                    3 => "SIGQUIT".into(),
                    4 => "SIGILL".into(),
                    6 => "SIGABRT".into(),
                    8 => "SIGFPE".into(),
                    9 => "SIGKILL".into(),
                    11 => "SIGSEGV".into(),
                    13 => "SIGPIPE".into(),
                    14 => "SIGALRM".into(),
                    15 => "SIGTERM".into(),
                    22 => "SIGTTOU".into(),
                    23 => "SIGURG".into(),
                    other => other.to_string().into(),
                };
                if matches!(self.cause, NodeErrorCause::GraceDuration) {
                    write!(
                        f,
                        "node was killed by dora because it didn't react to a stop message in time ({signal_str})"
                    )
                } else {
                    write!(f, "exited because of signal {signal_str}")
                }
            }
            NodeExitStatus::Unknown => write!(f, "unknown exit status"),
        }?;

        match &self.cause {
            NodeErrorCause::GraceDuration => {} // handled above
            NodeErrorCause::Cascading { caused_by_node } => write!(
                f,
                ". This error occurred because node `{caused_by_node}` exited before connecting to dora."
            )?,
            // Rendered by the early return at the top of this function. Render
            // it here too rather than `unreachable!()`: a `Display` impl must
            // never panic (it runs implicitly on every log/`to_string()` of a
            // `NodeError`, including on shutdown paths), and nothing structural
            // ties this arm to that distant early return.
            NodeErrorCause::FailedToSpawn(err) => write!(f, "failed to spawn node: {err}")?,
            NodeErrorCause::Other { stderr } if stderr.is_empty() => {}
            NodeErrorCause::Other { stderr } => {
                let line: &str = "---------------------------------------------------------------------------------\n";
                let stderr = stderr.trim_end();
                write!(f, " with stderr output:\n{line}{stderr}\n{line}")?
            }
        }

        Ok(())
    }
}

#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
pub enum NodeErrorCause {
    /// Node was killed because it didn't react to a stop message in time.
    GraceDuration,
    /// Node failed because another node failed before,
    Cascading {
        caused_by_node: NodeId,
    },
    FailedToSpawn(String),
    Other {
        stderr: String,
    },
}

/// How a node process ended.
///
/// Built from the node process's [`ExitStatus`](std::process::ExitStatus) (see
/// the [`From`] impl), so it distinguishes a clean exit, a non-zero exit code,
/// a killing signal (Unix), and the case where the daemon could not even wait
/// on the process ([`IoError`](Self::IoError)).
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
pub enum NodeExitStatus {
    /// The process exited successfully (exit code 0).
    Success,
    /// The daemon failed to launch or wait on the process.
    IoError(String),
    /// The process exited with this non-zero code.
    ExitCode(i32),
    /// The process was terminated by this signal (Unix only).
    Signal(i32),
    /// The process ended in a way that is neither a code nor a signal.
    Unknown,
}

impl NodeExitStatus {
    /// Whether the node exited cleanly (i.e. this is [`Success`](Self::Success)).
    ///
    /// ```
    /// use dora_message::common::NodeExitStatus;
    ///
    /// assert!(NodeExitStatus::Success.is_success());
    /// assert!(!NodeExitStatus::ExitCode(1).is_success());
    /// ```
    pub fn is_success(&self) -> bool {
        matches!(self, NodeExitStatus::Success)
    }
}

impl From<Result<std::process::ExitStatus, std::io::Error>> for NodeExitStatus {
    fn from(result: Result<std::process::ExitStatus, std::io::Error>) -> Self {
        match result {
            Ok(status) => {
                if status.success() {
                    NodeExitStatus::Success
                } else if let Some(code) = status.code() {
                    Self::ExitCode(code)
                } else {
                    #[cfg(unix)]
                    {
                        use std::os::unix::process::ExitStatusExt;
                        if let Some(signal) = status.signal() {
                            return Self::Signal(signal);
                        }
                    }
                    Self::Unknown
                }
            }
            Err(err) => Self::IoError(err.to_string()),
        }
    }
}

#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct Timestamped<T> {
    pub inner: T,
    pub timestamp: uhlc::Timestamp,
}

impl Timestamped<InterDaemonEvent> {
    /// Encode this event for the zenoh data plane and `dora record` files.
    pub fn serialize(&self) -> eyre::Result<Vec<u8>> {
        crate::encode_presized(self, self.inner.encode_size_hint())
            .wrap_err("failed to serialize timestamped message")
    }

    pub fn deserialize_inter_daemon_event(bytes: &[u8]) -> eyre::Result<Self> {
        crate::decode(bytes).wrap_err("failed to deserialize InterDaemonEvent")
    }
}

pub type SharedMemoryId = String;

#[derive(serde::Serialize, serde::Deserialize, Clone)]
pub enum DataMessage {
    Vec(#[serde(with = "crate::bulk_bytes")] AVec<u8, ConstAlign<128>>),
}

impl DataMessage {
    /// Byte length of the carried payload.
    pub fn len(&self) -> usize {
        match self {
            Self::Vec(v) => v.len(),
        }
    }

    /// Whether the carried payload is empty (zero bytes).
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }
}

impl fmt::Debug for DataMessage {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Vec(_) => f
                .debug_struct("Vec")
                .field("len", &self.len())
                .finish_non_exhaustive(),
        }
    }
}

/// Identity of a running daemon: an optional operator-supplied machine id
/// paired with a per-process time-ordered UUIDv7.
///
/// The machine id (typically a hostname) makes the [`Display`](std::fmt::Display)
/// form human-readable and lets the coordinator route by machine, while the UUID
/// keeps the id unique even when two daemons share a machine id (or none is set).
/// The `Display` form is `"{machine_id}-{uuid}"`, or a bare `"{uuid}"` when there
/// is no machine id; [`from_display_str`](Self::from_display_str) is its inverse.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, serde::Serialize, serde::Deserialize)]
pub struct DaemonId {
    machine_id: Option<String>,
    uuid: Uuid,
}

impl DaemonId {
    /// Create a fresh daemon id for the given machine, assigning a new
    /// time-ordered UUIDv7. Pass `None` when no machine id is configured.
    pub fn new(machine_id: Option<String>) -> Self {
        DaemonId {
            machine_id,
            uuid: Uuid::now_v7(),
        }
    }

    /// Whether this daemon was created with exactly the given machine id.
    ///
    /// Always `false` for a daemon created without a machine id.
    pub fn matches_machine_id(&self, machine_id: &str) -> bool {
        self.machine_id
            .as_ref()
            .map(|id| id == machine_id)
            .unwrap_or_default()
    }

    /// The machine id this daemon was created with, or `None` if none was set.
    pub fn machine_id(&self) -> Option<&str> {
        self.machine_id.as_deref()
    }

    /// Reverse of [`Display`](std::fmt::Display): parse `"{machine_id}-{uuid}"`, or a bare
    /// `"{uuid}"` when there is no machine id.
    ///
    /// Both the machine id (hostnames) and the canonical UUID contain `-`, so
    /// splitting on a hyphen drops or corrupts a hyphenated machine id. Split
    /// off the fixed-width 36-char canonical UUID suffix instead
    /// (dora-rs/dora#2027).
    ///
    /// Expects exact `Display` output (no surrounding whitespace). The
    /// machine-id path requires the canonical 36-char UUID suffix that
    /// `Display` emits; the bare path accepts any form `Uuid::parse_str`
    /// recognizes (canonical / simple / urn / braced).
    ///
    /// ```
    /// use dora_message::common::DaemonId;
    ///
    /// // A hyphenated machine id round-trips through `Display` (dora-rs/dora#2027)...
    /// let id = DaemonId::new(Some("my-host".to_string()));
    /// assert_eq!(DaemonId::from_display_str(&id.to_string()), Some(id.clone()));
    /// assert_eq!(id.machine_id(), Some("my-host"));
    /// assert!(id.matches_machine_id("my-host"));
    ///
    /// // ...as does a daemon with no machine id (a bare UUID).
    /// let anon = DaemonId::new(None);
    /// assert_eq!(DaemonId::from_display_str(&anon.to_string()), Some(anon.clone()));
    /// assert_eq!(anon.machine_id(), None);
    ///
    /// // Garbage does not parse to a bogus id.
    /// assert_eq!(DaemonId::from_display_str("not-a-daemon-id"), None);
    /// ```
    pub fn from_display_str(s: &str) -> Option<Self> {
        // No machine id: the whole string is the UUID.
        if let Ok(uuid) = Uuid::parse_str(s) {
            return Some(DaemonId {
                machine_id: None,
                uuid,
            });
        }
        // `Display` writes the UUID via `{}` (canonical 36-char hyphenated
        // form), preceded by `"{machine_id}-"`.
        const UUID_LEN: usize = 36;
        let split = s.len().checked_sub(UUID_LEN)?;
        let uuid = Uuid::parse_str(s.get(split..)?).ok()?;
        let machine_id = s.get(..split)?.strip_suffix('-')?;
        Some(DaemonId {
            machine_id: Some(machine_id.to_string()),
            uuid,
        })
    }
}

impl std::fmt::Display for DaemonId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if let Some(id) = &self.machine_id {
            write!(f, "{id}-")?;
        }
        write!(f, "{}", self.uuid)
    }
}

#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, PartialEq, Eq)]
pub struct GitSource {
    pub repo: String,
    pub commit_hash: String,
    /// Subdirectory of the repository the node lives in (monorepo support).
    /// Build, env preparation, and spawn are rooted at `<clone>/<subdir>`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub subdir: Option<String>,
    /// Hub provenance marker. Set when this git source was desugared from a
    /// `hub:` reference — it tells the daemon to use confined path
    /// resolution (no ambient `$PATH` fallback) for the node, and feeds the
    /// lockfile and `dora hub` commands.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub hub: Option<HubProvenance>,
}

/// Identity of the hub package a git source was resolved from.
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, PartialEq, Eq)]
pub struct HubProvenance {
    /// Index key (`namespace/name`).
    pub name: String,
    /// Resolved version.
    pub version: String,
    /// Digest of the index entry's manifest at lock time. The commit hash pins
    /// the *source tree*, but the entrypoint, build command, and typed contract
    /// (inputs/outputs/types) all live in the (mutable) index entry — so a
    /// rewritten entry could change any of them for an already-pinned version.
    /// `--locked` hard-errors if this digest no longer matches. `Option` for
    /// back-compat with lockfiles written before this field existed.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub manifest_digest: Option<String>,
}

/// Lockfile pin for a `hub:` node resolved to a prebuilt binary artifact
/// (spec §8.2). Mirrors [`GitSource`] for the binary source form: the
/// `url`+`sha256` pin the bytes (re-verified on download), and `hub` records
/// the package/version/manifest provenance for `--locked` tamper detection.
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, PartialEq, Eq)]
pub struct BinaryPin {
    /// Platform the artifact was selected for at lock time (`<os>-<arch>`).
    pub platform: String,
    /// Download URL of the prebuilt artifact.
    pub url: String,
    /// SHA-256 the download must match.
    pub sha256: String,
    /// Hub provenance (index key, version, manifest digest).
    pub hub: HubProvenance,
}

// Test roundtrip serialization of LogMessage
#[cfg(test)]
mod tests {
    use super::*;

    fn node_error_with_signal(signal: i32) -> NodeError {
        NodeError {
            timestamp: uhlc::HLC::default().new_timestamp(),
            cause: NodeErrorCause::Other {
                stderr: String::new(),
            },
            exit_status: NodeExitStatus::Signal(signal),
        }
    }

    #[test]
    fn node_error_signal_display_uses_linux_signal_names() {
        for (signal, name) in [(6, "SIGABRT"), (22, "SIGTTOU"), (23, "SIGURG")] {
            assert_eq!(
                node_error_with_signal(signal).to_string(),
                format!("exited because of signal {name}")
            );
        }
    }

    #[test]
    fn node_error_signal_display_falls_back_to_signal_number() {
        assert_eq!(
            node_error_with_signal(40).to_string(),
            "exited because of signal 40"
        );
    }

    #[test]
    fn test_log_message_serialization() {
        let log_message = LogMessage {
            build_id: Some(BuildId(Uuid::new_v4())),
            dataflow_id: Some(DataflowId::from(Uuid::new_v4())),
            node_id: Some(NodeId("node-1".to_string())),
            daemon_id: Some(DaemonId::new(Some("machine-1".to_string()))),
            level: LogLevelOrStdout::LogLevel(LogLevel::Info),
            target: Some("target".to_string()),
            module_path: Some("module::path".to_string()),
            file: Some("file.rs".to_string()),
            line: Some(42),
            message: "This is a log message".to_string(),
            timestamp: Utc::now(),
            fields: Some(BTreeMap::from([("key".to_string(), "value".to_string())])),
        };
        let serialized = serde_yaml::to_string(&log_message).unwrap();
        let deserialized: LogMessageHelper = serde_yaml::from_str(&serialized).unwrap();
        assert_eq!(log_message, LogMessage::from(deserialized));
    }

    #[test]
    fn stdout_passes_stdout_filter() {
        let stdout = LogLevelOrStdout::Stdout;
        assert!(stdout.passes(&LogLevelOrStdout::Stdout));
    }

    /// A `node_id` recovered from the untrusted `fields` map must go through
    /// `NodeId` validation. It was previously wrapped via the raw tuple
    /// constructor (`.map(NodeId)`), bypassing `validate_node_id` and yielding
    /// a `NodeId` that could contain `/` or dot-segments -- the very
    /// path-traversal characters the newtype exists to forbid. Every other
    /// field recovered here (`build_id`, `dataflow_id`, `daemon_id`) already
    /// parses defensively; `node_id` was the odd one out.
    #[test]
    fn node_id_recovered_from_fields_is_validated() {
        let make = |node_id: &str| LogMessageHelper {
            build_id: None,
            dataflow_id: None,
            node_id: None,
            daemon_id: None,
            level: LogLevelOrStdout::Stdout,
            target: None,
            module_path: None,
            file: None,
            line: None,
            message: Some("m".to_string()),
            timestamp: Utc::now(),
            fields: Some(BTreeMap::from([(
                "node_id".to_string(),
                node_id.to_string(),
            )])),
        };

        // A valid id is promoted to the typed field.
        assert_eq!(
            LogMessage::from(make("sensor")).node_id,
            Some("sensor".parse().unwrap())
        );

        // Invalid ids (path separator / dot-segment) are rejected rather than
        // silently wrapped into an unvalidated NodeId.
        assert_eq!(LogMessage::from(make("a/b")).node_id, None);
        assert_eq!(LogMessage::from(make("../evil")).node_id, None);
    }

    /// A `build_id` back-filled from the `fields` map must survive a
    /// `Display` round trip. `BuildId`'s `Display` wraps the UUID as
    /// `BuildId(<uuid>)` -- the exact string emitted by the idiomatic
    /// `tracing::info!(build_id = %build_id, ...)` (e.g. the coordinator's
    /// build warnings). Recovery previously used `Uuid::parse_str`, which
    /// rejects that wrapper and silently dropped the id; it now goes through
    /// `BuildId::from_display_str`, matching how `daemon_id` is recovered.
    #[test]
    fn build_id_recovered_from_fields_survives_display_round_trip() {
        let build_id = BuildId(Uuid::new_v4());
        let make = |value: &str| LogMessageHelper {
            build_id: None,
            dataflow_id: None,
            node_id: None,
            daemon_id: None,
            level: LogLevelOrStdout::Stdout,
            target: None,
            module_path: None,
            file: None,
            line: None,
            message: Some("m".to_string()),
            timestamp: Utc::now(),
            fields: Some(BTreeMap::from([(
                "build_id".to_string(),
                value.to_string(),
            )])),
        };

        // The `Display` form (`BuildId(<uuid>)`) is recovered...
        assert_eq!(
            LogMessage::from(make(&build_id.to_string())).build_id,
            Some(build_id)
        );
        // ...and a bare UUID still works, for backward compatibility.
        assert_eq!(
            LogMessage::from(make(&build_id.uuid().to_string())).build_id,
            Some(build_id)
        );
        // Garbage is rejected rather than wrapped into a bogus id.
        assert_eq!(LogMessage::from(make("not-a-build-id")).build_id, None);
    }

    /// #2027: `DaemonId` must survive a `Display` -> `from_display_str` round
    /// trip even when the machine id contains `-` (hostnames do). The old
    /// `splitn(2, '-')` parse split on the first hyphen, which corrupted the
    /// UUID (itself hyphenated) and silently dropped the daemon id.
    #[test]
    fn daemon_id_display_roundtrips_through_parse() {
        let uuid = Uuid::new_v4();
        for machine in [None, Some("host"), Some("my-host"), Some("a-b-c-d")] {
            let id = DaemonId {
                machine_id: machine.map(str::to_string),
                uuid,
            };
            let parsed = DaemonId::from_display_str(&id.to_string())
                .unwrap_or_else(|| panic!("failed to parse {id}"));
            assert_eq!(parsed, id, "round-trip failed for machine_id={machine:?}");
        }
    }

    /// A bare (machine-id-less) daemon id round-trips, and garbage does not
    /// parse to a bogus id.
    #[test]
    fn daemon_id_parse_edge_cases() {
        let uuid = Uuid::new_v4();
        let bare = DaemonId {
            machine_id: None,
            uuid,
        };
        assert_eq!(DaemonId::from_display_str(&bare.to_string()), Some(bare));
        assert_eq!(DaemonId::from_display_str("not-a-daemon-id"), None);
        assert_eq!(DaemonId::from_display_str(""), None);
    }

    #[test]
    fn stdout_fails_non_stdout_filters() {
        let stdout = LogLevelOrStdout::Stdout;
        assert!(!stdout.passes(&LogLevelOrStdout::LogLevel(LogLevel::Info)));
        assert!(!stdout.passes(&LogLevelOrStdout::LogLevel(LogLevel::Warn)));
        assert!(!stdout.passes(&LogLevelOrStdout::LogLevel(LogLevel::Error)));
    }

    #[test]
    fn any_log_level_passes_stdout_filter() {
        let stdout_filter = LogLevelOrStdout::Stdout;
        for level in [
            LogLevel::Error,
            LogLevel::Warn,
            LogLevel::Info,
            LogLevel::Debug,
            LogLevel::Trace,
        ] {
            assert!(
                LogLevelOrStdout::LogLevel(level).passes(&stdout_filter),
                "{level:?} should pass stdout filter"
            );
        }
    }

    #[test]
    fn error_passes_less_verbose_filters() {
        let error = LogLevelOrStdout::LogLevel(LogLevel::Error);
        assert!(error.passes(&LogLevelOrStdout::LogLevel(LogLevel::Error)));
        assert!(error.passes(&LogLevelOrStdout::LogLevel(LogLevel::Warn)));
        assert!(error.passes(&LogLevelOrStdout::LogLevel(LogLevel::Info)));
    }

    #[test]
    fn debug_fails_info_filter() {
        let debug = LogLevelOrStdout::LogLevel(LogLevel::Debug);
        assert!(!debug.passes(&LogLevelOrStdout::LogLevel(LogLevel::Info)));
    }

    #[test]
    fn same_level_passes_itself() {
        for level in [
            LogLevel::Error,
            LogLevel::Warn,
            LogLevel::Info,
            LogLevel::Debug,
            LogLevel::Trace,
        ] {
            let l = LogLevelOrStdout::LogLevel(level);
            assert!(l.passes(&l), "{level:?} should pass itself");
        }
    }

    #[test]
    fn trace_passes_trace_fails_debug() {
        let trace = LogLevelOrStdout::LogLevel(LogLevel::Trace);
        assert!(trace.passes(&LogLevelOrStdout::LogLevel(LogLevel::Trace)));
        assert!(!trace.passes(&LogLevelOrStdout::LogLevel(LogLevel::Debug)));
    }

    #[test]
    fn daemon_id_uses_v7_uuid() {
        let id = DaemonId::new(None);
        // v7 UUIDs have version nibble = 7
        assert_eq!(id.uuid.get_version_num(), 7);
    }
}