dora-coordinator 1.0.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
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
use crate::{log_subscriber::LogSubscriber, topic_subscriber::TopicSubscriber};
use dora_coordinator_store::{CoordinatorStore, DataflowRecord, DataflowStatus};
use dora_core::config::NodeId;
use dora_message::{
    common::DaemonId,
    coordinator_to_cli::{ControlRequestReply, LogMessage},
    coordinator_to_daemon::{StateCatchUpEntry, StateCatchUpOperation},
    daemon_to_coordinator::{FaultToleranceSnapshot, NodeMetrics},
    descriptor::{Descriptor, ResolvedNode},
};
use eyre::eyre;
use std::collections::{BTreeMap, BTreeSet, HashMap};
use std::sync::Arc;
use std::time::Instant;
use tokio::sync::{Mutex, mpsc, oneshot};
use uuid::Uuid;

/// A deferred restart: the coordinator has sent `StopDataflow` and is waiting
/// for all daemons to confirm the dataflow has actually finished before starting
/// the replacement. Avoids the race where new nodes spawn before old nodes'
/// Zenoh subscribers/declarations are torn down (dora-rs/dora#2082).
pub(crate) struct PendingRestart {
    pub descriptor: Descriptor,
    pub name: Option<String>,
    pub uv: bool,
    pub reply_sender: oneshot::Sender<eyre::Result<ControlRequestReply>>,
}

#[derive(Default)]
pub(crate) struct DaemonConnections {
    daemons: BTreeMap<DaemonId, DaemonConnection>,
}

impl DaemonConnections {
    pub(crate) fn add(&mut self, daemon_id: DaemonId, connection: DaemonConnection) {
        let previous = self.daemons.insert(daemon_id.clone(), connection);
        if previous.is_some() {
            tracing::info!("closing previous connection `{daemon_id}` on new register");
        }
    }

    pub(crate) fn get_mut(&mut self, id: &DaemonId) -> Option<&mut DaemonConnection> {
        self.daemons.get_mut(id)
    }

    pub(crate) fn get_matching_daemon_id(&self, machine_id: &str) -> Option<&DaemonId> {
        self.daemons
            .keys()
            .find(|id| id.matches_machine_id(machine_id))
    }

    /// Whether the given daemon advertised support for hub-sourced git nodes
    /// (`subdir` / `hub` provenance, P2.10). Unknown daemon → `false`.
    pub(crate) fn supports_hub_sources(&self, id: &DaemonId) -> bool {
        self.daemons.get(id).is_some_and(|c| c.supports_hub_sources)
    }

    pub(crate) fn drain(&mut self) -> impl Iterator<Item = (DaemonId, DaemonConnection)> {
        std::mem::take(&mut self.daemons).into_iter()
    }

    pub(crate) fn is_empty(&self) -> bool {
        self.daemons.is_empty()
    }

    pub(crate) fn iter_mut(&mut self) -> impl Iterator<Item = (&DaemonId, &mut DaemonConnection)> {
        self.daemons.iter_mut()
    }

    pub(crate) fn remove(&mut self, daemon_id: &DaemonId) -> Option<DaemonConnection> {
        self.daemons.remove(daemon_id)
    }

    /// Returns the `connection_id` of the currently-registered connection for
    /// `daemon_id`, or `None` if the daemon is not connected.
    pub(crate) fn connection_id_of(&self, daemon_id: &DaemonId) -> Option<Uuid> {
        self.daemons.get(daemon_id).map(|c| c.connection_id)
    }

    /// Zenoh endpoints of every connected daemon except `joining`, for a
    /// daemon that is registering now to dial.
    ///
    /// `joining` is excluded so a re-registering daemon is not told to dial
    /// its own previous listener: `add` has not replaced its entry yet at the
    /// point the register reply is built, and that endpoint is either its own
    /// (a self-dial) or dead (the process restarted with a fresh ephemeral
    /// port).
    pub(crate) fn zenoh_endpoints_for(&self, joining: &DaemonId) -> Vec<String> {
        self.daemons
            .iter()
            .filter(|(id, _)| *id != joining)
            .filter_map(|(_, conn)| conn.zenoh_listen_endpoint.clone())
            .collect()
    }

    /// Record (or, with `None`, withdraw) a daemon's zenoh endpoint after it
    /// verified its listener. Unknown daemon → no-op.
    pub(crate) fn set_zenoh_endpoint(&mut self, id: &DaemonId, endpoint: Option<String>) {
        if let Some(conn) = self.daemons.get_mut(id) {
            conn.zenoh_listen_endpoint = endpoint;
        }
    }

    pub(crate) fn unnamed(&self) -> impl Iterator<Item = &DaemonId> {
        self.daemons.keys().filter(|id| id.machine_id().is_none())
    }

    /// Find the first daemon whose labels are a superset of `required`.
    pub(crate) fn get_matching_daemon_by_labels(
        &self,
        required: &BTreeMap<String, String>,
    ) -> Option<&DaemonId> {
        self.daemons.iter().find_map(|(id, conn)| {
            let all_match = required.iter().all(|(k, v)| conn.labels.get(k) == Some(v));
            if all_match { Some(id) } else { None }
        })
    }
}

