Skip to main content

schedr_master/
dispatch.rs

1//! Giving tasks to workers and handling what workers report about them (see archive/PROJECT.md,
2//! Task assignment and Task rejections).
3//!
4//! - **Assign:** ready tasks, oldest ready first, each to the worker chosen by [`Workers::pick`];
5//!   the assignment is stored before `AssignTask` is sent.
6//! - **`Started`** means accepted. For an attempt that was taken back or ended, the worker is
7//!   told to kill it.
8//! - **`Rejected`** takes the assignment back (it isn't a try): a temporary reason queues the
9//!   task again at once; "code not there yet" after [`CODE_RETRY_DELAY`], and `unschedulable`
10//!   once every eligible worker said so and the code has been missing for the code wait; a
11//!   worker-specific reason leaves that worker out for the task, which becomes
12//!   `unschedulable` when every eligible worker rejected it, until the set of workers changes
13//!   or a user retries it. A task being cancelled is `cancelled` instead.
14//! - **Only the newest code runs:** a task goes only to workers that have its root at the
15//!   root's current hash (and sends that hash for the worker to check), with a schedr version
16//!   at least its parse's.
17//! - **A task that waits** shows why: no active worker serves its queue, none is recent
18//!   enough, none has the newest code yet, every one rejected it, or no free slot.
19//! - **`Finished`** is stored (the first one counts) and always acknowledged.
20//! - An attempt with no `Started` within the worker lease ends `assignment_expired` and the
21//!   task runs again without using a retry; a lost worker's attempts end `lost`.
22//!
23//! The dispatcher only builds messages; the gRPC server sends them (milestone 1.14).
24
25use 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
65/// The worker lease, by default: how long a replaced incarnation's attempts are held
66/// (decision 443); the master uses its own ([`Dispatcher::with_lease`]).
67pub const DEFAULT_LEASE: SignedDuration = SignedDuration::from_secs(10);
68
69/// How long a task whose assignment failed on its own is left out of the rounds before it is
70/// tried again, unless set otherwise (see [`Dispatcher::assign_into`]).
71pub const DEFAULT_SET_ASIDE: Duration = Duration::from_mins(1);
72
73/// How long a lost worker's cleanup waits before it moves, by default: the default cancel
74/// grace and some slack (decision 256).
75const DEFAULT_CLEANUP_MOVE_WAIT: Duration = Duration::from_secs(40);
76
77/// The acknowledgement of `attempt_id`'s `Finished`, for `worker_id`: its result is stored.
78#[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
91/// The error kind of a result the database refused (not retried).
92const RESULT_NOT_STORED: &str = "result_not_stored";
93
94/// An assignment picked, before its claim is stored (decision 482).
95#[derive(Debug)]
96struct Pick {
97    worker_id: String,
98    attempt_id: String,
99}
100
101/// The reason shown for a ready task a round didn't reach (decision 481).
102fn pending_reason(most: usize) -> String {
103    format!("pending: waiting for a round with room (a round assigns at most {most})")
104}
105
106/// What a round's assignments read once, for all their ready tasks, instead of once a task at
107/// each visit (decision 482): neither changes while the round assigns (an assignment adds an
108/// attempt not started; only rounds switch wait steps off or on).
109#[derive(Debug, Default)]
110struct RoundReads {
111    /// The wait steps switched off now, by DAG and task.
112    switched_off: BTreeMap<(String, String), schedr_db::strikes::WaitStepStrikes>,
113    /// Each ready wait step's first start (`None`: never started).
114    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
149/// Why a moved cleanup waits, shown as `unschedulable` (decision 244).
150const NO_CLEANUP_WORKER: &str = "no worker for the cleanup";
151
152/// What is done with the task results kept for a worker's attempts as it goes.
153#[derive(Debug, Clone, Copy, PartialEq, Eq)]
154pub enum KeptResults {
155    /// They end the attempts.
156    Used,
157    /// The database refused one: left out, the attempts fail instead (else the worker could
158    /// never be retired, nor the workers after it).
159    Refused,
160}
161
162/// How a commit cut off by the time limit or a lost connection is read back: whether the work
163/// is stored, checked at once, then every `interval` for up to `window`, since a server slow
164/// enough to have cut it off may still be committing it (`read_back_window`,
165/// `read_back_interval`). Never seen meanwhile: not stored (a stored round's attempts then
166/// never left the master: taken back with their worker's return or loss, B240). The master
167/// holds its lock meanwhile:
168/// only after a commit cut off, a database incident.
169#[derive(Debug, Clone, Copy, PartialEq, Eq)]
170pub struct ReadBack {
171    /// How long it goes on.
172    pub window: Duration,
173    /// How often it checks (zero is taken as 1 ms).
174    pub interval: Duration,
175}
176
177impl Default for ReadBack {
178    /// For 3 s, every 500 ms.
179    fn default() -> Self {
180        Self {
181            window: Duration::from_secs(3),
182            interval: Duration::from_millis(500),
183        }
184    }
185}
186
187impl ReadBack {
188    /// Whether the work is stored, by `stored` (true once it is).
189    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
208/// The most assignments a round makes (a few statements each, about 5-13 ms in stress runs):
209/// thousands of ready tasks and free slots go over a few rounds, the longest ready first
210/// (B18). Steady state stays under it (about 16 a round in scenario 1).
211pub const ASSIGNMENTS_PER_ROUND: usize = 50;
212
213/// The most assignments a round takes back as never started (B18).
214pub const EXPIRIES_PER_ROUND: usize = 50;
215
216/// Why a task of a DAG in an ID conflict waits (B193).
217pub const DAG_IN_CONFLICT: &str = "waiting: DAG ID conflict";
218
219/// The most waiting reasons a round writes (each a statement, about 3.5 ms in stress runs): a
220/// burst of runs leaves thousands of tasks waiting, and their reasons (only shown) are filled in
221/// over the following rounds rather than in one long one (B18). The waiting counts in the
222/// metrics still cover every task.
223pub const REASONS_PER_ROUND: usize = 100;
224
225/// The most pending reasons a round writes for the tasks past its cap (decision 481): one
226/// statement; a longer backlog gets them over the next rounds.
227pub const PENDING_PER_ROUND: usize = 500;
228
229/// When a task whose code wasn't on the worker yet is tried again: about the git-sync
230/// interval plus the settle time.
231pub const CODE_RETRY_DELAY: SignedDuration = SignedDuration::from_secs(35);
232
233/// How long a task's code may be missing on every eligible worker before the task is
234/// `unschedulable` (`[master] code_wait`).
235pub const DEFAULT_CODE_WAIT: Duration = Duration::from_mins(10);
236
237/// Error kinds of an attempt whose task or DAG file isn't in the code it ran with; when the
238/// DAG changed after the run started, its error summary says how.
239pub const CODE_GONE_ERRORS: [&str; 2] = [TASK_NOT_FOUND, DAG_FILE_MISSING];
240
241/// Inputs up to this size travel inside `AssignTask`, while the whole message stays within what
242/// a worker takes (B157); bigger ones are fetched separately.
243pub const INLINE_INPUTS_LIMIT: usize = 4 * 1024 * 1024;
244
245/// `MasterMessage.clock`'s field number.
246const CLOCK_FIELD: u32 = 20;
247
248/// Inputs over this size make the task fail (`inputs_too_large`, never retried).
249pub const MAX_INPUTS: usize = 64 * 1024 * 1024;
250
251/// The outcome of a wait step that ran out of time (`schedr.outcomes.TIMED_OUT_NAME`).
252const TIMED_OUT_OUTCOME: &str = "TimedOut";
253
254/// The least an `@sensor(wait_for=...)`'s call gets once it is handed a run that ended within its
255/// `max_wait`, though little or none of that is left (`SCHEDR_HIDDEN__MASTER__HANDED_CALL_MIN`).
256pub const DEFAULT_HANDED_CALL_MIN: Duration = Duration::from_mins(1);
257
258/// An attempt's failure the master itself decides.
259fn 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
267/// The error kind of a task whose inputs are over [`MAX_INPUTS`].
268pub const INPUTS_TOO_LARGE: &str = "inputs_too_large";
269
270/// The error kind of a task whose inputs don't fit its parameters (the runner's too); not
271/// retried.
272pub const INPUT_MISMATCH: &str = "input_mismatch";
273
274/// The grace time between SIGTERM and SIGKILL when an attempt is cancelled (master
275/// configuration; this is the default).
276pub const DEFAULT_CANCEL_GRACE: Duration = Duration::from_secs(30);
277
278/// A message for one worker.
279#[derive(Debug, Clone, PartialEq)]
280pub struct Outgoing {
281    /// The worker.
282    pub worker_id: String,
283    /// The message.
284    pub message: pb::MasterMessage,
285}
286
287/// Why a dispatcher operation failed.
288#[derive(Debug, thiserror::Error)]
289pub enum DispatchError {
290    /// The database failed.
291    #[error(transparent)]
292    Db(#[from] DbError),
293    /// Moving a run forward failed.
294    #[error(transparent)]
295    Execution(#[from] ExecutionError),
296    /// A message from a worker can't be understood.
297    #[error("message from worker `{worker_id}`: {reason}")]
298    BadMessage {
299        /// The worker.
300        worker_id: String,
301        /// What is wrong.
302        reason: String,
303    },
304    /// An assignment of a round's batch was ended by the master before it was sent (its inputs
305    /// don't fit its arguments, or are too large to send): the batch is redone one at a time,
306    /// each assignment ending, and what it ends, as it would alone (decision 482).
307    #[error("an assignment of a round's batch ended before it was sent")]
308    Redo,
309}
310
311impl DispatchError {
312    /// Whether it is about the data of a write, which would be refused again
313    /// ([`DbError::is_data_fault`]).
314    #[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    /// Whether it is a commit whose answer was lost: it may have stored.
325    #[must_use]
326    pub const fn commit_unknown(&self) -> bool {
327        matches!(self, Self::Db(DbError::CommitUnknown))
328    }
329}
330
331/// A liveness safeguard switched off by [`Dispatcher::weaken`]: the clock simulator's mutation
332/// tests (decision 446) show each is needed. Never in a master.
333#[doc(hidden)]
334#[derive(Debug, Clone, Copy, PartialEq, Eq)]
335pub enum Weakened {
336    /// An attempt not known unstarted counts as never started (B240): a `Started` held up on
337    /// its way is missed.
338    Echo,
339    /// A replaced incarnation's attempts end at once, with no hold (decision 443).
340    Hold,
341    /// A lost worker's cleanup moves at once (decisions 256 and 445).
342    MoveWait,
343}
344
345/// Tasks given to workers and their reports handled.
346#[derive(Debug)]
347pub struct Dispatcher {
348    db: Database,
349    execution: Execution,
350    /// Creates the runs `TriggerDagOperator`s start (the core's, shared, once set).
351    scheduler: crate::scheduler::Scheduler,
352    workers: Workers,
353    /// Workers a restarted master read back that haven't registered with it yet: within the
354    /// lease it gave them, they may come back with their attempts in their journals (F14).
355    away: BTreeSet<String>,
356    cancel_grace: Duration,
357    /// After how many host kills in a row a wait step is switched off (0: never).
358    switch_off_after: u32,
359    /// How long a wait step without a `max_wait` waits (`[sensors] default_max_wait`).
360    sensor_max_wait: Duration,
361    /// Workers that rejected a task instance for a worker-specific reason, with the detail.
362    rejections: BTreeMap<String, BTreeMap<String, String>>,
363    /// Task instances whose code a worker didn't have: since when, and which workers said so.
364    code_missing: BTreeMap<String, CodeMissing>,
365    code_wait: SignedDuration,
366    /// Each root's accepted content hashes (its current code, and newer code whose parse is on
367    /// its way) and the schedr version of its current parse: its tasks go to workers at one of
368    /// those hashes and of at least that version.
369    current_code: BTreeMap<String, (BTreeSet<String>, Option<SchedrVersion>)>,
370    /// Each root's connections from its current parse (decision 174), with that parse's
371    /// content hash: a connections job goes to a worker having the root at it.
372    connections: BTreeMap<String, (Option<String>, Arc<Registry>)>,
373    metrics: MasterMetrics,
374    /// The attempts this dispatcher's writes started or ended, in order, since
375    /// [`Self::take_witnesses`]: what a group's commit cut off is read back by (M4B.3, Grok's
376    /// review: the group's last message may have changed nothing).
377    witnesses: Vec<(String, Witness)>,
378    /// Attempts whose `Started` arrived but waits for the master: never taken back (B11).
379    arrivals: Arrivals,
380    /// Task instances whose assignment failed on its own, and until when they are left out.
381    set_aside: BTreeMap<String, Timestamp>,
382    /// How long they are left out.
383    set_aside_for: SignedDuration,
384    /// How long a lost worker's cleanup waits before it moves (decision 256).
385    cleanup_move_wait: SignedDuration,
386    /// The worker lease: how long a replaced incarnation's attempts are held (decision 443).
387    lease: SignedDuration,
388    /// An attempt not known unstarted counts as never started ([`Weakened::Echo`]).
389    trust_unknown: bool,
390    /// Master time, which its timers count on (B228; see [`crate::clock`]).
391    steady: crate::clock::Steady,
392    /// The wall clock, read with `steady` at one instant where the two are compared (M5.1m;
393    /// production: the system's); `None`: the `now` handed (tests on [`crate::clock::as_given`]).
394    wall: Option<fn() -> Timestamp>,
395    /// When each cleanup waiting to move may go to another worker, in master time (D256, B228);
396    /// after a restart, a whole wait from when it is first seen.
397    move_not_before: BTreeMap<String, Timestamp>,
398    /// When each attempt a replaced incarnation left behind was marked, in master time
399    /// (decision 443): it ends `lost` a lease after; after a restart, from when it is first
400    /// seen.
401    replaced_since: BTreeMap<String, Timestamp>,
402    /// No hold for a replaced incarnation's attempts ([`Weakened::Hold`]).
403    no_hold: bool,
404    /// How far behind its cursor an event sensor reads back, for an event committed late
405    /// (B185; the triggers' `event_lookback`).
406    event_lookback: SignedDuration,
407    /// How a commit cut off is read back.
408    read_back: ReadBack,
409    /// `CancelAttempt`s for running instances whose mapped task's step failed (75a), sent
410    /// with the next step.
411    stops: Vec<Outgoing>,
412    /// Mapped lists resolved during a step, shared by a task's instances.
413    resolved: mapping::Resolved,
414    /// What a round's assignments read once for all its ready tasks, while it assigns
415    /// (decision 482); none outside it.
416    round_reads: Option<RoundReads>,
417    /// Attempts a reconnecting worker runs whose start the database refused to record (B128):
418    /// not taken back as never started while a worker holds them.
419    adopted_unrecorded: BTreeSet<String>,
420    /// The open attempts counted for the concurrency limits (decision 88A).
421    active: Active,
422    /// Each DAG's current version, read at each round with tasks ready: the limits across runs
423    /// are its (87A).
424    current_versions: BTreeMap<DagId, String>,
425    /// How much a round does at most (decision 493).
426    rounds: crate::core::RoundLimits,
427    /// When a task whose code wasn't there yet is tried again.
428    code_retry_delay: SignedDuration,
429    /// The run each `@sensor(wait_for=...)` assigned this round is given, by instance
430    /// (decision 353): its function's first argument.
431    handing: BTreeMap<String, serde_json::Value>,
432    /// Tells the master's trigger loop to look (decision 486): a watcher slot or a trigger's
433    /// state changed in memory only, with no write to wake it (Grok's review of M5.1f2).
434    trigger_wake: std::sync::Arc<tokio::sync::Notify>,
435    /// The least such a call gets of its `max_wait`, the run having ended within it.
436    handed_call_min: Duration,
437    /// The largest message a worker takes (`[grpc] max_message_size`): a run handed to
438    /// an `@sensor(wait_for=...)` goes inside its assignment.
439    max_message_size: usize,
440}
441
442/// The dispatcher's memory that a worker's message changes (see [`Dispatcher::memory`]).
443#[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    /// `CancelAttempt`s queued for the next step: a rolled-back change queues none (B51).
450    stops: Vec<Outgoing>,
451    active: Active,
452}
453
454/// What a write did to an attempt, for a commit cut off to be read back by.
455#[derive(Debug, Clone, Copy, PartialEq, Eq)]
456pub enum Witness {
457    /// It recorded the attempt's first start.
458    Started,
459    /// It recorded the attempt's end.
460    Ended,
461}
462
463/// What a step's assignments count as they go.
464#[derive(Debug, Default)]
465struct Tally {
466    /// Tasks left waiting, by why.
467    waiting: BTreeMap<&'static str, i64>,
468    /// Assignments made (at most [`ASSIGNMENTS_PER_ROUND`]).
469    assigned: usize,
470    /// Waiting reasons to write, `(instance ID, reason)`: at most [`REASONS_PER_ROUND`],
471    /// written together at the step's end.
472    reasons: Vec<(String, String)>,
473    /// Each DAG version's tasks by ID (their places in its list), made once a step: a ready
474    /// task is looked up, not searched for (B148).
475    places: HashMap<String, HashMap<TaskId, usize>>,
476}
477
478impl Tally {
479    /// `id` in `dag`, the version `version_id`, by its index (made on its first use).
480    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/// A task's code missing on workers.
495#[derive(Debug, Clone)]
496struct CodeMissing {
497    since: Timestamp,
498    by: BTreeMap<String, String>,
499}
500
501impl Dispatcher {
502    /// A dispatcher over `db` with no workers.
503    #[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    /// How long a wait step without a `max_wait` waits.
553    #[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    /// After how many host kills in a row a wait step is switched off (0: never).
560    #[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    /// Creates the runs `TriggerDagOperator`s start with `scheduler` (the core's, sharing its
567    /// wakes), not one of its own.
568    pub fn set_scheduler(&mut self, scheduler: crate::scheduler::Scheduler) {
569        self.scheduler = scheduler;
570    }
571
572    /// Counts assignments, rejections, ended attempts, waiting tasks and finished runs in
573    /// `metrics`.
574    pub fn set_metrics(&mut self, metrics: MasterMetrics) {
575        self.execution.set_metrics(metrics.clone());
576        self.metrics = metrics;
577    }
578
579    /// Wakes the DAGs of the runs it finishes through `wakes`.
580    pub fn set_wakes(&mut self, wakes: Wakes) {
581        self.execution.set_wakes(wakes);
582    }
583
584    /// A copy of what a worker's message changes in memory (worker slots, rejections, code
585    /// missing, the cancels queued for the next step), to [`Self::restore`] if the message's
586    /// transaction rolls back: memory then shows only what is stored (code review of 2.10b;
587    /// metrics already counted stay).
588    #[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    /// Drops the concurrency limits' counts, read again from the database at the next round
601    /// with tasks ready: after a commit whose answer was lost (it may have stored what the
602    /// counts were changed for, or not), where neither the counts before nor after can be
603    /// trusted. Put back as they were, an expiry stored would leave its attempt counted for
604    /// good, its DAG's limit holding tasks back until a restart (Codex's review of M4.4).
605    pub fn recount(&mut self) {
606        self.active = Active::new();
607    }
608
609    /// Puts back a copy taken by [`Self::memory`] after its transaction failed; for a commit
610    /// whose answer was lost the counts are read again instead ([`Self::recount`]).
611    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    /// The attempts started or ended since the last call (see `witnesses`), and none from now.
619    pub fn take_witnesses(&mut self) -> Vec<(String, Witness)> {
620        std::mem::take(&mut self.witnesses)
621    }
622
623    /// Puts back a copy taken by [`Self::memory`].
624    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    /// The attempts a `CancelAttempt` is queued for, sent at the next step (for the
634    /// fault-injection harness's check).
635    #[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    /// The dispatcher reading which attempts' `Started` arrived from `arrivals` (the core's, which
649    /// the streams' readers fill), so it doesn't take them back as never started.
650    #[must_use]
651    pub fn with_arrivals(mut self, arrivals: Arrivals) -> Self {
652        self.arrivals = arrivals;
653        self
654    }
655
656    /// The dispatcher reading back `lookback` behind an event sensor's cursor (B185).
657    #[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    /// The dispatcher holding a replaced incarnation's attempts for `lease`, the worker lease
664    /// (decision 443): the old process may run them that long.
665    #[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    /// Switches `safeguard` off (the clock simulator's mutation tests, decision 446).
672    #[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    /// The dispatcher waiting `wait` before a lost worker's cleanup moves.
682    #[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    /// The dispatcher leaving a task whose assignment fails on its own out for `set_aside`,
689    /// and reading a commit cut off back as `read_back` says (`set_aside`,
690    /// `read_back_window`, `read_back_interval`).
691    #[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    /// How a commit cut off is read back (see [`ReadBack`]).
699    #[must_use]
700    pub const fn read_back(&self) -> ReadBack {
701        self.read_back
702    }
703
704    /// The dispatcher giving an `@sensor(wait_for=...)`'s call at least `least` once it is handed
705    /// its run (see [`DEFAULT_HANDED_CALL_MIN`]).
706    #[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    /// The largest message a worker takes (`[grpc] max_message_size`).
713    #[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    /// What finished runs and tasks notify (`[notifications]`).
720    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    /// The most instances a mapped task may have (`[mapping] max_instances`).
728    pub const fn set_max_instances(&mut self, max_instances: usize) {
729        self.execution.set_max_instances(max_instances);
730    }
731
732    /// How much a round does at most (decision 493), its execution's part too.
733    pub const fn set_rounds(&mut self, rounds: crate::core::RoundLimits) {
734        self.rounds = rounds;
735        self.execution.set_rounds(rounds);
736    }
737
738    /// When a task whose code wasn't on its worker yet is tried again (see
739    /// [`CODE_RETRY_DELAY`]).
740    #[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    /// The dispatcher with another code wait (see [`DEFAULT_CODE_WAIT`]).
747    #[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    /// The registered workers.
754    #[must_use]
755    pub const fn workers(&self) -> &Workers {
756        &self.workers
757    }
758
759    /// The open attempts counted for the concurrency limits.
760    #[must_use]
761    pub const fn active(&self) -> &Active {
762        &self.active
763    }
764
765    /// A worker registered. A new worker or a restarted one gives `unschedulable` tasks
766    /// another chance.
767    ///
768    /// # Errors
769    ///
770    /// [`DispatchError::Db`] if the database fails.
771    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    /// A root's accepted content hashes and its current parse's schedr version (see
789    /// [`crate::discovery`]): its tasks go only to workers that have the root at one of those
790    /// hashes and are of at least that version.
791    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    /// Each root's connections (decision 174): a task's assignment carries those it declares.
802    /// `parsed` is the content hash of each root's current parse (its registry's).
803    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    /// A worker's stream ended: no task, cleanup nor connections job goes to it until it
820    /// registers again.
821    pub fn worker_disconnected(&mut self, worker_id: &str) {
822        self.workers.disconnected(worker_id);
823    }
824
825    /// A worker a restarted master read back, not registered with it yet (see `away`).
826    pub fn worker_away(&mut self, worker_id: &str) {
827        self.away.insert(worker_id.to_owned());
828    }
829
830    /// The workers that may still come back with their attempts in their journals: read back
831    /// by a restarted master, or disconnected, and not lost yet (their leases running).
832    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    /// The roots having connections, by name.
840    #[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    /// A root's connections, if it has any.
852    #[must_use]
853    pub fn registry(&self, root: &str) -> Option<&Arc<Registry>> {
854        self.connections.get(root).map(|(_, registry)| registry)
855    }
856
857    /// The worker a connections job of `root` goes to (decision 193), with the hash it has
858    /// the root at: `wanted`, else a connected, active worker having the root's current code,
859    /// the one running the fewest attempts. Why none can, otherwise. The current code is the
860    /// current parse's exactly (not newer code whose parse is on its way): its connections are
861    /// the ones the job carries.
862    ///
863    /// # Errors
864    ///
865    /// Why no worker can take it, for the command's rejection.
866    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            // As for a task: a draining or drained worker takes no new work.
887            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    /// A worker's schedr version: it gets only tasks of parses no newer.
911    pub fn set_worker_version(&mut self, worker_id: &str, version: Option<SchedrVersion>) {
912        self.workers.set_version(worker_id, version);
913    }
914
915    /// A worker reported a root's content hash.
916    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    /// A worker withdrew a root (decision 303): its tasks no longer go there.
921    pub fn withdraw_root(&mut self, worker_id: &str, root: &str) {
922        self.workers.withdraw_root(worker_id, root);
923    }
924
925    /// A reconnecting worker still runs `attempt_id` (or holds its result): it keeps its
926    /// slot, and the attempt counts as started, so it isn't taken back for want of a
927    /// `Started` lost with the old stream (B50).
928    ///
929    /// # Errors
930    ///
931    /// [`DispatchError::Db`] if the database fails.
932    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            // Refused for its data, it would be refused at every registration, and the worker
941            // could never send the attempt's `Finished` (B128, as decision 115): left
942            // unrecorded, while its slot is taken all the same (the worker runs it).
943            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        // Whatever it held before this reconnect, it holds the slot its kind runs on once.
950        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    /// The task an attempt runs, as its run's DAG has it.
959    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    /// The inputs of an open attempt as JSON (see [`attempt_inputs`]).
966    ///
967    /// # Errors
968    ///
969    /// [`DispatchError::Db`] if the database fails.
970    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    /// A worker is draining: it gets no new tasks.
975    pub fn draining(&mut self, worker_id: &str) {
976        self.workers.draining(worker_id);
977    }
978
979    /// A worker is drained for maintenance: it gets no new tasks, and its pokes move at once:
980    /// the messages that say so.
981    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    /// A worker is drained, as it was before it registered: its pokes are moved once they are
1006    /// known again ([`Self::drain`]).
1007    pub fn set_drained(&mut self, worker_id: &str) {
1008        self.workers.set_drained(worker_id, true);
1009    }
1010
1011    /// Whether an attempt on a worker is a poke, which a drain moves at once.
1012    #[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    /// A worker's watcher slots.
1020    pub fn set_watcher_slots(&mut self, worker_id: &str, slots: u32) {
1021        self.workers.set_watcher_slots(worker_id, slots);
1022    }
1023
1024    /// A drained worker is resumed: like a new worker, it gives `unschedulable` tasks
1025    /// another chance.
1026    ///
1027    /// # Errors
1028    ///
1029    /// [`DispatchError::Db`] if the database fails.
1030    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    /// One step of the loop: new runs get their tasks, retries whose delay passed are queued,
1039    /// assignments with no `Started` are taken back, and ready tasks are assigned.
1040    ///
1041    /// # Errors
1042    ///
1043    /// [`DispatchError`] if the database fails.
1044    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    /// As [`Self::step`], into `outgoing`: the assignments made before a failure are there
1051    /// still (each stored before its message is built, B7).
1052    ///
1053    /// # Errors
1054    ///
1055    /// [`DispatchError`] if the database fails.
1056    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    /// A round's first part of the dispatcher's: runs prepared, due retries queued.
1067    ///
1068    /// # Errors
1069    ///
1070    /// [`DispatchError`] if the database fails.
1071    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        // Only a group's own writes are read back by (M4B.3); a round's aren't kept.
1078        self.witnesses.clear();
1079        self.execution.prepare_runs(now).await?;
1080        self.execution.queue_due_retries(now).await?;
1081        Ok(())
1082    }
1083
1084    /// A round's part: assignments past their worker's echo expired, replaced incarnations'
1085    /// attempts ended.
1086    ///
1087    /// # Errors
1088    ///
1089    /// [`DispatchError`] if the database fails.
1090    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    /// A round's assignments ([`Self::assign_into`]), the mapped lists read afresh: a worker's
1097    /// turn may have run since the round's last part (decision 469).
1098    ///
1099    /// # Errors
1100    ///
1101    /// [`DispatchError`] if the database fails.
1102    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    /// Assigns ready tasks to workers with free slots.
1112    ///
1113    /// # Errors
1114    ///
1115    /// [`DispatchError`] if the database fails.
1116    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    /// As [`Self::assign`], into `outgoing`: all of the step's assignments, or, after a failure,
1123    /// none (nothing of them stored either).
1124    ///
1125    /// # Errors
1126    ///
1127    /// [`DispatchError`] if the database fails.
1128    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        // Read for these assignments only: a later round, or a turn, reads afresh.
1135        self.round_reads = None;
1136        assigned
1137    }
1138
1139    /// [`Self::assign_into`], [`RoundReads`] read once its ready tasks are known.
1140    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        // The stops of a step a timeout failed go now, not a round later.
1148        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        // The `@sensor(wait_for=...)`s whose run has come are assigned with the others.
1163        ready.extend(self.wait_for_runs(now, &waits).await?);
1164        // Nothing ready (an idle round): no transaction, nothing to keep.
1165        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        // The step's assignments are one transaction: stored together, with one lease check
1172        // and one commit (T2, 2.10b). What they changed in memory (the slots reserved) and the
1173        // messages built for them go with a rollback.
1174        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            // Counted once stored (a step redone one at a time would count them twice).
1179            self.count_assignments(outgoing.len() - built);
1180            return Ok(());
1181        };
1182        // A commit cut off may have stored them all (they are one transaction): one of its new
1183        // attempts there means it did, and its messages go; none, or no answer, means it
1184        // didn't (taken back; a stored one is taken back once the worker's echo shows it
1185        // unstarted, B240).
1186        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            // Read back as not stored, or not read back at all.
1196            self.recount();
1197        }
1198        outgoing.truncate(built);
1199        if !task_specific(&error) {
1200            return Err(error);
1201        }
1202        // One task may fail every time (its data won't read, the database refuses it): one at
1203        // a time, the others go on and it is set aside, instead of every round failing on it.
1204        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    /// Cancels what the runs of removed DAGs haven't started (B192): each run whole or not at
1213    /// all, so a run that fails is found again the next round, never left with its tasks
1214    /// ended and itself running (Codex's review).
1215    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            // One run that can't be wound down holds no other assignment up.
1227            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    /// A removed DAG's assignments of `run_id` that haven't started (no `Started` stored or
1243    /// waiting) are cancelled as a task cancel is (Codex's review of B192): the worker is told
1244    /// not to start them. Resources' cleanups and moved cleanups go on.
1245    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    /// The ready tasks but those of a held DAG (its resources' cleanups still run): a removed
1276    /// DAG's are left out, [`Self::wind_down_removed`] cancelling them (B192); a DAG in an ID
1277    /// conflict's wait until it is resolved (B193, decision 107).
1278    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    /// Fails each resource's user `unschedulable` for longer than the resource's
1311    /// `unschedulable_timeout` (the shortest, when it uses several), so the cleanup can run
1312    /// (decision 273).
1313    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            // One transaction: the task's end and the run's, and the stops sent with them.
1334            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    /// The `wait_for` steps queued (decision 353): no worker takes them; each round each is
1352    /// ended once the run it waits for (or its task) has, or its `max_wait` ran out, and
1353    /// otherwise says what it waits for.
1354    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            // Parked before the look (decision 487): looked at again at its deadline, or when a
1392            // run or task of that DAG ends.
1393            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    /// An `@sensor(wait_for=...)` queued (decision 353): once a matching run has ended (one its
1430    /// function hasn't said `NOT_YET` to), it is to be assigned with that run, which is recorded;
1431    /// past its `max_wait` it ends `TimedOut` here; else it says what it waits for. Returns
1432    /// whether it is to be assigned.
1433    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        // Parked before the look (decision 487), as a `wait_for` node is.
1455        self.db
1456            .park_wait(
1457                &waiting.instance_id,
1458                deadline,
1459                (Some(run_of.dag.as_str()), None),
1460            )
1461            .await?;
1462        // A retry gets the run it was handed, unless its function said `NOT_YET` to it: the
1463        // data a call failed on isn't swapped for a newer run's (decision 353).
1464        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            // Another DAG's output, as anyone reading it through the API sees it (decision
1486            // 131; Grok's review of M4.11d2): secret fields and passwords masked.
1487            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            // One transaction: the attempt's end and the step's, or neither.
1498            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    /// When a wait waiting `since` with `max_wait_ms` (else `[sensors] default_max_wait`) times
1510    /// out.
1511    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    /// The run of `run_of` a wait planned for `planned_for`, waiting `since`, matches (decision
1520    /// 353): with `lag` the newest planned for that moment, else the first to end since then;
1521    /// after `seen` (one its function said `NOT_YET` to), a later one. A run that ended after
1522    /// `deadline` still runs as far as the wait knows, though seen only now (a round late, a
1523    /// master restarting).
1524    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        // A lag past the times there are matches no run: the step waits out its time.
1533        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            // With `lag`, the one said NOT_YET to stays the newest until a newer one comes.
1550            .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    /// What a `wait_for` step says it waits for; that its DAG isn't loaded, if it isn't (it may
1560    /// come from a folder that loads later, decision 353).
1561    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    /// Reads what the concurrency limits need: the open attempts, once (the master's first
1579    /// round with tasks ready; then kept in memory), and each DAG's current version.
1580    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    /// The DAG version whose limits across runs hold for `ready`: its DAG's current one, or
1589    /// its run's own if the DAG has none now (removed, in conflict) or it can't be read.
1590    /// With its version's ID.
1591    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    /// Whether one of `ready`'s concurrency limits is reached: then it waits, counted and its
1617    /// reason written (at most so many a round, as for the other reasons).
1618    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            // A resource's cleanup isn't held by any limit (decision 225); it needs a slot.
1626            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(&current_id, &current, &ready.task_id)
1633        };
1634        let Some(reached) = self.active.reached_with(
1635            (&current, &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    /// Counts `made` assignments, once stored.
1653    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    /// Whether the attempt of the first assignment in `built` is stored, after a commit whose
1660    /// outcome is unknown (see [`read_back`]; `false` if it can't be told).
1661    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    /// The `ready` tasks assigned each in a transaction of its own; one whose assignment fails
1674    /// on its own is set aside for [`SET_ASIDE`], with a warning. An error that isn't one
1675    /// task's (the database gone, the lease lost), or every task failing, is the step's.
1676    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            // The round's cap holds here too (Grok's review of M5.1c1): the rest as in a batch.
1686            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                // The rest of the round counts what is stored.
1710                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        // Every one that tried failed (more than one, none assigned): the database's trouble,
1720        // not theirs. Those that only waited for a slot don't count.
1721        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        // Its own transaction: shown only, and the assignments are stored already.
1736        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    /// Assigns the `ready` tasks to workers with free slots, each assignment's message into
1747    /// `outgoing` once it is stored (in [`Self::assign_into`]'s transaction).
1748    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        // Picked one by one (each sees the slots and limits the ones before it took), claimed
1756        // together, then each one's message built (decision 482).
1757        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    /// The ready tasks a round reaches once it has made its assignments (decision 481): not
1795    /// gone through for their limits and workers, but counted as waiting for the next round and
1796    /// shown pending, the reason written with the others (in statements over many tasks). A
1797    /// wait step switched off or out of time still ends now: read once a round
1798    /// ([`RoundReads`]), that check costs a statement only for one that ends.
1799    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        // At most a statement's worth a round (Grok's review): a reason stays once written,
1807        // so a longer backlog shows pending over the next rounds.
1808        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    /// Assigns one ready task to a worker with a free slot, its message into `outgoing` once
1831    /// it is stored; or says why it waits.
1832    /// The run's parameters as JSON, for the task; empty for a DAG that takes none (the runner
1833    /// reads `{}`), so nothing is read.
1834    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    /// The first part of an assignment (decision 482): whether `ready` goes this round, and to
1868    /// which worker, its slot and its place under the concurrency limits taken at once (so the
1869    /// next task picked sees them), under a new attempt ID; or why it waits.
1870    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        // Its concurrency limits first: a task over one waits for it, whatever the workers.
1884        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        // Workers that didn't have the code yet come last: the others are asked first.
1894        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            // At most so many a round: the rest in the next ones (B18).
1906            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    /// The last part of an assignment, once its claim is stored (`try_number`; `None`: the
1924    /// instance wasn't queued any more): its message built into `outgoing`, or the attempt
1925    /// ended for what the master finds (inputs that don't fit its arguments or are too large,
1926    /// a message too large to send). The slot and the limits' place [`Self::pick_one`] took are
1927    /// given back when it doesn't go.
1928    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            // Ending it may end its task or run, and so what the batch picked after it.
1961            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    /// Gives back what [`Self::pick_one`] took for an assignment that doesn't go.
2009    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    /// When `started` began, received `now`: the worker's start in this master's time
2016    /// (M5.1m) turned into the wall clock `now` is on, never after `now`; `now` itself from an
2017    /// older worker, without its estimate, or on another master's timeline.
2018    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        // How long ago in master time, the same span ago on the wall clock, both read now:
2029        // `now` was read earlier, before the lock and the transaction (Grok's review of M5.1m).
2030        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    /// A worker reported `Started`. Returns a `CancelAttempt` if the attempt was taken back,
2040    /// ended or belongs to another worker.
2041    ///
2042    /// # Errors
2043    ///
2044    /// [`DispatchError::Db`] if the database fails.
2045    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            // A start already recorded changes only the method: no witness of this write.
2061            if !attempt.started {
2062                self.witnesses.push((attempt.id.clone(), Witness::Started));
2063            }
2064            // It found a worker: who rejected it before doesn't matter any more.
2065            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    /// A turn's `Started`s together (M5.1d), as [`Self::started`] handles each: the attempts
2073    /// read in one query, their starts recorded in a statement for each start method. One that
2074    /// isn't this worker's, or is no longer running, is answered with a cancel.
2075    ///
2076    /// # Errors
2077    ///
2078    /// [`DispatchError::Db`] if the database fails: the caller's transaction rolls back, and
2079    /// the messages are handled one by one.
2080    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        // Each attempt's last start method, as one by one would leave it, and its first
2096        // `Started`'s time (a later one is kept by the database anyway).
2097        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            // A start already recorded changes only the method: no witness of this write.
2119            if !attempt.started {
2120                self.witnesses.push((attempt.id.clone(), Witness::Started));
2121            }
2122            // It found a worker: who rejected it before doesn't matter any more.
2123            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    /// Whether `worker_id` surely never started `attempt_id`, as its messages' echo says
2134    /// ([`crate::core::Arrivals::never_started`], B240).
2135    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    /// Times this dispatcher on `steady` (see [`crate::clock`]).
2140    pub fn set_steady(&mut self, steady: crate::clock::Steady) {
2141        self.steady = steady;
2142    }
2143
2144    /// Reads the wall clock from `wall` where it is compared with master time (M5.1m).
2145    pub fn set_wall(&mut self, wall: fn() -> Timestamp) {
2146        self.wall = Some(wall);
2147    }
2148
2149    /// A worker rejected an assignment.
2150    ///
2151    /// # Errors
2152    ///
2153    /// [`DispatchError::BadMessage`] for an unknown reason, or [`DispatchError::Db`].
2154    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            // A moved cleanup goes on waiting, this worker asked last.
2169            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            // Never a try, and nothing runs again: the task is cancelled (B5).
2195            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        // The workers that could run it: once each has rejected it, it is unschedulable.
2202        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    /// A worker's task ended and its cleanup starts: the instance is `cleaning_up`, its
2223    /// attempt open until `Finished`, and the task's result kept, for a worker lost meanwhile
2224    /// (decision 229). Only from the worker it was assigned to (B46).
2225    ///
2226    /// # Errors
2227    ///
2228    /// [`DispatchError`] if the database fails.
2229    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    /// A worker reported `Finished`: stored once (only from the worker the attempt was assigned
2250    /// to, B46), and always acknowledged.
2251    ///
2252    /// # Errors
2253    ///
2254    /// [`DispatchError::BadMessage`] for an unknown status, or a database failure.
2255    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            // A cleanup under way when its worker was cut off (decision 255), reported when it
2268            // came back, while the cleanup waits to move: it ran, so it counts and doesn't
2269            // move (decision 282). The worker ran the task too, if it is the first move: its
2270            // own result stands (see `kept` below).
2271            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            // The handles the master never got, cleaned by the worker its cleanup first moved
2276            // from (B169): added to the attempt's cleanup, ended or not. Said to be a rest, it
2277            // never counts as the whole cleanup, even from the attempt's worker now.
2278            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                // Added already, or not this worker's to clean: ignored.
2291                return Ok(finished_ack(worker_id, &finished.attempt_id));
2292            }
2293            if attempt.worker_id != worker_id && !left_by_it {
2294                // Not its attempt (B46): only the worker it was assigned to ran it. Acknowledged
2295                // so the sender stops resending, never stored, as `Started` is refused.
2296                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            // Only for a result not stored yet (a repeated one is dropped anyway).
2308            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            // A cleanup that moved knows nothing of the task: its result is the kept one
2320            // (a refused one is reported as `result_not_stored`, and stands). Only the worker
2321            // it first moved from ran the task: one it moved from later ran the cleanup alone.
2322            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    /// Common `Finished`s, as one batch (see [`Self::finished_group`]).
2342    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            // A wait step's success clears its strikes: the group's together, below, but
2362            // before any strike after it (Grok's review: two runs of one wait step, a success
2363            // then a struck failure, keep the strike, as one by one).
2364            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    /// A turn's `Finished`s together (M4B.4, B184): the attempts read in one query, the
2413    /// common case (the worker's own attempt, not moved, its first result) ended in one
2414    /// statement, its outputs in another, each run read and moved forward once. Any other
2415    /// (a moved cleanup's, a rest, another worker's, code gone missing, a repeat) goes through
2416    /// [`Self::finished`] alone, first. Each is acknowledged.
2417    ///
2418    /// # Errors
2419    ///
2420    /// [`DispatchError`] if a message is malformed or the database fails: the caller's
2421    /// transaction rolls back, and the messages are handled one by one.
2422    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                // Gone, or a repeat: acknowledged only (as `finished` does).
2445                None => {}
2446                Some(_) if !first => {}
2447                Some(attempt) if is_repeat(attempt, finished, worker_id) => {}
2448                // In its place (Grok's review): what came before it stored first, so a mapped
2449                // sibling's success before an uncommon failure stays a success, as one by one.
2450                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    /// Whether a wait step ended here, without a call: switched off, or out of time. A sensor
2465    /// handed a run that ended within its `max_wait` is called, though little of it is left
2466    /// (Grok's review of M4.11d2): the wait was answered in time.
2467    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    /// Fails a wait step switched off, whatever the workers: a run isn't kept open by what won't
2482    /// run. Returns whether it was.
2483    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    /// What is left of a wait step's `max_wait`, once it has started: it runs from its instance's
2506    /// first start, over retries and moves (decision 321). With it, that first start (for an
2507    /// `@sensor(wait_for=...)`, when it began to wait).
2508    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        // An `@sensor(wait_for=...)`'s runs from when it began to wait, over its calls (353).
2523        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    /// Ends a wait step whose time ran out while it waited to run again: it would only time out,
2551    /// and no worker has to be free for that, or its function called past its time. Returns
2552    /// whether it did.
2553    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    /// Ends a wait step `TimedOut` by the master, no worker hearing of it.
2572    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    /// The message of an attempt just assigned, if it is within what a worker takes; over, the
2594    /// attempt ends and it never leaves (Codex's review of M4.11d2: a wait step's handed run
2595    /// rides in it).
2596    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        // Inputs under the inline limit can still take the whole message over what a worker
2608        // takes, with the task, its params and connections (B157): then they go separately.
2609        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            // Ending it may end its task or run, and so what the batch picked after it.
2621            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    /// Takes the slot its kind of task runs on.
2630    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    /// A wait step's `max_wait` runs from its instance's first start, over retries and moves
2646    /// (decision 321): what it gets is what is left.
2647    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            // Tried again: `delay` (a plain `@sensor`) counts from its first try's start.
2671            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            // The run it waited for, as its function's first argument (decision 353).
2679            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    /// Ends an attempt just assigned, without its worker having heard of it.
2691    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    /// Why a wait step about to start can't, if it is switched off; on new code it is on again,
2705    /// with one chance (decision 338).
2706    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    /// Whether a wait step or trigger is switched off now; on new code it is on again, with one
2719    /// chance (decision 338).
2720    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    /// Whether a DAG's code has moved on from `code`: workers run other code now, and none is
2746    /// let run it. What isn't known yet (after a restart) hasn't moved on.
2747    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    /// The strikes of wait steps that succeeded cleared, as [`Self::count_strike`] does each:
2754    /// their DAGs read in one query, a statement for each DAG. A run that can't be read is
2755    /// left as `count_strike` leaves it.
2756    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    /// Counts how a wait step's attempt ended, the first time it is told (decision 338).
2780    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        // The code it ran: an old attempt says nothing of what came since.
2802        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    /// The cleanup of the handles the master never got, added to `attempt`'s (B169): the
2815    /// instance's cleanup result takes a failed or `ok` one, and a failure fails the run if it
2816    /// is still open; an ended `success` turns a yellow one (decision 309), logged as an error
2817    /// and counted.
2818    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    /// Takes back assignments the worker's echo shows it never started (B240): a message from
2860    /// it named the assignment's number as handled, with no `Started` (or `Finished`) before.
2861    /// They end `assignment_expired` and their tasks run again without using a retry; a moved
2862    /// cleanup never started goes on waiting for another worker. One not known unstarted
2863    /// stays: its worker hasn't handled it yet (it does, in order), or its lease runs out
2864    /// ([`Self::worker_lost`] decides), or it registers again (its journal decides,
2865    /// [`Self::unreported_unstarted`]). Returns how many attempts ended.
2866    ///
2867    /// # Errors
2868    ///
2869    /// [`DispatchError`] if the database fails.
2870    pub async fn expire(&mut self, now: Timestamp) -> Result<usize, DispatchError> {
2871        // Adopted attempts whose start wasn't recorded are kept while a worker holds them.
2872        let workers = &self.workers;
2873        self.adopted_unrecorded
2874            .retain(|attempt| workers.all().any(|w| w.attempts.contains(attempt)));
2875        // Nor those of a worker that may come back (F14): nothing of its stream is known.
2876        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            // Whole or not at all, memory with it (B49): ending the attempt and moving its
2910            // task are separate writes, and the slot is freed in memory before them.
2911            self.whole(async |dispatcher| dispatcher.record(attempt, &end, &result, now).await)
2912                .await?;
2913        }
2914        Ok(expired.len())
2915    }
2916
2917    /// A worker's agent restarted (a new incarnation), before its stream replaces the old
2918    /// one's: the attempts the old process may run and the new one doesn't report are marked,
2919    /// and end `lost` with a `WorkerRestarted` error summary once the old incarnation's lease
2920    /// is over in master time (decision 443, B230: the old process may still run them
2921    /// meanwhile; see [`Self::end_replaced`]), each using a retry, as for a lost worker (the
2922    /// crash may have been the task's own; see archive/PROJECT.md, Worker lifecycle). Those
2923    /// are the started ones, and the unstarted ones the old stream's echo doesn't show it
2924    /// never started (B240: its `Started` may have been lost with its stream). Those it shows
2925    /// never started are taken back now, without using a retry; a moved cleanup among them
2926    /// waits for another worker. Returns how many were marked.
2927    ///
2928    /// # Errors
2929    ///
2930    /// [`DispatchError`] if the database fails.
2931    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            // Not started here: the task never heard starting, or a moved cleanup assigned
2944            // here and not started (the task's own start was elsewhere).
2945            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    /// Takes back `attempt`, which its worker never started (B240): a moved cleanup waits for
2965    /// another worker; a task's attempt ends `assignment_expired`, its task queued again
2966    /// without using a retry (B17).
2967    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        // Whole or not at all, memory with it (B49).
2981        self.whole(async |dispatcher| {
2982            dispatcher
2983                .record(attempt, &end, &by_master(status), now)
2984                .await
2985        })
2986        .await
2987    }
2988
2989    /// The same process registered again (a stream broken, the worker running on): its
2990    /// journal holds every assignment it accepted, so one not started and not in it never
2991    /// started there, and is taken back now (B240; what its old stream still carries, it
2992    /// drops). Returns how many.
2993    ///
2994    /// # Errors
2995    ///
2996    /// [`DispatchError`] if the database fails.
2997    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    /// The attempts `worker_id`'s journal reports at its registration: alive there, none of
3017    /// its own is held for a replaced incarnation any more (Grok's review of decision 443: one
3018    /// told to continue was still ended when the hold ran out). Another worker's, which its
3019    /// journal can't keep, stays held.
3020    ///
3021    /// # Errors
3022    ///
3023    /// [`DispatchError`] if the database fails.
3024    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        // After a restart the hold isn't in memory yet: cleared in the database all the same.
3041        self.db.clear_replaced(&own).await?;
3042        for id in &own {
3043            self.replaced_since.remove(id);
3044        }
3045        Ok(())
3046    }
3047
3048    /// Ends `lost` the attempts a replaced incarnation left behind whose lease is over in master
3049    /// time (decision 443), each whole or not at all; a kept result the database refuses is
3050    /// dropped, as for a lost worker. Returns how many ended.
3051    ///
3052    /// # Errors
3053    ///
3054    /// [`DispatchError`] if the database fails.
3055    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            // A moved cleanup never heard starting there: the old process has stopped, so it
3072            // waits for another worker again, no move used (Grok's review of decision 443: ended
3073            // `lost` with no move left, it never ran).
3074            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            // `end_lost` clears the mark with it: a cleanup moved stays open, and mustn't be
3085            // moved again a lease later (Grok's review).
3086            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    /// A worker is lost or gone: its started attempts end `lost` with a `WorkerLost` error
3115    /// summary (each uses a retry), the ones it never started `assignment_expired` with a
3116    /// `WorkerLeft` one (queued again, no retry), and it is forgotten.
3117    ///
3118    /// # Errors
3119    ///
3120    /// [`DispatchError`] if the database fails.
3121    pub async fn worker_lost(
3122        &mut self,
3123        worker_id: &str,
3124        results: KeptResults,
3125        now: Timestamp,
3126    ) -> Result<(), DispatchError> {
3127        // Whole or not at all, memory with it (B49): the worker is forgotten in memory first.
3128        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            // Not heard starting: if the worker said it had handled the assignment and no start
3147            // came before, it never started there (B240). Otherwise it may run there, its
3148            // `Started` held up on the way (a one-way cut): as a started one, `lost` using a
3149            // retry, its cleanup moving if it may (B234), the worker running on with an
3150            // ordinary task (decision 252).
3151            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            // A moved cleanup never started there waits for another worker.
3157            if attempt.moving {
3158                self.take_back_cleanup(&attempt, now).await?;
3159                continue;
3160            }
3161            // Taken back like an expired assignment, queued again without using a retry (B17).
3162            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    /// Ends a started attempt whose worker can't report it any more: with the task's result if
3173    /// its process's end was reported (decision 229: it isn't run again), else `lost`, with
3174    /// `summary`. Its cleanup, if the task has one, didn't run (decision 220).
3175    async fn end_lost(
3176        &mut self,
3177        attempt: &StoredAttempt,
3178        summary: String,
3179        results: KeptResults,
3180        now: Timestamp,
3181    ) -> Result<(), DispatchError> {
3182        // Ended or moved here, a replaced incarnation's hold on it is over, whichever path
3183        // took it (Grok's review of decision 443: a lost worker's moved cleanup moved again).
3184        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    /// Ends an attempt whose kept result the database refuses, as a refused `Finished` is
3220    /// (B106): failed, not retried, the same data would be refused again.
3221    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    /// The cleanup of the attempt's task.
3247    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    /// The task's result kept for an attempt, and its status.
3256    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    /// Moves an attempt's cleanup off a lost worker (`cleanup_anywhere`, decision 243): the
3272    /// attempt stays open, its instance `cleaning_up`, the task `lost` unless it reported its
3273    /// end, and a later round gives it to another worker.
3274    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        // A worker only cut off is stopping the task meanwhile. Kept in master time (B228);
3288        // the stored one is for people.
3289        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    /// A moved cleanup's worker refused it or never started it: it waits again, and that
3306    /// worker's slot is free.
3307    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    /// Gives the moved cleanups waiting to workers, ahead of the tasks waiting and not held by
3322    /// limits (decision 246): their attempts are counted already.
3323    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        // All that wait, each moving once its wait in master time is over (B228): after a
3330        // restart, a whole wait from when this master first sees it.
3331        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            // A worker that refused it may take it yet: it does when no other can.
3351            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    /// The assignment of a moved cleanup: its task's, with its handles.
3389    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                    // It ran with them: what can't be read now fails on the worker, if at all.
3410                    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    /// Handles an attempt registered, kept for a cleanup on another worker (decision 242). Only
3434    /// from the worker it is assigned to (B46), while it is open, and up to what an attempt
3435    /// may hold (decision 228); a handle that doesn't read is left out.
3436    ///
3437    /// # Errors
3438    ///
3439    /// [`DispatchError`] if the database fails.
3440    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    /// Runs `work` in one transaction; if it fails, the memory it changed is put back as it
3483    /// was, so memory and database stay in step (B49). Call it with no transaction open:
3484    /// joined into an outer one, memory isn't put back if the outer one rolls back.
3485    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    /// Cancels one task of a run (see [`Execution::cancel_task`]); a `CancelAttempt` for its
3498    /// attempt if it runs.
3499    ///
3500    /// # Errors
3501    ///
3502    /// [`DispatchError`] for an unknown run or task, or a database failure.
3503    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        // -1 is the whole task, as the API lists it: every instance (execution agrees).
3510        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    /// Queues an `unschedulable` task of an unfinished run again (see
3531    /// [`Execution::retry_task`]), forgetting which workers rejected it (`schedr tasks retry`).
3532    ///
3533    /// # Errors
3534    ///
3535    /// [`DispatchError`] for an unknown run or task, or a database failure.
3536    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    /// Cancels a run; returns a `CancelAttempt` for each of its running attempts.
3554    ///
3555    /// # Errors
3556    ///
3557    /// [`DispatchError`] for an unknown run or a database failure.
3558    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    /// Queues `CancelAttempt`s for running instances whose mapped task's step failed (75a).
3604    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    /// Records a worker-specific rejection, or that the worker didn't have the code, and
3652    /// decides: `unschedulable` once every eligible worker said one or the other, and (if any
3653    /// said the code is missing) the code has been missing for the code wait; otherwise
3654    /// queued again, after [`CODE_RETRY_DELAY`] when the code was missing.
3655    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        // No eligible worker at all (none synced yet, say) isn't every one rejecting it.
3685        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                // Never none: a queued task without `ready_at` is never read as ready.
3715                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    /// How the attempt's DAG changed since its run started, if it did: removed, moved to
3730    /// another file, or without the attempt's task.
3731    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        // This DAG alone (B136: every DAG was read, an unrelated one that doesn't read too).
3738        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    /// What a task of `dag` in `queue`, of a parse by schedr `parse_version`, needs of a
3766    /// worker.
3767    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        // The run's parse, and the current code's: the code that runs needs both.
3776        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    /// Why no worker could be picked for a task with `needs`: the kind of reason (a metric's
3789    /// label) and the reason shown with the task.
3790    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    /// The worker to run a DAG's trigger: as a wait step's, on a watcher slot, which it takes.
3851    /// Gives the assignment and the code it was picked for; `None` when no worker has a free one,
3852    /// or the root's current code isn't known yet (a parse on its way after a restart).
3853    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(&registry.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    /// A worker: what the trigger pass asks of the one running a trigger.
3904    #[must_use]
3905    pub fn worker(&self, id: &str) -> Option<&crate::workers::Worker> {
3906        self.workers.get(id)
3907    }
3908
3909    /// A trigger keeps its watcher slot on the worker that came back with it.
3910    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    /// A trigger gave up its watcher slot: the trigger loop looks (another may start there).
3915    pub fn trigger_released(&mut self, instance: &str) {
3916        self.workers.release(instance);
3917        self.trigger_wake.notify_one();
3918    }
3919
3920    /// What the trigger loop waits on besides writes: told when a trigger's state changes in
3921    /// memory only.
3922    #[must_use]
3923    pub fn trigger_wake(&self) -> std::sync::Arc<tokio::sync::Notify> {
3924        self.trigger_wake.clone()
3925    }
3926
3927    /// What a run started by an event gets of it: nothing for any other run.
3928    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            // No current code known yet (a parse on its way after a restart): no check.
3976            // The hash the worker was picked for (it reported it); none while the root's
3977            // current code isn't known yet (a parse on its way after a restart): no check.
3978            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            // The task's own budget and cap (decisions 436, 438); the agent reads them from the
3993            // task too.
3994            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            // Only what the task declares (decision 179): the agent serves no other, and a
3998            // root's whole registry could outgrow the worker's 4 MiB message.
3999            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(&registry.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/// `task` as an assignment carries it: without what it maps over (B119: a literal list sent with
4013/// each instance, its square in all); the instance's element comes in its inputs (`$expand`).
4014/// A protocol timestamp as a time, if it is one.
4015#[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
4060/// An attempt's end and result as `finished` says, with `error_summary` and `cleanup` as read.
4061/// Whether a `Finished` takes the common path of [`Dispatcher::finished_group`]: its worker's
4062/// own attempt, not ended, never moved, its whole result (not a rest), its code there.
4063/// How a `Started` says its task started: forked, or spawned (also when it doesn't say).
4064fn 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
4071/// Whether `finished` repeats this worker's result already stored for `attempt` (sent again
4072/// before its acknowledgement came, M5.1d): acknowledged only, as [`Dispatcher::finished`]
4073/// would end up doing, without its reads and writes.
4074fn 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        // 0: not measured (a worker without `/proc`, or before 2.8).
4103        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
4129/// A result's error summary, as stored.
4130fn 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
4135/// Why a run is a yellow success: a cleanup after its end failed (decision 309).
4136pub const LATE_CLEANUP_FAILED: &str = "late_cleanup_failed";
4137
4138/// A cleanup standing in when the task's is gone from its DAG.
4139const 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
4150/// The cleanup of an attempt whose worker is gone: it didn't run, or not to its end, and that
4151/// fails the run (decision 220).
4152fn 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
4174/// A `Finished`'s cleanup, read.
4175fn 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
4191/// The error summary of an attempt that was running when its worker's agent restarted (the
4192/// agent doesn't report it again: it may have been killed for using too much memory).
4193fn 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
4200/// The error summary of an attempt whose worker was lost (no sign of life for the lease).
4201fn 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
4228/// An error summary (JSON text) with `context` before its message; a new one (`CodeChanged`)
4229/// without, keeping a summary that doesn't read as its text.
4230fn 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
4241/// Why `message` can't go to a worker that takes at most `limit` bytes, if it can't: a run
4242/// handed to a `wait_for=` function rides in it (decision 353; Grok's and Codex's reviews).
4243pub(crate) fn too_big_to_send(message: &pb::MasterMessage, limit: usize) -> Option<String> {
4244    // Unstamped yet: the clock `deliver` adds counts too, at its largest.
4245    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
4283/// The inputs of an open attempt as JSON (what `FetchInputs` streams when they were too big for
4284/// `AssignTask`); `None` for an unknown or ended attempt. Only reads the database, so it needs
4285/// none of the master's state, nor its lock: a busy master doesn't hold a task's start up (B11).
4286///
4287/// # Errors
4288///
4289/// [`DispatchError::Db`] if the database fails.
4290pub 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        // Ended when it was assigned: never sent.
4319        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
4326/// The outcomes of the upstream tasks the task uses (`""` for a skipped one), for
4327/// `AssignTask`: `.on(...)` references and `.outcome` read them.
4328async 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
4354/// Whether `error` is one task's own (data that won't read, a statement the database
4355/// refuses), so that setting the task aside lets the others go on; not the database gone, a
4356/// time limit, or the lease lost, which are every task's.
4357fn 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
4367/// Whether a task waits for another DAG's run before anything runs it: a `wait_for` node, or an
4368/// `@sensor(wait_for=...)` (decision 353).
4369/// Whether a task is a `TriggerDagOperator`, which the master carries out (decision 361).
4370const 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
4386/// Whether a run found (or its task) has ended, whatever its state: an `@sensor(wait_for=...)`
4387/// is called for any (`missing`: the run ended without the task).
4388fn run_ended(state: &str) -> bool {
4389    matches!(
4390        state,
4391        "success" | "failed" | "upstream_failed" | "skipped" | "cancelled" | "missing"
4392    )
4393}
4394
4395/// What the run found says (the newest planned for the moment, or the first to end): its ID
4396/// when it succeeded, `Failed` when it ended otherwise, nothing while it hasn't ended or none
4397/// is there.
4398fn 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}