1use std::collections::{BTreeMap, BTreeSet, HashMap};
26use std::sync::Arc;
27use std::time::Duration;
28
29use jiff::{SignedDuration, Timestamp};
30use prost::Message as _;
31use schedr_db::attempts::{AttemptEnd, CleanupEnd, ReadyInstance, StoredAttempt};
32use schedr_db::run_of::{Matching, OtherRun};
33use schedr_db::{Database, DbError};
34use schedr_model::connection::Registry;
35use schedr_model::ctx::MAX_CTX_MESSAGE_SIZE;
36use schedr_model::runner::{
37 CleanupHandle, DAG_FILE_MISSING, ErrorSummary, ProcessUsage, TASK_NOT_FOUND,
38};
39use schedr_model::task::{CleanupRun, RunOf, TaskCleanup};
40use schedr_model::task::{SensorWaitFor, WaitSource};
41use schedr_model::{
42 AttemptStatus, CleanupResult, Dag, DagId, Reference, SchedrVersion, TaskId, TaskInstanceState,
43};
44use schedr_model::{Task, TaskKind};
45use schedr_proto::convert::{
46 RejectReaction, attempt_status_from_proto, cleanup_result_from_proto, reject_reaction,
47 run_kind_to_proto,
48};
49use schedr_proto::pb;
50
51use crate::core::Arrivals;
52use crate::execution::{AttemptResult, Execution, ExecutionError, TaskCancel, TaskRetry, WaitEnd};
53use crate::limits::Active;
54use crate::mapping::{self, InputsError};
55use crate::metrics::{MasterMetrics, ReasonLabels};
56use crate::quiet::Wakes;
57use crate::workers::{Needs, Workers};
58
59pub(crate) mod chained;
60mod event_wait;
61pub(crate) use event_wait::event_value;
62#[cfg(test)]
63mod tests;
64
65pub const DEFAULT_LEASE: SignedDuration = SignedDuration::from_secs(10);
68
69pub const DEFAULT_SET_ASIDE: Duration = Duration::from_mins(1);
72
73const DEFAULT_CLEANUP_MOVE_WAIT: Duration = Duration::from_secs(40);
76
77#[must_use]
79pub fn finished_ack(worker_id: &str, attempt_id: &str) -> Outgoing {
80 Outgoing {
81 worker_id: worker_id.to_owned(),
82 message: pb::MasterMessage {
83 message: Some(pb::master_message::Message::FinishedAck(pb::FinishedAck {
84 attempt_id: attempt_id.to_owned(),
85 })),
86 clock: None,
87 },
88 }
89}
90
91const RESULT_NOT_STORED: &str = "result_not_stored";
93
94#[derive(Debug)]
96struct Pick {
97 worker_id: String,
98 attempt_id: String,
99}
100
101fn pending_reason(most: usize) -> String {
103 format!("pending: waiting for a round with room (a round assigns at most {most})")
104}
105
106#[derive(Debug, Default)]
110struct RoundReads {
111 switched_off: BTreeMap<(String, String), schedr_db::strikes::WaitStepStrikes>,
113 first_starts: BTreeMap<String, Option<Timestamp>>,
115}
116
117impl RoundReads {
118 async fn read(db: &Database, ready: &[ReadyInstance]) -> Result<Self, DispatchError> {
119 let waits: Vec<&str> = ready
120 .iter()
121 .filter(|r| {
122 r.dag
123 .task(&r.task_id)
124 .is_some_and(|t| matches!(t.kind, schedr_model::TaskKind::Sensor { .. }))
125 })
126 .map(|r| r.instance_id.as_str())
127 .collect();
128 if waits.is_empty() {
129 return Ok(Self::default());
130 }
131 let switched_off = db
132 .switched_off_wait_steps()
133 .await?
134 .into_iter()
135 .map(|s| ((s.dag_id.clone(), s.task_id.clone()), s))
136 .collect();
137 let started = db.first_starts(&waits).await?;
138 let first_starts = waits
139 .into_iter()
140 .map(|id| (id.to_owned(), started.get(id).copied()))
141 .collect();
142 Ok(Self {
143 switched_off,
144 first_starts,
145 })
146 }
147}
148
149const NO_CLEANUP_WORKER: &str = "no worker for the cleanup";
151
152#[derive(Debug, Clone, Copy, PartialEq, Eq)]
154pub enum KeptResults {
155 Used,
157 Refused,
160}
161
162#[derive(Debug, Clone, Copy, PartialEq, Eq)]
170pub struct ReadBack {
171 pub window: Duration,
173 pub interval: Duration,
175}
176
177impl Default for ReadBack {
178 fn default() -> Self {
180 Self {
181 window: Duration::from_secs(3),
182 interval: Duration::from_millis(500),
183 }
184 }
185}
186
187impl ReadBack {
188 pub async fn stored<F, Fut>(self, mut stored: F) -> bool
190 where
191 F: FnMut() -> Fut,
192 Fut: Future<Output = bool>,
193 {
194 let interval = self.interval.max(Duration::from_millis(1));
195 let deadline = tokio::time::Instant::now() + self.window;
196 loop {
197 if stored().await {
198 return true;
199 }
200 if tokio::time::Instant::now() + interval > deadline {
201 return false;
202 }
203 tokio::time::sleep(interval).await;
204 }
205 }
206}
207
208pub const ASSIGNMENTS_PER_ROUND: usize = 50;
212
213pub const EXPIRIES_PER_ROUND: usize = 50;
215
216pub const DAG_IN_CONFLICT: &str = "waiting: DAG ID conflict";
218
219pub const REASONS_PER_ROUND: usize = 100;
224
225pub const PENDING_PER_ROUND: usize = 500;
228
229pub const CODE_RETRY_DELAY: SignedDuration = SignedDuration::from_secs(35);
232
233pub const DEFAULT_CODE_WAIT: Duration = Duration::from_mins(10);
236
237pub const CODE_GONE_ERRORS: [&str; 2] = [TASK_NOT_FOUND, DAG_FILE_MISSING];
240
241pub const INLINE_INPUTS_LIMIT: usize = 4 * 1024 * 1024;
244
245const CLOCK_FIELD: u32 = 20;
247
248pub const MAX_INPUTS: usize = 64 * 1024 * 1024;
250
251const TIMED_OUT_OUTCOME: &str = "TimedOut";
253
254pub const DEFAULT_HANDED_CALL_MIN: Duration = Duration::from_mins(1);
257
258fn failed_by_master(kind: &str, exception: &str, why: &str) -> AttemptEnd {
260 AttemptEnd {
261 error_kind: Some(kind.to_owned()),
262 error_summary: Some(ErrorSummary::json(exception, why)),
263 ..AttemptEnd::by_master(AttemptStatus::Failed)
264 }
265}
266
267pub const INPUTS_TOO_LARGE: &str = "inputs_too_large";
269
270pub const INPUT_MISMATCH: &str = "input_mismatch";
273
274pub const DEFAULT_CANCEL_GRACE: Duration = Duration::from_secs(30);
277
278#[derive(Debug, Clone, PartialEq)]
280pub struct Outgoing {
281 pub worker_id: String,
283 pub message: pb::MasterMessage,
285}
286
287#[derive(Debug, thiserror::Error)]
289pub enum DispatchError {
290 #[error(transparent)]
292 Db(#[from] DbError),
293 #[error(transparent)]
295 Execution(#[from] ExecutionError),
296 #[error("message from worker `{worker_id}`: {reason}")]
298 BadMessage {
299 worker_id: String,
301 reason: String,
303 },
304 #[error("an assignment of a round's batch ended before it was sent")]
308 Redo,
309}
310
311impl DispatchError {
312 #[must_use]
315 pub fn is_data_fault(&self) -> bool {
316 match self {
317 Self::Db(error) | Self::Execution(ExecutionError::Db(error)) => error.is_data_fault(),
318 _ => false,
319 }
320 }
321}
322
323impl DispatchError {
324 #[must_use]
326 pub const fn commit_unknown(&self) -> bool {
327 matches!(self, Self::Db(DbError::CommitUnknown))
328 }
329}
330
331#[doc(hidden)]
334#[derive(Debug, Clone, Copy, PartialEq, Eq)]
335pub enum Weakened {
336 Echo,
339 Hold,
341 MoveWait,
343}
344
345#[derive(Debug)]
347pub struct Dispatcher {
348 db: Database,
349 execution: Execution,
350 scheduler: crate::scheduler::Scheduler,
352 workers: Workers,
353 away: BTreeSet<String>,
356 cancel_grace: Duration,
357 switch_off_after: u32,
359 sensor_max_wait: Duration,
361 rejections: BTreeMap<String, BTreeMap<String, String>>,
363 code_missing: BTreeMap<String, CodeMissing>,
365 code_wait: SignedDuration,
366 current_code: BTreeMap<String, (BTreeSet<String>, Option<SchedrVersion>)>,
370 connections: BTreeMap<String, (Option<String>, Arc<Registry>)>,
373 metrics: MasterMetrics,
374 witnesses: Vec<(String, Witness)>,
378 arrivals: Arrivals,
380 set_aside: BTreeMap<String, Timestamp>,
382 set_aside_for: SignedDuration,
384 cleanup_move_wait: SignedDuration,
386 lease: SignedDuration,
388 trust_unknown: bool,
390 steady: crate::clock::Steady,
392 wall: Option<fn() -> Timestamp>,
395 move_not_before: BTreeMap<String, Timestamp>,
398 replaced_since: BTreeMap<String, Timestamp>,
402 no_hold: bool,
404 event_lookback: SignedDuration,
407 read_back: ReadBack,
409 stops: Vec<Outgoing>,
412 resolved: mapping::Resolved,
414 round_reads: Option<RoundReads>,
417 adopted_unrecorded: BTreeSet<String>,
420 active: Active,
422 current_versions: BTreeMap<DagId, String>,
425 rounds: crate::core::RoundLimits,
427 code_retry_delay: SignedDuration,
429 handing: BTreeMap<String, serde_json::Value>,
432 trigger_wake: std::sync::Arc<tokio::sync::Notify>,
435 handed_call_min: Duration,
437 max_message_size: usize,
440}
441
442#[derive(Debug, Clone)]
444pub struct Memory {
445 workers: Workers,
446 away: BTreeSet<String>,
447 rejections: BTreeMap<String, BTreeMap<String, String>>,
448 code_missing: BTreeMap<String, CodeMissing>,
449 stops: Vec<Outgoing>,
451 active: Active,
452}
453
454#[derive(Debug, Clone, Copy, PartialEq, Eq)]
456pub enum Witness {
457 Started,
459 Ended,
461}
462
463#[derive(Debug, Default)]
465struct Tally {
466 waiting: BTreeMap<&'static str, i64>,
468 assigned: usize,
470 reasons: Vec<(String, String)>,
473 places: HashMap<String, HashMap<TaskId, usize>>,
476}
477
478impl Tally {
479 fn task_in<'d>(&mut self, version_id: &str, dag: &'d Dag, id: &TaskId) -> Option<&'d Task> {
481 if !self.places.contains_key(version_id) {
482 let places = dag
483 .tasks
484 .iter()
485 .enumerate()
486 .map(|(i, t)| (t.id.clone(), i))
487 .collect();
488 self.places.insert(version_id.to_owned(), places);
489 }
490 self.places[version_id].get(id).map(|&i| &dag.tasks[i])
491 }
492}
493
494#[derive(Debug, Clone)]
496struct CodeMissing {
497 since: Timestamp,
498 by: BTreeMap<String, String>,
499}
500
501impl Dispatcher {
502 #[must_use]
504 pub fn new(db: Database, cancel_grace: Duration) -> Self {
505 Self {
506 execution: Execution::new(db.clone()),
507 scheduler: crate::scheduler::Scheduler::new(db.clone()),
508 db,
509 workers: Workers::new(),
510 away: BTreeSet::new(),
511 cancel_grace,
512 switch_off_after: 3,
513 sensor_max_wait: Duration::from_hours(24),
514 rejections: BTreeMap::new(),
515 code_missing: BTreeMap::new(),
516 code_wait: SignedDuration::ZERO,
517 current_code: BTreeMap::new(),
518 connections: BTreeMap::new(),
519 metrics: MasterMetrics::default(),
520 witnesses: Vec::new(),
521 arrivals: Arrivals::default(),
522 adopted_unrecorded: BTreeSet::new(),
523 set_aside: BTreeMap::new(),
524 handing: BTreeMap::new(),
525 trigger_wake: std::sync::Arc::default(),
526 handed_call_min: DEFAULT_HANDED_CALL_MIN,
527 max_message_size: crate::service::DEFAULT_MAX_MESSAGE_SIZE,
528 cleanup_move_wait: SignedDuration::try_from(DEFAULT_CLEANUP_MOVE_WAIT)
529 .unwrap_or(SignedDuration::MAX),
530 lease: DEFAULT_LEASE,
531 trust_unknown: false,
532 steady: crate::clock::as_given,
533 wall: None,
534 move_not_before: BTreeMap::new(),
535 replaced_since: BTreeMap::new(),
536 no_hold: false,
537 event_lookback: SignedDuration::from_mins(1),
538 set_aside_for: SignedDuration::try_from(DEFAULT_SET_ASIDE)
539 .unwrap_or(SignedDuration::MAX),
540 read_back: ReadBack::default(),
541 stops: Vec::new(),
542 resolved: mapping::Resolved::new(),
543 round_reads: None,
544 active: Active::new(),
545 current_versions: BTreeMap::new(),
546 rounds: crate::core::RoundLimits::default(),
547 code_retry_delay: CODE_RETRY_DELAY,
548 }
549 .with_code_wait(DEFAULT_CODE_WAIT)
550 }
551
552 #[must_use]
554 pub const fn with_sensor_max_wait(mut self, max_wait: Duration) -> Self {
555 self.sensor_max_wait = max_wait;
556 self
557 }
558
559 #[must_use]
561 pub const fn with_switch_off_after(mut self, times: u32) -> Self {
562 self.switch_off_after = times;
563 self
564 }
565
566 pub fn set_scheduler(&mut self, scheduler: crate::scheduler::Scheduler) {
569 self.scheduler = scheduler;
570 }
571
572 pub fn set_metrics(&mut self, metrics: MasterMetrics) {
575 self.execution.set_metrics(metrics.clone());
576 self.metrics = metrics;
577 }
578
579 pub fn set_wakes(&mut self, wakes: Wakes) {
581 self.execution.set_wakes(wakes);
582 }
583
584 #[must_use]
589 pub fn memory(&self) -> Memory {
590 Memory {
591 workers: self.workers.clone(),
592 away: self.away.clone(),
593 rejections: self.rejections.clone(),
594 code_missing: self.code_missing.clone(),
595 stops: self.stops.clone(),
596 active: self.active.clone(),
597 }
598 }
599
600 pub fn recount(&mut self) {
606 self.active = Active::new();
607 }
608
609 pub fn undo(&mut self, memory: Memory, error: &DispatchError) {
612 self.restore(memory);
613 if error.commit_unknown() {
614 self.recount();
615 }
616 }
617
618 pub fn take_witnesses(&mut self) -> Vec<(String, Witness)> {
620 std::mem::take(&mut self.witnesses)
621 }
622
623 pub fn restore(&mut self, memory: Memory) {
625 self.workers = memory.workers;
626 self.away = memory.away;
627 self.rejections = memory.rejections;
628 self.code_missing = memory.code_missing;
629 self.stops = memory.stops;
630 self.active = memory.active;
631 }
632
633 #[cfg(test)]
636 pub(crate) fn queued_cancels(&self) -> Vec<(String, String)> {
637 self.stops
638 .iter()
639 .filter_map(|o| match &o.message.message {
640 Some(pb::master_message::Message::CancelAttempt(c)) => {
641 Some((o.worker_id.clone(), c.attempt_id.clone()))
642 }
643 _ => None,
644 })
645 .collect()
646 }
647
648 #[must_use]
651 pub fn with_arrivals(mut self, arrivals: Arrivals) -> Self {
652 self.arrivals = arrivals;
653 self
654 }
655
656 #[must_use]
658 pub fn with_event_lookback(mut self, lookback: Duration) -> Self {
659 self.event_lookback = SignedDuration::try_from(lookback).unwrap_or(SignedDuration::MAX);
660 self
661 }
662
663 #[must_use]
666 pub fn with_lease(mut self, lease: Duration) -> Self {
667 self.lease = SignedDuration::try_from(lease).unwrap_or(SignedDuration::MAX);
668 self
669 }
670
671 #[doc(hidden)]
673 pub fn weaken(&mut self, safeguard: Weakened) {
674 match safeguard {
675 Weakened::Echo => self.trust_unknown = true,
676 Weakened::Hold => self.no_hold = true,
677 Weakened::MoveWait => self.cleanup_move_wait = SignedDuration::ZERO,
678 }
679 }
680
681 #[must_use]
683 pub fn with_cleanup_move_wait(mut self, wait: Duration) -> Self {
684 self.cleanup_move_wait = SignedDuration::try_from(wait).unwrap_or(SignedDuration::MAX);
685 self
686 }
687
688 #[must_use]
692 pub fn with_set_aside(mut self, set_aside: Duration, read_back: ReadBack) -> Self {
693 self.set_aside_for = SignedDuration::try_from(set_aside).unwrap_or(SignedDuration::MAX);
694 self.read_back = read_back;
695 self
696 }
697
698 #[must_use]
700 pub const fn read_back(&self) -> ReadBack {
701 self.read_back
702 }
703
704 #[must_use]
707 pub const fn with_handed_call_min(mut self, least: Duration) -> Self {
708 self.handed_call_min = least;
709 self
710 }
711
712 #[must_use]
714 pub const fn with_max_message_size(mut self, bytes: usize) -> Self {
715 self.max_message_size = bytes;
716 self
717 }
718
719 pub fn set_notifications(
721 &mut self,
722 notifications: std::sync::Arc<crate::notifications::Notifications>,
723 ) {
724 self.execution.set_notifications(notifications);
725 }
726
727 pub const fn set_max_instances(&mut self, max_instances: usize) {
729 self.execution.set_max_instances(max_instances);
730 }
731
732 pub const fn set_rounds(&mut self, rounds: crate::core::RoundLimits) {
734 self.rounds = rounds;
735 self.execution.set_rounds(rounds);
736 }
737
738 #[must_use]
741 pub fn with_code_retry_delay(mut self, delay: Duration) -> Self {
742 self.code_retry_delay = SignedDuration::try_from(delay).unwrap_or(SignedDuration::MAX);
743 self
744 }
745
746 #[must_use]
748 pub fn with_code_wait(mut self, code_wait: Duration) -> Self {
749 self.code_wait = SignedDuration::try_from(code_wait).unwrap_or(SignedDuration::MAX);
750 self
751 }
752
753 #[must_use]
755 pub const fn workers(&self) -> &Workers {
756 &self.workers
757 }
758
759 #[must_use]
761 pub const fn active(&self) -> &Active {
762 &self.active
763 }
764
765 pub async fn register(
772 &mut self,
773 worker_id: &str,
774 incarnation: &str,
775 queues: &[String],
776 slots: u32,
777 now: Timestamp,
778 ) -> Result<(), DispatchError> {
779 self.away.remove(worker_id);
780 if self.workers.register(worker_id, incarnation, queues, slots) {
781 self.rejections.clear();
782 self.code_missing.clear();
783 self.db.requeue_unschedulable(now).await?;
784 }
785 Ok(())
786 }
787
788 pub fn set_current_code(
792 &mut self,
793 root: &str,
794 accepted: &BTreeSet<String>,
795 version: Option<SchedrVersion>,
796 ) {
797 self.current_code
798 .insert(root.to_owned(), (accepted.clone(), version));
799 }
800
801 pub fn set_connections(
804 &mut self,
805 registries: &BTreeMap<String, Arc<Registry>>,
806 parsed: &BTreeMap<String, String>,
807 ) {
808 self.connections = registries
809 .iter()
810 .map(|(root, registry)| {
811 (
812 root.clone(),
813 (parsed.get(root).cloned(), Arc::clone(registry)),
814 )
815 })
816 .collect();
817 }
818
819 pub fn worker_disconnected(&mut self, worker_id: &str) {
822 self.workers.disconnected(worker_id);
823 }
824
825 pub fn worker_away(&mut self, worker_id: &str) {
827 self.away.insert(worker_id.to_owned());
828 }
829
830 fn may_come_back(&self) -> Vec<String> {
833 let disconnected = self.workers.all().filter(|worker| !worker.connected);
834 let mut ids: BTreeSet<String> = disconnected.map(|worker| worker.id.clone()).collect();
835 ids.extend(self.away.iter().cloned());
836 ids.into_iter().collect()
837 }
838
839 #[must_use]
841 pub fn connection_roots(&self) -> Vec<String> {
842 self.connections
843 .iter()
844 .filter(|(_, (_, registry))| {
845 !registry.connections.is_empty() || !registry.refused.is_empty()
846 })
847 .map(|(root, _)| root.clone())
848 .collect()
849 }
850
851 #[must_use]
853 pub fn registry(&self, root: &str) -> Option<&Arc<Registry>> {
854 self.connections.get(root).map(|(_, registry)| registry)
855 }
856
857 pub fn connection_worker(
867 &self,
868 root: &str,
869 wanted: Option<&str>,
870 ) -> Result<(String, String), String> {
871 let Some(parsed) = self
872 .connections
873 .get(root)
874 .and_then(|(hash, _)| hash.as_ref())
875 else {
876 return Err(format!("root `{root}` has no parsed code yet"));
877 };
878 let current =
879 |w: &crate::workers::Worker| w.roots.get(root).filter(|hash| *hash == parsed).cloned();
880 if let Some(id) = wanted {
881 let worker = self
882 .workers
883 .get(id)
884 .filter(|w| w.connected)
885 .ok_or_else(|| format!("worker `{id}` isn't connected"))?;
886 if worker.state != crate::workers::WorkerState::Active || worker.drained {
888 return Err(format!("worker `{id}` is draining or drained"));
889 }
890 return current(worker)
891 .map(|hash| (id.to_owned(), hash))
892 .ok_or_else(|| {
893 format!("worker `{id}` doesn't have root `{root}` at its current code")
894 });
895 }
896 self.workers
897 .all()
898 .filter(|w| w.state == crate::workers::WorkerState::Active && !w.drained && w.connected)
899 .filter_map(|w| current(w).map(|hash| (w, hash)))
900 .min_by(|(a, _), (b, _)| {
901 a.attempts
902 .len()
903 .cmp(&b.attempts.len())
904 .then(a.id.cmp(&b.id))
905 })
906 .map(|(w, hash)| (w.id.clone(), hash))
907 .ok_or_else(|| format!("no active worker has root `{root}` at its current code"))
908 }
909
910 pub fn set_worker_version(&mut self, worker_id: &str, version: Option<SchedrVersion>) {
912 self.workers.set_version(worker_id, version);
913 }
914
915 pub fn report_root(&mut self, worker_id: &str, root: &str, hash: &str) {
917 self.workers.report_root(worker_id, root, hash);
918 }
919
920 pub fn withdraw_root(&mut self, worker_id: &str, root: &str) {
922 self.workers.withdraw_root(worker_id, root);
923 }
924
925 pub async fn adopt(
933 &mut self,
934 worker_id: &str,
935 attempt_id: &str,
936 now: Timestamp,
937 ) -> Result<(), DispatchError> {
938 match self.db.mark_adopted(attempt_id, now).await {
939 Ok(()) => {}
940 Err(error) if error.is_data_fault() => {
944 tracing::warn!(attempt_id, worker_id, %error, "can't record an adopted attempt's start");
945 self.adopted_unrecorded.insert(attempt_id.to_owned());
946 }
947 Err(error) => return Err(error.into()),
948 }
949 self.workers.release(attempt_id);
951 match self.task_of_attempt(attempt_id).await {
952 Some(task) => self.take_slot(&task, (worker_id, attempt_id), now),
953 None => self.workers.reserve(worker_id, attempt_id, now),
954 }
955 Ok(())
956 }
957
958 async fn task_of_attempt(&self, attempt_id: &str) -> Option<schedr_model::Task> {
960 let attempt = self.db.attempt(attempt_id).await.ok().flatten()?;
961 let dag = self.db.run_dag(&attempt.run_id).await.ok().flatten()?;
962 dag.task(&attempt.task_id).cloned()
963 }
964
965 pub async fn attempt_inputs(&self, attempt_id: &str) -> Result<Option<Vec<u8>>, DispatchError> {
971 attempt_inputs(&self.db, attempt_id).await
972 }
973
974 pub fn draining(&mut self, worker_id: &str) {
976 self.workers.draining(worker_id);
977 }
978
979 pub fn drain(&mut self, worker_id: &str) -> Vec<Outgoing> {
982 self.workers.set_drained(worker_id, true);
983 let pokes = self
984 .workers
985 .get(worker_id)
986 .map(|worker| worker.pokes.iter().cloned().collect::<Vec<_>>())
987 .unwrap_or_default();
988 pokes
989 .iter()
990 .map(|attempt_id| Outgoing {
991 worker_id: worker_id.to_owned(),
992 message: pb::MasterMessage {
993 message: Some(pb::master_message::Message::CancelAttempt(
994 pb::CancelAttempt {
995 attempt_id: attempt_id.clone(),
996 interrupted: true,
997 },
998 )),
999 clock: None,
1000 },
1001 })
1002 .collect()
1003 }
1004
1005 pub fn set_drained(&mut self, worker_id: &str) {
1008 self.workers.set_drained(worker_id, true);
1009 }
1010
1011 #[must_use]
1013 pub fn is_poke(&self, worker_id: &str, attempt_id: &str) -> bool {
1014 self.workers
1015 .get(worker_id)
1016 .is_some_and(|worker| worker.pokes.contains(attempt_id))
1017 }
1018
1019 pub fn set_watcher_slots(&mut self, worker_id: &str, slots: u32) {
1021 self.workers.set_watcher_slots(worker_id, slots);
1022 }
1023
1024 pub async fn resume(&mut self, worker_id: &str, now: Timestamp) -> Result<(), DispatchError> {
1031 self.workers.set_drained(worker_id, false);
1032 self.rejections.clear();
1033 self.code_missing.clear();
1034 self.db.requeue_unschedulable(now).await?;
1035 Ok(())
1036 }
1037
1038 pub async fn step(&mut self, now: Timestamp) -> Result<Vec<Outgoing>, DispatchError> {
1045 let mut outgoing = Vec::new();
1046 self.step_into(now, &mut outgoing).await?;
1047 Ok(outgoing)
1048 }
1049
1050 pub async fn step_into(
1057 &mut self,
1058 now: Timestamp,
1059 outgoing: &mut Vec<Outgoing>,
1060 ) -> Result<(), DispatchError> {
1061 self.prepare(now, outgoing).await?;
1062 self.expire_round(now).await?;
1063 self.assign_round(now, outgoing).await
1064 }
1065
1066 pub async fn prepare(
1072 &mut self,
1073 now: Timestamp,
1074 outgoing: &mut Vec<Outgoing>,
1075 ) -> Result<(), DispatchError> {
1076 outgoing.append(&mut self.stops);
1077 self.witnesses.clear();
1079 self.execution.prepare_runs(now).await?;
1080 self.execution.queue_due_retries(now).await?;
1081 Ok(())
1082 }
1083
1084 pub async fn expire_round(&mut self, now: Timestamp) -> Result<(), DispatchError> {
1091 self.expire(now).await?;
1092 self.end_replaced(now).await?;
1093 Ok(())
1094 }
1095
1096 pub async fn assign_round(
1103 &mut self,
1104 now: Timestamp,
1105 outgoing: &mut Vec<Outgoing>,
1106 ) -> Result<(), DispatchError> {
1107 self.resolved.clear();
1108 self.assign_into(now, outgoing).await
1109 }
1110
1111 pub async fn assign(&mut self, now: Timestamp) -> Result<Vec<Outgoing>, DispatchError> {
1117 let mut outgoing = Vec::new();
1118 self.assign_into(now, &mut outgoing).await?;
1119 Ok(outgoing)
1120 }
1121
1122 pub async fn assign_into(
1129 &mut self,
1130 now: Timestamp,
1131 outgoing: &mut Vec<Outgoing>,
1132 ) -> Result<(), DispatchError> {
1133 let assigned = self.assign_reading(now, outgoing).await;
1134 self.round_reads = None;
1136 assigned
1137 }
1138
1139 async fn assign_reading(
1141 &mut self,
1142 now: Timestamp,
1143 outgoing: &mut Vec<Outgoing>,
1144 ) -> Result<(), DispatchError> {
1145 self.set_aside.retain(|_, until| *until > now);
1146 self.fail_waiting_users(now).await?;
1147 outgoing.append(&mut self.stops);
1149 self.assign_cleanups(now, outgoing).await?;
1150 self.wind_down_removed(now, outgoing).await?;
1151 let ready = self.db.ready_instances(now).await?;
1152 let ready = self.unless_held(ready, now).await?;
1153 let (waits, ready): (Vec<ReadyInstance>, Vec<ReadyInstance>) = ready
1154 .into_iter()
1155 .filter(|r| !self.set_aside.contains_key(&r.instance_id))
1156 .partition(|r| r.dag.task(&r.task_id).is_some_and(waits_for_a_run));
1157 let (chained, mut ready): (Vec<ReadyInstance>, Vec<ReadyInstance>) = ready
1158 .into_iter()
1159 .partition(|r| r.dag.task(&r.task_id).is_some_and(starts_a_run));
1160 self.chained_into(now, &chained, outgoing).await?;
1161 self.handing.clear();
1162 ready.extend(self.wait_for_runs(now, &waits).await?);
1164 if ready.is_empty() {
1166 self.metrics.set_waiting(&[]);
1167 return Ok(());
1168 }
1169 self.round_reads = Some(RoundReads::read(&self.db, &ready).await?);
1170 self.read_limits().await?;
1171 let (workers, active, built) = (self.workers.clone(), self.active.clone(), outgoing.len());
1175 let db = self.db.clone();
1176 let together = Box::pin(db.atomically(self.assign_each(now, &ready, outgoing))).await;
1177 let Err(error) = together else {
1178 self.count_assignments(outgoing.len() - built);
1180 return Ok(());
1181 };
1182 if matches!(error, DispatchError::Db(DbError::CommitUnknown))
1187 && self.stored(&outgoing[built..]).await
1188 {
1189 self.count_assignments(outgoing.len() - built);
1190 return Ok(());
1191 }
1192 self.workers = workers;
1193 self.active = active;
1194 if error.commit_unknown() {
1195 self.recount();
1197 }
1198 outgoing.truncate(built);
1199 if !task_specific(&error) {
1200 return Err(error);
1201 }
1202 if matches!(error, DispatchError::Redo) {
1205 tracing::debug!("an assignment of the round's batch ended: assigning one at a time");
1206 } else {
1207 tracing::warn!(%error, "a round's assignments failed together: assigning one at a time");
1208 }
1209 self.assign_one_by_one(now, &ready, outgoing).await
1210 }
1211
1212 async fn wind_down_removed(
1216 &mut self,
1217 now: Timestamp,
1218 outgoing: &mut Vec<Outgoing>,
1219 ) -> Result<(), DispatchError> {
1220 let runs = self.db.removed_dags_runs().await?;
1221 if runs.is_empty() {
1222 return Ok(());
1223 }
1224 let open = self.db.open_attempts(None).await?;
1225 for run_id in runs {
1226 let wound = Box::pin(self.db.atomically(self.execution.wind_down(&run_id, now))).await;
1228 let stopped = match wound {
1229 Ok(_) => self.cancel_unstarted(&run_id, &open, now).await,
1230 Err(error) => Err(error.into()),
1231 };
1232 match stopped {
1233 Ok(stops) => outgoing.extend(stops),
1234 Err(error) => {
1235 tracing::warn!(run_id, %error, "a removed DAG's run not wound down yet");
1236 }
1237 }
1238 }
1239 Ok(())
1240 }
1241
1242 async fn cancel_unstarted(
1246 &mut self,
1247 run_id: &str,
1248 open: &[schedr_db::attempts::StoredAttempt],
1249 now: Timestamp,
1250 ) -> Result<Vec<Outgoing>, DispatchError> {
1251 let Some(run) = self.db.run_tasks(run_id).await? else {
1252 return Ok(Vec::new());
1253 };
1254 let mut stops = Vec::new();
1255 for attempt in open.iter().filter(|a| a.run_id == run_id) {
1256 let unstarted = !attempt.started
1257 && !attempt.moving
1258 && !self.arrivals.start_waiting(&attempt.id)
1259 && run.dag.resource_of_cleanup(&attempt.task_id).is_none();
1260 let instance = run
1261 .instances
1262 .iter()
1263 .find(|i| i.task_id == attempt.task_id && i.map_index == attempt.map_index);
1264 let running = instance.is_some_and(|i| {
1265 i.state == schedr_model::TaskInstanceState::Running && !run.cancels(i)
1266 });
1267 if unstarted && running {
1268 let key = (&attempt.task_id, Some(attempt.map_index));
1269 stops.extend(self.cancel_task(run_id, key, now).await?.1);
1270 }
1271 }
1272 Ok(stops)
1273 }
1274
1275 async fn unless_held(
1279 &mut self,
1280 ready: Vec<ReadyInstance>,
1281 now: Timestamp,
1282 ) -> Result<Vec<ReadyInstance>, DispatchError> {
1283 if ready.is_empty() {
1284 return Ok(ready);
1285 }
1286 let held = self.db.held_dags().await?;
1287 let mut free = Vec::with_capacity(ready.len());
1288 let mut reasons = Vec::new();
1289 for instance in ready {
1290 let cleanup = instance
1291 .dag
1292 .resource_of_cleanup(&instance.task_id)
1293 .is_some();
1294 match held.get(instance.dag.id.as_str()) {
1295 Some(true) if !cleanup => {}
1296 Some(false) if !cleanup => {
1297 if instance.queued_reason.as_deref() != Some(DAG_IN_CONFLICT) {
1298 reasons.push((instance.instance_id.clone(), DAG_IN_CONFLICT.to_owned()));
1299 }
1300 }
1301 _ => free.push(instance),
1302 }
1303 }
1304 if !reasons.is_empty() {
1305 self.db.set_queued_reasons(&reasons, now).await?;
1306 }
1307 Ok(free)
1308 }
1309
1310 async fn fail_waiting_users(&mut self, now: Timestamp) -> Result<(), DispatchError> {
1314 for waiting in self.db.unschedulable_instances().await? {
1315 let Some(limit) = waiting
1316 .dag
1317 .resources
1318 .iter()
1319 .filter(|r| r.users.contains(&waiting.task_id))
1320 .filter_map(|r| r.unschedulable_timeout_ms)
1321 .min()
1322 else {
1323 continue;
1324 };
1325 let limit = SignedDuration::from_millis(i64::try_from(limit).unwrap_or(i64::MAX));
1326 if waiting.since.checked_add(limit).unwrap_or(Timestamp::MAX) > now {
1327 continue;
1328 }
1329 let reason = format!(
1330 "no worker within {limit:#}: it uses a resource whose `unschedulable_timeout` \
1331 ran out"
1332 );
1333 self.whole(async |me| {
1335 let (_, stops) = me
1336 .execution
1337 .fail_unschedulable(
1338 &waiting.run_id,
1339 (&waiting.task_id, waiting.map_index),
1340 reason,
1341 now,
1342 )
1343 .await?;
1344 me.stop(&waiting.run_id, &stops).await
1345 })
1346 .await?;
1347 }
1348 Ok(())
1349 }
1350
1351 async fn wait_for_runs(
1355 &mut self,
1356 now: Timestamp,
1357 waits: &[ReadyInstance],
1358 ) -> Result<Vec<ReadyInstance>, DispatchError> {
1359 let mut reasons = Vec::new();
1360 let mut handed = Vec::new();
1361 for waiting in waits {
1362 let (run_of, max_wait_ms) = match waiting.dag.task(&waiting.task_id).map(|t| &t.kind) {
1363 Some(TaskKind::WaitFor {
1364 run_of,
1365 max_wait_ms,
1366 }) => (run_of, max_wait_ms),
1367 Some(TaskKind::WaitForEvent { event, max_wait_ms }) => {
1368 self.wait_for_event(waiting, event, *max_wait_ms, now, &mut reasons)
1369 .await?;
1370 continue;
1371 }
1372 Some(TaskKind::Sensor {
1373 wait_for: Some(wait_for),
1374 max_wait_ms,
1375 ..
1376 }) => {
1377 if self
1378 .sensor_run(waiting, wait_for, *max_wait_ms, now, &mut reasons)
1379 .await?
1380 {
1381 handed.push(waiting.clone());
1382 }
1383 continue;
1384 }
1385 _ => continue,
1386 };
1387 let Some(since) = self.db.ready_since(&waiting.instance_id).await? else {
1388 continue;
1389 };
1390 let deadline = self.deadline(since, *max_wait_ms);
1391 self.db
1394 .park_wait(
1395 &waiting.instance_id,
1396 deadline,
1397 (Some(run_of.dag.as_str()), None),
1398 )
1399 .await?;
1400 let found = self
1401 .matching_run(run_of, waiting.planned_for, since, None, deadline)
1402 .await?;
1403 let ended = match decide(found.as_ref()) {
1404 Some(ended) => ended,
1405 None if now >= deadline => WaitEnd::TimedOut,
1406 None => {
1407 let reason = self.wait_reason(run_of).await?;
1408 if waiting.queued_reason.as_deref() != Some(reason.as_str()) {
1409 reasons.push((waiting.instance_id.clone(), reason));
1410 }
1411 continue;
1412 }
1413 };
1414 self.whole(async |me| {
1415 let (_, stops) = me
1416 .execution
1417 .wait_ended(&waiting.run_id, &waiting.task_id, ended, now)
1418 .await?;
1419 me.stop(&waiting.run_id, &stops).await
1420 })
1421 .await?;
1422 }
1423 if !reasons.is_empty() {
1424 self.db.set_queued_reasons(&reasons, now).await?;
1425 }
1426 Ok(handed)
1427 }
1428
1429 async fn sensor_run(
1434 &mut self,
1435 waiting: &ReadyInstance,
1436 wait_for: &SensorWaitFor,
1437 max_wait_ms: Option<u64>,
1438 now: Timestamp,
1439 reasons: &mut Vec<(String, String)>,
1440 ) -> Result<bool, DispatchError> {
1441 let Some(wait) = self.db.sensor_wait(&waiting.instance_id, now).await? else {
1442 return Ok(false);
1443 };
1444 let deadline = self.deadline(wait.since, max_wait_ms);
1445 let run_of = match wait_for.source() {
1446 Some(WaitSource::RunOf(run_of)) => run_of,
1447 Some(WaitSource::Event(event)) => {
1448 return self
1449 .sensor_event(waiting, event, &wait, (deadline, now), reasons)
1450 .await;
1451 }
1452 None => return Ok(false),
1453 };
1454 self.db
1456 .park_wait(
1457 &waiting.instance_id,
1458 deadline,
1459 (Some(run_of.dag.as_str()), None),
1460 )
1461 .await?;
1462 let again = wait
1465 .handed
1466 .clone()
1467 .filter(|(handed, _)| wait.waited.as_ref().is_none_or(|(seen, _)| seen != handed));
1468 let found = match again {
1469 Some(handed) => Some(handed),
1470 None => self
1471 .matching_run(
1472 run_of,
1473 waiting.planned_for,
1474 wait.since,
1475 wait.waited.as_ref(),
1476 deadline,
1477 )
1478 .await?
1479 .filter(|run| run_ended(&run.state))
1480 .map(|run| (run.run_id, run.ended_at.unwrap_or(now))),
1481 };
1482 if let Some((run_id, ended)) = found
1483 && let Some(mut result) = self.db.run_result(&run_id, run_of.task.as_ref()).await?
1484 {
1485 if let Some(output) = result.get_mut("output") {
1488 schedr_config::masked::mask_data(output);
1489 }
1490 self.db
1491 .hand_run(&waiting.instance_id, &run_id, ended)
1492 .await?;
1493 self.handing.insert(waiting.instance_id.clone(), result);
1494 return Ok(true);
1495 }
1496 if now >= deadline {
1497 self.whole(async |me| me.time_out(waiting, now).await)
1499 .await?;
1500 return Ok(false);
1501 }
1502 let reason = self.wait_reason(run_of).await?;
1503 if waiting.queued_reason.as_deref() != Some(reason.as_str()) {
1504 reasons.push((waiting.instance_id.clone(), reason));
1505 }
1506 Ok(false)
1507 }
1508
1509 fn deadline(&self, since: Timestamp, max_wait_ms: Option<u64>) -> Timestamp {
1512 let max_wait = max_wait_ms.map_or(self.sensor_max_wait, Duration::from_millis);
1513 SignedDuration::try_from(max_wait)
1514 .ok()
1515 .and_then(|wait| since.checked_add(wait).ok())
1516 .unwrap_or(Timestamp::MAX)
1517 }
1518
1519 async fn matching_run(
1525 &self,
1526 run_of: &RunOf,
1527 planned_for: Timestamp,
1528 since: Timestamp,
1529 seen: Option<&(String, Timestamp)>,
1530 deadline: Timestamp,
1531 ) -> Result<Option<OtherRun>, DispatchError> {
1532 let matching = match (run_of.lag_ms, seen) {
1534 (Some(lag), _) => planned_for
1535 .checked_sub(SignedDuration::from_millis(lag))
1536 .ok()
1537 .map(Matching::PlannedFor),
1538 (None, Some((run, at))) => Some(Matching::EndedAfterRun(*at, run.clone())),
1539 (None, None) => Some(Matching::EndedAfter(since)),
1540 };
1541 let task = run_of.task.as_ref().map(TaskId::as_str);
1542 let Some(matching) = matching else {
1543 return Ok(None);
1544 };
1545 let found = self.db.runs_of(run_of.dag.as_str(), task, matching).await?;
1546 Ok(found
1547 .into_iter()
1548 .next()
1549 .filter(|run| seen.is_none_or(|(seen, _)| &run.run_id != seen))
1551 .map(|mut run| {
1552 if run.ended_at.is_some_and(|at| at > deadline) {
1553 "running".clone_into(&mut run.state);
1554 }
1555 run
1556 }))
1557 }
1558
1559 async fn wait_reason(&self, run_of: &RunOf) -> Result<String, DispatchError> {
1562 let what = match &run_of.task {
1563 Some(task) => format!("task `{task}` of a run of `{}`", run_of.dag),
1564 None => format!("a run of `{}`", run_of.dag),
1565 };
1566 let loaded = self
1567 .db
1568 .stored_dag(&run_of.dag)
1569 .await?
1570 .is_some_and(|d| d.current.is_some());
1571 Ok(if loaded {
1572 format!("waiting for {what}")
1573 } else {
1574 format!("waiting for {what}; no DAG `{}` is loaded", run_of.dag)
1575 })
1576 }
1577
1578 async fn read_limits(&mut self) -> Result<(), DispatchError> {
1581 if !self.active.is_loaded() {
1582 self.active.load(self.db.active_attempts().await?);
1583 }
1584 self.current_versions = self.db.active_dag_versions().await?.into_iter().collect();
1585 Ok(())
1586 }
1587
1588 async fn current_dag(
1592 &self,
1593 ready: &ReadyInstance,
1594 ) -> Result<(Arc<Dag>, String), DispatchError> {
1595 let own = || Ok((Arc::clone(&ready.dag), ready.version_id.clone()));
1596 let Some(current) = self.current_versions.get(&ready.dag.id) else {
1597 return own();
1598 };
1599 if *current == ready.version_id {
1600 return own();
1601 }
1602 match self.db.dag_version(current).await {
1603 Ok(dag) => Ok((dag, current.clone())),
1604 Err(error) if error.is_data_fault() => {
1605 tracing::warn!(
1606 %error,
1607 dag_id = %ready.dag.id,
1608 "the DAG's current version doesn't read: its run's own limits hold"
1609 );
1610 own()
1611 }
1612 Err(error) => Err(error.into()),
1613 }
1614 }
1615
1616 async fn held_back(
1619 &self,
1620 ready: &ReadyInstance,
1621 task: &Task,
1622 tally: &mut Tally,
1623 ) -> Result<bool, DispatchError> {
1624 if ready.dag.resource_of_cleanup(&ready.task_id).is_some() {
1625 return Ok(false);
1627 }
1628 let (current, current_id) = self.current_dag(ready).await?;
1629 let in_current = if current_id == ready.version_id {
1630 Some(task)
1631 } else {
1632 tally.task_in(¤t_id, ¤t, &ready.task_id)
1633 };
1634 let Some(reached) = self.active.reached_with(
1635 (¤t, &ready.dag),
1636 (in_current, Some(task)),
1637 &ready.run_id,
1638 &ready.task_id,
1639 ) else {
1640 return Ok(false);
1641 };
1642 *tally.waiting.entry(reached.name).or_default() += 1;
1643 let reason = reached.reason();
1644 if ready.queued_reason.as_deref() != Some(reason.as_str())
1645 && tally.reasons.len() < self.rounds.waiting_reasons
1646 {
1647 tally.reasons.push((ready.instance_id.clone(), reason));
1648 }
1649 Ok(true)
1650 }
1651
1652 fn count_assignments(&self, made: usize) {
1654 self.metrics
1655 .assignments
1656 .inc_by(u64::try_from(made).unwrap_or(u64::MAX));
1657 }
1658
1659 async fn stored(&self, built: &[Outgoing]) -> bool {
1662 let Some(attempt_id) = built.iter().find_map(|o| match &o.message.message {
1663 Some(pb::master_message::Message::AssignTask(assign)) => Some(&assign.attempt_id),
1664 _ => None,
1665 }) else {
1666 return false;
1667 };
1668 self.read_back
1669 .stored(|| async { matches!(self.db.attempt(attempt_id).await, Ok(Some(_))) })
1670 .await
1671 }
1672
1673 async fn assign_one_by_one(
1677 &mut self,
1678 now: Timestamp,
1679 ready: &[ReadyInstance],
1680 outgoing: &mut Vec<Outgoing>,
1681 ) -> Result<(), DispatchError> {
1682 let mut tally = Tally::default();
1683 let (mut failed, mut made) = (Vec::new(), 0);
1684 for (n, one) in ready.iter().enumerate() {
1685 if tally.assigned >= self.rounds.assignments {
1687 let db = self.db.clone();
1688 let rest = Box::pin(db.atomically(self.past_the_cap(now, &ready[n..], &mut tally)));
1689 if let Err(error) = rest.await {
1690 tracing::warn!(%error, "the tasks past the round's cap not gone through");
1691 }
1692 break;
1693 }
1694 let (workers, active, built) =
1695 (self.workers.clone(), self.active.clone(), outgoing.len());
1696 let counted = tally.assigned;
1697 let db = self.db.clone();
1698 let assigned =
1699 Box::pin(db.atomically(self.assign_one(now, one, outgoing, &mut tally))).await;
1700 let Err(error) = assigned else {
1701 made += outgoing.len() - built;
1702 self.count_assignments(outgoing.len() - built);
1703 continue;
1704 };
1705 self.workers = workers;
1706 self.active = active;
1707 tally.assigned = counted;
1708 if error.commit_unknown() {
1709 self.recount();
1711 self.read_limits().await?;
1712 }
1713 outgoing.truncate(built);
1714 if !task_specific(&error) {
1715 return Err(error);
1716 }
1717 failed.push((one, error));
1718 }
1719 if made == 0 && failed.len() > 1 {
1722 return Err(failed.swap_remove(0).1);
1723 }
1724 for (one, error) in failed {
1725 let until = now.checked_add(self.set_aside_for).unwrap_or(now);
1726 tracing::warn!(
1727 %error,
1728 run_id = one.run_id,
1729 task_id = %one.task_id,
1730 %until,
1731 "a task's assignment failed on its own: set aside, the others go on"
1732 );
1733 self.set_aside.insert(one.instance_id.clone(), until);
1734 }
1735 let db = self.db.clone();
1737 let written = Box::pin(db.atomically(db.set_queued_reasons(&tally.reasons, now))).await;
1738 if let Err(error) = written {
1739 tracing::warn!(%error, "waiting reasons not written");
1740 }
1741 let waiting: Vec<(&'static str, i64)> = tally.waiting.into_iter().collect();
1742 self.metrics.set_waiting(&waiting);
1743 Ok(())
1744 }
1745
1746 async fn assign_each(
1749 &mut self,
1750 now: Timestamp,
1751 ready: &[ReadyInstance],
1752 outgoing: &mut Vec<Outgoing>,
1753 ) -> Result<(), DispatchError> {
1754 let mut tally = Tally::default();
1755 let mut picks = Vec::new();
1758 for (n, one) in ready.iter().enumerate() {
1759 if tally.assigned >= self.rounds.assignments {
1760 self.past_the_cap(now, &ready[n..], &mut tally).await?;
1761 break;
1762 }
1763 if let Some(pick) = self.pick_one(now, one, &mut tally).await? {
1764 picks.push((one, pick));
1765 }
1766 }
1767 let claims: Vec<(&str, &str, &str)> = picks
1768 .iter()
1769 .map(|(one, pick)| {
1770 (
1771 one.instance_id.as_str(),
1772 pick.worker_id.as_str(),
1773 pick.attempt_id.as_str(),
1774 )
1775 })
1776 .collect();
1777 let tries = if claims.is_empty() {
1778 BTreeMap::new()
1779 } else {
1780 self.db.claim_attempts(&claims, now).await?
1781 };
1782 let in_batch = picks.len() > 1;
1783 for (one, pick) in picks {
1784 let try_number = tries.get(&one.instance_id).copied();
1785 self.build_one(now, one, (pick, try_number), in_batch, outgoing, &mut tally)
1786 .await?;
1787 }
1788 self.db.set_queued_reasons(&tally.reasons, now).await?;
1789 let waiting: Vec<(&'static str, i64)> = tally.waiting.into_iter().collect();
1790 self.metrics.set_waiting(&waiting);
1791 Ok(())
1792 }
1793
1794 async fn past_the_cap(
1800 &mut self,
1801 now: Timestamp,
1802 rest: &[ReadyInstance],
1803 tally: &mut Tally,
1804 ) -> Result<(), DispatchError> {
1805 let pending = pending_reason(self.rounds.assignments);
1806 let mut shown = 0;
1809 for ready in rest {
1810 let dag = Arc::clone(&ready.dag);
1811 let Some(task) = tally.task_in(&ready.version_id, &dag, &ready.task_id) else {
1812 continue;
1813 };
1814 if self.ended_before_its_call(ready, task, now).await? {
1815 continue;
1816 }
1817 *tally.waiting.entry("next_round").or_default() += 1;
1818 if ready.queued_reason.as_deref() != Some(pending.as_str())
1819 && shown < self.rounds.pending_reasons
1820 {
1821 shown += 1;
1822 tally
1823 .reasons
1824 .push((ready.instance_id.clone(), pending.clone()));
1825 }
1826 }
1827 Ok(())
1828 }
1829
1830 async fn params_json(&self, ready: &ReadyInstance) -> Result<Vec<u8>, DispatchError> {
1835 if ready.dag.params.is_none() {
1836 return Ok(Vec::new());
1837 }
1838 Ok(self
1839 .db
1840 .run_params(&ready.run_id)
1841 .await?
1842 .map(|p| p.to_string().into_bytes())
1843 .unwrap_or_default())
1844 }
1845
1846 async fn assign_one(
1847 &mut self,
1848 now: Timestamp,
1849 ready: &ReadyInstance,
1850 outgoing: &mut Vec<Outgoing>,
1851 tally: &mut Tally,
1852 ) -> Result<(), DispatchError> {
1853 let Some(pick) = self.pick_one(now, ready, tally).await? else {
1854 return Ok(());
1855 };
1856 let claim = [(
1857 ready.instance_id.as_str(),
1858 pick.worker_id.as_str(),
1859 pick.attempt_id.as_str(),
1860 )];
1861 let tries = self.db.claim_attempts(&claim, now).await?;
1862 let try_number = tries.get(&ready.instance_id).copied();
1863 self.build_one(now, ready, (pick, try_number), false, outgoing, tally)
1864 .await
1865 }
1866
1867 async fn pick_one(
1871 &mut self,
1872 now: Timestamp,
1873 ready: &ReadyInstance,
1874 tally: &mut Tally,
1875 ) -> Result<Option<Pick>, DispatchError> {
1876 let dag = Arc::clone(&ready.dag);
1877 let Some(task) = tally.task_in(&ready.version_id, &dag, &ready.task_id) else {
1878 return Ok(None);
1879 };
1880 if self.ended_before_its_call(ready, task, now).await? {
1881 return Ok(None);
1882 }
1883 if self.held_back(ready, task, tally).await? {
1885 return Ok(None);
1886 }
1887 let excluded: BTreeSet<String> = self
1888 .rejections
1889 .get(&ready.instance_id)
1890 .map(|r| r.keys().cloned().collect())
1891 .unwrap_or_default();
1892 let needs = self.needs_of(ready, task);
1893 let mut without_code = excluded.clone();
1895 if let Some(missing) = self.code_missing.get(&ready.instance_id) {
1896 without_code.extend(missing.by.keys().cloned());
1897 }
1898 let picked = self
1899 .workers
1900 .pick(needs, &without_code)
1901 .or_else(|| self.workers.pick(needs, &excluded));
1902 let Some(worker_id) = picked.map(str::to_owned) else {
1903 let (why, reason) = self.why_waiting(needs, &excluded);
1904 *tally.waiting.entry(why).or_default() += 1;
1905 if ready.queued_reason.as_deref() != Some(reason.as_str())
1907 && tally.reasons.len() < self.rounds.waiting_reasons
1908 {
1909 tally.reasons.push((ready.instance_id.clone(), reason));
1910 }
1911 return Ok(None);
1912 };
1913 let attempt_id = uuid::Uuid::now_v7().to_string();
1914 self.take_slot(task, (&worker_id, &attempt_id), now);
1915 self.active.assigned(&attempt_id, ready);
1916 tally.assigned += 1;
1917 Ok(Some(Pick {
1918 worker_id,
1919 attempt_id,
1920 }))
1921 }
1922
1923 async fn build_one(
1929 &mut self,
1930 now: Timestamp,
1931 ready: &ReadyInstance,
1932 (pick, try_number): (Pick, Option<u32>),
1933 in_batch: bool,
1934 outgoing: &mut Vec<Outgoing>,
1935 tally: &mut Tally,
1936 ) -> Result<(), DispatchError> {
1937 let Pick {
1938 worker_id,
1939 attempt_id,
1940 } = pick;
1941 let dag = Arc::clone(&ready.dag);
1942 let (Some(try_number), Some(task)) = (
1943 try_number,
1944 tally.task_in(&ready.version_id, &dag, &ready.task_id),
1945 ) else {
1946 self.unpick(&attempt_id, tally);
1947 return Ok(());
1948 };
1949 let inputs = mapping::inputs(
1950 &self.db,
1951 &ready.dag,
1952 &ready.run_id,
1953 (task, ready.map_index),
1954 &mut self.resolved,
1955 )
1956 .await;
1957 let inputs = match inputs {
1958 Ok(inputs) => inputs,
1959 Err(InputsError::Db(error)) => return Err(error.into()),
1960 Err(InputsError::NotArguments(_)) if in_batch => return Err(DispatchError::Redo),
1962 Err(InputsError::NotArguments(why)) => {
1963 self.unpick(&attempt_id, tally);
1964 let end = failed_by_master(INPUT_MISMATCH, "InputMismatch", &why);
1965 self.end_ready(ready, &attempt_id, end, now).await?;
1966 return Ok(());
1967 }
1968 };
1969 let inputs = serde_json::to_vec(&inputs).unwrap_or_else(|_| b"{}".to_vec());
1970 let outcomes =
1971 upstream_outcomes(&self.db, &ready.dag, &ready.run_id, &ready.task_id).await?;
1972 let params = self.params_json(ready).await?;
1973 if inputs.len() > MAX_INPUTS {
1974 if in_batch {
1975 return Err(DispatchError::Redo);
1976 }
1977 self.unpick(&attempt_id, tally);
1978 self.end(
1979 &attempt_id,
1980 &ready.run_id,
1981 (&ready.task_id, ready.map_index),
1982 inputs_too_large(),
1983 now,
1984 )
1985 .await?;
1986 return Ok(());
1987 }
1988 let mut message = self.assign_message(
1989 ready,
1990 &worker_id,
1991 &attempt_id,
1992 try_number,
1993 (inputs, outcomes, params),
1994 );
1995 self.add_event(ready, &mut message).await?;
1996 self.keep_deadline(ready, task, &mut message, now).await?;
1997 let fits = self
1998 .if_it_fits(ready, &attempt_id, (message, in_batch), now)
1999 .await?;
2000 let Some(message) = fits else {
2001 self.unpick(&attempt_id, tally);
2002 return Ok(());
2003 };
2004 outgoing.push(Outgoing { worker_id, message });
2005 Ok(())
2006 }
2007
2008 fn unpick(&mut self, attempt_id: &str, tally: &mut Tally) {
2010 self.workers.release(attempt_id);
2011 self.active.remove(attempt_id);
2012 tally.assigned = tally.assigned.saturating_sub(1);
2013 }
2014
2015 fn start_time(&self, started: &pb::Started, now: Timestamp) -> Timestamp {
2019 let Some(ms) = started.started_master_ms else {
2020 return now;
2021 };
2022 if started.started_timeline != crate::clock::timeline() {
2023 return now;
2024 }
2025 let Ok(at) = Timestamp::from_millisecond(ms) else {
2026 return now;
2027 };
2028 let wall = self.wall.map_or(now, |wall| wall());
2031 let ago = (self.steady)(wall).duration_since(at);
2032 if ago.is_negative() {
2033 return now;
2034 }
2035 self.metrics.start_recorded.observe(ago.as_secs_f64());
2036 wall.checked_sub(ago).map_or(now, |start| start.min(now))
2037 }
2038
2039 pub async fn started(
2046 &mut self,
2047 worker_id: &str,
2048 started: &pb::Started,
2049 now: Timestamp,
2050 ) -> Result<Option<Outgoing>, DispatchError> {
2051 let method = start_method(started);
2052 let at = self.start_time(started, now);
2053 let attempt = self.db.attempt(&started.attempt_id).await?;
2054 if let Some(attempt) = attempt.filter(|a| a.worker_id == worker_id)
2055 && self
2056 .db
2057 .mark_started(&started.attempt_id, method, at)
2058 .await?
2059 {
2060 if !attempt.started {
2062 self.witnesses.push((attempt.id.clone(), Witness::Started));
2063 }
2064 self.rejections.remove(&attempt.instance_id);
2066 self.code_missing.remove(&attempt.instance_id);
2067 return Ok(None);
2068 }
2069 Ok(Some(cancel(worker_id, &started.attempt_id)))
2070 }
2071
2072 pub async fn started_group(
2081 &mut self,
2082 worker_id: &str,
2083 group: &[pb::Started],
2084 now: Timestamp,
2085 ) -> Result<Vec<Outgoing>, DispatchError> {
2086 let ids: Vec<&str> = group.iter().map(|s| s.attempt_id.as_str()).collect();
2087 let attempts: BTreeMap<String, StoredAttempt> = self
2088 .db
2089 .attempts_by_ids(&ids)
2090 .await?
2091 .into_iter()
2092 .filter(|a| a.worker_id == worker_id)
2093 .map(|a| (a.id.clone(), a))
2094 .collect();
2095 let mut methods: BTreeMap<&str, (&str, Timestamp)> = BTreeMap::new();
2098 for started in group {
2099 if attempts.contains_key(&started.attempt_id) {
2100 let at = self.start_time(started, now);
2101 methods
2102 .entry(&started.attempt_id)
2103 .and_modify(|(method, _)| *method = start_method(started))
2104 .or_insert((start_method(started), at));
2105 }
2106 }
2107 let mut running = BTreeSet::new();
2108 for method in ["fork", "spawn"] {
2109 let of: Vec<(&str, Timestamp)> = methods
2110 .iter()
2111 .filter(|&(_, (m, _))| *m == method)
2112 .map(|(id, (_, at))| (*id, *at))
2113 .collect();
2114 running.extend(self.db.mark_started_many(&of, method).await?);
2115 }
2116 for id in &running {
2117 let attempt = &attempts[id];
2118 if !attempt.started {
2120 self.witnesses.push((attempt.id.clone(), Witness::Started));
2121 }
2122 self.rejections.remove(&attempt.instance_id);
2124 self.code_missing.remove(&attempt.instance_id);
2125 }
2126 Ok(group
2127 .iter()
2128 .filter(|s| !running.contains(&s.attempt_id))
2129 .map(|s| cancel(worker_id, &s.attempt_id))
2130 .collect())
2131 }
2132
2133 fn never_started(&self, worker_id: &str, attempt_id: &str) -> bool {
2136 self.trust_unknown || self.arrivals.never_started(worker_id, attempt_id)
2137 }
2138
2139 pub fn set_steady(&mut self, steady: crate::clock::Steady) {
2141 self.steady = steady;
2142 }
2143
2144 pub fn set_wall(&mut self, wall: fn() -> Timestamp) {
2146 self.wall = Some(wall);
2147 }
2148
2149 pub async fn rejected(
2155 &mut self,
2156 worker_id: &str,
2157 rejected: &pb::Rejected,
2158 now: Timestamp,
2159 ) -> Result<(), DispatchError> {
2160 let reaction = reject_reaction(rejected.reason).map_err(|e| DispatchError::BadMessage {
2161 worker_id: worker_id.to_owned(),
2162 reason: e.to_string(),
2163 })?;
2164 let Some(attempt) = self.db.attempt(&rejected.attempt_id).await? else {
2165 return Ok(());
2166 };
2167 if attempt.moving && attempt.worker_id == worker_id && attempt.status.is_none() {
2168 self.rejections
2170 .entry(attempt.instance_id.clone())
2171 .or_default()
2172 .insert(worker_id.to_owned(), rejected.detail.clone());
2173 self.take_back_cleanup(&attempt, now).await?;
2174 return Ok(());
2175 }
2176 if attempt.worker_id != worker_id || attempt.status.is_some() || attempt.started {
2177 return Ok(());
2178 }
2179 let reason = pb::RejectReason::try_from(rejected.reason)
2180 .map_or("unknown", |r| r.as_str_name())
2181 .trim_start_matches("REJECT_REASON_")
2182 .to_lowercase();
2183 self.metrics
2184 .rejections
2185 .get_or_create(&ReasonLabels { reason })
2186 .inc();
2187 self.workers.release(&attempt.id);
2188 self.active.remove(&attempt.id);
2189 let run = self.db.run_tasks(&attempt.run_id).await?;
2190 let cancelling = run
2191 .as_ref()
2192 .is_some_and(|run| run.cancels_instance(&attempt.instance_id));
2193 if cancelling {
2194 self.db
2196 .undo_assignment(&attempt.id, TaskInstanceState::Cancelled, None, None, now)
2197 .await?;
2198 self.execution.settle(&attempt.run_id, now).await?;
2199 return Ok(());
2200 }
2201 let eligible: Option<Vec<String>> = run.and_then(|run| {
2203 let queue = &run.dag.task(&attempt.task_id)?.settings.queue;
2204 let needs = self.needs(&run.dag, queue, &run.parse_version);
2205 Some(self.workers.eligible(needs).map(|w| w.id.clone()).collect())
2206 });
2207 let (state, ready_at, reason) = match reaction {
2208 RejectReaction::Temporary => (TaskInstanceState::Queued, Some(now), None),
2209 RejectReaction::CodeNotThereYet => {
2210 self.not_here(&attempt, rejected, true, eligible.as_deref(), now)
2211 }
2212 RejectReaction::WorkerSpecific => {
2213 self.not_here(&attempt, rejected, false, eligible.as_deref(), now)
2214 }
2215 };
2216 self.db
2217 .undo_assignment(&attempt.id, state, ready_at, reason.as_deref(), now)
2218 .await?;
2219 Ok(())
2220 }
2221
2222 pub async fn task_ended(
2230 &mut self,
2231 worker_id: &str,
2232 result: &pb::Finished,
2233 now: Timestamp,
2234 ) -> Result<(), DispatchError> {
2235 if let Some(attempt) = self.db.attempt(&result.attempt_id).await?
2236 && attempt.worker_id == worker_id
2237 && attempt.status.is_none()
2238 {
2239 self.db
2240 .set_task_result(&attempt.id, &result.encode_to_vec())
2241 .await?;
2242 self.execution
2243 .cleaning_up(&attempt.run_id, &attempt.task_id, attempt.map_index, now)
2244 .await?;
2245 }
2246 Ok(())
2247 }
2248
2249 pub async fn finished(
2256 &mut self,
2257 worker_id: &str,
2258 finished: &pb::Finished,
2259 now: Timestamp,
2260 ) -> Result<Outgoing, DispatchError> {
2261 let status =
2262 attempt_status_from_proto(finished.status).map_err(|e| DispatchError::BadMessage {
2263 worker_id: worker_id.to_owned(),
2264 reason: e.to_string(),
2265 })?;
2266 if let Some(attempt) = self.db.attempt(&finished.attempt_id).await? {
2267 let left_by_it = attempt.worker_id.is_empty()
2272 && attempt.status.is_none()
2273 && finished.cleanup.is_some()
2274 && self.db.cleanup_moved_from(&attempt.id).await?.as_deref() == Some(worker_id);
2275 let rest_only = finished.cleanup.as_ref().is_some_and(|c| c.rest);
2279 if (rest_only || (attempt.worker_id != worker_id && !left_by_it))
2280 && let Some(rest) = &finished.cleanup
2281 && self.db.rest_owed_by(&attempt.id).await?.as_deref() == Some(worker_id)
2282 {
2283 let rest = cleanup_end(rest, worker_id)?;
2284 if self.db.add_rest_cleanup(&attempt.id, &rest).await? {
2285 self.rest_cleaned(&attempt, &rest, now).await?;
2286 }
2287 return Ok(finished_ack(worker_id, &finished.attempt_id));
2288 }
2289 if rest_only {
2290 return Ok(finished_ack(worker_id, &finished.attempt_id));
2292 }
2293 if attempt.worker_id != worker_id && !left_by_it {
2294 tracing::warn!(
2297 worker_id,
2298 attempt_id = %finished.attempt_id,
2299 owner = %attempt.worker_id,
2300 "a worker reported the end of another worker's attempt; ignored"
2301 );
2302 return Ok(finished_ack(worker_id, &finished.attempt_id));
2303 }
2304 self.count_strike(&attempt, finished, status, now).await?;
2305 let mut error_summary = (!finished.error_summary_json.is_empty())
2306 .then(|| String::from_utf8_lossy(&finished.error_summary_json).into_owned());
2307 if attempt.status.is_none()
2309 && CODE_GONE_ERRORS.contains(&finished.error_kind.as_str())
2310 && let Some(context) = self.changed_since(&attempt).await?
2311 {
2312 error_summary = Some(with_context(error_summary.as_deref(), &context));
2313 }
2314 let cleanup = finished
2315 .cleanup
2316 .as_ref()
2317 .map(|c| cleanup_end(c, worker_id))
2318 .transpose()?;
2319 let ran_the_task = left_by_it && attempt.cleanup_moves == 1;
2323 let kept = if attempt.cleanup_moves > 0
2324 && !ran_the_task
2325 && finished.error_kind != RESULT_NOT_STORED
2326 {
2327 self.kept_result(&attempt).await?
2328 } else {
2329 None
2330 };
2331 let (end, result) = if let Some((kept, status)) = kept {
2332 ended(&kept, status, summary_of(&kept), cleanup)
2333 } else {
2334 ended(finished, status, error_summary, cleanup)
2335 };
2336 self.record(&attempt, &end, &result, now).await?;
2337 }
2338 Ok(finished_ack(worker_id, &finished.attempt_id))
2339 }
2340
2341 async fn finish_common(
2343 &mut self,
2344 worker_id: &str,
2345 common: &[(&StoredAttempt, &pb::Finished)],
2346 now: Timestamp,
2347 ) -> Result<(), DispatchError> {
2348 if common.is_empty() {
2349 return Ok(());
2350 }
2351 let mut ends = Vec::with_capacity(common.len());
2352 let mut results = Vec::with_capacity(common.len());
2353 let mut cleared = Vec::new();
2354 for &(attempt, finished) in common {
2355 let status = attempt_status_from_proto(finished.status).map_err(|e| {
2356 DispatchError::BadMessage {
2357 worker_id: worker_id.to_owned(),
2358 reason: e.to_string(),
2359 }
2360 })?;
2361 if finished.wait_step && !finished.struck && status == AttemptStatus::Success {
2365 cleared.push(attempt);
2366 } else {
2367 if finished.wait_step && finished.struck {
2368 self.clear_wait_steps(&std::mem::take(&mut cleared)).await?;
2369 }
2370 self.count_strike(attempt, finished, status, now).await?;
2371 }
2372 let cleanup = finished
2373 .cleanup
2374 .as_ref()
2375 .map(|c| cleanup_end(c, worker_id))
2376 .transpose()?;
2377 let (end, result) = ended(finished, status, summary_of(finished), cleanup);
2378 self.workers.release(&attempt.id);
2379 self.active.remove(&attempt.id);
2380 ends.push(end);
2381 results.push((attempt, result));
2382 }
2383 let rows: Vec<(&str, &AttemptEnd)> = common
2384 .iter()
2385 .zip(&ends)
2386 .map(|((attempt, _), end)| (attempt.id.as_str(), end))
2387 .collect();
2388 self.clear_wait_steps(&cleared).await?;
2389 let recorded = self.db.end_attempts(&rows, now).await?;
2390 let mut by_run: BTreeMap<&str, Vec<(&TaskId, i32, &AttemptResult)>> = BTreeMap::new();
2391 for ((attempt, result), end) in results.iter().zip(&ends) {
2392 if recorded.contains(&attempt.id) {
2393 self.witnesses.push((attempt.id.clone(), Witness::Ended));
2394 self.metrics.attempt_ended(&end.status);
2395 by_run.entry(attempt.run_id.as_str()).or_default().push((
2396 &attempt.task_id,
2397 attempt.map_index,
2398 result,
2399 ));
2400 }
2401 }
2402 for (run_id, results) in by_run {
2403 let done = self
2404 .execution
2405 .attempts_finished(run_id, &results, now)
2406 .await?;
2407 self.stop(run_id, &done.stops).await?;
2408 }
2409 Ok(())
2410 }
2411
2412 pub async fn finished_group(
2423 &mut self,
2424 worker_id: &str,
2425 group: &[pb::Finished],
2426 now: Timestamp,
2427 ) -> Result<Vec<Outgoing>, DispatchError> {
2428 let ids: Vec<&str> = group.iter().map(|f| f.attempt_id.as_str()).collect();
2429 let attempts: BTreeMap<String, StoredAttempt> = self
2430 .db
2431 .attempts_by_ids(&ids)
2432 .await?
2433 .into_iter()
2434 .map(|a| (a.id.clone(), a))
2435 .collect();
2436 let mut seen = BTreeSet::new();
2437 let mut common = Vec::new();
2438 for finished in group {
2439 let first = seen.insert(finished.attempt_id.as_str());
2440 match attempts.get(&finished.attempt_id) {
2441 Some(attempt) if first && is_common(attempt, finished, worker_id) => {
2442 common.push((attempt, finished));
2443 }
2444 None => {}
2446 Some(_) if !first => {}
2447 Some(attempt) if is_repeat(attempt, finished, worker_id) => {}
2448 Some(_) => {
2451 self.finish_common(worker_id, &std::mem::take(&mut common), now)
2452 .await?;
2453 self.finished(worker_id, finished, now).await?;
2454 }
2455 }
2456 }
2457 self.finish_common(worker_id, &common, now).await?;
2458 Ok(group
2459 .iter()
2460 .map(|f| finished_ack(worker_id, &f.attempt_id))
2461 .collect())
2462 }
2463
2464 async fn ended_before_its_call(
2468 &mut self,
2469 ready: &ReadyInstance,
2470 task: &schedr_model::Task,
2471 now: Timestamp,
2472 ) -> Result<bool, DispatchError> {
2473 if !matches!(task.kind, schedr_model::TaskKind::Sensor { .. }) {
2474 return Ok(false);
2475 }
2476 let handed = self.handing.contains_key(&ready.instance_id);
2477 Ok(self.failed_as_switched_off(ready, now).await?
2478 || (!handed && self.timed_out_waiting(ready, task, now).await?))
2479 }
2480
2481 async fn failed_as_switched_off(
2484 &mut self,
2485 ready: &ReadyInstance,
2486 now: Timestamp,
2487 ) -> Result<bool, DispatchError> {
2488 let Some(why) = self.switched_off(ready).await? else {
2489 return Ok(false);
2490 };
2491 if let Some((attempt_id, _)) = self.db.assign_attempt(&ready.instance_id, "", now).await? {
2492 let end = failed_by_master(schedr_model::runner::SWITCHED_OFF, "SwitchedOff", &why);
2493 self.end_ready(ready, &attempt_id, end, now).await?;
2494 }
2495 Ok(true)
2496 }
2497
2498 fn needs_of<'a>(&'a self, ready: &'a ReadyInstance, task: &'a schedr_model::Task) -> Needs<'a> {
2499 Needs {
2500 wait_step: matches!(task.kind, schedr_model::TaskKind::Sensor { .. }),
2501 ..self.needs(&ready.dag, &task.settings.queue, &ready.parse_version)
2502 }
2503 }
2504
2505 async fn time_left(
2509 &self,
2510 ready: &ReadyInstance,
2511 task: &schedr_model::Task,
2512 now: Timestamp,
2513 ) -> Result<Option<(u64, Timestamp)>, DispatchError> {
2514 let schedr_model::TaskKind::Sensor {
2515 max_wait_ms,
2516 wait_for,
2517 ..
2518 } = &task.kind
2519 else {
2520 return Ok(None);
2521 };
2522 let first = if wait_for.is_some() {
2524 self.db
2525 .sensor_wait(&ready.instance_id, now)
2526 .await?
2527 .map(|wait| wait.since)
2528 } else if let Some(first) = self
2529 .round_reads
2530 .as_ref()
2531 .and_then(|reads| reads.first_starts.get(&ready.instance_id))
2532 {
2533 *first
2534 } else {
2535 self.db.first_start(&ready.instance_id).await?
2536 };
2537 let Some(first) = first else {
2538 return Ok(None);
2539 };
2540 let max_wait_ms = *max_wait_ms;
2541 let max_wait = max_wait_ms
2542 .unwrap_or_else(|| u64::try_from(self.sensor_max_wait.as_millis()).unwrap_or(u64::MAX));
2543 let gone = now.duration_since(first).as_millis().max(0);
2544 Ok(Some((
2545 max_wait.saturating_sub(u64::try_from(gone).unwrap_or(u64::MAX)),
2546 first,
2547 )))
2548 }
2549
2550 async fn timed_out_waiting(
2554 &mut self,
2555 ready: &ReadyInstance,
2556 task: &schedr_model::Task,
2557 now: Timestamp,
2558 ) -> Result<bool, DispatchError> {
2559 if self
2560 .time_left(ready, task, now)
2561 .await?
2562 .map(|(left, _)| left)
2563 != Some(0)
2564 {
2565 return Ok(false);
2566 }
2567 self.time_out(ready, now).await?;
2568 Ok(true)
2569 }
2570
2571 async fn time_out(
2573 &mut self,
2574 ready: &ReadyInstance,
2575 now: Timestamp,
2576 ) -> Result<(), DispatchError> {
2577 let Some((attempt_id, _)) = self.db.assign_attempt(&ready.instance_id, "", now).await?
2578 else {
2579 return Ok(());
2580 };
2581 if let Some(attempt) = self.db.attempt(&attempt_id).await? {
2582 let end = AttemptEnd::by_master(AttemptStatus::Success);
2583 let result = AttemptResult {
2584 output: Some(serde_json::json!({})),
2585 outcome: Some(TIMED_OUT_OUTCOME.to_owned()),
2586 ..by_master(AttemptStatus::Success)
2587 };
2588 self.record(&attempt, &end, &result, now).await?;
2589 }
2590 Ok(())
2591 }
2592
2593 async fn if_it_fits(
2597 &mut self,
2598 ready: &ReadyInstance,
2599 attempt_id: &str,
2600 (assign, in_batch): (pb::AssignTask, bool),
2601 now: Timestamp,
2602 ) -> Result<Option<pb::MasterMessage>, DispatchError> {
2603 let mut message = pb::MasterMessage {
2604 message: Some(pb::master_message::Message::AssignTask(assign)),
2605 clock: None,
2606 };
2607 if too_big_to_send(&message, self.max_message_size).is_some()
2610 && let Some(pb::master_message::Message::AssignTask(assign)) = &mut message.message
2611 && !assign.inputs_external
2612 {
2613 assign.inputs_json = Vec::new();
2614 assign.inputs_external = true;
2615 }
2616 let Some(why) = too_big_to_send(&message, self.max_message_size) else {
2617 return Ok(Some(message));
2618 };
2619 if in_batch {
2620 return Err(DispatchError::Redo);
2622 }
2623 self.handing.remove(&ready.instance_id);
2624 let end = failed_by_master(INPUTS_TOO_LARGE, "InputsTooLarge", &why);
2625 self.end_ready(ready, attempt_id, end, now).await?;
2626 Ok(None)
2627 }
2628
2629 fn take_slot(
2631 &mut self,
2632 task: &schedr_model::Task,
2633 (worker, attempt): (&str, &str),
2634 now: Timestamp,
2635 ) {
2636 match task.kind {
2637 schedr_model::TaskKind::Sensor { mode, .. } => {
2638 let poke = mode == schedr_model::SensorMode::Poke;
2639 self.workers.reserve_wait_step(worker, attempt, poke, now);
2640 }
2641 _ => self.workers.reserve(worker, attempt, now),
2642 }
2643 }
2644
2645 async fn keep_deadline(
2648 &self,
2649 ready: &ReadyInstance,
2650 task: &schedr_model::Task,
2651 message: &mut pb::AssignTask,
2652 now: Timestamp,
2653 ) -> Result<(), DispatchError> {
2654 let handed = self.handing.get(&ready.instance_id);
2655 let (left, first) = self.time_left(ready, task, now).await?.unzip();
2656 if left.is_none() && handed.is_none() {
2657 return Ok(());
2658 }
2659 let mut task = task.clone();
2660 if let schedr_model::TaskKind::Sensor {
2661 max_wait_ms,
2662 wait_for,
2663 arguments,
2664 ..
2665 } = &mut task.kind
2666 {
2667 if left.is_some() {
2668 *max_wait_ms = left;
2669 }
2670 if wait_for.is_none() {
2672 message.first_started = first.map(proto_time);
2673 }
2674 if handed.is_some() {
2675 let least = u64::try_from(self.handed_call_min.as_millis()).unwrap_or(u64::MAX);
2676 *max_wait_ms = Some(max_wait_ms.unwrap_or(least).max(least));
2677 }
2678 if let (Some(wait_for), Some(run)) = (wait_for, handed) {
2680 arguments.insert(
2681 wait_for.param.clone(),
2682 schedr_model::value::Value::Literal(run.clone()),
2683 );
2684 }
2685 }
2686 message.task_json = serde_json::to_vec(&as_sent(&task)).unwrap_or_default();
2687 Ok(())
2688 }
2689
2690 async fn end_ready(
2692 &mut self,
2693 ready: &ReadyInstance,
2694 attempt_id: &str,
2695 end: AttemptEnd,
2696 now: Timestamp,
2697 ) -> Result<(), DispatchError> {
2698 let instance = (&ready.task_id, ready.map_index);
2699 self.end(attempt_id, &ready.run_id, instance, end, now)
2700 .await?;
2701 Ok(())
2702 }
2703
2704 async fn switched_off(&self, ready: &ReadyInstance) -> Result<Option<String>, DispatchError> {
2707 let (dag, task) = (ready.dag.id.as_str(), ready.task_id.as_str());
2708 if !self.is_switched_off(&ready.dag, task).await? {
2709 return Ok(None);
2710 }
2711 Ok(Some(format!(
2712 "this wait step is switched off: it got its host killed too many times in a row, \
2713 holding up the wait steps it shares a process with. New code switches it on, or \
2714 `schedr sensors switch-on {dag} {task}`"
2715 )))
2716 }
2717
2718 pub(crate) async fn is_switched_off(
2721 &self,
2722 dag: &schedr_model::Dag,
2723 task: &str,
2724 ) -> Result<bool, DispatchError> {
2725 let strikes = match &self.round_reads {
2726 Some(reads) => reads
2727 .switched_off
2728 .get(&(dag.id.to_string(), task.to_owned()))
2729 .cloned(),
2730 None => self.db.wait_step_strikes(dag.id.as_str(), task).await?,
2731 };
2732 let Some(strikes) = strikes else {
2733 return Ok(false);
2734 };
2735 if strikes.off_at.is_none() {
2736 return Ok(false);
2737 }
2738 if self.code_is_gone(dag, strikes.off_code.as_deref().unwrap_or_default()) {
2739 self.db.wait_step_on_new_code(dag.id.as_str(), task).await?;
2740 return Ok(false);
2741 }
2742 Ok(true)
2743 }
2744
2745 pub(crate) fn code_is_gone(&self, dag: &schedr_model::Dag, code: &str) -> bool {
2748 self.current_code
2749 .get(dag.location.root.as_str())
2750 .is_some_and(|(accepted, _)| !accepted.is_empty() && !accepted.contains(code))
2751 }
2752
2753 async fn clear_wait_steps(&self, succeeded: &[&StoredAttempt]) -> Result<(), DispatchError> {
2757 if succeeded.is_empty() {
2758 return Ok(());
2759 }
2760 let runs: BTreeSet<&str> = succeeded.iter().map(|a| a.run_id.as_str()).collect();
2761 let runs: Vec<&str> = runs.into_iter().collect();
2762 let dags = self.db.run_dag_ids(&runs).await.unwrap_or_default();
2763 let mut by_dag: BTreeMap<&str, BTreeSet<&str>> = BTreeMap::new();
2764 for attempt in succeeded {
2765 if let Some(dag_id) = dags.get(&attempt.run_id) {
2766 by_dag
2767 .entry(dag_id)
2768 .or_default()
2769 .insert(attempt.task_id.as_str());
2770 }
2771 }
2772 for (dag_id, tasks) in by_dag {
2773 let tasks: Vec<&str> = tasks.into_iter().collect();
2774 self.db.clear_wait_steps(dag_id, &tasks).await?;
2775 }
2776 Ok(())
2777 }
2778
2779 async fn count_strike(
2781 &self,
2782 attempt: &StoredAttempt,
2783 finished: &pb::Finished,
2784 status: AttemptStatus,
2785 now: Timestamp,
2786 ) -> Result<(), DispatchError> {
2787 if !finished.wait_step
2788 || attempt.status.is_some()
2789 || !(finished.struck || status == AttemptStatus::Success)
2790 {
2791 return Ok(());
2792 }
2793 let Some(dag) = self.db.run_dag(&attempt.run_id).await.ok().flatten() else {
2794 return Ok(());
2795 };
2796 let (dag_id, task_id) = (dag.id.as_str(), attempt.task_id.as_str());
2797 if !finished.struck {
2798 self.db.clear_wait_step(dag_id, task_id).await?;
2799 return Ok(());
2800 }
2801 let code = finished.code_hash.as_str();
2803 let limit = self.switch_off_after;
2804 if self
2805 .db
2806 .strike_wait_step((dag_id, task_id), limit, code, now)
2807 .await?
2808 {
2809 tracing::warn!(dag_id, task_id, "a wait step was switched off");
2810 }
2811 Ok(())
2812 }
2813
2814 async fn rest_cleaned(
2819 &self,
2820 attempt: &StoredAttempt,
2821 rest: &CleanupEnd,
2822 now: Timestamp,
2823 ) -> Result<(), DispatchError> {
2824 if rest.result == CleanupResult::NotNeeded {
2825 return Ok(());
2826 }
2827 self.db
2828 .set_cleanup_result(&attempt.instance_id, rest.result, now)
2829 .await?;
2830 if !rest.result.fails_the_run() {
2831 return Ok(());
2832 }
2833 if let Some(dag_id) = self
2834 .db
2835 .mark_late_failure(&attempt.run_id, LATE_CLEANUP_FAILED)
2836 .await?
2837 {
2838 tracing::error!(
2839 dag_id,
2840 run_id = %attempt.run_id,
2841 task_id = %attempt.task_id,
2842 attempt_id = %attempt.id,
2843 error_kind = rest.error_kind.as_deref().unwrap_or_default(),
2844 "a cleanup after the run's success failed: handles may be left behind; the run \
2845 is a yellow success (late_cleanup_failed)"
2846 );
2847 self.metrics.run_late_failed(&dag_id, LATE_CLEANUP_FAILED);
2848 let error = rest
2849 .error_summary
2850 .as_deref()
2851 .map(schedr_db::notifications::readable);
2852 self.execution
2853 .late_cleanup_failed(&attempt.run_id, attempt.task_id.as_str(), error, now)
2854 .await?;
2855 }
2856 Ok(())
2857 }
2858
2859 pub async fn expire(&mut self, now: Timestamp) -> Result<usize, DispatchError> {
2871 let workers = &self.workers;
2873 self.adopted_unrecorded
2874 .retain(|attempt| workers.all().any(|w| w.attempts.contains(attempt)));
2875 let coming_back = self.may_come_back();
2877 let unstarted = self
2878 .db
2879 .unstarted_attempts(Timestamp::MAX, &coming_back, u32::MAX)
2880 .await?;
2881 let cleanups = self
2882 .db
2883 .unstarted_cleanups(Timestamp::MAX, &coming_back, u32::MAX)
2884 .await?;
2885 let mut expired = Vec::new();
2886 let mut taken_back = Vec::new();
2887 for (attempt, cleanup) in unstarted
2888 .into_iter()
2889 .map(|a| (a, false))
2890 .chain(cleanups.into_iter().map(|a| (a, true)))
2891 {
2892 if self.adopted_unrecorded.contains(&attempt.id)
2893 || !self.never_started(&attempt.worker_id, &attempt.id)
2894 {
2895 continue;
2896 }
2897 if cleanup {
2898 taken_back.push(attempt);
2899 } else if expired.len() < self.rounds.expiries {
2900 expired.push(attempt);
2901 }
2902 }
2903 for attempt in &taken_back {
2904 self.take_back_cleanup(attempt, now).await?;
2905 }
2906 for attempt in &expired {
2907 let end = AttemptEnd::by_master(AttemptStatus::AssignmentExpired);
2908 let result = by_master(AttemptStatus::AssignmentExpired);
2909 self.whole(async |dispatcher| dispatcher.record(attempt, &end, &result, now).await)
2912 .await?;
2913 }
2914 Ok(expired.len())
2915 }
2916
2917 pub async fn incarnation_replaced(
2932 &mut self,
2933 worker_id: &str,
2934 reported: &BTreeSet<&str>,
2935 now: Timestamp,
2936 ) -> Result<usize, DispatchError> {
2937 let mut left = Vec::new();
2938 let mut never = Vec::new();
2939 for attempt in self.db.open_attempts(Some(worker_id)).await? {
2940 if reported.contains(attempt.id.as_str()) {
2941 continue;
2942 }
2943 if (!attempt.started || attempt.moving) && self.never_started(worker_id, &attempt.id) {
2946 never.push(attempt);
2947 } else {
2948 left.push(attempt.id);
2949 }
2950 }
2951 self.db.mark_replaced(&left, now).await?;
2952 let since = (self.steady)(now);
2953 for attempt_id in &left {
2954 self.replaced_since
2955 .entry(attempt_id.clone())
2956 .or_insert(since);
2957 }
2958 for attempt in &never {
2959 self.take_back_unstarted(attempt, now).await?;
2960 }
2961 Ok(left.len())
2962 }
2963
2964 async fn take_back_unstarted(
2968 &mut self,
2969 attempt: &StoredAttempt,
2970 now: Timestamp,
2971 ) -> Result<(), DispatchError> {
2972 if attempt.moving {
2973 return self.take_back_cleanup(attempt, now).await;
2974 }
2975 let status = AttemptStatus::AssignmentExpired;
2976 let end = AttemptEnd {
2977 error_summary: Some(not_started_summary(&attempt.worker_id)),
2978 ..AttemptEnd::by_master(status)
2979 };
2980 self.whole(async |dispatcher| {
2982 dispatcher
2983 .record(attempt, &end, &by_master(status), now)
2984 .await
2985 })
2986 .await
2987 }
2988
2989 pub async fn unreported_unstarted(
2998 &mut self,
2999 worker_id: &str,
3000 reported: &BTreeSet<&str>,
3001 now: Timestamp,
3002 ) -> Result<usize, DispatchError> {
3003 let unstarted: Vec<StoredAttempt> = self
3004 .db
3005 .open_attempts(Some(worker_id))
3006 .await?
3007 .into_iter()
3008 .filter(|a| (!a.started || a.moving) && !reported.contains(a.id.as_str()))
3009 .collect();
3010 for attempt in &unstarted {
3011 self.take_back_unstarted(attempt, now).await?;
3012 }
3013 Ok(unstarted.len())
3014 }
3015
3016 pub async fn reported(
3025 &mut self,
3026 worker_id: &str,
3027 attempt_ids: &[String],
3028 ) -> Result<(), DispatchError> {
3029 if attempt_ids.is_empty() {
3030 return Ok(());
3031 }
3032 let own: Vec<String> = self
3033 .db
3034 .open_attempts(Some(worker_id))
3035 .await?
3036 .into_iter()
3037 .map(|attempt| attempt.id)
3038 .filter(|id| attempt_ids.contains(id))
3039 .collect();
3040 self.db.clear_replaced(&own).await?;
3042 for id in &own {
3043 self.replaced_since.remove(id);
3044 }
3045 Ok(())
3046 }
3047
3048 pub async fn end_replaced(&mut self, now: Timestamp) -> Result<usize, DispatchError> {
3056 let left = self.db.replaced_attempts().await?;
3057 let steady = (self.steady)(now);
3058 self.replaced_since.retain(|id, _| left.contains(id));
3059 let mut ended = 0;
3060 for attempt_id in left {
3061 let since = *self
3062 .replaced_since
3063 .entry(attempt_id.clone())
3064 .or_insert(steady);
3065 if !self.no_hold && steady.duration_since(since) < self.lease {
3066 continue;
3067 }
3068 let Some(attempt) = self.db.attempt(&attempt_id).await? else {
3069 continue;
3070 };
3071 if attempt.moving {
3075 self.db
3076 .clear_replaced(std::slice::from_ref(&attempt.id))
3077 .await?;
3078 self.take_back_cleanup(&attempt, now).await?;
3079 self.replaced_since.remove(&attempt_id);
3080 ended += 1;
3081 continue;
3082 }
3083 let summary = restarted_summary(&attempt.worker_id);
3084 let done = self
3087 .whole(async |dispatcher| {
3088 dispatcher
3089 .end_lost(&attempt, summary.clone(), KeptResults::Used, now)
3090 .await
3091 })
3092 .await;
3093 match done {
3094 Err(error) if error.is_data_fault() => {
3095 tracing::error!(attempt_id, %error, "a kept result the database refuses");
3096 self.whole(async |dispatcher| {
3097 dispatcher
3098 .end_lost(&attempt, summary.clone(), KeptResults::Refused, now)
3099 .await
3100 })
3101 .await?;
3102 }
3103 done => done?,
3104 }
3105 self.replaced_since.remove(&attempt_id);
3106 ended += 1;
3107 }
3108 self.metrics
3109 .replaced_held
3110 .set(i64::try_from(self.replaced_since.len()).unwrap_or(i64::MAX));
3111 Ok(ended)
3112 }
3113
3114 pub async fn worker_lost(
3122 &mut self,
3123 worker_id: &str,
3124 results: KeptResults,
3125 now: Timestamp,
3126 ) -> Result<(), DispatchError> {
3127 self.whole(async |dispatcher| dispatcher.forget_worker(worker_id, results, now).await)
3129 .await
3130 }
3131
3132 async fn forget_worker(
3133 &mut self,
3134 worker_id: &str,
3135 results: KeptResults,
3136 now: Timestamp,
3137 ) -> Result<(), DispatchError> {
3138 self.workers.remove(worker_id);
3139 self.away.remove(worker_id);
3140 for attempt in self.db.open_attempts(Some(worker_id)).await? {
3141 if attempt.started && !attempt.moving {
3142 self.end_lost(&attempt, lost_summary(worker_id), results, now)
3143 .await?;
3144 continue;
3145 }
3146 if !self.never_started(worker_id, &attempt.id) {
3152 self.end_lost(&attempt, maybe_started_summary(worker_id), results, now)
3153 .await?;
3154 continue;
3155 }
3156 if attempt.moving {
3158 self.take_back_cleanup(&attempt, now).await?;
3159 continue;
3160 }
3161 let status = AttemptStatus::AssignmentExpired;
3163 let end = AttemptEnd {
3164 error_summary: Some(not_started_summary(worker_id)),
3165 ..AttemptEnd::by_master(status)
3166 };
3167 self.record(&attempt, &end, &by_master(status), now).await?;
3168 }
3169 Ok(())
3170 }
3171
3172 async fn end_lost(
3176 &mut self,
3177 attempt: &StoredAttempt,
3178 summary: String,
3179 results: KeptResults,
3180 now: Timestamp,
3181 ) -> Result<(), DispatchError> {
3182 self.db
3185 .clear_replaced(std::slice::from_ref(&attempt.id))
3186 .await?;
3187 self.replaced_since.remove(&attempt.id);
3188 if results == KeptResults::Refused && attempt.result_kept {
3189 return self.end_refused(attempt, now).await;
3190 }
3191 let task_cleanup = self.task_cleanup(attempt).await?;
3192 let kept = self.kept_result(attempt).await?;
3193 if let Some(wanted) = &task_cleanup
3194 && wanted.anywhere
3195 && attempt.cleanup_moves <= wanted.retries
3196 {
3197 return self.move_cleanup(attempt, &summary, now).await;
3198 }
3199 let cleanup = task_cleanup
3200 .as_ref()
3201 .map(|wanted| cleanup_not_run(&attempt.worker_id, wanted));
3202 let (end, result) = if let Some((finished, status)) = kept {
3203 ended(&finished, status, summary_of(&finished), cleanup)
3204 } else {
3205 let result = AttemptResult {
3206 cleanup: cleanup.as_ref().map(|c| c.result),
3207 ..by_master(AttemptStatus::Lost)
3208 };
3209 let end = AttemptEnd {
3210 error_summary: Some(summary),
3211 cleanup,
3212 ..AttemptEnd::by_master(AttemptStatus::Lost)
3213 };
3214 (end, result)
3215 };
3216 self.record(attempt, &end, &result, now).await
3217 }
3218
3219 async fn end_refused(
3222 &mut self,
3223 attempt: &StoredAttempt,
3224 now: Timestamp,
3225 ) -> Result<(), DispatchError> {
3226 let wanted = self.task_cleanup(attempt).await?.unwrap_or_else(no_cleanup);
3227 let cleanup = cleanup_not_run(&attempt.worker_id, &wanted);
3228 let kind = RESULT_NOT_STORED.to_owned();
3229 let result = AttemptResult {
3230 error_kind: Some(kind.clone()),
3231 cleanup: Some(cleanup.result),
3232 ..by_master(AttemptStatus::Failed)
3233 };
3234 let end = AttemptEnd {
3235 error_kind: Some(kind),
3236 error_summary: Some(ErrorSummary::json(
3237 "ResultNotStored",
3238 "the task's result couldn't be stored, and its worker is gone",
3239 )),
3240 cleanup: Some(cleanup),
3241 ..AttemptEnd::by_master(AttemptStatus::Failed)
3242 };
3243 self.record(attempt, &end, &result, now).await
3244 }
3245
3246 async fn task_cleanup(
3248 &self,
3249 attempt: &StoredAttempt,
3250 ) -> Result<Option<TaskCleanup>, DispatchError> {
3251 let run = self.db.run_tasks(&attempt.run_id).await?;
3252 Ok(run.and_then(|run| run.dag.task(&attempt.task_id)?.cleanup.clone()))
3253 }
3254
3255 async fn kept_result(
3257 &self,
3258 attempt: &StoredAttempt,
3259 ) -> Result<Option<(pb::Finished, AttemptStatus)>, DispatchError> {
3260 Ok(self
3261 .db
3262 .task_result(&attempt.id)
3263 .await?
3264 .and_then(|bytes| pb::Finished::decode(bytes.as_slice()).ok())
3265 .and_then(|finished| {
3266 let status = attempt_status_from_proto(finished.status).ok()?;
3267 Some((finished, status))
3268 }))
3269 }
3270
3271 async fn move_cleanup(
3275 &mut self,
3276 attempt: &StoredAttempt,
3277 summary: &str,
3278 now: Timestamp,
3279 ) -> Result<(), DispatchError> {
3280 self.workers.release(&attempt.id);
3281 let lost = pb::Finished {
3282 attempt_id: attempt.id.clone(),
3283 status: pb::AttemptStatus::Lost.into(),
3284 error_summary_json: summary.as_bytes().to_vec(),
3285 ..pb::Finished::default()
3286 };
3287 let not_before = now
3290 .checked_add(self.cleanup_move_wait)
3291 .unwrap_or(Timestamp::MAX);
3292 let steady = (self.steady)(now)
3293 .checked_add(self.cleanup_move_wait)
3294 .unwrap_or(Timestamp::MAX);
3295 self.move_not_before.insert(attempt.id.clone(), steady);
3296 self.db
3297 .move_cleanup(&attempt.id, &lost.encode_to_vec(), not_before)
3298 .await?;
3299 self.execution
3300 .cleaning_up(&attempt.run_id, &attempt.task_id, attempt.map_index, now)
3301 .await?;
3302 Ok(())
3303 }
3304
3305 async fn take_back_cleanup(
3308 &mut self,
3309 attempt: &StoredAttempt,
3310 now: Timestamp,
3311 ) -> Result<(), DispatchError> {
3312 self.workers.release(&attempt.id);
3313 self.db.unassign_cleanup(&attempt.id).await?;
3314 let until = now
3315 .checked_add(self.set_aside_for)
3316 .unwrap_or(Timestamp::MAX);
3317 self.set_aside.insert(attempt.instance_id.clone(), until);
3318 Ok(())
3319 }
3320
3321 async fn assign_cleanups(
3324 &mut self,
3325 now: Timestamp,
3326 outgoing: &mut Vec<Outgoing>,
3327 ) -> Result<(), DispatchError> {
3328 let mut reasons = Vec::new();
3329 let waiting = self.db.waiting_cleanups(Timestamp::MAX).await?;
3332 let steady = (self.steady)(now);
3333 let first_seen = steady
3334 .checked_add(self.cleanup_move_wait)
3335 .unwrap_or(Timestamp::MAX);
3336 self.move_not_before
3337 .retain(|id, _| waiting.iter().any(|(waiting, _)| waiting == id));
3338 for (attempt_id, ready) in waiting {
3339 let not_before = *self
3340 .move_not_before
3341 .entry(attempt_id.clone())
3342 .or_insert(first_seen);
3343 if steady < not_before || self.set_aside.contains_key(&ready.instance_id) {
3344 continue;
3345 }
3346 let Some(task) = ready.dag.task(&ready.task_id) else {
3347 continue;
3348 };
3349 let needs = self.needs(&ready.dag, &task.settings.queue, &ready.parse_version);
3350 let refused: BTreeSet<String> = self
3352 .rejections
3353 .get(&ready.instance_id)
3354 .map(|by| by.keys().cloned().collect())
3355 .unwrap_or_default();
3356 let Some(worker_id) = self
3357 .workers
3358 .pick(needs, &refused)
3359 .or_else(|| self.workers.pick(needs, &BTreeSet::new()))
3360 .map(str::to_owned)
3361 else {
3362 if ready.queued_reason.as_deref() != Some(NO_CLEANUP_WORKER) {
3363 reasons.push((ready.instance_id.clone(), NO_CLEANUP_WORKER.to_owned()));
3364 }
3365 continue;
3366 };
3367 if !self.db.assign_cleanup(&attempt_id, &worker_id, now).await? {
3368 continue;
3369 }
3370 let message = self
3371 .cleanup_message(&ready, &worker_id, &attempt_id)
3372 .await?;
3373 self.workers.reserve(&worker_id, &attempt_id, now);
3374 outgoing.push(Outgoing {
3375 worker_id,
3376 message: pb::MasterMessage {
3377 message: Some(pb::master_message::Message::AssignTask(message)),
3378 clock: None,
3379 },
3380 });
3381 }
3382 if !reasons.is_empty() {
3383 self.db.set_queued_reasons(&reasons, now).await?;
3384 }
3385 Ok(())
3386 }
3387
3388 async fn cleanup_message(
3390 &mut self,
3391 ready: &ReadyInstance,
3392 worker_id: &str,
3393 attempt_id: &str,
3394 ) -> Result<pb::AssignTask, DispatchError> {
3395 let task = ready.dag.task(&ready.task_id);
3396 let inputs = match task {
3397 Some(task) => {
3398 let inputs = mapping::inputs(
3399 &self.db,
3400 &ready.dag,
3401 &ready.run_id,
3402 (task, ready.map_index),
3403 &mut self.resolved,
3404 )
3405 .await;
3406 match inputs {
3407 Ok(inputs) => serde_json::to_vec(&inputs).unwrap_or_else(|_| b"{}".to_vec()),
3408 Err(InputsError::Db(error)) => return Err(error.into()),
3409 Err(InputsError::NotArguments(_)) => b"{}".to_vec(),
3411 }
3412 }
3413 None => b"{}".to_vec(),
3414 };
3415 let outcomes =
3416 upstream_outcomes(&self.db, &ready.dag, &ready.run_id, &ready.task_id).await?;
3417 let params = self.params_json(ready).await?;
3418 let handles = self.db.cleanup_handles(attempt_id).await?;
3419 let mut message = self.assign_message(
3420 ready,
3421 worker_id,
3422 attempt_id,
3423 ready.try_number,
3424 (inputs, outcomes, params),
3425 );
3426 self.add_event(ready, &mut message).await?;
3427 message.cleanup_only = Some(pb::CleanupOnly {
3428 handle_json: handles.into_iter().map(String::into_bytes).collect(),
3429 });
3430 Ok(message)
3431 }
3432
3433 pub async fn handles_added(
3441 &mut self,
3442 worker_id: &str,
3443 added: &pb::HandlesAdded,
3444 ) -> Result<(), DispatchError> {
3445 let Some(attempt) = self.db.attempt(&added.attempt_id).await? else {
3446 return Ok(());
3447 };
3448 if attempt.worker_id != worker_id || attempt.status.is_some() {
3449 return Ok(());
3450 }
3451 let handles: Option<Vec<String>> = added
3452 .handle_json
3453 .iter()
3454 .map(|json| {
3455 serde_json::from_slice::<CleanupHandle>(json).ok()?;
3456 String::from_utf8(json.clone()).ok()
3457 })
3458 .collect();
3459 let Some(handles) = handles else {
3460 tracing::warn!(
3461 worker_id,
3462 attempt_id = attempt.id,
3463 "a handle that doesn't read"
3464 );
3465 return Ok(());
3466 };
3467 let limit = MAX_CTX_MESSAGE_SIZE as usize;
3468 let fitted = self
3469 .db
3470 .add_cleanup_handles(&attempt.id, added.first, &handles, limit)
3471 .await?;
3472 if !fitted {
3473 tracing::warn!(
3474 worker_id,
3475 attempt_id = attempt.id,
3476 "more handles than an attempt may hold"
3477 );
3478 }
3479 Ok(())
3480 }
3481
3482 async fn whole<T>(
3486 &mut self,
3487 work: impl AsyncFnOnce(&mut Self) -> Result<T, DispatchError>,
3488 ) -> Result<T, DispatchError> {
3489 let (db, memory) = (self.db.clone(), self.memory());
3490 let done = Box::pin(db.atomically(work(self))).await;
3491 if let Err(error) = &done {
3492 self.undo(memory, error);
3493 }
3494 done
3495 }
3496
3497 pub async fn cancel_task(
3504 &mut self,
3505 run_id: &str,
3506 (task_id, map_index): (&TaskId, Option<i32>),
3507 now: Timestamp,
3508 ) -> Result<(TaskCancel, Vec<Outgoing>), DispatchError> {
3509 let map_index = map_index.filter(|i| *i >= 0);
3511 let cancelled = self
3512 .execution
3513 .cancel_task(run_id, (task_id, map_index), now)
3514 .await?;
3515 if cancelled != TaskCancel::Stopping {
3516 return Ok((cancelled, Vec::new()));
3517 }
3518 let stopping = self
3519 .db
3520 .open_attempts(None)
3521 .await?
3522 .into_iter()
3523 .filter(|a| a.run_id == run_id && &a.task_id == task_id)
3524 .filter(|a| map_index.is_none_or(|i| a.map_index == i))
3525 .map(|a| cancel(&a.worker_id, &a.id))
3526 .collect();
3527 Ok((cancelled, stopping))
3528 }
3529
3530 pub async fn retry_task(
3537 &mut self,
3538 run_id: &str,
3539 (task_id, map_index): (&TaskId, Option<i32>),
3540 now: Timestamp,
3541 ) -> Result<TaskRetry, DispatchError> {
3542 let retried = self
3543 .execution
3544 .retry_task(run_id, (task_id, map_index), now)
3545 .await?;
3546 if let TaskRetry::Queued(instance_id) = &retried {
3547 self.rejections.remove(instance_id);
3548 self.code_missing.remove(instance_id);
3549 }
3550 Ok(retried)
3551 }
3552
3553 pub async fn cancel_run(
3559 &mut self,
3560 run_id: &str,
3561 now: Timestamp,
3562 ) -> Result<Vec<Outgoing>, DispatchError> {
3563 let cancelled = self.execution.cancel_run(run_id, now).await?;
3564 let running: BTreeSet<(&TaskId, i32)> =
3565 cancelled.running.iter().map(|(t, i)| (t, *i)).collect();
3566 Ok(self
3567 .db
3568 .open_attempts(None)
3569 .await?
3570 .into_iter()
3571 .filter(|a| a.run_id == run_id && running.contains(&(&a.task_id, a.map_index)))
3572 .map(|a| cancel(&a.worker_id, &a.id))
3573 .collect())
3574 }
3575
3576 async fn record(
3577 &mut self,
3578 attempt: &StoredAttempt,
3579 end: &AttemptEnd,
3580 result: &AttemptResult,
3581 now: Timestamp,
3582 ) -> Result<(), DispatchError> {
3583 self.workers.release(&attempt.id);
3584 self.active.remove(&attempt.id);
3585 if self.db.end_attempt(&attempt.id, end, now).await? {
3586 self.witnesses.push((attempt.id.clone(), Witness::Ended));
3587 self.metrics.attempt_ended(&end.status);
3588 let recorded = self
3589 .execution
3590 .attempt_finished(
3591 &attempt.run_id,
3592 &attempt.task_id,
3593 attempt.map_index,
3594 result,
3595 now,
3596 )
3597 .await?;
3598 self.stop(&attempt.run_id, &recorded.stops).await?;
3599 }
3600 Ok(())
3601 }
3602
3603 async fn stop(&mut self, run_id: &str, stops: &[(TaskId, i32)]) -> Result<(), DispatchError> {
3605 if stops.is_empty() {
3606 return Ok(());
3607 }
3608 let stopping: BTreeSet<(&TaskId, i32)> = stops.iter().map(|(t, i)| (t, *i)).collect();
3609 let attempts = self.db.open_attempts(None).await?;
3610 self.stops.extend(
3611 attempts
3612 .iter()
3613 .filter(|a| {
3614 a.run_id == run_id
3615 && !a.worker_id.is_empty()
3616 && stopping.contains(&(&a.task_id, a.map_index))
3617 })
3618 .map(|a| cancel(&a.worker_id, &a.id)),
3619 );
3620 Ok(())
3621 }
3622
3623 async fn end(
3624 &mut self,
3625 attempt_id: &str,
3626 run_id: &str,
3627 (task_id, map_index): (&TaskId, i32),
3628 end: AttemptEnd,
3629 now: Timestamp,
3630 ) -> Result<(), DispatchError> {
3631 let result = AttemptResult {
3632 status: end.status,
3633 error_kind: end.error_kind.clone(),
3634 output: None,
3635 outcome: None,
3636 cleanup: None,
3637 };
3638 self.active.remove(attempt_id);
3639 if self.db.end_attempt(attempt_id, &end, now).await? {
3640 self.witnesses.push((attempt_id.to_owned(), Witness::Ended));
3641 self.metrics.attempt_ended(&end.status);
3642 let recorded = self
3643 .execution
3644 .attempt_finished(run_id, task_id, map_index, &result, now)
3645 .await?;
3646 self.stop(run_id, &recorded.stops).await?;
3647 }
3648 Ok(())
3649 }
3650
3651 fn not_here(
3656 &mut self,
3657 attempt: &StoredAttempt,
3658 rejected: &pb::Rejected,
3659 code: bool,
3660 eligible: Option<&[String]>,
3661 now: Timestamp,
3662 ) -> (TaskInstanceState, Option<Timestamp>, Option<String>) {
3663 let instance = &attempt.instance_id;
3664 let detail = (attempt.worker_id.clone(), rejected.detail.clone());
3665 if code {
3666 let missing = self
3667 .code_missing
3668 .entry(instance.clone())
3669 .or_insert_with(|| CodeMissing {
3670 since: now,
3671 by: BTreeMap::new(),
3672 });
3673 missing.by.insert(detail.0, detail.1);
3674 } else {
3675 let by = self.rejections.entry(instance.clone()).or_default();
3676 by.insert(detail.0, detail.1);
3677 }
3678 let specific = self.rejections.get(instance);
3679 let missing = self.code_missing.get(instance);
3680 let said = |worker: &str| {
3681 specific.is_some_and(|r| r.contains_key(worker))
3682 || missing.is_some_and(|m| m.by.contains_key(worker))
3683 };
3684 let everyone =
3686 eligible.is_none_or(|workers| !workers.is_empty() && workers.iter().all(|w| said(w)));
3687 let waited = missing.map(|m| now.duration_since(m.since));
3688 let code_due = waited.is_none_or(|waited| waited >= self.code_wait);
3689 if everyone && code_due {
3690 let mut reasons: Vec<String> = specific
3691 .into_iter()
3692 .flatten()
3693 .map(|(w, d)| format!("{w}: {d}"))
3694 .collect();
3695 reasons.extend(
3696 missing
3697 .into_iter()
3698 .flat_map(|m| &m.by)
3699 .map(|(w, d)| format!("{w}: {d}")),
3700 );
3701 let reason = match (specific, waited) {
3702 (None, Some(waited)) => format!(
3703 "the code is missing on every eligible worker after {} min ({})",
3704 waited.as_mins(),
3705 reasons.join("; ")
3706 ),
3707 _ => format!("every eligible worker rejected it ({})", reasons.join("; ")),
3708 };
3709 return (TaskInstanceState::Unschedulable, None, Some(reason));
3710 }
3711 if code {
3712 (
3713 TaskInstanceState::Queued,
3714 Some(
3716 now.checked_add(self.code_retry_delay)
3717 .unwrap_or(Timestamp::MAX),
3718 ),
3719 Some(format!(
3720 "waiting for the code on the workers: {}",
3721 rejected.detail
3722 )),
3723 )
3724 } else {
3725 (TaskInstanceState::Queued, Some(now), None)
3726 }
3727 }
3728
3729 async fn changed_since(&self, attempt: &StoredAttempt) -> Result<Option<String>, DbError> {
3732 let Some(run) = self.db.run_tasks(&attempt.run_id).await? else {
3733 return Ok(None);
3734 };
3735 let ran = &run.dag;
3736 let place = |l: &schedr_model::DagLocation| format!("{}:{}", l.root, l.path);
3737 let stored = self.db.stored_dag(&ran.id).await?;
3739 let now = stored
3740 .as_ref()
3741 .filter(|d| !d.removed)
3742 .and_then(|d| d.current.as_ref());
3743 let task = &attempt.task_id;
3744 Ok(match now {
3745 None => Some(format!(
3746 "DAG `{}` was removed from `{}` after this run started",
3747 ran.id,
3748 place(&ran.location)
3749 )),
3750 Some(now) if now.dag.location != ran.location => Some(format!(
3751 "DAG `{}` moved from `{}` to `{}` after this run started",
3752 ran.id,
3753 place(&ran.location),
3754 place(&now.dag.location)
3755 )),
3756 Some(now) if now.dag.task(task).is_none() => Some(format!(
3757 "task `{task}` was removed from DAG `{}` (`{}`) after this run started",
3758 ran.id,
3759 place(&ran.location)
3760 )),
3761 Some(_) => None,
3762 })
3763 }
3764
3765 fn needs<'a>(
3768 &'a self,
3769 dag: &'a schedr_model::Dag,
3770 queue: &'a str,
3771 parse_version: &str,
3772 ) -> Needs<'a> {
3773 let root = dag.location.root.as_str();
3774 let current = self.current_code.get(root);
3775 let version = parse_version
3777 .parse::<SchedrVersion>()
3778 .ok()
3779 .max(current.and_then(|(_, version)| *version));
3780 Needs {
3781 queue,
3782 code: current.map(|(hashes, _)| (root, hashes)),
3783 version,
3784 wait_step: false,
3785 }
3786 }
3787
3788 fn why_waiting(&self, needs: Needs<'_>, excluded: &BTreeSet<String>) -> (&'static str, String) {
3791 let queue = needs.queue;
3792 let serving: Vec<_> = self.workers.serving(queue).collect();
3793 if serving.is_empty() {
3794 if self.workers.drained_serving(queue) {
3795 return (
3796 "drained",
3797 format!(
3798 "the workers serving queue `{queue}` are drained (`schedr workers resume`)"
3799 ),
3800 );
3801 }
3802 return (
3803 "no_worker",
3804 format!("no active worker serves queue `{queue}`"),
3805 );
3806 }
3807 let recent: Vec<_> = serving
3808 .into_iter()
3809 .filter(|w| w.runs(needs.version))
3810 .collect();
3811 if recent.is_empty() {
3812 let version = needs.version.map(|v| v.to_string()).unwrap_or_default();
3813 return (
3814 "schedr_version",
3815 format!("no worker with schedr ≥ {version} serves queue `{queue}`"),
3816 );
3817 }
3818 let current: Vec<_> = recent
3819 .into_iter()
3820 .filter(|w| w.has_code(needs.code))
3821 .collect();
3822 if current.is_empty() {
3823 let root = needs.code.map(|(root, _)| root).unwrap_or_default();
3824 return (
3825 "newest_code",
3826 format!(
3827 "waiting for workers serving queue `{queue}` to have the newest code of \
3828 root `{root}`"
3829 ),
3830 );
3831 }
3832 if current.iter().all(|w| excluded.contains(&w.id)) {
3833 return (
3834 "rejected",
3835 format!("every active worker serving queue `{queue}` rejected it"),
3836 );
3837 }
3838 if needs.wait_step {
3839 return (
3840 "no_watcher_slot",
3841 format!("waiting for a free watcher slot on the workers serving queue `{queue}`"),
3842 );
3843 }
3844 (
3845 "no_slot",
3846 format!("waiting for a free slot on the workers serving queue `{queue}`"),
3847 )
3848 }
3849
3850 pub fn place_trigger(
3854 &mut self,
3855 active: &schedr_db::runs::ActiveDag,
3856 instance: &str,
3857 (after, failures): (Option<String>, u32),
3858 now: Timestamp,
3859 ) -> Option<(Outgoing, String)> {
3860 let dag = &active.dag;
3861 let schedr_model::Trigger::Event { task, .. } = &dag.trigger else {
3862 return None;
3863 };
3864 let needs = Needs {
3865 wait_step: true,
3866 ..self.needs(dag, &task.settings.queue, "")
3867 };
3868 let root = &dag.location.root;
3869 self.current_code.get(root)?;
3870 let worker_id = self.workers.pick(needs, &BTreeSet::new())?.to_owned();
3871 let code = self.workers.get(&worker_id)?.roots.get(root)?.clone();
3872 let message = pb::AssignTrigger {
3873 instance_id: instance.to_owned(),
3874 dag_id: dag.id.to_string(),
3875 task_json: serde_json::to_vec(&as_sent(task)).unwrap_or_default(),
3876 dag_file: Some(pb::DagFileRef {
3877 root: root.clone(),
3878 path: dag.location.path.clone(),
3879 }),
3880 expected_code_hash: code.clone(),
3881 after,
3882 failures,
3883 cancel_grace_ms: u64::try_from(self.cancel_grace.as_millis()).unwrap_or(u64::MAX),
3884 connections_json: match self.registry(root) {
3885 Some(registry) if !task.connections.is_empty() => {
3886 serde_json::to_vec(®istry.only(&task.connections)).unwrap_or_default()
3887 }
3888 _ => Vec::new(),
3889 },
3890 };
3891 self.workers
3892 .reserve_wait_step(&worker_id, instance, false, now);
3893 let outgoing = Outgoing {
3894 worker_id,
3895 message: pb::MasterMessage {
3896 message: Some(pb::master_message::Message::AssignTrigger(message)),
3897 clock: None,
3898 },
3899 };
3900 Some((outgoing, code))
3901 }
3902
3903 #[must_use]
3905 pub fn worker(&self, id: &str) -> Option<&crate::workers::Worker> {
3906 self.workers.get(id)
3907 }
3908
3909 pub fn trigger_kept(&mut self, worker: &str, instance: &str, now: Timestamp) {
3911 self.workers.reserve_wait_step(worker, instance, false, now);
3912 }
3913
3914 pub fn trigger_released(&mut self, instance: &str) {
3916 self.workers.release(instance);
3917 self.trigger_wake.notify_one();
3918 }
3919
3920 #[must_use]
3923 pub fn trigger_wake(&self) -> std::sync::Arc<tokio::sync::Notify> {
3924 self.trigger_wake.clone()
3925 }
3926
3927 async fn add_event(
3929 &self,
3930 ready: &ReadyInstance,
3931 message: &mut pb::AssignTask,
3932 ) -> Result<(), DispatchError> {
3933 if !ready.dag.trigger.brings_event() {
3934 return Ok(());
3935 }
3936 if let (Some(run), Some(event)) =
3937 (&mut message.run, self.db.run_event(&ready.run_id).await?)
3938 {
3939 run.event_json = serde_json::to_vec(&event).unwrap_or_default();
3940 }
3941 Ok(())
3942 }
3943
3944 fn assign_message(
3945 &self,
3946 ready: &ReadyInstance,
3947 worker_id: &str,
3948 attempt_id: &str,
3949 try_number: u32,
3950 (inputs, outcomes, params): (Vec<u8>, BTreeMap<String, String>, Vec<u8>),
3951 ) -> pb::AssignTask {
3952 let task = ready.dag.task(&ready.task_id);
3953 let external = inputs.len() > INLINE_INPUTS_LIMIT;
3954 pb::AssignTask {
3955 attempt_id: attempt_id.to_owned(),
3956 task_id: ready.task_id.to_string(),
3957 map_index: ready.map_index,
3958 try_number,
3959 run: Some(pb::RunInfo {
3960 params_json: params,
3961 run_id: ready.run_id.clone(),
3962 kind: run_kind_to_proto(ready.run_kind),
3963 planned_for: Some(proto_time(ready.planned_for)),
3964 since: Some(proto_time(ready.since)),
3965 dag_id: ready.dag.id.to_string(),
3966 event_json: Vec::new(),
3967 }),
3968 task_json: task
3969 .and_then(|t| serde_json::to_vec(&as_sent(t)).ok())
3970 .unwrap_or_default(),
3971 dag_file: Some(pb::DagFileRef {
3972 root: ready.dag.location.root.clone(),
3973 path: ready.dag.location.path.clone(),
3974 }),
3975 expected_code_hash: self
3979 .current_code
3980 .get(&ready.dag.location.root)
3981 .and_then(|_| {
3982 self.workers
3983 .get(worker_id)?
3984 .roots
3985 .get(&ready.dag.location.root)
3986 })
3987 .cloned()
3988 .unwrap_or_default(),
3989 inputs_json: if external { Vec::new() } else { inputs },
3990 inputs_external: external,
3991 cancel_grace_ms: u64::try_from(self.cancel_grace.as_millis()).unwrap_or(u64::MAX),
3992 memory_budget_bytes: task.and_then(|t| t.settings.memory_bytes).unwrap_or(0),
3995 setrlimit: task.is_some_and(|t| t.settings.hard_memory_limit),
3996 upstream_outcomes: outcomes.into_iter().collect(),
3997 connections_json: match (task, self.registry(&ready.dag.location.root)) {
4000 (Some(task), Some(registry)) if !task.connections.is_empty() => {
4001 serde_json::to_vec(®istry.only(&task.connections)).unwrap_or_default()
4002 }
4003 _ => Vec::new(),
4004 },
4005 cleanup_only: None,
4006 resource_cleanup: ready.dag.resource_of_cleanup(&ready.task_id).is_some(),
4007 first_started: None,
4008 }
4009 }
4010}
4011
4012#[must_use]
4016pub(crate) fn time_of(time: &prost_types::Timestamp) -> Option<Timestamp> {
4017 Timestamp::new(time.seconds, time.nanos).ok()
4018}
4019
4020fn as_sent(task: &schedr_model::Task) -> schedr_model::Task {
4021 schedr_model::Task {
4022 id: task.id.clone(),
4023 kind: task.kind.clone(),
4024 settings: task.settings.clone(),
4025 output_type: task.output_type.clone(),
4026 outcomes: task.outcomes.clone(),
4027 group: task.group.clone(),
4028 expand: None,
4029 cleanup: task.cleanup.clone(),
4030 secrets: task.secrets.clone(),
4031 connections: task.connections.clone(),
4032 }
4033}
4034
4035fn cancel(worker_id: &str, attempt_id: &str) -> Outgoing {
4036 Outgoing {
4037 worker_id: worker_id.to_owned(),
4038 message: pb::MasterMessage {
4039 message: Some(pb::master_message::Message::CancelAttempt(
4040 pb::CancelAttempt {
4041 interrupted: false,
4042 attempt_id: attempt_id.to_owned(),
4043 },
4044 )),
4045 clock: None,
4046 },
4047 }
4048}
4049
4050const fn by_master(status: AttemptStatus) -> AttemptResult {
4051 AttemptResult {
4052 status,
4053 error_kind: None,
4054 output: None,
4055 outcome: None,
4056 cleanup: None,
4057 }
4058}
4059
4060fn start_method(started: &pb::Started) -> &'static str {
4065 match pb::StartMethod::try_from(started.start_method) {
4066 Ok(pb::StartMethod::Fork) => "fork",
4067 _ => "spawn",
4068 }
4069}
4070
4071fn is_repeat(attempt: &StoredAttempt, finished: &pb::Finished, worker_id: &str) -> bool {
4075 attempt.worker_id == worker_id
4076 && attempt.status.is_some()
4077 && attempt.cleanup_moves == 0
4078 && !finished.cleanup.as_ref().is_some_and(|c| c.rest)
4079}
4080
4081fn is_common(attempt: &StoredAttempt, finished: &pb::Finished, worker_id: &str) -> bool {
4082 attempt.worker_id == worker_id
4083 && attempt.status.is_none()
4084 && attempt.cleanup_moves == 0
4085 && !finished.cleanup.as_ref().is_some_and(|c| c.rest)
4086 && !CODE_GONE_ERRORS.contains(&finished.error_kind.as_str())
4087}
4088
4089fn ended(
4090 finished: &pb::Finished,
4091 status: AttemptStatus,
4092 error_summary: Option<String>,
4093 cleanup: Option<CleanupEnd>,
4094) -> (AttemptEnd, AttemptResult) {
4095 let output = (status == AttemptStatus::Success)
4096 .then(|| serde_json::from_slice(&finished.output_json).ok())
4097 .flatten();
4098 let end = AttemptEnd {
4099 status,
4100 exit_code: finished.exit_code,
4101 signal: finished.signal,
4102 peak_memory_bytes: (finished.peak_memory_bytes > 0).then_some(finished.peak_memory_bytes),
4104 usage: finished.usage.map(|u| ProcessUsage {
4105 user_cpu_micros: u.user_cpu_micros,
4106 system_cpu_micros: u.system_cpu_micros,
4107 peak_rss_bytes: u.peak_rss_bytes,
4108 major_faults: u.major_faults,
4109 voluntary_context_switches: u.voluntary_context_switches,
4110 involuntary_context_switches: u.involuntary_context_switches,
4111 }),
4112 core_dumped: finished.core_dumped,
4113 duration_ms: finished.duration_ms,
4114 error_kind: non_empty(&finished.error_kind),
4115 error_summary,
4116 code_hash: non_empty(&finished.code_hash),
4117 cleanup,
4118 };
4119 let result = AttemptResult {
4120 status,
4121 error_kind: end.error_kind.clone(),
4122 output,
4123 outcome: non_empty(&finished.outcome),
4124 cleanup: end.cleanup.as_ref().map(|c| c.result),
4125 };
4126 (end, result)
4127}
4128
4129fn summary_of(finished: &pb::Finished) -> Option<String> {
4131 (!finished.error_summary_json.is_empty())
4132 .then(|| String::from_utf8_lossy(&finished.error_summary_json).into_owned())
4133}
4134
4135pub const LATE_CLEANUP_FAILED: &str = "late_cleanup_failed";
4137
4138const fn no_cleanup() -> TaskCleanup {
4140 TaskCleanup {
4141 run: CleanupRun::Python,
4142 timeout_ms: None,
4143 retries: 0,
4144 retry_delay_ms: 0,
4145 handles: None,
4146 anywhere: false,
4147 }
4148}
4149
4150fn cleanup_not_run(worker_id: &str, wanted: &TaskCleanup) -> CleanupEnd {
4153 let message = if wanted.anywhere {
4154 format!(
4155 "the cleanup didn't run to its end: worker `{worker_id}` is gone, the last of {} it \
4156 may be moved to",
4157 wanted.retries.saturating_add(1)
4158 )
4159 } else {
4160 format!(
4161 "the cleanup didn't run to its end: worker `{worker_id}` is gone; with \
4162 `cleanup_anywhere=True` it runs on another worker"
4163 )
4164 };
4165 CleanupEnd {
4166 result: CleanupResult::WorkerLost,
4167 tries: 0,
4168 duration_ms: 0,
4169 error_kind: Some("worker_lost".to_owned()),
4170 error_summary: Some(ErrorSummary::json("WorkerLost", &message)),
4171 }
4172}
4173
4174fn cleanup_end(cleanup: &pb::CleanupResult, worker_id: &str) -> Result<CleanupEnd, DispatchError> {
4176 Ok(CleanupEnd {
4177 result: cleanup_result_from_proto(cleanup.status).map_err(|e| {
4178 DispatchError::BadMessage {
4179 worker_id: worker_id.to_owned(),
4180 reason: e.to_string(),
4181 }
4182 })?,
4183 tries: cleanup.tries,
4184 duration_ms: cleanup.duration_ms,
4185 error_kind: non_empty(&cleanup.error_kind),
4186 error_summary: (!cleanup.error_summary_json.is_empty())
4187 .then(|| String::from_utf8_lossy(&cleanup.error_summary_json).into_owned()),
4188 })
4189}
4190
4191fn restarted_summary(worker_id: &str) -> String {
4194 ErrorSummary::json(
4195 "WorkerRestarted",
4196 &format!("worker `{worker_id}` restarted while the attempt ran (possibly out of memory)"),
4197 )
4198}
4199
4200fn not_started_summary(worker_id: &str) -> String {
4202 ErrorSummary::json(
4203 "WorkerLeft",
4204 &format!("worker `{worker_id}` left before starting the attempt: it runs again"),
4205 )
4206}
4207
4208fn maybe_started_summary(worker_id: &str) -> String {
4209 ErrorSummary::json(
4210 "WorkerLost",
4211 &format!(
4212 "worker `{worker_id}` stopped answering after the attempt was sent to it, and may \
4213 have started it (its start not heard)"
4214 ),
4215 )
4216}
4217
4218fn lost_summary(worker_id: &str) -> String {
4219 ErrorSummary::json(
4220 "WorkerLost",
4221 &format!(
4222 "worker `{worker_id}` stopped answering while the attempt ran (its pod or node \
4223 gone, or out of memory)"
4224 ),
4225 )
4226}
4227
4228fn with_context(summary: Option<&str>, context: &str) -> String {
4231 match summary.map(|s| (s, serde_json::from_str::<ErrorSummary>(s))) {
4232 Some((_, Ok(mut summary))) => {
4233 summary.message = format!("{context}: {}", summary.message);
4234 serde_json::to_string(&summary).unwrap_or_default()
4235 }
4236 Some((text, Err(_))) => ErrorSummary::json("CodeChanged", &format!("{context}: {text}")),
4237 None => ErrorSummary::json("CodeChanged", context),
4238 }
4239}
4240
4241pub(crate) fn too_big_to_send(message: &pb::MasterMessage, limit: usize) -> Option<String> {
4244 let stamp = message.clock.is_none().then_some(pb::MasterClock {
4246 timeline: u64::MAX,
4247 master_ms: i64::MIN,
4248 heard_sequence: u64::MAX,
4249 wall_ms: i64::MIN,
4250 lease_epoch: i64::MIN,
4251 sequence: u64::MAX,
4252 });
4253 let size = prost::Message::encoded_len(message)
4254 + stamp.map_or(0, |clock| {
4255 prost::encoding::message::encoded_len(CLOCK_FIELD, &clock)
4256 });
4257 (size > limit).then(|| {
4258 format!(
4259 "its assignment, with the run it is given, is {size} bytes, over the {limit} a \
4260 worker takes ([grpc] max_message_size)"
4261 )
4262 })
4263}
4264
4265fn inputs_too_large() -> AttemptEnd {
4266 AttemptEnd {
4267 error_kind: Some(INPUTS_TOO_LARGE.to_owned()),
4268 ..AttemptEnd::by_master(AttemptStatus::Failed)
4269 }
4270}
4271
4272fn non_empty(text: &str) -> Option<String> {
4273 (!text.is_empty()).then(|| text.to_owned())
4274}
4275
4276fn proto_time(t: Timestamp) -> prost_types::Timestamp {
4277 prost_types::Timestamp {
4278 seconds: t.as_second(),
4279 nanos: t.subsec_nanosecond(),
4280 }
4281}
4282
4283pub async fn attempt_inputs(
4291 db: &Database,
4292 attempt_id: &str,
4293) -> Result<Option<Vec<u8>>, DispatchError> {
4294 let Some(attempt) = db.attempt(attempt_id).await? else {
4295 return Ok(None);
4296 };
4297 if attempt.status.is_some() {
4298 return Ok(None);
4299 }
4300 let Some(run) = db.run_tasks(&attempt.run_id).await? else {
4301 return Ok(None);
4302 };
4303 let Some(task) = run.dag.task(&attempt.task_id) else {
4304 return Ok(Some(b"{}".to_vec()));
4305 };
4306 let mut resolved = mapping::Resolved::new();
4307 let inputs = mapping::inputs(
4308 db,
4309 &run.dag,
4310 &attempt.run_id,
4311 (task, attempt.map_index),
4312 &mut resolved,
4313 )
4314 .await;
4315 let inputs = match inputs {
4316 Ok(inputs) => inputs,
4317 Err(InputsError::Db(error)) => return Err(error.into()),
4318 Err(InputsError::NotArguments(_)) => return Ok(None),
4320 };
4321 Ok(Some(
4322 serde_json::to_vec(&inputs).unwrap_or_else(|_| b"{}".to_vec()),
4323 ))
4324}
4325
4326async fn upstream_outcomes(
4329 db: &Database,
4330 dag: &schedr_model::Dag,
4331 run_id: &str,
4332 task_id: &TaskId,
4333) -> Result<BTreeMap<String, String>, DispatchError> {
4334 let Some(task) = dag.task(task_id) else {
4335 return Ok(BTreeMap::new());
4336 };
4337 let used: BTreeSet<&TaskId> = task
4338 .references()
4339 .into_iter()
4340 .filter_map(Reference::upstream_task)
4341 .collect();
4342 if used.is_empty() {
4343 return Ok(BTreeMap::new());
4344 }
4345 let wanted: Vec<&TaskId> = used.into_iter().collect();
4346 Ok(db
4347 .upstream_outcomes(run_id, &wanted)
4348 .await?
4349 .into_iter()
4350 .map(|(task, outcome)| (task.to_string(), outcome.unwrap_or_default()))
4351 .collect())
4352}
4353
4354fn task_specific(error: &DispatchError) -> bool {
4358 let db = match error {
4359 DispatchError::Db(db) | DispatchError::Execution(ExecutionError::Db(db)) => db,
4360 DispatchError::Execution(_) | DispatchError::BadMessage { .. } | DispatchError::Redo => {
4361 return true;
4362 }
4363 };
4364 db.is_data_fault()
4365}
4366
4367const fn starts_a_run(task: &schedr_model::Task) -> bool {
4371 matches!(task.kind, TaskKind::TriggerDag { .. })
4372}
4373
4374fn waits_for_a_run(task: &schedr_model::Task) -> bool {
4375 matches!(
4376 task.kind,
4377 TaskKind::WaitFor { .. }
4378 | TaskKind::WaitForEvent { .. }
4379 | TaskKind::Sensor {
4380 wait_for: Some(_),
4381 ..
4382 }
4383 )
4384}
4385
4386fn run_ended(state: &str) -> bool {
4389 matches!(
4390 state,
4391 "success" | "failed" | "upstream_failed" | "skipped" | "cancelled" | "missing"
4392 )
4393}
4394
4395fn decide(found: Option<&OtherRun>) -> Option<WaitEnd> {
4399 let run = found?;
4400 match run.state.as_str() {
4401 "success" => Some(WaitEnd::Ran {
4402 run_id: run.run_id.clone(),
4403 }),
4404 "failed" | "upstream_failed" | "skipped" | "cancelled" => Some(WaitEnd::Failed {
4405 state: run.state.clone(),
4406 run_id: run.run_id.clone(),
4407 }),
4408 _ => None,
4409 }
4410}