#[derive(Clone)]
pub(crate) struct DaemonConnection {
    pub(crate) sender: mpsc::Sender<String>,
    /// Shared with the ws_daemon handler task to resolve correlation-based replies.
    pub(crate) pending_replies: Arc<Mutex<HashMap<Uuid, oneshot::Sender<String>>>>,
    /// The daemon's WS peer address as seen by the coordinator (set at
    /// registration). Lets other daemons reach this daemon's direct-TCP
    /// memory-pool data listener.
    pub(crate) peer_addr: Option<std::net::SocketAddr>,
    pub(crate) last_heartbeat: Instant,
    pub(crate) labels: BTreeMap<String, String>,
    /// Latest fault tolerance stats from this daemon (updated on each heartbeat).
    pub(crate) ft_stats: Option<FaultToleranceSnapshot>,
    /// Whether this daemon can build/spawn hub-sourced git nodes (`subdir` /
    /// `hub` provenance, P2.10). Reported at registration; defaults `false`
    /// for a daemon too old to advertise it, so the coordinator can refuse to
    /// route a hub node to it with a clear error.
    pub(crate) supports_hub_sources: bool,
    /// Unique ID for this connection instance. Used to distinguish a stale
    /// connection's `DaemonExit` from a freshly re-registered connection
    /// that reused the same `DaemonId` (daemon reconnect race, #2392).
    pub(crate) connection_id: Uuid,
    /// The zenoh endpoint this daemon reported as bound, handed to daemons
    /// that register later so they can dial it.
    ///
    /// `None` until the daemon reports one, and it only reports a listener it
    /// verified as bound — so an entry here always has something behind it.
    /// Lives on the connection rather than in a side map so it is pruned with
    /// the connection: a daemon that dropped must not keep being advertised,
    /// and a restarted one replaces its own stale entry on re-register.
    pub(crate) zenoh_listen_endpoint: Option<String>,
}

/// The envelope `handle_daemon_response` (see `ws_daemon.rs`) produces when a
/// daemon replies with a WS-level `error` instead of a result. `deny_unknown_fields`
/// keeps it from ever matching a real `DaemonCoordinatorReply` payload.
#[derive(serde::Deserialize)]
#[serde(deny_unknown_fields)]
struct WsErrorEnvelope {
    ws_error: String,
}

impl DaemonConnection {
    pub(crate) fn new(
        sender: mpsc::Sender<String>,
        pending_replies: Arc<Mutex<HashMap<Uuid, oneshot::Sender<String>>>>,
        labels: BTreeMap<String, String>,
    ) -> Self {
        Self {
            sender,
            pending_replies,
            peer_addr: None,
            last_heartbeat: Instant::now(),
            labels,
            ft_stats: None,
            // set from the register request at the real registration site;
            // conservative default keeps non-registration constructors safe
            supports_hub_sources: false,
            connection_id: Uuid::new_v4(),
            zenoh_listen_endpoint: None,
        }
    }

    /// Maximum number of in-flight requests per daemon WebSocket connection.
    ///
    /// `pending_replies` is an `Arc<Mutex<_>>` shared by every
    /// `DaemonConnection` clone, so this cap is enforced globally across all
    /// clones of one connection rather than independently per clone.
    const MAX_PENDING_REPLIES: usize = 256;

