dora-coordinator 1.0.1

`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
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
use crate::{
    log_subscriber::LogSubscriber,
    run::{SpawnedDataflow, resolve_daemon, spawn_dataflow},
    state::{
        self, ArchivedDataflow, CachedResult, DaemonConnection, DaemonConnections, RunningBuild,
        RunningDataflow,
    },
    topic_subscriber::TopicSubscriber,
};
use dora_core::{
    config::{NodeId, OperatorId},
    descriptor::DescriptorExt,
    uhlc::{self, HLC},
};
use dora_message::{
    BuildId, SessionId,
    common::{DaemonId, GitSource},
    coordinator_to_cli::{DataflowResult, LogMessage},
    coordinator_to_daemon::{BuildDataflowNodes, DaemonCoordinatorEvent, Timestamped},
    daemon_to_coordinator::{DaemonCoordinatorReply, DataflowDaemonResult},
    descriptor::{Descriptor, ResolvedNode},
};
use eyre::{ContextCompat, WrapErr, bail, eyre};
use futures::future::join_all;
use std::{
    collections::{BTreeMap, BTreeSet, HashMap},
    path::PathBuf,
    time::Duration,
};
use uuid::Uuid;

const MAX_TOPIC_DEBUG_PAYLOAD_BYTES: usize = 64 * 1024 * 1024;

// Resolve the dataflow name.
pub(crate) fn resolve_name(
    name: String,
    running_dataflows: &HashMap<Uuid, RunningDataflow>,
    archived_dataflows: &indexmap::IndexMap<Uuid, ArchivedDataflow>,
) -> eyre::Result<Uuid> {
    let uuids: Vec<_> = running_dataflows
        .iter()
        .filter(|(_, v)| v.name.as_deref() == Some(name.as_str()))
        .map(|(k, _)| k)
        .copied()
        .collect();
    let archived_uuids: Vec<_> = archived_dataflows
        .iter()
        .filter(|(_, v)| v.name.as_deref() == Some(name.as_str()))
        .map(|(k, _)| k)
        .copied()
        .collect();

    if uuids.is_empty() {
        if archived_uuids.is_empty() {
            bail!("no dataflow with name `{name}`");
        } else if let [uuid] = archived_uuids.as_slice() {
            Ok(*uuid)
        } else {
            bail!(
                "multiple archived dataflows found with name `{name}`, Please provide the UUID instead."
            );
        }
    } else if let [uuid] = uuids.as_slice() {
        Ok(*uuid)
    } else {
        bail!("multiple dataflows found with name `{name}`");
    }
}

pub(crate) async fn send_log_message(
    log_subscribers: &mut Vec<LogSubscriber>,
    message: &LogMessage,
) {
    for subscriber in log_subscribers.iter_mut() {
        let send_result =
            tokio::time::timeout(Duration::from_millis(100), subscriber.send_message(message));

        if send_result.await.is_err() {
            subscriber.close();
        }
    }
    log_subscribers.retain(|s| !s.is_closed());
}

pub(crate) async fn send_topic_frames(
    topic_subscribers: &mut BTreeMap<Uuid, TopicSubscriber>,
    subscription_ids: Vec<Uuid>,
    payload: Vec<u8>,
) {
    if payload.len() > MAX_TOPIC_DEBUG_PAYLOAD_BYTES {
        tracing::warn!(
            "dropping oversized topic debug payload ({} bytes) for {} subscription(s)",
            payload.len(),
            subscription_ids.len()
        );
        return;
    }
    let shared_payload: std::sync::Arc<[u8]> = payload.into();
    const MAX_CONSECUTIVE_TOPIC_SEND_TIMEOUTS: usize = 100;
    for subscription_id in subscription_ids {
        if let Some(subscriber) = topic_subscribers.get_mut(&subscription_id) {
            let frame = crate::topic_subscriber::TopicFrame {
                subscription_id,
                payload: shared_payload.clone(),
            };
            let send_result =
                tokio::time::timeout(Duration::from_millis(100), subscriber.send_frame(frame))
                    .await;
            match send_result {
                Ok(Ok(())) => {
                    subscriber.reset_timeout_streak();
                }
                Ok(Err(_)) => {
                    subscriber.close();
                }
                Err(_) => {
                    let timeouts = subscriber.record_timeout();
                    if timeouts >= MAX_CONSECUTIVE_TOPIC_SEND_TIMEOUTS {
                        tracing::warn!(
                            %subscription_id,
                            timeouts,
                            "closing slow topic debug subscriber after repeated send timeouts"
                        );
                        subscriber.close();
                    } else {
                        tracing::warn!(
                            %subscription_id,
                            timeouts,
                            "timed out sending topic debug frame to CLI subscriber; keeping subscription active"
                        );
                    }
                }
            }
        }
    }
    topic_subscribers.retain(|_, s| !s.is_closed());
}

pub(crate) fn dataflow_result(
    results: &BTreeMap<DaemonId, DataflowDaemonResult>,
    dataflow_uuid: Uuid,
    clock: &uhlc::HLC,
) -> DataflowResult {
    let mut node_results = BTreeMap::new();
    for result in results.values() {
        node_results.extend(result.node_results.clone());
        if let Err(err) = clock.update_with_timestamp(&result.timestamp) {
            tracing::warn!("failed to update HLC: {err}");
        }
    }

    DataflowResult {
        uuid: dataflow_uuid,
        timestamp: clock.new_timestamp(),
        node_results,
    }
}

pub(crate) async fn handle_destroy(
    running_dataflows: &mut HashMap<Uuid, RunningDataflow>,
    daemon_connections: &mut DaemonConnections,
    abortable_events: &futures::stream::AbortHandle,
    clock: &HLC,
    store: &dyn dora_coordinator_store::CoordinatorStore,
) -> Result<(), eyre::ErrReport> {
    abortable_events.abort();
    // Persist Stopping for all running dataflows before sending stop messages.
    for dataflow in running_dataflows.values_mut() {
        if let Err(e) = dataflow
            .make_record(dora_coordinator_store::DataflowStatus::Stopping)
            .and_then(|r| store.put_dataflow(&r))
        {
            tracing::warn!("failed to persist dataflow stopping on destroy: {e}");
        }
    }
    for dataflow_uuid in running_dataflows.keys().cloned().collect::<Vec<_>>() {
        if let Err(e) = stop_dataflow(
            running_dataflows,
            dataflow_uuid,
            daemon_connections,
            clock.new_timestamp(),
            None,
            false,
        )
        .await
        {
            tracing::warn!("failed to stop dataflow {dataflow_uuid} during destroy: {e:#}");
        }
    }

    // `stop_dataflow` returns once the daemons have acknowledged the
    // *request*; the grace → SIGTERM → SIGKILL ladder then runs inside each
    // daemon, long after this returns. Destroying them here used to race that
    // ladder and orphan any node that ignored the cooperative `Stop`
    // (dora-rs/dora#2980). The wait now lives in the daemon's `Destroy`
    // handler, which reaps its own children before it replies — so this await
    // is what makes `dora down` return only after the nodes are gone, for
    // every route that reaches `Destroy` (`dora cluster down`, Ctrl-C, and
    // any direct control-protocol client).
    destroy_daemons(daemon_connections, clock.new_timestamp()).await?;
    // Brief grace period so daemons have time to flush final messages and
    // close their WS connections before the coordinator shuts down the
    // listener. Without this, daemons see "Connection refused" when they
    // try to send a final acknowledgement or reconnect during teardown.
    tokio::time::sleep(std::time::Duration::from_millis(200)).await;
    Ok(())
}

pub(crate) async fn send_heartbeat_message(
    connection: &mut DaemonConnection,
    timestamp: uhlc::Timestamp,
) -> eyre::Result<()> {
    let message = serde_json::to_vec(&Timestamped {
        inner: DaemonCoordinatorEvent::Heartbeat,
        timestamp,
    })
    .context("Could not serialize heartbeat message")?;

    connection
        .send(&message)
        .await
        .wrap_err("failed to send heartbeat message to daemon")
}

pub(crate) async fn stop_dataflow<'a>(
    running_dataflows: &'a mut HashMap<Uuid, RunningDataflow>,
    dataflow_uuid: Uuid,
    daemon_connections: &mut DaemonConnections,
    timestamp: uhlc::Timestamp,
    grace_duration: Option<Duration>,
    force: bool,
) -> eyre::Result<&'a mut RunningDataflow> {
    let Some(dataflow) = running_dataflows.get_mut(&dataflow_uuid) else {
        bail!("no known running dataflow found with UUID `{dataflow_uuid}`")
    };

    let message = serde_json::to_vec(&Timestamped {
        inner: DaemonCoordinatorEvent::StopDataflow {
            dataflow_id: dataflow_uuid,
            grace_duration,
            force,
        },
        timestamp,
    })?;

    // Best-effort: attempt the stop on every daemon even if some fail, so one
    // unreachable/erroring daemon does not orphan the nodes running on the
    // remaining healthy daemons. Errors are aggregated and reported after all
    // daemons have been attempted (mirrors `run::rollback_spawned_daemons`).
    let mut errors: Vec<(DaemonId, eyre::Report)> = Vec::new();
    for daemon_id in &dataflow.daemons {
        let result: eyre::Result<()> = async {
            let daemon_connection = daemon_connections
                .get_mut(daemon_id)
                .wrap_err("no daemon connection")?;

            let reply_raw = daemon_connection
                .send_and_receive(&message)
                .await
                .wrap_err("failed to send/receive stop message")?;
            match serde_json::from_slice(&reply_raw)
                .wrap_err("failed to deserialize stop reply from daemon")?
            {
                DaemonCoordinatorReply::StopResult(result) => result
                    .map_err(|e| eyre!(e))
                    .wrap_err("failed to stop dataflow")?,
                other => bail!("unexpected reply after sending stop: {other:?}"),
            }
            Ok(())
        }
        .await;

        if let Err(err) = result {
            errors.push((daemon_id.clone(), err));
        }
    }

    if !errors.is_empty() {
        let daemon_list = errors
            .iter()
            .map(|(id, err)| format!("{id}: {err:#}"))
            .collect::<Vec<_>>()
            .join("; ");
        return Err(eyre!(
            "failed to stop dataflow `{dataflow_uuid}` on {} of {} daemon(s): {daemon_list}",
            errors.len(),
            dataflow.daemons.len(),
        ));
    }

    tracing::info!("successfully send stop dataflow `{dataflow_uuid}` to all daemons");

    Ok(dataflow)
}

pub(crate) async fn reload_dataflow(
    running_dataflows: &HashMap<Uuid, RunningDataflow>,
    dataflow_id: Uuid,
    node_id: NodeId,
    operator_id: Option<OperatorId>,
    daemon_connections: &mut DaemonConnections,
    timestamp: uhlc::Timestamp,
) -> eyre::Result<()> {
    let Some(dataflow) = running_dataflows.get(&dataflow_id) else {
        bail!("No running dataflow found with UUID `{dataflow_id}`")
    };
    let message = serde_json::to_vec(&Timestamped {
        inner: DaemonCoordinatorEvent::ReloadDataflow {
            dataflow_id,
            node_id,
            operator_id,
        },
        timestamp,
    })?;

    for machine_id in &dataflow.daemons {
        let daemon_connection = daemon_connections
            .get_mut(machine_id)
            .wrap_err("no daemon connection")?;

        let reply_raw = daemon_connection
            .send_and_receive(&message)
            .await
            .wrap_err("failed to send/receive reload message")?;
        match serde_json::from_slice(&reply_raw)
            .wrap_err("failed to deserialize reload reply from daemon")?
        {
            DaemonCoordinatorReply::ReloadResult(result) => result
                .map_err(|e| eyre!(e))
                .wrap_err("failed to reload dataflow")?,
            other => bail!("unexpected reply after sending reload: {other:?}"),
        }
    }
    tracing::info!("successfully reloaded dataflow `{dataflow_id}`");

    Ok(())
}

/// Send a single-node command (restart or stop) to the appropriate daemon.
async fn dispatch_node_command(
    running_dataflows: &HashMap<Uuid, RunningDataflow>,
    dataflow_id: Uuid,
    node_id: &NodeId,
    event: DaemonCoordinatorEvent,
    daemon_connections: &mut DaemonConnections,
    timestamp: uhlc::Timestamp,
    action: &str,
) -> eyre::Result<DaemonCoordinatorReply> {
    let Some(dataflow) = running_dataflows.get(&dataflow_id) else {
        bail!("No running dataflow found with UUID `{dataflow_id}`")
    };
    let daemon_id = dataflow
        .node_to_daemon
        .get(node_id)
        .with_context(|| format!("node `{node_id}` not found in dataflow `{dataflow_id}`"))?;

    let message = serde_json::to_vec(&Timestamped {
        inner: event,
        timestamp,
    })?;

    let daemon_connection = daemon_connections
        .get_mut(daemon_id)
        .wrap_err("no daemon connection")?;
    let reply_raw = daemon_connection
        .send_and_receive(&message)
        .await
        .wrap_err_with(|| format!("failed to send/receive {action} node message"))?;
    serde_json::from_slice(&reply_raw)
        .wrap_err_with(|| format!("failed to deserialize {action} node reply"))
}

pub(crate) async fn restart_node(
    running_dataflows: &HashMap<Uuid, RunningDataflow>,
    dataflow_id: Uuid,
    node_id: NodeId,
    grace_duration: Option<Duration>,
    daemon_connections: &mut DaemonConnections,
    timestamp: uhlc::Timestamp,
) -> eyre::Result<()> {
    let reply = dispatch_node_command(
        running_dataflows,
        dataflow_id,
        &node_id,
        DaemonCoordinatorEvent::RestartNode {
            dataflow_id,
            node_id: node_id.clone(),
            grace_duration,
        },
        daemon_connections,
        timestamp,
        "restart",
    )
    .await?;
    match reply {
        DaemonCoordinatorReply::RestartNodeResult(result) => result
            .map_err(|e| eyre!(e))
            .wrap_err("failed to restart node")?,
        other => bail!("unexpected reply after sending restart node: {other:?}"),
    }
    tracing::info!("successfully restarted node `{node_id}` in dataflow `{dataflow_id}`");
    Ok(())
}

pub(crate) async fn stop_node(
    running_dataflows: &HashMap<Uuid, RunningDataflow>,
    dataflow_id: Uuid,
    node_id: NodeId,
    grace_duration: Option<Duration>,
    daemon_connections: &mut DaemonConnections,
    timestamp: uhlc::Timestamp,
) -> eyre::Result<()> {
    let reply = dispatch_node_command(
        running_dataflows,
        dataflow_id,
        &node_id,
        DaemonCoordinatorEvent::StopNode {
            dataflow_id,
            node_id: node_id.clone(),
            grace_duration,
        },
        daemon_connections,
        timestamp,
        "stop",
    )
    .await?;
    match reply {
        DaemonCoordinatorReply::StopNodeResult(result) => result
            .map_err(|e| eyre!(e))
            .wrap_err("failed to stop node")?,
        other => bail!("unexpected reply after sending stop node: {other:?}"),
    }
    tracing::info!("successfully stopped node `{node_id}` in dataflow `{dataflow_id}`");
    Ok(())
}

/// Pick the daemon that runs `node_id`, for a log request.
///
/// For a **running** dataflow the coordinator already records the exact
/// node→daemon assignment in `node_to_daemon`; that daemon is where the node
/// was spawned and is authoritative. Re-deriving the daemon from the node's
/// `deploy.machine` (as the archived path must) is wrong for a node without an
/// explicit machine when more than one *unnamed* daemon is connected: the
/// machine-`None` branch collects every unnamed daemon and bails with
/// "multiple matching daemon connections", making `dora logs` unavailable for
/// a node that is definitely running on one specific daemon.
///
/// Archived dataflows keep no `node_to_daemon` map, so they still fall back to
/// the machine-based derivation. Archived takes priority when a dataflow id is
/// somehow present in both, matching the previous behavior.
fn resolve_log_daemon_id(
    running_node_to_daemon: Option<&BTreeMap<NodeId, DaemonId>>,
    archived_nodes: Option<&BTreeMap<NodeId, ResolvedNode>>,
    dataflow_id: Uuid,
    node_id: &NodeId,
    daemon_connections: &DaemonConnections,
) -> eyre::Result<DaemonId> {
    if let Some(nodes) = archived_nodes {
        // `nodes` is keyed by `NodeId` and every `ResolvedNode.id` equals its map
        // key (see `resolve_aliases_and_set_defaults_in_topology`, which also
        // rejects duplicate ids), so a direct lookup is equivalent to — and
        // cheaper than — scanning every entry for a matching `id`. The previous
        // `Vec` scan additionally carried an "more than one machine" arm that the
        // map key uniqueness made unreachable.
        let machine_id = match nodes.get(node_id) {
            Some(node) => node.deploy.as_ref().and_then(|d| d.machine.clone()),
            None => bail!("No machine contains {}/{}", dataflow_id, node_id),
        };

        let daemon_ids: Vec<_> = match &machine_id {
            None => daemon_connections.unnamed().collect(),
            Some(machine_id) => daemon_connections
                .get_matching_daemon_id(machine_id)
                .into_iter()
                .collect(),
        };
        match &daemon_ids[..] {
            [id] => Ok((*id).clone()),
            [] => bail!("no matching daemon connections for machine ID `{machine_id:?}`"),
            _ => bail!("multiple matching daemon connections for machine ID `{machine_id:?}`"),
        }
    } else if let Some(node_to_daemon) = running_node_to_daemon {
        node_to_daemon.get(node_id).cloned().ok_or_else(|| {
            eyre!("node `{node_id}` is not part of running dataflow `{dataflow_id}`")
        })
    } else {
        bail!("No dataflow found with UUID `{dataflow_id}`")
    }
}

pub(crate) async fn retrieve_logs(
    running_dataflows: &HashMap<Uuid, RunningDataflow>,
    archived_dataflows: &indexmap::IndexMap<Uuid, ArchivedDataflow>,
    dataflow_id: Uuid,
    node_id: NodeId,
    daemon_connections: &mut DaemonConnections,
    timestamp: uhlc::Timestamp,
    tail: Option<usize>,
) -> eyre::Result<Vec<u8>> {
    let daemon_id = resolve_log_daemon_id(
        running_dataflows
            .get(&dataflow_id)
            .map(|d| &d.node_to_daemon),
        archived_dataflows.get(&dataflow_id).map(|d| &d.nodes),
        dataflow_id,
        &node_id,
        daemon_connections,
    )?;

    let message = serde_json::to_vec(&Timestamped {
        inner: DaemonCoordinatorEvent::Logs {
            dataflow_id,
            node_id: node_id.clone(),
            tail,
        },
        timestamp,
    })?;

    let daemon_connection = daemon_connections
        .get_mut(&daemon_id)
        .wrap_err_with(|| format!("no daemon connection to `{daemon_id}`"))?;

    let reply_raw = daemon_connection
        .send_and_receive(&message)
        .await
        .wrap_err("failed to send/receive logs message")?;
    let reply_logs = match serde_json::from_slice(&reply_raw)
        .wrap_err("failed to deserialize logs reply from daemon")?
    {
        DaemonCoordinatorReply::Logs(logs) => logs,
        other => bail!("unexpected reply after sending logs: {other:?}"),
    };
    tracing::info!("successfully retrieved logs for `{dataflow_id}/{node_id}`");

    reply_logs.map_err(|err| eyre!(err))
}

#[allow(clippy::too_many_arguments)]
#[tracing::instrument(skip(daemon_connections, clock))]
pub(crate) async fn build_dataflow(
    build_id: BuildId,
    session_id: SessionId,
    dataflow: Descriptor,
    git_sources: BTreeMap<NodeId, GitSource>,
    prev_git_sources: BTreeMap<NodeId, GitSource>,
    local_working_dir: Option<PathBuf>,
    clock: &HLC,
    uv: bool,
    daemon_connections: &mut DaemonConnections,
) -> eyre::Result<RunningBuild> {
    let nodes = dataflow.resolve_aliases_and_set_defaults()?;

    // Resolve each node to its target daemon, group git sources by daemon.
    let mut nodes_by_daemon: BTreeMap<DaemonId, Vec<NodeId>> = BTreeMap::new();
    let mut git_sources_by_daemon: BTreeMap<DaemonId, BTreeMap<NodeId, GitSource>> =
        BTreeMap::new();
    let mut prev_git_sources_by_daemon: BTreeMap<DaemonId, BTreeMap<NodeId, GitSource>> =
        BTreeMap::new();

    for (node_id, node) in &nodes {
        let daemon_id = resolve_daemon(daemon_connections, node.deploy.as_ref())?;
        // A hub-sourced node carries `subdir` / `hub` provenance on its git
        // source. A daemon too old to understand those fields can't build it,
        // and the central desugar means it would otherwise fail with an opaque
        // error on the daemon. Refuse up front with a clear, per-node message
        // (P2.10) — the version gate alone can't catch this within an rc line
        // where a pre-hub daemon and a hub-aware coordinator share a version.
        if let Some(gs) = git_sources.get(node_id)
            && (gs.subdir.is_some() || gs.hub.is_some())
            && !daemon_connections.supports_hub_sources(&daemon_id)
        {
            eyre::bail!(
                "node `{node_id}` is a hub package (or a monorepo `subdir` git node), but \
                 daemon `{daemon_id}` is too old to build it — it does not support hub \
                 `subdir`/`hub:` git sources. Upgrade that daemon to a dora build with hub support."
            );
        }
        nodes_by_daemon
            .entry(daemon_id.clone())
            .or_default()
            .push(node_id.clone());
        if let Some(gs) = git_sources.get(node_id) {
            git_sources_by_daemon
                .entry(daemon_id.clone())
                .or_default()
                .insert(node_id.clone(), gs.clone());
        }
        if let Some(gs) = prev_git_sources.get(node_id) {
            prev_git_sources_by_daemon
                .entry(daemon_id)
                .or_default()
                .insert(node_id.clone(), gs.clone());
        }
    }

    let mut daemons = BTreeSet::new();
    for (daemon_id, nodes_on_daemon) in &nodes_by_daemon {
        tracing::debug!(
            "Running dataflow build `{build_id}` on daemon `{daemon_id}` (nodes: {nodes_on_daemon:?})"
        );

        let build_command = BuildDataflowNodes {
            build_id,
            session_id,
            local_working_dir: local_working_dir.clone(),
            git_sources: git_sources_by_daemon.remove(daemon_id).unwrap_or_default(),
            prev_git_sources: prev_git_sources_by_daemon
                .remove(daemon_id)
                .unwrap_or_default(),
            dataflow_descriptor: dataflow.clone(),
            nodes_on_machine: nodes_on_daemon.iter().cloned().collect(),
            uv,
        };
        let message = serde_json::to_vec(&Timestamped {
            inner: DaemonCoordinatorEvent::Build(build_command),
            timestamp: clock.new_timestamp(),
        })?;

        let daemon_connection = daemon_connections
            .get_mut(daemon_id)
            .wrap_err_with(|| format!("no daemon connection for daemon `{daemon_id}`"))?;

        let reply_raw = daemon_connection
            .send_and_receive(&message)
            .await
            .wrap_err("failed to send/receive build message")?;
        match serde_json::from_slice(&reply_raw)
            .wrap_err("failed to deserialize build reply from daemon")?
        {
            DaemonCoordinatorReply::TriggerBuildResult(result) => result
                .map_err(|e| eyre!(e))
                .wrap_err("daemon returned an error")?,
            _ => bail!("unexpected reply"),
        }

        daemons.insert(daemon_id.clone());
    }

    tracing::info!("successfully triggered dataflow build `{build_id}`",);

    Ok(RunningBuild {
        errors: Vec::new(),
        build_result: CachedResult::default(),
        buffered_log_messages: Vec::new(),
        log_subscribers: Vec::new(),
        pending_build_results: daemons,
        build_started_at: std::time::Instant::now(),
    })
}

#[allow(clippy::too_many_arguments)]
pub(crate) async fn start_dataflow(
    build_id: Option<BuildId>,
    session_id: SessionId,
    dataflow: Descriptor,
    local_working_dir: Option<PathBuf>,
    name: Option<String>,
    daemon_connections: &mut DaemonConnections,
    clock: &HLC,
    uv: bool,
    write_events_to: Option<PathBuf>,
) -> eyre::Result<RunningDataflow> {
    let SpawnedDataflow {
        uuid,
        daemons,
        nodes,
        node_to_daemon,
    } = spawn_dataflow(
        build_id,
        session_id,
        dataflow.clone(),
        local_working_dir,
        daemon_connections,
        clock,
        uv,
        write_events_to,
    )
    .await?;
    Ok(RunningDataflow {
        uuid,
        name,
        descriptor: dataflow,
        pending_daemons: if daemons.len() > 1 {
            daemons.clone()
        } else {
            BTreeSet::new()
        },
        exited_before_subscribe: Default::default(),
        ready_barrier_released: false,
        daemons: daemons.clone(),
        nodes,
        node_to_daemon,
        node_metrics: BTreeMap::new(),
        node_finalized: BTreeSet::new(),
        node_stopped_at: BTreeMap::new(),
        network_metrics: None,
        spawn_result: CachedResult::default(),
        stop_reply_senders: Vec::new(),
        buffered_log_messages: Vec::new(),
        log_subscribers: Vec::new(),
        topic_subscribers: BTreeMap::new(),
        daemon_ack_sequence: daemons.iter().map(|d| (d.clone(), 0)).collect(),
        pending_spawn_results: daemons,
        // Capture the spawn-dispatch start time before any per-daemon
        // spawn RPC has fired so the watchdog can compare against the
        // earliest meaningful moment. The dispatch itself happened in
        // `spawn_dataflow` just above; the `Instant::now()` here is at
        // most a few microseconds late.
        spawn_started_at: std::time::Instant::now(),
        created_at: state::now_millis(),
        store_generation: 0,
        last_recovery_attempt: BTreeMap::new(),
        last_replay_attempt: BTreeMap::new(),
        uv,
        state_log_sequence: 0,
        state_log: Vec::new(),
    })
}

async fn destroy_daemon(
    daemon_id: DaemonId,
    daemon_connection: DaemonConnection,
    timestamp: uhlc::Timestamp,
) -> eyre::Result<()> {
    let message = serde_json::to_vec(&Timestamped {
        inner: DaemonCoordinatorEvent::Destroy,
        timestamp,
    })?;

    let reply_raw = daemon_connection
        .send_and_receive(&message)
        .await
        .wrap_err(format!(
            "failed to send/receive destroy message to daemon `{daemon_id}`"
        ))?;
    match serde_json::from_slice(&reply_raw)
        .wrap_err("failed to deserialize destroy reply from daemon")?
    {
        DaemonCoordinatorReply::DestroyResult { result, .. } => result
            .map_err(|e| eyre!(e))
            .wrap_err("failed to destroy dataflow")?,
        other => bail!("unexpected reply after sending `destroy`: {other:?}"),
    }

    tracing::info!("successfully destroyed daemon `{daemon_id}`");
    Ok(())
}

async fn destroy_daemons(
    daemon_connections: &mut DaemonConnections,
    timestamp: uhlc::Timestamp,
) -> eyre::Result<()> {
    let futures = daemon_connections
        .drain()
        .map(|(daemon_id, daemon_connection)| {
            destroy_daemon(daemon_id, daemon_connection, timestamp)
        })
        .collect::<Vec<_>>();
    let results: Vec<std::result::Result<(), eyre::Error>> =
        join_all(futures).await.into_iter().collect::<Vec<_>>();
    for result in results {
        result?;
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::state::DaemonConnection;
    use crate::topic_subscriber::TopicSubscriber;

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

    #[test]
    fn running_logs_use_node_to_daemon_with_multiple_unnamed_daemons() {
        // Two unnamed daemons are connected and the target node has no explicit
        // deploy machine. The machine-based derivation would collect both and
        // bail; `node_to_daemon` resolves the exact daemon that runs the node.
        let node = NodeId::from("worker".to_string());
        let d1 = DaemonId::new(None);
        let d2 = DaemonId::new(None);

        let mut daemon_connections = DaemonConnections::default();
        daemon_connections.add(d1.clone(), dummy_connection());
        daemon_connections.add(d2.clone(), dummy_connection());

        let mut node_to_daemon = BTreeMap::new();
        node_to_daemon.insert(node.clone(), d2.clone());

        let resolved = resolve_log_daemon_id(
            Some(&node_to_daemon),
            None,
            Uuid::nil(),
            &node,
            &daemon_connections,
        )
        .expect("running node must resolve to its recorded daemon");
        assert_eq!(resolved, d2);
    }

    #[test]
    fn running_logs_error_when_node_not_in_dataflow() {
        let node_to_daemon = BTreeMap::new();
        let daemon_connections = DaemonConnections::default();
        let err = resolve_log_daemon_id(
            Some(&node_to_daemon),
            None,
            Uuid::nil(),
            &NodeId::from("ghost".to_string()),
            &daemon_connections,
        )
        .expect_err("a node absent from the dataflow must error");
        assert!(err.to_string().contains("ghost"), "got: {err}");
    }

    #[test]
    fn unknown_dataflow_errors() {
        let daemon_connections = DaemonConnections::default();
        let err = resolve_log_daemon_id(
            None,
            None,
            Uuid::nil(),
            &NodeId::from("n".to_string()),
            &daemon_connections,
        )
        .expect_err("unknown dataflow must error");
        assert!(err.to_string().contains("No dataflow found"), "got: {err}");
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
    async fn send_topic_frames_resets_timeout_streak_on_successful_send() {
        let subscription_id = Uuid::new_v4();
        let (tx, mut rx) = tokio::sync::mpsc::channel(4);
        let mut subscriber = TopicSubscriber::new(BTreeMap::new(), tx);
        // Prime the counter: simulate 3 prior timeouts.
        assert_eq!(subscriber.record_timeout(), 1);
        assert_eq!(subscriber.record_timeout(), 2);
        assert_eq!(subscriber.record_timeout(), 3);

        let mut subscribers = BTreeMap::new();
        subscribers.insert(subscription_id, subscriber);

        // A real send should succeed (channel has capacity) and reset the streak.
        send_topic_frames(&mut subscribers, vec![subscription_id], vec![1, 2, 3]).await;

        let frame = rx.try_recv().expect("subscriber should receive frame");
        assert_eq!(&*frame.payload, &[1u8, 2, 3]);
        // Streak must be back to 0 after a successful send.
        assert_eq!(
            subscribers
                .get_mut(&subscription_id)
                .unwrap()
                .record_timeout(),
            1
        );
    }

    #[tokio::test(flavor = "current_thread", start_paused = true)]
    async fn send_topic_frames_closes_subscriber_after_100_consecutive_timeouts() {
        // Capacity 1 + pre-filled + rx never drained = every send_frame times out.
        // `start_paused = true` makes tokio auto-advance through the 100 × 100ms
        // timeouts without real wall-clock delay.
        let subscription_id = Uuid::new_v4();
        let (tx, _rx_never_drained) = tokio::sync::mpsc::channel(1);
        tx.send(crate::topic_subscriber::TopicFrame {
            subscription_id,
            payload: std::sync::Arc::from(vec![].into_boxed_slice()),
        })
        .await
        .unwrap();

        let subscriber = TopicSubscriber::new(BTreeMap::new(), tx);
        let mut subscribers = BTreeMap::new();
        subscribers.insert(subscription_id, subscriber);

        for i in 1..=99 {
            send_topic_frames(&mut subscribers, vec![subscription_id], vec![0]).await;
            assert!(
                subscribers.contains_key(&subscription_id),
                "subscriber evicted prematurely at iteration {i}"
            );
        }
        // 100th consecutive timeout triggers the close + retain eviction.
        send_topic_frames(&mut subscribers, vec![subscription_id], vec![0]).await;
        assert!(
            !subscribers.contains_key(&subscription_id),
            "subscriber should be evicted after 100 consecutive timeouts"
        );
    }

    /// Build a minimal `RunningDataflow` running on exactly `daemons`.
    fn dataflow_on(uuid: Uuid, daemons: impl IntoIterator<Item = DaemonId>) -> RunningDataflow {
        let descriptor: Descriptor = serde_json::from_value(serde_json::json!({
            "nodes": [{ "id": "sender", "outputs": ["message"] }]
        }))
        .expect("valid test descriptor");

        RunningDataflow {
            name: None,
            uuid,
            descriptor,
            daemons: daemons.into_iter().collect(),
            pending_daemons: BTreeSet::new(),
            exited_before_subscribe: vec![],
            nodes: BTreeMap::new(),
            node_to_daemon: BTreeMap::new(),
            node_metrics: BTreeMap::new(),
            node_finalized: BTreeSet::new(),
            node_stopped_at: BTreeMap::new(),
            network_metrics: None,
            ready_barrier_released: false,
            spawn_result: CachedResult::default(),
            stop_reply_senders: vec![],
            buffered_log_messages: vec![],
            log_subscribers: vec![],
            topic_subscribers: BTreeMap::new(),
            pending_spawn_results: BTreeSet::new(),
            spawn_started_at: std::time::Instant::now(),
            created_at: 0,
            store_generation: 0,
            last_recovery_attempt: BTreeMap::new(),
            last_replay_attempt: BTreeMap::new(),
            uv: false,
            state_log_sequence: 0,
            state_log: Vec::new(),
            daemon_ack_sequence: BTreeMap::new(),
        }
    }

    /// A connection emulating the ws_daemon handler task for a *healthy* daemon:
    /// it records each request it receives and completes the matching
    /// `pending_replies` oneshot with a successful `StopResult`. Returns the
    /// connection plus the shared log of requests the daemon actually received.
    fn healthy_daemon() -> (
        DaemonConnection,
        std::sync::Arc<tokio::sync::Mutex<Vec<String>>>,
    ) {
        let received = std::sync::Arc::new(tokio::sync::Mutex::new(Vec::new()));
        let pending: std::sync::Arc<
            tokio::sync::Mutex<HashMap<Uuid, tokio::sync::oneshot::Sender<String>>>,
        > = std::sync::Arc::new(tokio::sync::Mutex::new(HashMap::new()));
        let (tx, mut rx) = tokio::sync::mpsc::channel::<String>(8);
        let conn = DaemonConnection::new(tx, pending.clone(), BTreeMap::new());

        let received_task = received.clone();
        tokio::spawn(async move {
            while let Some(msg) = rx.recv().await {
                let value: serde_json::Value =
                    serde_json::from_str(&msg).expect("outgoing request is JSON");
                let id: Uuid = value["id"]
                    .as_str()
                    .expect("request carries an id")
                    .parse()
                    .expect("id is a uuid");
                // Record receipt *before* replying, so a returned `Ok` from
                // `send_and_receive` guarantees the request is already logged.
                received_task.lock().await.push(msg.clone());
                let reply = serde_json::to_string(&DaemonCoordinatorReply::StopResult(Ok(())))
                    .expect("serialize reply");
                if let Some(sender) = pending.lock().await.remove(&id) {
                    let _ = sender.send(reply);
                }
            }
        });

        (conn, received)
    }

    /// A connection whose receiver is dropped, so the very first `send` fails —
    /// modelling an unreachable/disconnected daemon.
    fn broken_daemon() -> DaemonConnection {
        let (tx, rx) = tokio::sync::mpsc::channel::<String>(1);
        drop(rx);
        DaemonConnection::new(
            tx,
            std::sync::Arc::new(tokio::sync::Mutex::new(HashMap::new())),
            BTreeMap::new(),
        )
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn stop_dataflow_is_best_effort_when_a_daemon_fails() {
        // A dataflow on two daemons where the one iterated *first* is
        // unreachable. `DaemonId` orders by machine id, so `broken` (b) sorts
        // before `healthy` (h) in `dataflow.daemons` (a `BTreeSet`): under the
        // old first-failure `?` code the healthy daemon would never be reached
        // and its nodes would be orphaned. Best-effort must still stop it.
        let dataflow_uuid = Uuid::new_v4();
        let broken = DaemonId::new(Some("broken".to_string()));
        let healthy = DaemonId::new(Some("healthy".to_string()));

        let mut daemon_connections = DaemonConnections::default();
        daemon_connections.add(broken.clone(), broken_daemon());
        let (healthy_conn, healthy_received) = healthy_daemon();
        daemon_connections.add(healthy.clone(), healthy_conn);

        let mut running_dataflows = HashMap::new();
        running_dataflows.insert(
            dataflow_uuid,
            dataflow_on(dataflow_uuid, [broken.clone(), healthy.clone()]),
        );

        let timestamp = HLC::default().new_timestamp();
        // `stop_dataflow`'s `Ok` is `&mut RunningDataflow` (not `Debug`), so
        // destructure by hand rather than via `expect_err`.
        let err = match stop_dataflow(
            &mut running_dataflows,
            dataflow_uuid,
            &mut daemon_connections,
            timestamp,
            None,
            false,
        )
        .await
        {
            Ok(_) => panic!("a failing daemon must surface an aggregated error"),
            Err(err) => err,
        };

        // The core property: the healthy daemon was still told to stop even
        // though the daemon iterated before it failed.
        let received = healthy_received.lock().await;
        assert_eq!(
            received.len(),
            1,
            "healthy daemon must receive exactly one stop request"
        );
        assert!(
            received[0].contains("StopDataflow"),
            "healthy daemon must receive a StopDataflow, got: {}",
            received[0]
        );

        // The error is aggregated: it reports one of two daemons failed and
        // names the failing one (so the CLI still learns what broke).
        let msg = format!("{err:#}");
        assert!(
            msg.contains("1 of 2 daemon(s)"),
            "error must aggregate the per-daemon outcome: {msg}"
        );
        assert!(
            msg.contains("broken"),
            "error must name the failed daemon: {msg}"
        );
    }
}