    /// Send a message to the daemon and wait for a reply.
    ///
    /// `message` is already-serialized JSON, so it is embedded into the envelope
    /// verbatim rather than re-parsed into a `serde_json::Value` first.
    pub(crate) async fn send_and_receive(&self, message: &[u8]) -> eyre::Result<Vec<u8>> {
        let id = Uuid::new_v4();
        let params_str =
            std::str::from_utf8(message).map_err(|e| eyre!("outgoing message not UTF-8: {e}"))?;
        let json = format!(r#"{{"id":"{id}","method":"daemon_command","params":{params_str}}}"#);

        let (reply_tx, reply_rx) = oneshot::channel();
        {
            let mut pending = self.pending_replies.lock().await;
            if pending.len() >= Self::MAX_PENDING_REPLIES {
                return Err(eyre!(
                    "too many pending daemon replies ({}), refusing new request",
                    pending.len()
                ));
            }
            pending.insert(id, reply_tx);
        }

        if self.sender.send(json).await.is_err() {
            // The send failed, so no reply will ever arrive for `id`. Remove the
            // pending entry we just inserted; otherwise it lingers in the map
            // until the connection is dropped, needlessly consuming one of the
            // `MAX_PENDING_REPLIES` slots. Mirrors the cleanup in the timeout
            // arm below.
            self.pending_replies.lock().await.remove(&id);
            return Err(eyre!("WS daemon send channel closed"));
        }

        let response_json =
            match tokio::time::timeout(dora_message::TCP_READ_TIMEOUT, reply_rx).await {
                Ok(result) => result.map_err(|_| eyre!("daemon WS reply channel dropped"))?,
                Err(_) => {
                    self.pending_replies.lock().await.remove(&id);
                    return Err(eyre!("timeout waiting for daemon WS reply"));
                }
            };

        // A WS-level failure on the daemon side arrives as a `{"ws_error": ...}`
        // envelope (see `handle_daemon_response` in `ws_daemon.rs`). It matches
        // no `DaemonCoordinatorReply` variant, so returning it verbatim would
        // make every caller fail with an opaque "failed to deserialize ... reply"
        // and drop the daemon's real error text (it would survive only in a log
        // line). Surface it as an `Err` carrying that text instead.
        if let Ok(WsErrorEnvelope { ws_error }) =
            serde_json::from_str::<WsErrorEnvelope>(&response_json)
        {
            return Err(eyre!("daemon returned error: {ws_error}"));
        }

        Ok(response_json.into_bytes())
    }

    /// Send a message to the daemon without waiting for a reply (fire-and-forget).
    ///
    /// `message` is already-serialized JSON, so it is embedded into the envelope
    /// verbatim rather than re-parsed into a `serde_json::Value` first.
    pub(crate) async fn send(&self, message: &[u8]) -> eyre::Result<()> {
        let params_str =
            std::str::from_utf8(message).map_err(|e| eyre!("outgoing message not UTF-8: {e}"))?;
        let id = Uuid::new_v4();
        let json = format!(r#"{{"id":"{id}","method":"daemon_event","params":{params_str}}}"#);
        self.sender
            .send(json)
            .await
            .map_err(|_| eyre!("WS daemon send channel closed"))
    }
}

pub(crate) struct RunningBuild {
    pub(crate) errors: Vec<String>,
    pub(crate) build_result: CachedResult,

    /// Buffer for log messages that were sent before there were any subscribers.
    pub(crate) buffered_log_messages: Vec<LogMessage>,
    pub(crate) log_subscribers: Vec<LogSubscriber>,

    pub(crate) pending_build_results: BTreeSet<DaemonId>,

    /// Coordinator-local timestamp captured when this `RunningBuild` was
    /// constructed (i.e. just after the per-daemon `TriggerBuild` dispatch).
    /// Used by the heartbeat-driven watchdog to detect distributed builds
    /// that have been pending past `BUILD_RESULT_TIMEOUT` so `wait_for_build`
    /// waiters can be released with a clear error instead of hanging on the
    /// client-side RPC deadline. Mirrors `RunningDataflow::spawn_started_at`
    /// (#1465).
    pub(crate) build_started_at: Instant,
}

pub(crate) struct RunningDataflow {
    pub(crate) name: Option<String>,
    pub(crate) uuid: Uuid,
    pub(crate) descriptor: Descriptor,
    /// The IDs of the daemons that the dataflow is running on.
    pub(crate) daemons: BTreeSet<DaemonId>,
    /// IDs of daemons that are waiting until all nodes are started.
    pub(crate) pending_daemons: BTreeSet<DaemonId>,
    pub(crate) exited_before_subscribe: Vec<NodeId>,
    /// Whether the ready barrier has already been broadcast for this
    /// dataflow.
    ///
    /// The broadcast goes to `daemons` at the moment it fires, so a daemon
    /// that is disconnected then never receives it — and nothing replays it
    /// on reconnect, leaving every node it owns parked in `init_from_env()`
    /// forever (dora-rs/dora#2998). Remembering the release lets the
    /// reconnect path re-send it to just that daemon.
    ///
    /// Mirrored into the persisted record (`make_record`) and restored by
    /// [`RunningDataflow::recovered`], because this entry does not survive
    /// orphan reclaim or a coordinator restart. It cannot be left in memory
    /// only and reconstructed later from a fresh `ReadyOnDaemon`: the daemon
    /// never sends one, since `PendingNodes::reported_init_to_coordinator` is
    /// set once and never reset.
    pub(crate) ready_barrier_released: bool,
    pub(crate) nodes: BTreeMap<NodeId, ResolvedNode>,
    /// Maps each node to the daemon it's running on
    pub(crate) node_to_daemon: BTreeMap<NodeId, DaemonId>,
    /// Latest metrics for each node (from daemons)
    pub(crate) node_metrics: BTreeMap<NodeId, NodeMetrics>,
    /// Nodes the daemon has reported as finalized via `DaemonEvent::NodeStopped`.
    /// Authoritative: any subsequent `NodeMetrics` push from the daemon for
    /// a node in this set is dropped on the floor (stale pre-exit snapshot).
    /// Covers BOTH `NodeStatus::Stopped` (clean) and `NodeStatus::Failed`
    /// (crash / final-failure) so a delayed metrics task cannot resurrect
    /// either kind of finalized row back to "Running" indefinitely.
    /// Cleared by the grace-period sweep (for Stopped) or by `AddNode`
    /// (when the same node id is added back to the dataflow).
    pub(crate) node_finalized: BTreeSet<NodeId>,
    /// When a node entered `NodeStatus::Stopped` (clean teardown only).
    /// Drives the auto-expire sweep: after the grace window the row is
    /// dropped from `node_metrics`/`node_finalized` so `dora node list`
    /// stops showing zombies. `Failed` rows are NOT inserted here — they
    /// stay visible until the dataflow itself is stopped so `dora doctor`
    /// keeps reporting the crash.
    pub(crate) node_stopped_at: BTreeMap<NodeId, Instant>,
    pub(crate) network_metrics: Option<dora_message::daemon_to_coordinator::NetworkMetrics>,

    pub(crate) spawn_result: CachedResult,
    pub(crate) stop_reply_senders: Vec<oneshot::Sender<eyre::Result<ControlRequestReply>>>,

    /// Buffer for log messages that were sent before there were any subscribers.
    pub(crate) buffered_log_messages: Vec<LogMessage>,
    pub(crate) log_subscribers: Vec<LogSubscriber>,
    pub(crate) topic_subscribers: BTreeMap<Uuid, TopicSubscriber>,

    pub(crate) pending_spawn_results: BTreeSet<DaemonId>,
    /// Coordinator-local timestamp captured when this `RunningDataflow` was
    /// constructed (i.e. just before the per-daemon spawn dispatch). Used by
    /// the heartbeat-driven watchdog to detect spawn flows that have been
    /// pending past `SPAWN_RESULT_TIMEOUT` so waiters can be released with a
    /// clear error instead of hanging on the client-side RPC deadline.
    /// Rescue of [#1593](https://github.com/dora-rs/dora/pull/1593).
    pub(crate) spawn_started_at: Instant,

    /// Timestamp (unix millis) when this dataflow was first persisted.
    pub(crate) created_at: u64,
    /// Monotonically increasing version; bumped on every persist.
    pub(crate) store_generation: u64,

    /// Per-daemon timestamp of last auto-recovery attempt (for backoff).
    pub(crate) last_recovery_attempt: BTreeMap<DaemonId, Instant>,
    /// Per-daemon timestamp of last full fallback param replay attempt
    /// (for state catch-up backoff on pruned logs).
    pub(crate) last_replay_attempt: BTreeMap<DaemonId, Instant>,

    /// Whether UV was used for this dataflow (needed for restart).
    pub(crate) uv: bool,

    // --- State catch-up replication log ---
    /// Monotonically increasing sequence counter for state mutations.
    pub(crate) state_log_sequence: u64,
    /// In-memory replication log of state mutations for incremental catch-up.
    pub(crate) state_log: Vec<StateCatchUpEntry>,
    /// Last state_log sequence acknowledged by each daemon.
    pub(crate) daemon_ack_sequence: BTreeMap<DaemonId, u64>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum ParamTarget {
    Running { daemon_id: DaemonId },
    // Dataflow exists in persisted store and contains the node, but is not
    // currently running. Mutations remain allowed for pre-provisioning.
    PersistedOnly,
}

pub(crate) fn resolve_param_target(
    running_dataflows: &HashMap<dora_message::DataflowId, RunningDataflow>,
    store: &dyn CoordinatorStore,
    dataflow_id: &dora_message::DataflowId,
    node_id: &NodeId,
) -> eyre::Result<ParamTarget> {
    if let Some(dataflow) = running_dataflows.get(dataflow_id) {
        let daemon_id = dataflow
            .node_to_daemon
            .get(node_id)
            .cloned()
            .ok_or_else(|| eyre::eyre!("node `{node_id}` not found in dataflow `{dataflow_id}`"))?;
        return Ok(ParamTarget::Running { daemon_id });
    }

    let Some(record) = store.get_dataflow(dataflow_id)? else {
        eyre::bail!(
            "dataflow `{dataflow_id}` not found for node `{node_id}`; \
             cannot operate params on unknown dataflow"
        );
    };

    let descriptor: dora_message::descriptor::Descriptor =
        serde_json::from_str(&record.descriptor_json).map_err(|e| {
            eyre::eyre!("failed to parse persisted descriptor for `{dataflow_id}`: {e}")
        })?;
    let node_exists = descriptor.nodes.iter().any(|n| n.id == *node_id);
    if !node_exists {
        eyre::bail!("node `{node_id}` not found in dataflow `{dataflow_id}`");
    }

    Ok(ParamTarget::PersistedOnly)
}

pub(crate) fn now_millis() -> u64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap_or_default()
        .as_millis() as u64
}

/// Maximum bytes for error strings persisted in `DataflowStatus::Failed`.
const MAX_ERROR_BYTES: usize = 4096;

/// Truncate `s` to at most `max_bytes` bytes on a UTF-8 char boundary.
pub(crate) fn truncate_str(s: &str, max_bytes: usize) -> &str {
    if s.len() <= max_bytes {
        return s;
    }
    let mut end = max_bytes;
    while end > 0 && !s.is_char_boundary(end) {
        end -= 1;
    }
    &s[..end]
}

/// Maximum number of entries in the replication log before pruning.
const MAX_STATE_LOG_ENTRIES: usize = 10_000;

impl RunningDataflow {
    /// Append a state mutation to the replication log.
    pub(crate) fn append_state_log(&mut self, operation: StateCatchUpOperation) {
        self.state_log_sequence += 1;
        self.state_log.push(StateCatchUpEntry {
            sequence: self.state_log_sequence,
            operation,
        });
        // Hard-cap: drop oldest entries if the log is too large.
        if self.state_log.len() > MAX_STATE_LOG_ENTRIES {
            let drain_count = self.state_log.len() - MAX_STATE_LOG_ENTRIES;
            tracing::warn!(
                "state replication log exceeded {MAX_STATE_LOG_ENTRIES} entries, \
                 dropping {drain_count} oldest (disconnected daemons will need full replay)"
            );
            self.state_log.drain(..drain_count);
        }
    }

    /// Prune log entries that all daemons have acknowledged.
    pub(crate) fn prune_state_log(&mut self) {
        // Gate pruning on the acks of *live* daemons only. A daemon that
        // disconnects is removed from `self.daemons`, but its (now frozen)
        // `daemon_ack_sequence` entry is deliberately retained for a possible
        // reclaim. Counting that stale entry here would pin `min_ack` at the
        // disconnected daemon's last ack forever, so the log could never shrink
        // — it would grow until the `MAX_STATE_LOG_ENTRIES` hard cap, forcing a
        // full param replay for *every* daemon (including healthy ones). If a
        // disconnected daemon reconnects after its missed entries were pruned,
        // `state_log_delta` already falls back to a full replay for it.
        let min_ack = self
            .daemons
            .iter()
            .map(|daemon| self.daemon_ack_sequence.get(daemon).copied().unwrap_or(0))
            .min()
            .unwrap_or(0);
        self.state_log.retain(|entry| entry.sequence > min_ack);
    }

    /// Return the entries a daemon has missed since `last_ack`.
    /// Returns `None` if the log has been pruned past `last_ack` (caller
    /// should fall back to a full param replay).
    pub(crate) fn state_log_delta(&self, last_ack: u64) -> Option<Vec<StateCatchUpEntry>> {
        if self.state_log.is_empty() {
            // An empty log only means "up to date" when nothing newer than
            // `last_ack` ever existed. If `last_ack < state_log_sequence`, the
            // entries the daemon still needs (`last_ack+1..=state_log_sequence`)
            // were pruned away — the daemon must fall back to a full replay,
            // not be told it is current. This happens on relink: a daemon that
            // was never seeded into `daemon_ack_sequence` queries with
            // `last_ack == 0` after peers acked and drained the log
            // (dora-rs/dora#2601). It also covers a disconnected daemon whose
            // stale ack is now excluded from pruning (see `prune_state_log`).
            if last_ack < self.state_log_sequence {
                return None;
            }
            return Some(Vec::new());
        }
        let oldest = self.state_log[0].sequence;
        if last_ack.saturating_add(1) < oldest {
            // There's a gap: entries between last_ack and oldest were pruned.
            return None;
        }
        Some(
            self.state_log
                .iter()
                .filter(|e| e.sequence > last_ack)
                .cloned()
                .collect(),
        )
    }

    /// Reconstruct the live `RunningDataflow` for a dataflow that survived a
    /// coordinator-connection drop, from its persisted record + a reconnecting
    /// daemon's status report (dora-rs/dora#2029 P1).
    ///
    /// Spawn already succeeded, so `spawn_result` is cached `Ok`; per-node
    /// metrics / log-subscriber / topic-subscriber state starts empty and the
    /// daemon re-reports/-subscribes. `node_to_daemon` is seeded from the
    /// reporting daemon's nodes; in a multi-daemon dataflow each daemon's
    /// reconnect relinks its own share (see the caller's relink branch).
    pub(crate) fn recovered(
        record: &DataflowRecord,
        descriptor: Descriptor,
        nodes: BTreeMap<NodeId, ResolvedNode>,
        daemon_id: DaemonId,
        reported_nodes: &[NodeId],
    ) -> Self {
        let daemons: BTreeSet<DaemonId> = std::iter::once(daemon_id.clone()).collect();
        let node_to_daemon = reported_nodes
            .iter()
            .map(|n| (n.clone(), daemon_id.clone()))
            .collect();
        RunningDataflow {
            uuid: record.uuid,
            name: record.name.clone(),
            descriptor,
            daemons: daemons.clone(),
            pending_daemons: BTreeSet::new(),
            // Restored, not reset: the live entry is destroyed by orphan
            // reclaim and by coordinator restart, and the daemon cannot prompt
            // a fresh broadcast because its `reported_init_to_coordinator` is
            // never reset. Dropping the verdict here is what left a
            // reconnecting daemon hanging forever (dora-rs/dora#2998).
            exited_before_subscribe: record
                .barrier_exited_before_subscribe
                .iter()
                .map(|n| NodeId::from(n.clone()))
                .collect(),
            ready_barrier_released: record.ready_barrier_released,
            nodes,
            node_to_daemon,
            node_metrics: BTreeMap::new(),
            node_finalized: BTreeSet::new(),
            node_stopped_at: BTreeMap::new(),
            network_metrics: None,
            spawn_result: CachedResult::Cached {
                result: Box::new(Ok(ControlRequestReply::DataflowSpawned {
                    uuid: record.uuid,
                })),
            },
            stop_reply_senders: Vec::new(),
            buffered_log_messages: Vec::new(),
            log_subscribers: Vec::new(),
            topic_subscribers: BTreeMap::new(),
            pending_spawn_results: BTreeSet::new(),
            spawn_started_at: Instant::now(),
            created_at: record.created_at,
            store_generation: record.generation,
            last_recovery_attempt: BTreeMap::new(),
            last_replay_attempt: BTreeMap::new(),
            uv: record.uv,
            state_log_sequence: 0,
            state_log: Vec::new(),
            daemon_ack_sequence: daemons.iter().map(|d| (d.clone(), 0)).collect(),
        }
    }

    /// Create a persistable [`DataflowRecord`] snapshot of this dataflow.
    /// Increments `store_generation` on each call.
    pub(crate) fn make_record(&mut self, status: DataflowStatus) -> eyre::Result<DataflowRecord> {
        self.store_generation += 1;
        let descriptor_json = serde_json::to_string(&self.descriptor)
            .map_err(|e| eyre::eyre!("failed to serialize descriptor: {e}"))?;
        let status = match status {
            DataflowStatus::Failed { error, terminal } => DataflowStatus::Failed {
                error: truncate_str(&error, MAX_ERROR_BYTES).to_owned(),
                terminal,
            },
            other => other,
        };
        Ok(DataflowRecord {
            uuid: self.uuid,
            name: self.name.clone(),
            descriptor_json,
            status,
            daemon_ids: self.daemons.iter().cloned().collect(),
            node_to_daemon: self
                .node_to_daemon
                .iter()
                .map(|(k, v)| (k.to_string(), v.to_string()))
                .collect(),
            uv: self.uv,
            ready_barrier_released: self.ready_barrier_released,
            barrier_exited_before_subscribe: self
                .exited_before_subscribe
                .iter()
                .map(|n| n.to_string())
                .collect(),
            generation: self.store_generation,
            created_at: self.created_at,
            updated_at: now_millis(),
        })
    }
}

pub(crate) enum CachedResult {
    Pending {
        result_senders: Vec<oneshot::Sender<eyre::Result<ControlRequestReply>>>,
    },
    // Boxed because `ControlRequestReply` is large: without the box the
    // `Cached` variant dwarfs `Pending`, which trips clippy's
    // `large_enum_variant` on some targets (e.g. Windows) but not others (#2979).
    Cached {
        result: Box<eyre::Result<ControlRequestReply>>,
    },
}

impl Default for CachedResult {
    fn default() -> Self {
        Self::Pending {
            result_senders: Vec::new(),
        }
    }
}

impl CachedResult {
    pub(crate) fn register(
        &mut self,
        reply_sender: oneshot::Sender<eyre::Result<ControlRequestReply>>,
    ) {
        match self {
            CachedResult::Pending { result_senders } => result_senders.push(reply_sender),
            CachedResult::Cached { result } => {
                Self::send_result_to(result, reply_sender);
            }
        }
    }

    pub(crate) fn set_result(&mut self, result: eyre::Result<ControlRequestReply>) {
        match self {
            CachedResult::Pending { result_senders } => {
                for sender in result_senders.drain(..) {
                    Self::send_result_to(&result, sender);
                }
                *self = CachedResult::Cached {
                    result: Box::new(result),
                };
            }
            CachedResult::Cached { .. } => {}
        }
    }

    /// Returns `true` if no result has been recorded yet. Used by the
    /// heartbeat-driven spawn-timeout watchdog to decide whether to fire a
    /// rollback-with-error path on a stuck pending spawn.
    pub(crate) fn is_pending(&self) -> bool {
        matches!(self, CachedResult::Pending { .. })
    }

    /// Returns `true` if a terminally-failed result has already been cached.
    /// Used by other handlers (auto-recovery, late `DataflowSpawnResult`
    /// arms) to skip operations that would resurrect or muddle a dataflow
    /// the spawn-timeout watchdog (or any other terminal-failure path)
    /// has already marked as failed.
    pub(crate) fn is_terminal_error(&self) -> bool {
        matches!(self, CachedResult::Cached { result } if result.is_err())
    }

    /// Returns `true` if a successful result has been cached, i.e. the dataflow
    /// finished spawning successfully. Used by the daemon-disconnect cleanup to
    /// gate ready-barrier release and orphaned-dataflow teardown to dataflows
    /// that are past spawn — spawn-pending ones remain the spawn-timeout
    /// watchdog's domain. See #2028.
    pub(crate) fn is_cached_ok(&self) -> bool {
        matches!(self, CachedResult::Cached { result } if result.is_ok())
    }

    fn send_result_to(
        result: &eyre::Result<ControlRequestReply>,
        sender: oneshot::Sender<eyre::Result<ControlRequestReply>>,
    ) {
        let result = match result {
            Ok(r) => Ok(r.clone()),
            Err(err) => Err(eyre!("{err:?}")),
        };
        let _ = sender.send(result);
    }
}

pub(crate) struct ArchivedDataflow {
    pub(crate) name: Option<String>,
    pub(crate) nodes: BTreeMap<NodeId, ResolvedNode>,
}

impl From<&RunningDataflow> for ArchivedDataflow {
    fn from(dataflow: &RunningDataflow) -> ArchivedDataflow {
        ArchivedDataflow {
            name: dataflow.name.clone(),
            nodes: dataflow.nodes.clone(),
        }
    }
}

#[cfg(test)]
mod hub_capability_tests {
    use super::*;

    fn conn(supports_hub: bool) -> DaemonConnection {
        let (tx, _rx) = mpsc::channel(1);
        let mut c =
            DaemonConnection::new(tx, Arc::new(Mutex::new(HashMap::new())), BTreeMap::new());
        c.supports_hub_sources = supports_hub;
        c
    }

    #[test]
    fn supports_hub_sources_reflects_registration_and_unknown_is_false() {
        let mut conns = DaemonConnections::default();
        let hub_aware = DaemonId::new(Some("new".into()));
        let legacy = DaemonId::new(Some("old".into()));
        conns.add(hub_aware.clone(), conn(true));
        conns.add(legacy.clone(), conn(false));

        assert!(conns.supports_hub_sources(&hub_aware));
        assert!(!conns.supports_hub_sources(&legacy));
        // unknown daemon → false (fail-closed: refuse to route a hub node)
        assert!(!conns.supports_hub_sources(&DaemonId::new(Some("ghost".into()))));
    }
}

#[cfg(test)]
mod send_and_receive_tests {
    use super::*;

    #[tokio::test]
    async fn send_failure_does_not_leak_pending_reply() {
        // A closed receiver makes every `sender.send` fail. The request id is
        // inserted into `pending_replies` before the send, so the error path
        // must remove it again — otherwise it lingers until the connection is
        // dropped, consuming a `MAX_PENDING_REPLIES` slot for nothing.
        let (tx, rx) = mpsc::channel(1);
        drop(rx);
        let pending: Arc<Mutex<HashMap<Uuid, oneshot::Sender<String>>>> =
            Arc::new(Mutex::new(HashMap::new()));
        let conn = DaemonConnection::new(tx, pending.clone(), BTreeMap::new());

        let result = conn.send_and_receive(b"{}").await;

        assert!(result.is_err(), "send_and_receive should fail on closed WS");
        assert!(
            pending.lock().await.is_empty(),
            "pending reply leaked after send failure"
        );
    }

    #[tokio::test]
    async fn ws_error_envelope_surfaces_as_err() {
        // The daemon-side WS error path delivers a `{"ws_error": ...}` string to
        // the pending reply (see `handle_daemon_response` in `ws_daemon.rs`).
        // `send_and_receive` must turn that into an `Err` carrying the daemon's
        // text — not return an envelope its callers cannot deserialize, which
        // would surface as an opaque "failed to deserialize ... reply".
        let (tx, mut rx) = mpsc::channel::<String>(1);
        let pending: Arc<Mutex<HashMap<Uuid, oneshot::Sender<String>>>> =
            Arc::new(Mutex::new(HashMap::new()));
        let conn = DaemonConnection::new(tx, pending.clone(), BTreeMap::new());

        let pending_bg = pending.clone();
        tokio::spawn(async move {
            let outgoing = rx.recv().await.expect("request should be sent");
            let value: serde_json::Value =
                serde_json::from_str(&outgoing).expect("outgoing request is JSON");
            let id: Uuid = value["id"]
                .as_str()
                .expect("request carries an id")
                .parse()
                .expect("id is a UUID");
            let sender = pending_bg
                .lock()
                .await
                .remove(&id)
                .expect("pending reply is registered before the send");
            let _ = sender.send(r#"{"ws_error":"daemon blew up"}"#.to_string());
        });

        let err = conn
            .send_and_receive(b"{}")
            .await
            .expect_err("ws_error envelope must be surfaced as an error");
        assert!(
            err.to_string().contains("daemon blew up"),
            "error should carry the daemon's message, got: {err}"
        );
    }
}

#[cfg(test)]
mod zenoh_endpoint_registry_tests {
    use super::*;

    fn connection() -> DaemonConnection {
        let (tx, _rx) = mpsc::channel(1);
        DaemonConnection::new(tx, Arc::new(Mutex::new(HashMap::new())), BTreeMap::new())
    }

    fn daemon(machine: &str) -> DaemonId {
        DaemonId::new(Some(machine.to_string()))
    }

    /// The joining daemon is handed every *other* daemon's endpoint. This is
    /// the whole mechanism: without it a multi-machine deployment has to name
    /// each daemon's address on every other daemon's command line.
    #[test]
    fn a_joining_daemon_is_given_the_endpoints_of_the_daemons_before_it() {
        let mut connections = DaemonConnections::default();
        let (a, b) = (daemon("A"), daemon("B"));
        connections.add(a.clone(), connection());
        connections.add(b.clone(), connection());
        connections.set_zenoh_endpoint(&a, Some("tcp/10.0.2.100:5456".into()));
        connections.set_zenoh_endpoint(&b, Some("tcp/10.0.2.101:5456".into()));

        let mut given = connections.zenoh_endpoints_for(&daemon("C"));
        given.sort();
        assert_eq!(given, ["tcp/10.0.2.100:5456", "tcp/10.0.2.101:5456"]);
    }

    /// A daemon must never be told to dial itself. On re-registration its old
    /// connection is still in the map when the reply is built, and that
    /// endpoint is either its own or a dead one from the previous process.
    #[test]
    fn a_re_registering_daemon_is_not_told_to_dial_itself() {
        let mut connections = DaemonConnections::default();
        let a = daemon("A");
        connections.add(a.clone(), connection());
        connections.set_zenoh_endpoint(&a, Some("tcp/10.0.2.100:5456".into()));

        assert!(connections.zenoh_endpoints_for(&a).is_empty());
    }

    /// The ordering the whole mechanism rests on: a daemon's endpoint is set on
    /// its connection *before* that connection is added, so it is already
    /// visible to the next daemon's register reply. The coordinator's event
    /// loop handles registrations one at a time, so two daemons starting
    /// simultaneously are ordered by it and the later one always sees the
    /// earlier — there is no window in which both see nothing.
    #[test]
    fn an_endpoint_registered_with_the_connection_is_visible_to_the_next_daemon() {
        let mut connections = DaemonConnections::default();

        // What the register handler does for daemon A.
        let mut conn_a = connection();
        conn_a.zenoh_listen_endpoint = Some("tcp/10.0.2.100:5456".into());
        connections.add(daemon("A"), conn_a);

        // B registers immediately afterwards, before A has confirmed anything.
        assert_eq!(
            connections.zenoh_endpoints_for(&daemon("B")),
            ["tcp/10.0.2.100:5456"],
        );
    }

    /// A daemon whose listener failed to bind withdraws its endpoint, so it
    /// stops being handed to daemons that register later. Without this the
    /// coordinator would keep advertising a port with nothing behind it.
    #[test]
    fn a_withdrawn_endpoint_is_no_longer_handed_out() {
        let mut connections = DaemonConnections::default();
        let a = daemon("A");
        let mut conn_a = connection();
        conn_a.zenoh_listen_endpoint = Some("tcp/10.0.2.100:5456".into());
        connections.add(a.clone(), conn_a);

        connections.set_zenoh_endpoint(&a, None);

        assert!(connections.zenoh_endpoints_for(&daemon("B")).is_empty());
    }

    /// A daemon that has not reported an endpoint contributes none. It has
    /// either not opened its session yet or bound loopback, and advertising a
    /// loopback endpoint would point a remote peer at its own machine.
    #[test]
    fn a_daemon_without_a_reported_endpoint_contributes_nothing() {
        let mut connections = DaemonConnections::default();
        let (a, b) = (daemon("A"), daemon("B"));
        connections.add(a.clone(), connection());
        connections.add(b.clone(), connection());
        connections.set_zenoh_endpoint(&b, Some("tcp/10.0.2.101:5456".into()));

        assert_eq!(
            connections.zenoh_endpoints_for(&daemon("C")),
            ["tcp/10.0.2.101:5456"]
        );
    }

    /// A dropped daemon stops being advertised, because the endpoint lives on
    /// the connection rather than in a side map that would have to be pruned
    /// separately.
    #[test]
    fn removing_a_daemon_withdraws_its_endpoint() {
        let mut connections = DaemonConnections::default();
        let a = daemon("A");
        connections.add(a.clone(), connection());
        connections.set_zenoh_endpoint(&a, Some("tcp/10.0.2.100:5456".into()));
        connections.remove(&a);

        assert!(connections.zenoh_endpoints_for(&daemon("C")).is_empty());
    }

    /// Setting an endpoint for a daemon that is not connected is a no-op
    /// rather than an insertion: a late report from a connection the
    /// coordinator has already dropped must not resurrect it.
    #[test]
    fn reporting_an_endpoint_for_an_unknown_daemon_is_ignored() {
        let mut connections = DaemonConnections::default();
        connections.set_zenoh_endpoint(&daemon("ghost"), Some("tcp/10.0.2.100:5456".into()));
        assert!(connections.zenoh_endpoints_for(&daemon("C")).is_empty());
    }
}