Skip to main content

schedr_master/
core.rs

1//! The master's protocol logic, apart from any transport: registering workers, their messages,
2//! disconnects, the periodic tick, parse uploads and inputs (see archive/PROJECT.md, Master–worker
3//! protocol and Worker lifecycle).
4//!
5//! The gRPC service ([`crate::service`]) only moves messages between workers' streams and
6//! this core, so everything here is tested without a network.
7
8use std::collections::{BTreeMap, BTreeSet};
9use std::sync::Arc;
10use std::time::Duration;
11
12use jiff::{SignedDuration, Timestamp};
13use schedr_db::workers::{WatcherHostRecord, WorkerRegistration, WorkerWarning};
14use schedr_db::{Database, DbError};
15use schedr_model::commands::{
16    CONNECTION_ANSWER_MARGIN_MS, ConnectionJobResult, ConnectionReport, ConnectionsResult, JobState,
17};
18use schedr_model::runner::ErrorSummary;
19use schedr_model::{SchedrVersion, WorkerState};
20use schedr_proto::convert::parsed_file_from_proto;
21use schedr_proto::pb::{self, master_message, worker_message};
22use schedr_proto::{PROTOCOL_VERSION, check_worker_version};
23
24use crate::commands::{Applied, CommandError, Commander, parse_connection_job_id};
25use crate::discovery::{Discovery, ParseUpload};
26use crate::dispatch::{
27    DEFAULT_CANCEL_GRACE, DEFAULT_CODE_WAIT, DispatchError, Dispatcher, KeptResults, Outgoing,
28};
29use crate::execution::ExecutionError;
30use crate::metrics::MasterMetrics;
31use crate::parse_jobs::{PARSE_JOB_TIMEOUT, ParseAssignment, ParseJobs, ParseKey};
32use crate::quiet::{QuietSettings, Wakes};
33use crate::scheduler::{Scheduler, SchedulerError};
34
35pub mod task_api;
36pub(crate) mod triggers;
37
38#[cfg(test)]
39mod tests;
40
41/// How often a worker's usage is written from its heartbeats (decision 463): a minute, the
42/// samples' own step (decision 464), so the stored figure is never older than a sample needs
43/// and a heartbeat adds no statement in between.
44pub const USAGE_EVERY: SignedDuration = SignedDuration::from_secs(60);
45
46/// How long a script root may be unreported before it counts as absent (decision 303).
47pub const DEFAULT_SCRIPT_ROOT_GRACE: Duration = Duration::from_mins(5);
48
49/// The master's timing, sent to every worker in `Registered` so all behave the same.
50#[derive(Debug, Clone, Copy, PartialEq, Eq)]
51pub struct Settings {
52    /// How often workers send `Heartbeat`.
53    pub heartbeat_interval: Duration,
54    /// A worker silent for this long is lost.
55    pub lease_timeout: Duration,
56    /// How long a deposed leader may still believe it leads, and answer its workers'
57    /// heartbeats: its lease period less the query timeout (decision 444). A worker restored
58    /// at a takeover is lost only this plus its lease after the takeover.
59    pub takeover_wait: Duration,
60    /// The time between SIGTERM and SIGKILL when an attempt is cancelled.
61    pub cancel_grace: Duration,
62    /// After how many host kills in a row a wait step is switched off (0: never).
63    pub switch_off_after: u32,
64    /// Queued event runs of a DAG that stop its trigger.
65    pub max_queued_events: u32,
66    /// Errors in a row that make a trigger `failing`.
67    pub failing_after: u32,
68    /// How long a wait step without a `max_wait` waits.
69    pub sensor_max_wait: Duration,
70    /// How long a worker has for a parse job.
71    pub parse_job_timeout: Duration,
72    /// How long a task's code may be missing on every eligible worker.
73    pub code_wait: Duration,
74    /// How long a task whose assignment fails on its own is set aside.
75    pub set_aside: Duration,
76    /// The least an `@sensor(wait_for=...)`'s call gets once handed its run (decision 353).
77    pub handed_call_min: Duration,
78    /// How long a lost worker's cleanup waits before it moves, on top of `cancel_grace`.
79    pub cleanup_move_wait: Duration,
80    /// How long no alive worker must report a script root (counted from the master's start
81    /// too) before it counts as absent: DAG roots using it are then no longer withdrawn for it
82    /// (decision 303).
83    pub script_root_grace: Duration,
84    /// How far before the newest event an `EventNamed` trigger acted on it looks again, for one
85    /// stored late (`SCHEDR_HIDDEN__MASTER__EVENT_LOOKBACK`, decision 354).
86    pub event_lookback: Duration,
87    /// How a commit cut off is read back (see [`crate::dispatch::ReadBack`]).
88    pub read_back: crate::dispatch::ReadBack,
89    /// How often to try listening for commands again after it failed to start.
90    pub listen_retry: Duration,
91    /// How its loop and its parse jobs are paced.
92    pub timings: MasterTimings,
93    /// Which DAGs a round visits (`[master] quiet_dags`, decision 485).
94    pub quiet: QuietSettings,
95    /// The largest message a worker may send (`[grpc] max_message_size`).
96    pub max_message_size: usize,
97    /// The most messages of one worker handled in one turn of the core's lock
98    /// (`SCHEDR_HIDDEN__MASTER__MESSAGES_PER_TURN`, M4B.3).
99    pub messages_per_turn: usize,
100    /// The most instances a mapped task may have (`[mapping] max_instances`).
101    pub max_instances: usize,
102    /// The most fire times a backfill's range may have (`[backfill] max_runs`).
103    pub backfill_max_runs: u32,
104    /// The most records of one kind, and characters of each text, kept of what a worker
105    /// reports (wait step hosts, warnings; B183).
106    pub worker_report: ReportLimits,
107    /// `[retention]` and its job's timing (decisions 430-435).
108    pub retention: crate::retention::RetentionSettings,
109    /// How processes are sampled and their samples kept (decision 464).
110    pub samples: crate::samples::SampleSettings,
111    /// Whether this master's own process runs the webserver too (standalone): its sample says
112    /// so, and no webserver samples it again.
113    pub with_webserver: bool,
114    /// How much one round or pass does at most (decision 493).
115    pub rounds: RoundLimits,
116    /// How far ahead of the master's clock a run's `--for` may be
117    /// (`SCHEDR_HIDDEN__MASTER__FOR_FUTURE_TOLERANCE`).
118    pub for_future_tolerance: Duration,
119    /// When a task whose code wasn't on its worker yet is tried again
120    /// (`SCHEDR_HIDDEN__MASTER__CODE_RETRY_DELAY`).
121    pub code_retry_delay: Duration,
122    /// The most messages of a failed group handled one by one in a turn
123    /// (`SCHEDR_HIDDEN__MASTER__FAILED_GROUP_MESSAGES_PER_TURN`, M4B.3).
124    pub failed_group_messages_per_turn: usize,
125    /// The messages that wait for a worker before it is taken for one that stopped reading
126    /// (`SCHEDR_HIDDEN__MASTER__WORKER_STREAM_BUFFER`).
127    pub worker_stream_buffer: usize,
128}
129
130/// How much one round or pass of the master does at most (B18's caps, decision 493), each a
131/// `SCHEDR_HIDDEN__MASTER__*` limit: a burst goes over a few rounds instead of holding one up.
132#[derive(Debug, Clone, Copy, PartialEq, Eq)]
133pub struct RoundLimits {
134    /// Assignments made (`ASSIGNMENTS_PER_ROUND`).
135    pub assignments: usize,
136    /// Assignments taken back as never started (`EXPIRIES_PER_ROUND`).
137    pub expiries: usize,
138    /// Waiting reasons written, a statement each (`WAITING_REASONS_PER_ROUND`).
139    pub waiting_reasons: usize,
140    /// Pending reasons written for the tasks past the cap (`PENDING_REASONS_PER_ROUND`).
141    pub pending_reasons: usize,
142    /// Commands applied (`COMMANDS_PER_ROUND`).
143    pub commands: u32,
144    /// Scheduled runs created for one DAG (`SCHEDULED_RUNS_PER_ROUND`).
145    pub scheduled_runs: usize,
146    /// Task instances created for runs that just started (`STARTED_INSTANCES_PER_ROUND`).
147    pub started_instances: usize,
148    /// Failed tasks queued again (`RETRIES_PER_ROUND`).
149    pub retries: usize,
150    /// Runs the scheduler creates for one DAG in one pass (`RUNS_PER_PLANNING_PASS`).
151    pub planning_pass_runs: usize,
152    /// Runs one pass starts for a DAG started by `RunOf` (`RUN_OF_RUNS_PER_PASS`).
153    pub run_of_runs: u32,
154}
155
156impl Default for RoundLimits {
157    /// The caps measured in the stress runs (B18).
158    fn default() -> Self {
159        Self {
160            assignments: crate::dispatch::ASSIGNMENTS_PER_ROUND,
161            expiries: crate::dispatch::EXPIRIES_PER_ROUND,
162            waiting_reasons: crate::dispatch::REASONS_PER_ROUND,
163            pending_reasons: crate::dispatch::PENDING_PER_ROUND,
164            commands: crate::commands::COMMANDS_PER_ROUND,
165            scheduled_runs: crate::scheduler::SCHEDULED_PER_ROUND,
166            started_instances: crate::execution::INSTANCES_PER_ROUND,
167            retries: crate::execution::RETRIES_PER_ROUND,
168            planning_pass_runs: crate::planning::MAX_RUNS_PER_PASS,
169            run_of_runs: crate::core::triggers::RUNS_OF_A_PASS,
170        }
171    }
172}
173
174/// How the master's loop and its parse jobs are paced.
175#[derive(Debug, Clone, Copy, PartialEq, Eq)]
176pub struct MasterTimings {
177    /// The wait before a failed trigger starts again; it doubles with each failure in a row.
178    pub trigger_restart_backoff: Duration,
179    /// The most it waits.
180    pub trigger_restart_backoff_max: Duration,
181    /// At most one extra round every this long (`round_gap`).
182    pub round_gap: Duration,
183    /// How long until failed notifications are tried again (`notification_retry`).
184    pub notification_retry: Duration,
185    /// How often its loop turns at least while it waits (`alive_interval`).
186    pub alive: Duration,
187    /// How often its gauges are read (`gauge_refresh`).
188    pub gauge_refresh: Duration,
189    /// The first wait before a failed parse job is tried again (`parse_retry_first`).
190    pub parse_retry_first: Duration,
191    /// The longest one (`parse_retry_max`).
192    pub parse_retry_max: Duration,
193    /// How long its listener waits after a failed accept (`accept_retry`).
194    pub accept_retry: Duration,
195}
196
197impl Default for MasterTimings {
198    /// What every master runs with.
199    fn default() -> Self {
200        Self {
201            round_gap: crate::service::ROUND_GAP,
202            notification_retry: crate::service::NOTIFICATION_RETRY,
203            alive: crate::service::ALIVE_INTERVAL,
204            gauge_refresh: crate::metrics::GAUGE_REFRESH,
205            parse_retry_first: crate::parse_jobs::FIRST_RETRY_DELAY,
206            parse_retry_max: crate::parse_jobs::MAX_RETRY_DELAY,
207            accept_retry: Duration::from_millis(100),
208            trigger_restart_backoff: Duration::from_secs(5),
209            trigger_restart_backoff_max: Duration::from_mins(5),
210        }
211    }
212}
213
214/// A turn's `Started`s and `Finished`s, each kind in its order (M4B.3): stored together by
215/// [`MasterCore::handle_group`].
216#[derive(Debug, Default)]
217pub struct Group {
218    /// Its `Started`s, stored first.
219    pub started: Vec<pb::Started>,
220    /// Its `Finished`s, after them.
221    pub finished: Vec<pb::Finished>,
222}
223
224impl Group {
225    /// Whether it holds nothing.
226    #[must_use]
227    pub fn is_empty(&self) -> bool {
228        self.started.is_empty() && self.finished.is_empty()
229    }
230
231    /// Its messages, `Started`s first, to be handled one by one.
232    #[must_use]
233    pub fn into_messages(self) -> Vec<worker_message::Message> {
234        self.started
235            .into_iter()
236            .map(worker_message::Message::Started)
237            .chain(
238                self.finished
239                    .into_iter()
240                    .map(worker_message::Message::Finished),
241            )
242            .collect()
243    }
244
245    fn attempt_ids(&self) -> impl Iterator<Item = &str> {
246        self.started
247            .iter()
248            .map(|s| s.attempt_id.as_str())
249            .chain(self.finished.iter().map(|f| f.attempt_id.as_str()))
250    }
251}
252
253impl Default for Settings {
254    /// Heartbeat every 10 s, lost after 60 s, 30 s cancel grace, 10 min per parse job, 10 min
255    /// for missing code, messages up to 64 MiB.
256    fn default() -> Self {
257        Self {
258            heartbeat_interval: Duration::from_secs(10),
259            lease_timeout: Duration::from_secs(60),
260            takeover_wait: crate::lease::DEFAULT_LEASE_PERIOD
261                .saturating_sub(schedr_db::database::DEFAULT_QUERY_TIMEOUT),
262            cancel_grace: DEFAULT_CANCEL_GRACE,
263            switch_off_after: 3,
264            max_queued_events: 1000,
265            failing_after: 5,
266            sensor_max_wait: Duration::from_hours(24),
267            parse_job_timeout: PARSE_JOB_TIMEOUT,
268            code_wait: DEFAULT_CODE_WAIT,
269            set_aside: crate::dispatch::DEFAULT_SET_ASIDE,
270            handed_call_min: crate::dispatch::DEFAULT_HANDED_CALL_MIN,
271            cleanup_move_wait: Duration::from_secs(10),
272            script_root_grace: DEFAULT_SCRIPT_ROOT_GRACE,
273            event_lookback: Duration::from_mins(1),
274            read_back: crate::dispatch::ReadBack::default(),
275            listen_retry: Duration::from_mins(30),
276            timings: MasterTimings::default(),
277            quiet: QuietSettings::default(),
278            max_message_size: crate::service::DEFAULT_MAX_MESSAGE_SIZE,
279            messages_per_turn: crate::service::MESSAGES_PER_TURN,
280            max_instances: crate::execution::DEFAULT_MAX_INSTANCES,
281            backfill_max_runs: crate::scheduler::backfill::DEFAULT_MAX_RUNS,
282            worker_report: ReportLimits::default(),
283            retention: crate::retention::RetentionSettings::default(),
284            samples: crate::samples::SampleSettings::default(),
285            with_webserver: false,
286            rounds: RoundLimits::default(),
287            for_future_tolerance: crate::planning::FOR_TOLERANCE.unsigned_abs(),
288            code_retry_delay: crate::dispatch::CODE_RETRY_DELAY.unsigned_abs(),
289            failed_group_messages_per_turn: crate::service::ALONE_PER_TURN,
290            worker_stream_buffer: crate::service::STREAM_BUFFER,
291        }
292    }
293}
294
295/// How much of what a worker reports for people (wait step hosts, warnings) the master keeps
296/// (B183): an honest agent sends a few short records; more are dropped, longer texts cut.
297#[derive(Debug, Clone, Copy, PartialEq, Eq)]
298pub struct ReportLimits {
299    /// The most records of one kind.
300    pub records: usize,
301    /// The most characters of each text.
302    pub text: usize,
303}
304
305impl Default for ReportLimits {
306    /// 256 records, 4096 characters (`SCHEDR_HIDDEN__MASTER__WORKER_REPORT_*`).
307    fn default() -> Self {
308        Self {
309            records: 256,
310            text: 4096,
311        }
312    }
313}
314
315impl ReportLimits {
316    /// Why a registration is over the limits, if it is (B183): what it says is kept and matched
317    /// on (its ID, queues), so it is refused rather than cut. Its configuration, shown only,
318    /// may be up to as many texts as records.
319    fn oversized(self, register: &pb::Register) -> Option<String> {
320        let long = |text: &str| text.chars().count() > self.text;
321        let texts = [
322            ("worker ID", register.worker_id.as_str()),
323            ("incarnation", &register.incarnation_id),
324            ("schedr version", &register.schedr_version),
325            ("log endpoint", &register.log_endpoint),
326            ("process ID", &register.process_id),
327        ];
328        if let Some((what, _)) = texts.iter().find(|(_, text)| long(text)) {
329            return Some(format!("its {what} is over {} characters", self.text));
330        }
331        for (what, list) in [
332            ("queues", &register.queues),
333            ("secret storages", &register.secret_storages),
334        ] {
335            if list.len() > self.records {
336                return Some(format!("it has over {} {what}", self.records));
337            }
338            if list.iter().any(|text| long(text)) {
339                return Some(format!(
340                    "one of its {what} is over {} characters",
341                    self.text
342                ));
343            }
344        }
345        let config_limit = self.text.saturating_mul(self.records);
346        (register.config_json.len() > config_limit)
347            .then(|| format!("its configuration is over {config_limit} bytes"))
348    }
349
350    /// `text` cut to the limit, at a character.
351    fn cut(self, text: String) -> String {
352        match text.char_indices().nth(self.text) {
353            Some((end, _)) => text[..end].to_owned(),
354            None => text,
355        }
356    }
357
358    /// `records` within the limit, saying in the log when some were dropped.
359    fn take<T>(self, worker_id: &str, what: &str, mut records: Vec<T>) -> Vec<T> {
360        if records.len() > self.records {
361            tracing::warn!(
362                worker_id,
363                sent = records.len(),
364                kept = self.records,
365                "worker sent more {what} than the master keeps: the rest are dropped"
366            );
367            records.truncate(self.records);
368        }
369        records
370    }
371}
372
373/// Why the master refused or failed something.
374#[derive(Debug, thiserror::Error)]
375pub enum CoreError {
376    /// A registration is refused (the worker is told why and the stream ends).
377    #[error("registration refused: {0}")]
378    Refused(String),
379    /// A message can't be understood.
380    #[error("message from worker `{worker_id}`: {reason}")]
381    BadMessage {
382        /// The worker.
383        worker_id: String,
384        /// What is wrong.
385        reason: String,
386    },
387    /// The database failed.
388    #[error(transparent)]
389    Db(#[from] DbError),
390    /// Dispatching failed.
391    #[error(transparent)]
392    Dispatch(#[from] DispatchError),
393    /// Applying commands failed.
394    #[error(transparent)]
395    Command(#[from] CommandError),
396    /// The scheduler failed.
397    #[error(transparent)]
398    Scheduler(#[from] SchedulerError),
399}
400
401impl CoreError {
402    /// Whether the database refused the data a message would store (see
403    /// [`DbError::is_data_fault`]): sent again, it is refused again.
404    #[must_use]
405    pub fn is_data_fault(&self) -> bool {
406        match self {
407            Self::Db(error)
408            | Self::Dispatch(
409                DispatchError::Db(error) | DispatchError::Execution(ExecutionError::Db(error)),
410            ) => error.is_data_fault(),
411            _ => false,
412        }
413    }
414}
415
416/// Whether a `TaskEnded` cut off at its commit stored what it was for: the result kept, or the
417/// attempt over (nothing to keep it for).
418fn result_landed(attempt: Option<&schedr_db::attempts::StoredAttempt>) -> bool {
419    attempt.is_none_or(|a| a.result_kept || a.status.is_some())
420}
421
422/// A `Finished` whose result the database refused, as the attempt's failure: kind
423/// `result_not_stored` (not retried: the same result would be refused again), what ran kept.
424fn not_stored(finished: &pb::Finished, error: &CoreError) -> pb::Finished {
425    pb::Finished {
426        attempt_id: finished.attempt_id.clone(),
427        status: pb::AttemptStatus::Failed.into(),
428        exit_code: finished.exit_code,
429        signal: finished.signal,
430        output_json: Vec::new(),
431        outcome: String::new(),
432        duration_ms: finished.duration_ms,
433        peak_memory_bytes: finished.peak_memory_bytes,
434        error_kind: "result_not_stored".to_owned(),
435        error_summary_json: ErrorSummary::json(
436            "ResultNotStored",
437            &format!("the result couldn't be stored: {error}"),
438        )
439        .into_bytes(),
440        // The worker's text, kept, must not be refused again (B127): Postgres stores no NUL.
441        code_hash: finished.code_hash.replace('\0', "\u{fffd}"),
442        usage: finished.usage,
443        core_dumped: finished.core_dumped,
444        cleanup: finished.cleanup.clone(),
445        wait_step: finished.wait_step,
446        struck: finished.struck,
447    }
448}
449
450/// A connected (or recently disconnected) worker.
451#[derive(Debug, Clone, PartialEq, Eq)]
452struct Connection {
453    incarnation: String,
454    schedr_version: String,
455    /// When it was last heard from, in master time (B228; see [`crate::clock`]): its lease
456    /// counts from it.
457    heard: Timestamp,
458    /// When its last sign of life was last written to the registry (at most once per heartbeat
459    /// interval).
460    persisted: Timestamp,
461    live: bool,
462    /// The secret storages it has configured (`Register`): a DAG it parses that names another
463    /// is refused. None until it registers with this master (restored from the database).
464    secret_storages: Option<BTreeSet<String>>,
465    /// What its wait step hosts looked like when last written to the registry.
466    watcher_hosts: Vec<pb::WatcherHost>,
467    /// When what it uses was last written to the registry (decision 463).
468    usage_at: Option<Timestamp>,
469}
470
471/// What has arrived from workers before the master handled it (cheap to clone; clones share
472/// it). A stream's reader records each message as it is read, before the message waits for the
473/// master's lock, so a busy master doesn't count its own delay against workers:
474/// - when each worker's latest message arrived: the lease counts from it, so a master stuck in
475///   a slow write doesn't declare workers lost whose messages keep arriving (B6);
476/// - which attempts' `Started` (or `Finished`) arrived and wait to be handled: they aren't
477///   taken back as never started (B11);
478/// - on each worker's current stream, which number each assignment went out with, and the
479///   latest of the master's messages a message from it said it had handled (B240): an
480///   assignment it had handled without a `Started` before never started there.
481#[derive(Debug, Clone, Default)]
482pub struct Arrivals(Arc<std::sync::Mutex<Arrived>>);
483
484#[derive(Debug, Default)]
485struct Arrived {
486    last: BTreeMap<String, Timestamp>,
487    /// Attempts whose start arrived and waits to be handled, with their worker.
488    started: BTreeMap<String, String>,
489    /// Each worker's current stream, as numbered (B240).
490    streams: BTreeMap<String, StreamRead>,
491    /// The last stream's ID handed out.
492    last_stream: u64,
493    /// Assignments the master never sent (no stream, or one full or closed), with the worker
494    /// they were for: surely never started there (Grok's review of B240).
495    unsent: BTreeMap<String, String>,
496}
497
498/// What is known of a worker's current stream's numbering (B240).
499#[derive(Debug, Default)]
500struct StreamRead {
501    id: u64,
502    /// The highest `MasterClock.sequence` a message from the worker said it had handled.
503    read: u64,
504    /// The number each assignment sent on it went out with, until it is heard starting or
505    /// refusing it, or the stream is replaced. (One the master expires stays: few, gone with
506    /// the stream.)
507    assigned: BTreeMap<String, u64>,
508}
509
510impl Arrivals {
511    fn inner(&self) -> std::sync::MutexGuard<'_, Arrived> {
512        self.0
513            .lock()
514            .unwrap_or_else(std::sync::PoisonError::into_inner)
515    }
516
517    /// A message from `worker_id` arrived `at`.
518    pub fn arrived(&self, worker_id: &str, at: Timestamp) {
519        let mut inner = self.inner();
520        let last = inner.last.entry(worker_id.to_owned()).or_insert(at);
521        *last = (*last).max(at);
522    }
523
524    /// When the latest message from `worker_id` arrived, if one has since it was forgotten.
525    #[must_use]
526    pub fn last(&self, worker_id: &str) -> Option<Timestamp> {
527        self.inner().last.get(worker_id).copied()
528    }
529
530    /// Forgets `worker_id` (it is gone), and the starts of its that wait: their messages won't
531    /// be handled any more.
532    pub fn forget(&self, worker_id: &str) {
533        let mut inner = self.inner();
534        inner.last.remove(worker_id);
535        inner.started.retain(|_, worker| worker != worker_id);
536        inner.streams.remove(worker_id);
537        inner.unsent.retain(|_, worker| worker != worker_id);
538    }
539
540    /// `worker_id` has a new stream (it registered): its ID; what was known of its earlier
541    /// stream's numbering is forgotten (B240), and its unsent assignments: its registration,
542    /// just before, has taken back or kept each (so the map doesn't grow on a long-lived worker).
543    #[must_use]
544    pub fn new_stream(&self, worker_id: &str) -> u64 {
545        let mut inner = self.inner();
546        inner.unsent.retain(|_, worker| worker != worker_id);
547        inner.last_stream += 1;
548        let id = inner.last_stream;
549        inner.streams.insert(
550            worker_id.to_owned(),
551            StreamRead {
552                id,
553                ..StreamRead::default()
554            },
555        );
556        id
557    }
558
559    /// `attempt_id`'s assignment went out as message `number` of `worker_id`'s stream `stream`.
560    pub fn assigned(&self, worker_id: &str, stream: u64, attempt_id: &str, number: u64) {
561        let mut inner = self.inner();
562        inner.unsent.remove(attempt_id);
563        if let Some(read) = inner.streams.get_mut(worker_id)
564            && read.id == stream
565        {
566            read.assigned.insert(attempt_id.to_owned(), number);
567        }
568    }
569
570    /// `attempt_id`'s assignment to `worker_id` was never sent: no stream to it, or one full
571    /// or closed (Grok's review of B240). It never started there.
572    pub fn unsent(&self, worker_id: &str, attempt_id: &str) {
573        self.inner()
574            .unsent
575            .insert(attempt_id.to_owned(), worker_id.to_owned());
576    }
577
578    /// A message of `worker_id`'s stream `stream` said it had handled the master's messages up
579    /// to `number`.
580    pub fn read(&self, worker_id: &str, stream: u64, number: u64) {
581        if let Some(read) = self.inner().streams.get_mut(worker_id)
582            && read.id == stream
583        {
584            read.read = read.read.max(number);
585        }
586    }
587
588    /// `worker_id` started or refused `attempt_id`, as heard: its assignment's number isn't
589    /// needed any more.
590    pub fn answered(&self, worker_id: &str, attempt_id: &str) {
591        if let Some(read) = self.inner().streams.get_mut(worker_id) {
592            read.assigned.remove(attempt_id);
593        }
594    }
595
596    /// Whether `worker_id` surely never started `attempt_id`: a message from it said it had
597    /// handled the assignment's message, and no start of it has arrived. What a worker sends
598    /// while handling an assignment (`Started`, `Rejected`) is queued before anything naming
599    /// it, so a start would have arrived first (B240). Not known (another stream, a message
600    /// not heard, an older worker): `false`, it may run there.
601    #[must_use]
602    pub fn never_started(&self, worker_id: &str, attempt_id: &str) -> bool {
603        let inner = self.inner();
604        !inner.started.contains_key(attempt_id)
605            && (inner.unsent.get(attempt_id).is_some_and(|w| w == worker_id)
606                || inner.streams.get(worker_id).is_some_and(|read| {
607                    read.assigned
608                        .get(attempt_id)
609                        .is_some_and(|number| *number <= read.read)
610                }))
611    }
612
613    /// A `Started` or `Finished` for `attempt_id` arrived from `worker_id`: the attempt started.
614    pub fn start_arrived(&self, worker_id: &str, attempt_id: &str) {
615        let _ = self.start_known(worker_id, attempt_id);
616    }
617
618    /// As [`Self::start_arrived`]; returns whether the start wasn't known already.
619    #[must_use]
620    pub fn start_known(&self, worker_id: &str, attempt_id: &str) -> bool {
621        self.inner()
622            .started
623            .insert(attempt_id.to_owned(), worker_id.to_owned())
624            .is_none()
625    }
626
627    /// Whether a `Started` or `Finished` for `attempt_id` arrived and isn't handled yet.
628    #[must_use]
629    pub fn start_waiting(&self, attempt_id: &str) -> bool {
630        self.inner().started.contains_key(attempt_id)
631    }
632
633    /// How many `Started` or `Finished` messages arrived and aren't handled yet.
634    #[must_use]
635    pub fn starts_waiting(&self) -> usize {
636        self.inner().started.len()
637    }
638
639    /// Forgets the starts of `worker_id`'s that wait: it registered, and its journal is what
640    /// stands now.
641    pub fn forget_starts(&self, worker_id: &str) {
642        self.inner().started.retain(|_, worker| worker != worker_id);
643    }
644
645    /// The message about `attempt_id`'s start was handled (or failed to be).
646    pub fn start_handled(&self, attempt_id: &str) {
647        self.inner().started.remove(attempt_id);
648    }
649}
650
651/// A part of a round, in the order a round runs them (`master_round_part_seconds`). The service
652/// takes the core's lock for each on its own (decision 469).
653#[derive(Debug, Clone, Copy, PartialEq, Eq)]
654pub enum RoundPart {
655    /// Commands applied, and their follow-ups (drains, resumes).
656    Commands,
657    /// The scheduler's pass: runs created.
658    Scheduler,
659    /// Triggers given, moved or stopped.
660    Triggers,
661    /// Runs prepared, due retries queued.
662    Prepare,
663    /// Assignments expired, replaced incarnations' attempts ended.
664    Expire,
665    /// Cleanups, chained runs and assignments.
666    Assign,
667    /// Parse jobs past their time given again, lost workers forgotten.
668    Rest,
669}
670
671impl RoundPart {
672    /// Every part, in a round's order.
673    pub const ALL: [Self; 7] = [
674        Self::Commands,
675        Self::Scheduler,
676        Self::Triggers,
677        Self::Prepare,
678        Self::Expire,
679        Self::Assign,
680        Self::Rest,
681    ];
682
683    /// Its `part` label.
684    #[must_use]
685    pub const fn name(self) -> &'static str {
686        match self {
687            Self::Commands => "commands",
688            Self::Scheduler => "scheduler",
689            Self::Triggers => "triggers",
690            Self::Prepare => "prepare",
691            Self::Expire => "expire",
692            Self::Assign => "assign",
693            Self::Rest => "rest",
694        }
695    }
696}
697
698/// The master's state between messages.
699#[derive(Debug)]
700pub struct MasterCore {
701    db: Database,
702    /// Boxed: kept off the core's futures, which are large already.
703    settings: Box<Settings>,
704    discovery: Discovery,
705    dispatcher: Dispatcher,
706    scheduler: Scheduler,
707    commander: Commander,
708    connections: BTreeMap<String, Connection>,
709    arrivals: Arrivals,
710    metrics: MasterMetrics,
711    /// Workers resumed whose follow-up (their parse jobs) failed: tried again each round, as
712    /// the resume command isn't applied again (B99).
713    unresumed: BTreeSet<String>,
714    /// The script roots each DAG root uses as last sent to the live workers (decision 304); a
715    /// change goes to them all at the next tick (a worker registering gets them in
716    /// `Registered`).
717    sent_uses: crate::discovery::ScriptUses,
718    /// When an alive worker last reported each script root, and when this master started
719    /// looking (decision 303's grace).
720    script_roots_seen: (BTreeMap<String, Timestamp>, Option<Timestamp>),
721    /// The connection jobs sent and not answered, by job ID, with their worker (lost with
722    /// it) and when they are given up on (`schedr connections check` / `test`).
723    connection_jobs: BTreeMap<String, (String, Timestamp)>,
724    /// Triggers told to stop and not heard of since, by instance, with their worker and DAG: each
725    /// keeps its watcher slot, as the worker's own count does, and what it ends with still counts
726    /// (a strike for getting its host killed on the way).
727    stopping_triggers: BTreeMap<String, (String, String)>,
728    /// The API tasks call through their agents (M4.11h); none: they are refused.
729    task_api: Option<Arc<dyn task_api::TaskApi>>,
730    /// `[notifications]`.
731    notifications: Arc<crate::notifications::Notifications>,
732    /// Master time, which its liveness decisions read (B228; see [`crate::clock`]).
733    steady: crate::clock::Steady,
734}
735
736impl MasterCore {
737    /// The master over `db`, with no workers yet.
738    #[must_use]
739    pub fn new(db: Database, settings: Settings) -> Self {
740        let arrivals = Arrivals::default();
741        // What changes runs or DAGs marks them, so the scheduler wakes them if quiet.
742        let wakes = Wakes::default();
743        let mut discovery = Discovery::new(
744            db.clone(),
745            SchedrVersion::current(),
746            ParseJobs::new(settings.parse_job_timeout).with_retry(
747                settings.timings.parse_retry_first,
748                settings.timings.parse_retry_max,
749            ),
750        )
751        .with_max_message_size(settings.max_message_size);
752        discovery.set_wakes(wakes.clone());
753        let mut dispatcher = Dispatcher::new(db.clone(), settings.cancel_grace)
754            .with_switch_off_after(settings.switch_off_after)
755            .with_sensor_max_wait(settings.sensor_max_wait)
756            .with_max_message_size(settings.max_message_size)
757            .with_code_wait(settings.code_wait)
758            .with_set_aside(settings.set_aside, settings.read_back)
759            .with_handed_call_min(settings.handed_call_min)
760            .with_cleanup_move_wait(
761                settings
762                    .cancel_grace
763                    .saturating_add(settings.cleanup_move_wait),
764            )
765            .with_lease(settings.lease_timeout)
766            .with_event_lookback(settings.event_lookback)
767            .with_code_retry_delay(settings.code_retry_delay)
768            .with_arrivals(arrivals.clone());
769        dispatcher.set_wakes(wakes.clone());
770        dispatcher.set_max_instances(settings.max_instances);
771        dispatcher.set_rounds(settings.rounds);
772        let scheduler = Scheduler::with_quiet(db.clone(), settings.quiet, wakes)
773            .with_limits(&settings.rounds, settings.for_future_tolerance);
774        dispatcher.set_scheduler(scheduler.clone());
775        Self {
776            discovery,
777            dispatcher,
778            scheduler,
779            commander: Commander::new(db.clone())
780                .with_backfill_max_runs(settings.backfill_max_runs)
781                .with_commands_per_round(settings.rounds.commands),
782            connections: BTreeMap::new(),
783            arrivals,
784            metrics: MasterMetrics::default(),
785            unresumed: BTreeSet::new(),
786            sent_uses: crate::discovery::ScriptUses::new(),
787            script_roots_seen: (BTreeMap::new(), None),
788            connection_jobs: BTreeMap::new(),
789            stopping_triggers: BTreeMap::new(),
790            task_api: None,
791            notifications: Arc::default(),
792            steady: crate::clock::as_given,
793            settings: Box::new(settings),
794            db,
795        }
796        // One set shared by every part, replaced by the caller's to register them.
797        .with_metrics(MasterMetrics::default())
798    }
799
800    /// The master deciding liveness on `steady` (production: [`crate::clock::monotonic`], set
801    /// by [`crate::service::Hub::new`]; tests: the times they pass).
802    #[must_use]
803    pub fn with_steady(mut self, steady: crate::clock::Steady) -> Self {
804        self.steady = steady;
805        self.dispatcher.set_steady(steady);
806        self.discovery.jobs_mut().set_steady(steady);
807        self
808    }
809
810    /// The wall clock read with master time where the two are compared (M5.1m; production:
811    /// [`Timestamp::now`], set by [`crate::service::Hub::new`]; tests: the times they pass).
812    #[must_use]
813    pub fn with_wall(mut self, wall: fn() -> Timestamp) -> Self {
814        self.dispatcher.set_wall(wall);
815        self
816    }
817
818    /// Switches one of its liveness safeguards off (the clock simulator's mutation tests,
819    /// decision 446). Never in a master.
820    #[doc(hidden)]
821    pub fn weaken(&mut self, safeguard: crate::dispatch::Weakened) {
822        self.dispatcher.weaken(safeguard);
823    }
824
825    /// How it reads master time (see [`crate::clock`]).
826    #[must_use]
827    pub const fn steady_clock(&self) -> crate::clock::Steady {
828        self.steady
829    }
830
831    /// The master sending notifications as `notifications` says (`[notifications]`): what
832    /// runs, tasks and triggers queue, and the checks on DAGs' `notify=`.
833    #[must_use]
834    pub fn with_notifications(
835        mut self,
836        notifications: Arc<crate::notifications::Notifications>,
837    ) -> Self {
838        self.dispatcher.set_notifications(notifications.clone());
839        self.discovery.set_notifications(notifications.clone());
840        self.notifications = notifications;
841        self
842    }
843
844    /// The master serving tasks' REST requests through `api` (M4.11h).
845    #[must_use]
846    pub fn with_task_api(mut self, api: Arc<dyn task_api::TaskApi>) -> Self {
847        self.task_api = Some(api);
848        self
849    }
850
851    /// The master recording its metrics in `metrics` (registered by the caller).
852    #[must_use]
853    pub fn with_metrics(mut self, metrics: MasterMetrics) -> Self {
854        self.dispatcher.set_metrics(metrics.clone());
855        self.discovery.set_metrics(metrics.clone());
856        self.commander.set_metrics(metrics.clone());
857        self.scheduler.set_metrics(metrics.clone());
858        self.metrics = metrics;
859        self
860    }
861
862    /// Its metrics.
863    #[must_use]
864    pub const fn metrics(&self) -> &MasterMetrics {
865        &self.metrics
866    }
867
868    /// Its database.
869    #[must_use]
870    pub const fn db(&self) -> &Database {
871        &self.db
872    }
873
874    /// The master's timing.
875    #[must_use]
876    pub fn settings(&self) -> Settings {
877        *self.settings
878    }
879
880    /// The dispatcher (its workers, for status and tests).
881    #[must_use]
882    pub const fn dispatcher(&self) -> &Dispatcher {
883        &self.dispatcher
884    }
885
886    /// When each worker's latest message arrived, for the streams' readers to record.
887    #[must_use]
888    pub fn arrivals(&self) -> Arrivals {
889        self.arrivals.clone()
890    }
891
892    /// Reads the worker registry back at start: every worker not gone counts as disconnected
893    /// from `now` plus [`Settings::takeover_wait`], so its lease starts from zero once a
894    /// deposed leader can no longer answer it (decision 444; master downtime doesn't count
895    /// against workers) and one that never comes back is lost, its attempts with it. Returns
896    /// how many workers were restored.
897    ///
898    /// # Errors
899    ///
900    /// [`CoreError::Db`] if the database fails.
901    pub async fn restore(&mut self, now: Timestamp) -> Result<usize, CoreError> {
902        let mut restored = 0;
903        let takeover =
904            SignedDuration::try_from(self.settings.takeover_wait).unwrap_or(SignedDuration::MAX);
905        let heard = (self.steady)(now)
906            .checked_add(takeover)
907            .unwrap_or(Timestamp::MAX);
908        for worker in self.db.workers().await? {
909            if worker.state.is_gone() {
910                continue;
911            }
912            self.db
913                .set_worker_state(&worker.id, WorkerState::Disconnected, now)
914                .await?;
915            self.dispatcher.worker_away(&worker.id);
916            self.connections.insert(
917                worker.id,
918                Connection {
919                    incarnation: worker.incarnation,
920                    schedr_version: worker.schedr_version,
921                    heard,
922                    persisted: now,
923                    live: false,
924                    secret_storages: None,
925                    watcher_hosts: Vec::new(),
926                    usage_at: None,
927                },
928            );
929            restored += 1;
930        }
931        // The jobs a previous master sent: their answers would come to it.
932        self.db
933            .connections_commands_lost("the master restarted before the answer came")
934            .await?;
935        Ok(restored)
936    }
937
938    /// Whether a worker has a live stream.
939    #[must_use]
940    pub fn is_live(&self, worker_id: &str) -> bool {
941        self.connections.get(worker_id).is_some_and(|c| c.live)
942    }
943
944    /// A worker registers (the first message on its stream). Returns `Registered`, with a
945    /// decision per journal entry, and the parse jobs for its roots.
946    ///
947    /// # Errors
948    ///
949    /// [`CoreError::Refused`] for an incompatible protocol version or a worker ID that already
950    /// has a live stream; [`CoreError::Db`] / [`CoreError::Dispatch`] if the database fails.
951    pub async fn register(
952        &mut self,
953        register: &pb::Register,
954        now: Timestamp,
955    ) -> Result<(pb::Registered, Vec<Outgoing>), CoreError> {
956        check_worker_version(PROTOCOL_VERSION, register.protocol)
957            .map_err(|e| CoreError::Refused(e.to_string()))?;
958        let worker_id = register.worker_id.as_str();
959        if worker_id.is_empty() {
960            return Err(CoreError::Refused(
961                "the worker sent no worker ID".to_owned(),
962            ));
963        }
964        if let Some(why) = self.settings.worker_report.oversized(register) {
965            return Err(CoreError::Refused(why));
966        }
967        if self.is_live(worker_id) {
968            return Err(CoreError::Refused(format!(
969                "worker `{worker_id}` already has a live stream"
970            )));
971        }
972        let accepted = match self.accept(register, now).await {
973            Ok((registered, mut outgoing)) => {
974                let triggers = self
975                    .triggers_on_register(worker_id, &register.running_triggers, now)
976                    .await;
977                triggers.map(|triggers| {
978                    outgoing.extend(triggers);
979                    (registered, outgoing)
980                })
981            }
982            Err(error) => Err(error),
983        };
984        if accepted.is_err()
985            && let Some(connection) = self.connections.get_mut(worker_id)
986        {
987            // A registration that failed half-way (the database) leaves no live stream behind:
988            // the worker's next attempt is accepted, or its lease runs out.
989            connection.live = false;
990        }
991        accepted
992    }
993
994    /// Records the registering worker's node for the Deployments page: this master (the lease's
995    /// holder it writes as), the worker's process and its configuration, masked again here
996    /// (it came from the worker; one that isn't JSON isn't kept).
997    async fn record_node(&self, register: &pb::Register) -> Result<(), CoreError> {
998        let config = if register.config_json.is_empty() {
999            None
1000        } else {
1001            match serde_json::from_str::<serde_json::Value>(&register.config_json) {
1002                Ok(mut config) => {
1003                    schedr_config::masked::mask(&mut config);
1004                    Some(config)
1005                }
1006                Err(error) => {
1007                    tracing::warn!(
1008                        worker_id = register.worker_id,
1009                        %error,
1010                        "the worker's configuration isn't JSON; not shown"
1011                    );
1012                    None
1013                }
1014            }
1015        };
1016        let process_id = Some(register.process_id.as_str()).filter(|id| !id.is_empty());
1017        self.db
1018            .set_worker_node(
1019                &register.worker_id,
1020                self.db.fenced_as(),
1021                process_id,
1022                config.as_ref(),
1023            )
1024            .await?;
1025        Ok(())
1026    }
1027
1028    /// A worker came back as a new incarnation: its unreported attempts end lost once the old
1029    /// one's lease is over (decision 443); its jobs are lost now.
1030    async fn incarnation_replaced(
1031        &mut self,
1032        register: &pb::Register,
1033        now: Timestamp,
1034    ) -> Result<(), CoreError> {
1035        let worker_id = register.worker_id.as_str();
1036        let reported = register
1037            .journal
1038            .iter()
1039            .map(|entry| entry.attempt_id.as_str())
1040            .collect();
1041        let ended = self
1042            .dispatcher
1043            .incarnation_replaced(worker_id, &reported, now)
1044            .await?;
1045        tracing::warn!(
1046            worker_id,
1047            unreported = ended,
1048            "worker restarted (a new incarnation): the attempts it doesn't report end lost once \
1049             the old one's lease is over (possibly out of memory)"
1050        );
1051        // The old incarnation's jobs: none will answer.
1052        self.connection_jobs_lost(
1053            worker_id,
1054            &format!("worker `{worker_id}` restarted before answering"),
1055        )
1056        .await
1057    }
1058
1059    /// What a registering worker left open here from before: a replaced incarnation's, or the
1060    /// same process's (or one with nothing open here), whose journal decides what it never
1061    /// started (B240).
1062    async fn reconcile(
1063        &mut self,
1064        register: &pb::Register,
1065        now: Timestamp,
1066    ) -> Result<(), CoreError> {
1067        let worker_id = register.worker_id.as_str();
1068        let replaced = self
1069            .connections
1070            .get(worker_id)
1071            .is_some_and(|known| known.incarnation != register.incarnation_id);
1072        if replaced {
1073            return self.incarnation_replaced(register, now).await;
1074        }
1075        let reported = register
1076            .journal
1077            .iter()
1078            .map(|entry| entry.attempt_id.as_str())
1079            .collect();
1080        self.dispatcher
1081            .unreported_unstarted(worker_id, &reported, now)
1082            .await?;
1083        Ok(())
1084    }
1085
1086    /// Accepts a registration that passed the checks: reconciles a replaced incarnation,
1087    /// records the worker, and decides on its journal.
1088    async fn accept(
1089        &mut self,
1090        register: &pb::Register,
1091        now: Timestamp,
1092    ) -> Result<(pb::Registered, Vec<Outgoing>), CoreError> {
1093        let worker_id = register.worker_id.as_str();
1094        self.reconcile(register, now).await?;
1095        self.connections.insert(
1096            worker_id.to_owned(),
1097            Connection {
1098                incarnation: register.incarnation_id.clone(),
1099                schedr_version: register.schedr_version.clone(),
1100                heard: (self.steady)(now),
1101                persisted: now,
1102                live: true,
1103                secret_storages: Some(register.secret_storages.iter().cloned().collect()),
1104                watcher_hosts: Vec::new(),
1105                usage_at: None,
1106            },
1107        );
1108        let protocol = register
1109            .protocol
1110            .as_ref()
1111            .map(|p| format!("{}.{}", p.major, p.minor))
1112            .unwrap_or_default();
1113        // The queues it serves, as stored and shown: none configured is `default`.
1114        let queues = if register.queues.is_empty() {
1115            vec![crate::workers::DEFAULT_QUEUE.to_owned()]
1116        } else {
1117            register.queues.clone()
1118        };
1119        self.db
1120            .register_worker(
1121                &WorkerRegistration {
1122                    id: worker_id,
1123                    incarnation: &register.incarnation_id,
1124                    protocol_version: &protocol,
1125                    schedr_version: &register.schedr_version,
1126                    queues: &queues,
1127                    slots: register.slots,
1128                    watcher_slots: register.watcher_slots,
1129                    log_endpoint: &register.log_endpoint,
1130                },
1131                now,
1132            )
1133            .await?;
1134        self.record_node(register).await?;
1135        self.dispatcher
1136            .register(
1137                worker_id,
1138                &register.incarnation_id,
1139                &register.queues,
1140                register.slots,
1141                now,
1142            )
1143            .await?;
1144        self.dispatcher
1145            .set_watcher_slots(worker_id, register.watcher_slots);
1146        // Failing, discovery's memory goes back as it was: the worker registers again with the
1147        // same reports, and a switch among them is seen again (B91).
1148        let memory = self.discovery.memory();
1149        let reported = self.report_roots(register, now).await;
1150        if reported.is_err() {
1151            self.discovery.restore(memory);
1152            self.sync_code();
1153        }
1154        let mut outgoing = reported?;
1155        let reported: Vec<String> = register
1156            .journal
1157            .iter()
1158            .map(|entry| entry.attempt_id.clone())
1159            .collect();
1160        self.dispatcher.reported(worker_id, &reported).await?;
1161        let mut decisions = Vec::with_capacity(register.journal.len());
1162        for entry in &register.journal {
1163            let (decision, cleanup_from, cancel) =
1164                self.journal_decision(worker_id, entry, now).await?;
1165            decisions.push(pb::JournalDecision {
1166                attempt_id: entry.attempt_id.clone(),
1167                decision: decision.into(),
1168                cleanup_from,
1169            });
1170            outgoing.extend(cancel);
1171        }
1172        let registered = pb::Registered {
1173            timing: Some(pb::Timing {
1174                heartbeat_interval_ms: millis(self.settings.heartbeat_interval),
1175                lease_timeout_ms: millis(self.settings.lease_timeout),
1176                cancel_grace_ms: millis(self.settings.cancel_grace),
1177            }),
1178            decisions,
1179            max_message_size: u64::try_from(self.settings.max_message_size).unwrap_or(u64::MAX),
1180            script_uses: root_uses(&self.script_uses_at(now)),
1181        };
1182        Ok((registered, outgoing))
1183    }
1184
1185    /// A worker is draining: its parsing moves to the others.
1186    async fn worker_draining(
1187        &mut self,
1188        worker_id: &str,
1189        now: Timestamp,
1190    ) -> Result<Vec<Outgoing>, CoreError> {
1191        self.dispatcher.draining(worker_id);
1192        self.db
1193            .set_worker_state(worker_id, WorkerState::Draining, now)
1194            .await?;
1195        let moved = self.discovery.stop_parsing(worker_id, now);
1196        Ok(moved.into_iter().map(assign_parse).collect())
1197    }
1198
1199    /// A task's process ended and its cleanup starts: the result is kept for a worker lost
1200    /// meanwhile (decision 229); `Finished` settles the attempt otherwise.
1201    async fn task_ended(
1202        &mut self,
1203        worker_id: &str,
1204        ended: pb::TaskEnded,
1205        now: Timestamp,
1206    ) -> Result<(), CoreError> {
1207        let Some(result) = ended.result else {
1208            return Ok(());
1209        };
1210        let (db, memory) = (self.db.clone(), self.dispatcher.memory());
1211        let id = result.attempt_id.as_str();
1212        let handled =
1213            Box::pin(db.atomically(self.dispatcher.task_ended(worker_id, &result, now))).await;
1214        self.settle(handled, memory, id, result_landed).await?;
1215        Ok(())
1216    }
1217
1218    /// Any message is a sign of life.
1219    async fn heard_from(&mut self, worker_id: &str, now: Timestamp) {
1220        let heartbeat = SignedDuration::try_from(self.settings.heartbeat_interval)
1221            .unwrap_or(SignedDuration::MAX);
1222        let steady = (self.steady)(now);
1223        if let Some(connection) = self.connections.get_mut(worker_id) {
1224            connection.heard = steady;
1225            if now.duration_since(connection.persisted) >= heartbeat {
1226                connection.persisted = now;
1227                // A sign of life in the registry is for people: a failed write mustn't cost
1228                // the message it came with (the next interval writes it again).
1229                // Housekeeping: nothing a trigger depends on (decision 486).
1230                if let Err(error) = self.db.quietly(self.db.worker_seen(worker_id, now)).await {
1231                    tracing::warn!(worker_id, %error, "worker's last heartbeat not recorded");
1232                }
1233            }
1234        }
1235    }
1236
1237    /// What a worker uses, by part (decision 463), written at most once every [`USAGE_EVERY`]:
1238    /// for people, a failed write logged (the next heartbeat writes it).
1239    async fn heard_of_usage(&mut self, worker_id: &str, usage: pb::WorkerUsage, now: Timestamp) {
1240        let Some(connection) = self.connections.get_mut(worker_id) else {
1241            return;
1242        };
1243        if connection
1244            .usage_at
1245            .is_some_and(|at| now.duration_since(at) < USAGE_EVERY)
1246        {
1247            return;
1248        }
1249        let Some(process) = usage.process else {
1250            return;
1251        };
1252        // Within the limits before anything keeps it (B183).
1253        let limits = self.settings.worker_report;
1254        let largest_tasks = limits
1255            .take(worker_id, "largest tasks", usage.largest_tasks)
1256            .into_iter()
1257            .map(|task| schedr_model::usage::TaskMemory {
1258                attempt_id: limits.cut(task.attempt_id),
1259                dag_id: limits.cut(task.dag_id),
1260                run_id: limits.cut(task.run_id),
1261                task_id: limits.cut(task.task_id),
1262                map_index: task.map_index,
1263                bytes: task.bytes,
1264            })
1265            .collect();
1266        let record = schedr_model::usage::WorkerUsage {
1267            process: schedr_model::usage::NodeUsage {
1268                resident_bytes: process.resident_bytes,
1269                // A worker's own figure: never a NaN or an infinity in the stored JSON.
1270                cpu_seconds: if process.cpu_seconds.is_finite() {
1271                    process.cpu_seconds.max(0.0)
1272                } else {
1273                    0.0
1274                },
1275                container_bytes: process.container_bytes,
1276                container_limit_bytes: process.container_limit_bytes,
1277            },
1278            fork_servers_bytes: usage.fork_servers_bytes,
1279            watcher_hosts_bytes: usage.watcher_hosts_bytes,
1280            tasks_bytes: usage.tasks_bytes,
1281            largest_tasks,
1282        };
1283        // Housekeeping: nothing a trigger depends on (decision 486).
1284        match self
1285            .db
1286            .quietly(self.db.set_worker_usage(worker_id, &record, now))
1287            .await
1288        {
1289            Ok(()) => connection.usage_at = Some(now),
1290            Err(error) => tracing::warn!(worker_id, %error, "what the worker uses not recorded"),
1291        }
1292    }
1293
1294    /// For people, like the last heartbeat: a failed write is logged, not the message's failure
1295    /// (the next heartbeat that differs from what was written writes it).
1296    async fn heard_of_hosts(&mut self, worker_id: &str, hosts: Vec<pb::WatcherHost>) {
1297        let Some(connection) = self.connections.get_mut(worker_id) else {
1298            return;
1299        };
1300        // Within the limits before anything keeps it: the database and this cache (B183).
1301        let limits = self.settings.worker_report;
1302        let hosts: Vec<pb::WatcherHost> = limits
1303            .take(worker_id, "wait step hosts", hosts)
1304            .into_iter()
1305            .map(|host| pb::WatcherHost {
1306                code: limits.cut(host.code),
1307                ..host
1308            })
1309            .collect();
1310        if connection.watcher_hosts == hosts {
1311            return;
1312        }
1313        let records: Vec<WatcherHostRecord> = hosts
1314            .iter()
1315            .map(|host| WatcherHostRecord {
1316                code: host.code.clone(),
1317                wait_steps: host.wait_steps,
1318                threads: host.threads,
1319                tied_threads: host.tied_threads.min(host.threads),
1320                memory_bytes: host.memory_bytes,
1321                hosts_lost: host.hosts_lost,
1322            })
1323            .collect();
1324        match self.db.set_worker_hosts(worker_id, &records).await {
1325            Ok(()) => connection.watcher_hosts = hosts,
1326            Err(error) => {
1327                tracing::warn!(worker_id, %error, "worker's wait step hosts not recorded");
1328            }
1329        }
1330    }
1331
1332    /// Handles an attempt registered.
1333    async fn handles_added(
1334        &mut self,
1335        worker_id: &str,
1336        added: &pb::HandlesAdded,
1337    ) -> Result<Vec<Outgoing>, CoreError> {
1338        match Box::pin(self.dispatcher.handles_added(worker_id, added)).await {
1339            // Refused for its data, it would end the stream on every reconnect.
1340            Err(error) if error.is_data_fault() => {
1341                tracing::error!(worker_id, %error, "handles the database refuses");
1342            }
1343            handled => handled?,
1344        }
1345        Ok(Vec::new())
1346    }
1347
1348    /// A worker's warnings recorded, as many and as long as kept (B183).
1349    async fn worker_warnings(&self, worker_id: &str, reported: pb::Warnings) {
1350        let limits = self.settings.worker_report;
1351        let warnings: Vec<WorkerWarning> = limits
1352            .take(worker_id, "warnings", reported.warnings)
1353            .into_iter()
1354            .map(|w| WorkerWarning {
1355                kind: limits.cut(w.kind),
1356                interpreter: limits.cut(w.interpreter),
1357                message: limits.cut(w.message),
1358            })
1359            .collect();
1360        if let Err(error) = self.db.set_worker_warnings(worker_id, &warnings).await {
1361            tracing::warn!(worker_id, %error, "worker's warnings not recorded");
1362        }
1363    }
1364
1365    /// A message on a registered worker's stream.
1366    ///
1367    /// # Errors
1368    ///
1369    /// [`CoreError::BadMessage`] for a message that doesn't fit (a second `Register`, unknown
1370    /// enum values), or a database failure.
1371    pub async fn handle(
1372        &mut self,
1373        worker_id: &str,
1374        message: worker_message::Message,
1375        now: Timestamp,
1376    ) -> Result<Vec<Outgoing>, CoreError> {
1377        self.heard_from(worker_id, now).await;
1378        Ok(match message {
1379            worker_message::Message::Register(_) => {
1380                return Err(CoreError::BadMessage {
1381                    worker_id: worker_id.to_owned(),
1382                    reason: "`Register` is only the first message".to_owned(),
1383                });
1384            }
1385            worker_message::Message::Heartbeat(beat) => {
1386                self.heard_of_hosts(worker_id, beat.watcher_hosts).await;
1387                if let Some(usage) = beat.usage {
1388                    self.heard_of_usage(worker_id, usage, now).await;
1389                }
1390                self.triggers_reported(worker_id, &beat.running_triggers)
1391                    .await?
1392            }
1393            message @ (worker_message::Message::TriggerEvent(_)
1394            | worker_message::Message::TriggerPoked(_)
1395            | worker_message::Message::TriggerStopped(_)) => {
1396                self.trigger_message(worker_id, message, now).await?
1397            }
1398            // For people, like the last heartbeat: a failed write is logged, not the message's
1399            // failure (the worker sends them again after its next registration).
1400            worker_message::Message::Warnings(reported) => {
1401                self.worker_warnings(worker_id, reported).await;
1402                Vec::new()
1403            }
1404            // A message's writes are one transaction: stored whole or not at all, with one
1405            // lease check and one commit (T1, 2.10b).
1406            worker_message::Message::CodeVersionChanged(changed) => match changed.root {
1407                Some(root) => self.code_version_changed(worker_id, &root, now).await?,
1408                None => Vec::new(),
1409            },
1410            // Rolled back, their changes to memory are put back too; a commit cut off is read
1411            // back first (D1): stored, memory stays as the message left it.
1412            worker_message::Message::Started(started) => {
1413                let (db, memory) = (self.db.clone(), self.dispatcher.memory());
1414                let handled =
1415                    Box::pin(db.atomically(self.dispatcher.started(worker_id, &started, now)))
1416                        .await;
1417                let id = started.attempt_id.as_str();
1418                let settled = self
1419                    .settle(handled, memory, id, |a| a.is_some_and(|a| a.started))
1420                    .await;
1421                // Not stored, the start stays known in memory: the attempt runs, and isn't
1422                // taken back meanwhile; its `Finished` (or a reconnect's journal) settles it.
1423                if settled.is_ok() {
1424                    self.arrivals.start_handled(id);
1425                }
1426                match settled? {
1427                    Some(out) => out.into_iter().collect(),
1428                    None => Vec::new(),
1429                }
1430            }
1431            worker_message::Message::Rejected(rejected) => {
1432                let (db, memory) = (self.db.clone(), self.dispatcher.memory());
1433                let handled =
1434                    Box::pin(db.atomically(self.dispatcher.rejected(worker_id, &rejected, now)))
1435                        .await;
1436                let id = rejected.attempt_id.as_str();
1437                // Undone, the attempt is deleted.
1438                self.settle(handled, memory, id, |a| a.is_none()).await?;
1439                Vec::new()
1440            }
1441            worker_message::Message::Finished(finished) => {
1442                let settled = match self.finished(worker_id, &finished, now).await {
1443                    // Refused for its data, it would be refused again after every reconnect,
1444                    // the worker's later results waiting behind it: stored as the attempt's
1445                    // failure instead, and acknowledged (B106).
1446                    Err(error) if error.is_data_fault() => {
1447                        tracing::error!(
1448                            worker_id,
1449                            attempt_id = finished.attempt_id,
1450                            %error,
1451                            "a result the database refuses is stored as the attempt's failure"
1452                        );
1453                        self.finished(worker_id, &not_stored(&finished, &error), now)
1454                            .await
1455                    }
1456                    settled => settled,
1457                };
1458                let id = finished.attempt_id.as_str();
1459                // As for `Started`: not stored, the worker sends it again (B41), and the
1460                // attempt isn't taken back meanwhile.
1461                if settled.is_ok() {
1462                    self.arrivals.start_handled(id);
1463                }
1464                vec![settled?.unwrap_or_else(|| crate::dispatch::finished_ack(worker_id, id))]
1465            }
1466            worker_message::Message::ApiCall(call) => self.api_call(worker_id, call, now).await?,
1467            worker_message::Message::HandlesAdded(added) => {
1468                self.handles_added(worker_id, &added).await?
1469            }
1470            worker_message::Message::TaskEnded(ended) => {
1471                self.task_ended(worker_id, ended, now).await?;
1472                Vec::new()
1473            }
1474            worker_message::Message::Draining(_) => self.worker_draining(worker_id, now).await?,
1475            worker_message::Message::Deregister(_) => self.deregistered(worker_id, now).await,
1476            worker_message::Message::ConnectionJobDone(done) => {
1477                self.connection_job_done(worker_id, done).await?;
1478                Vec::new()
1479            }
1480        })
1481    }
1482
1483    /// A worker answered a connections job: its reports into the command's result.
1484    async fn connection_job_done(
1485        &mut self,
1486        worker_id: &str,
1487        done: pb::ConnectionJobDone,
1488    ) -> Result<(), CoreError> {
1489        let mut reports = Vec::with_capacity(done.report_json.len());
1490        for json in &done.report_json {
1491            let report: ConnectionReport =
1492                serde_json::from_slice(json).map_err(|e| CoreError::BadMessage {
1493                    worker_id: worker_id.to_owned(),
1494                    reason: format!("a connection report doesn't read: {e}"),
1495                })?;
1496            reports.push(report);
1497        }
1498        // Only its own worker's answer, and once stored: until then it can still be lost.
1499        if self
1500            .connection_jobs
1501            .get(&done.job_id)
1502            .is_some_and(|(worker, _)| worker != worker_id)
1503        {
1504            return Ok(());
1505        }
1506        self.update_connection_job(&done.job_id, worker_id, |job| {
1507            job.state = JobState::Done;
1508            job.connections = reports;
1509        })
1510        .await?;
1511        self.connection_jobs.remove(&done.job_id);
1512        Ok(())
1513    }
1514
1515    /// Changes one job of a connections command's stored result, if it is `worker_id`'s and
1516    /// still running (an answer after the job was given up on is dropped).
1517    async fn update_connection_job(
1518        &self,
1519        job_id: &str,
1520        worker_id: &str,
1521        update: impl FnOnce(&mut ConnectionJobResult),
1522    ) -> Result<(), CoreError> {
1523        let Some((command_id, root)) = parse_connection_job_id(job_id) else {
1524            return Ok(());
1525        };
1526        let Some(record) = self.db.command(command_id).await? else {
1527            return Ok(());
1528        };
1529        let Some(mut result) = record
1530            .result
1531            .and_then(|value| serde_json::from_value::<ConnectionsResult>(value).ok())
1532        else {
1533            return Ok(());
1534        };
1535        let Some(job) = result.jobs.iter_mut().find(|job| {
1536            job.root == root && job.worker == worker_id && job.state == JobState::Running
1537        }) else {
1538            return Ok(());
1539        };
1540        update(job);
1541        let value = serde_json::to_value(&result).unwrap_or_default();
1542        self.db.set_command_result(command_id, &value).await?;
1543        Ok(())
1544    }
1545
1546    /// The connections jobs of a worker that went away (or restarted, `why`): lost, so their
1547    /// command finishes.
1548    async fn connection_jobs_lost(&mut self, worker_id: &str, why: &str) -> Result<(), CoreError> {
1549        let lost: Vec<String> = self
1550            .connection_jobs
1551            .iter()
1552            .filter(|(_, (worker, _))| worker == worker_id)
1553            .map(|(job, _)| job.clone())
1554            .collect();
1555        for job_id in lost {
1556            self.connection_job_lost(&job_id, worker_id, why.to_owned())
1557                .await?;
1558        }
1559        Ok(())
1560    }
1561
1562    async fn connection_job_lost(
1563        &mut self,
1564        job_id: &str,
1565        worker_id: &str,
1566        why: String,
1567    ) -> Result<(), CoreError> {
1568        self.update_connection_job(job_id, worker_id, |job| {
1569            job.state = JobState::Lost;
1570            job.reason = Some(why);
1571        })
1572        .await?;
1573        self.connection_jobs.remove(job_id);
1574        Ok(())
1575    }
1576
1577    /// The connections jobs past their time: lost (their answer, if any, went with a stream
1578    /// that ended).
1579    async fn connection_jobs_overdue(&mut self, now: Timestamp) -> Result<(), CoreError> {
1580        let overdue: Vec<(String, String)> = self
1581            .connection_jobs
1582            .iter()
1583            .filter(|(_, (_, deadline))| *deadline <= (self.steady)(now))
1584            .map(|(job, (worker, _))| (job.clone(), worker.clone()))
1585            .collect();
1586        for (job_id, worker_id) in overdue {
1587            let why = format!("worker `{worker_id}` didn't answer in time");
1588            self.connection_job_lost(&job_id, &worker_id, why).await?;
1589        }
1590        Ok(())
1591    }
1592
1593    /// A worker's stream ended: it may reconnect (same incarnation, tasks still running)
1594    /// within the lease timeout, or it is lost at the next tick after that.
1595    ///
1596    /// # Errors
1597    ///
1598    /// [`CoreError::Db`] if the registry can't be written.
1599    pub async fn disconnected(&mut self, worker_id: &str, now: Timestamp) -> Result<(), CoreError> {
1600        if let Some(connection) = self.connections.get_mut(worker_id)
1601            && connection.live
1602        {
1603            connection.live = false;
1604            self.dispatcher.worker_disconnected(worker_id);
1605            self.db
1606                .set_worker_state(worker_id, WorkerState::Disconnected, now)
1607                .await?;
1608        }
1609        Ok(())
1610    }
1611
1612    /// One pass of the master's loop: commands, the scheduler, dispatching, parse jobs past
1613    /// their timeout, and workers past their lease.
1614    ///
1615    /// # Errors
1616    ///
1617    /// The first failure; what was done before it stays done, and the next tick goes on.
1618    pub async fn tick(&mut self, now: Timestamp) -> Result<Vec<Outgoing>, CoreError> {
1619        let (outgoing, result) = self.tick_partial(now).await;
1620        result.map(|()| outgoing)
1621    }
1622
1623    /// As [`Self::tick`], with the messages built before a failure: each is built after the
1624    /// write it stands for is stored, so they are delivered whatever comes after (B7: a cancel
1625    /// dropped with its failed round was sent again only when the worker reconnected).
1626    pub async fn tick_partial(&mut self, now: Timestamp) -> (Vec<Outgoing>, Result<(), CoreError>) {
1627        let mut outgoing = Vec::new();
1628        let result = self.tick_into(&mut outgoing, now).await;
1629        (outgoing, result)
1630    }
1631
1632    async fn tick_into(
1633        &mut self,
1634        outgoing: &mut Vec<Outgoing>,
1635        now: Timestamp,
1636    ) -> Result<(), CoreError> {
1637        for part in RoundPart::ALL {
1638            self.round_part(part, now, outgoing).await?;
1639        }
1640        Ok(())
1641    }
1642
1643    /// One part of a round, its messages into `outgoing` (each built after the write it stands
1644    /// for is stored). The service takes the core's lock for each part on its own, so a
1645    /// worker's turn gets in between them (decision 469); [`Self::tick`] runs them all.
1646    ///
1647    /// # Errors
1648    ///
1649    /// The part's failure: the round's later parts wait for the next round.
1650    pub async fn round_part(
1651        &mut self,
1652        part: RoundPart,
1653        now: Timestamp,
1654        outgoing: &mut Vec<Outgoing>,
1655    ) -> Result<(), CoreError> {
1656        let started = std::time::Instant::now();
1657        let result = match part {
1658            RoundPart::Commands => self.round_commands(outgoing, now).await,
1659            RoundPart::Scheduler => (self.scheduler.pass(now).await)
1660                .map(|_| ())
1661                .map_err(CoreError::from),
1662            RoundPart::Triggers => Box::pin(self.trigger_pass(now, outgoing)).await,
1663            RoundPart::Prepare => {
1664                (self.dispatcher.prepare(now, outgoing).await).map_err(CoreError::from)
1665            }
1666            RoundPart::Expire => (self.dispatcher.expire_round(now).await).map_err(CoreError::from),
1667            RoundPart::Assign => {
1668                (self.dispatcher.assign_round(now, outgoing).await).map_err(CoreError::from)
1669            }
1670            RoundPart::Rest => self.round_rest(outgoing, now).await,
1671        };
1672        self.metrics.round_part_done(part.name(), started.elapsed());
1673        result
1674    }
1675
1676    /// A round's commands applied, with their follow-ups (drains, resumes): the commands part
1677    /// whole, as [`Self::tick`] runs it; the service takes the lock for each command on its own
1678    /// (decision 483).
1679    async fn round_commands(
1680        &mut self,
1681        outgoing: &mut Vec<Outgoing>,
1682        now: Timestamp,
1683    ) -> Result<(), CoreError> {
1684        let pending = self.commands_to_apply(outgoing, now).await?;
1685        let mut failed = Ok(());
1686        for command in pending {
1687            failed = self.apply_command(command, outgoing, now).await;
1688            if failed.is_err() {
1689                break;
1690            }
1691        }
1692        self.commands_done(outgoing, now).await;
1693        failed
1694    }
1695
1696    /// The commands part's start: the script roots' uses sent, the round's commands read.
1697    ///
1698    /// # Errors
1699    ///
1700    /// [`CoreError`] if the database fails.
1701    pub async fn commands_to_apply(
1702        &mut self,
1703        outgoing: &mut Vec<Outgoing>,
1704        now: Timestamp,
1705    ) -> Result<Vec<schedr_db::commands::PendingCommand>, CoreError> {
1706        self.send_uses(outgoing, now);
1707        Ok(self.commander.pending().await?)
1708    }
1709
1710    /// One command applied in its own transaction (decision 483), with its follow-ups: the
1711    /// connection jobs it sent timed, a drain's or resume's parse jobs moved. What a failed
1712    /// command kept (a commit whose answer was lost) gets its follow-ups too.
1713    ///
1714    /// # Errors
1715    ///
1716    /// [`CoreError`] if the database fails: the command stays pending, the round's later ones
1717    /// wait for the next round.
1718    pub async fn apply_command(
1719        &mut self,
1720        pending: schedr_db::commands::PendingCommand,
1721        outgoing: &mut Vec<Outgoing>,
1722        now: Timestamp,
1723    ) -> Result<(), CoreError> {
1724        let mut applied = Applied::default();
1725        let result = self
1726            .commander
1727            .apply_one(
1728                pending,
1729                &self.scheduler,
1730                &mut self.dispatcher,
1731                &mut applied,
1732                now,
1733            )
1734            .await;
1735        outgoing.append(&mut applied.outgoing);
1736        for job in applied.connection_jobs.drain(..) {
1737            let deadline = (self.steady)(now)
1738                .checked_add(job.allowed + Duration::from_millis(CONNECTION_ANSWER_MARGIN_MS))
1739                .unwrap_or(now);
1740            self.connection_jobs
1741                .insert(job.job_id, (job.worker_id, deadline));
1742        }
1743        for (worker_id, drained) in std::mem::take(&mut applied.drained) {
1744            self.follow_up(worker_id, drained, outgoing, now).await;
1745        }
1746        result.map_err(CoreError::from)
1747    }
1748
1749    /// The commands part's end: overdue connection jobs marked lost, and the resumes whose
1750    /// follow-up failed tried again (B99), whether or not a command failed.
1751    pub async fn commands_done(&mut self, outgoing: &mut Vec<Outgoing>, now: Timestamp) {
1752        if let Err(error) = self.connection_jobs_overdue(now).await {
1753            tracing::warn!(%error, "overdue connection jobs not marked lost yet");
1754        }
1755        // A resume whose follow-up failed is tried again each round until it succeeds, or the
1756        // worker is drained again (B99).
1757        for worker_id in std::mem::take(&mut self.unresumed) {
1758            self.follow_up(worker_id, false, outgoing, now).await;
1759        }
1760    }
1761
1762    /// A drain's (`drained`) or resume's follow-up: the worker's parse jobs moved away, or
1763    /// given back to it.
1764    async fn follow_up(
1765        &mut self,
1766        worker_id: String,
1767        drained: bool,
1768        outgoing: &mut Vec<Outgoing>,
1769        now: Timestamp,
1770    ) {
1771        if drained {
1772            self.unresumed.remove(&worker_id);
1773            let moved = self.discovery.stop_parsing(&worker_id, now);
1774            outgoing.extend(moved.into_iter().map(assign_parse));
1775        } else if self
1776            .dispatcher
1777            .workers()
1778            .get(&worker_id)
1779            .is_none_or(|w| w.state == crate::workers::WorkerState::Active)
1780        {
1781            // Not if the agent itself is draining (shutting down).
1782            match self.discovery.allow_parsing(&worker_id, now).await {
1783                Ok(jobs) => outgoing.extend(jobs.into_iter().map(assign_parse)),
1784                Err(error) => {
1785                    // Logged, not failing the round: the rest of it doesn't depend on it.
1786                    tracing::error!(
1787                        worker_id,
1788                        %error,
1789                        "resumed worker's parse jobs not found: tried again next round"
1790                    );
1791                    self.unresumed.insert(worker_id);
1792                }
1793            }
1794        }
1795    }
1796
1797    /// A round's last part: parse jobs past their time given again, lost workers forgotten.
1798    async fn round_rest(
1799        &mut self,
1800        outgoing: &mut Vec<Outgoing>,
1801        now: Timestamp,
1802    ) -> Result<(), CoreError> {
1803        let expired = self.discovery.jobs_mut().expire(now);
1804        outgoing.extend(expired.into_iter().map(assign_parse));
1805        let lease =
1806            SignedDuration::try_from(self.settings.lease_timeout).unwrap_or(SignedDuration::MAX);
1807        let steady = (self.steady)(now);
1808        let lost: Vec<String> = self
1809            .connections
1810            .iter()
1811            .filter(|(id, c)| {
1812                // The later of its last handled message and its last arrived one.
1813                let seen = self.arrivals.last(id).map_or(c.heard, |a| a.max(c.heard));
1814                steady.duration_since(seen) > lease
1815            })
1816            .map(|(id, _)| id.clone())
1817            .collect();
1818        for worker_id in lost {
1819            self.forget(&worker_id, WorkerState::Lost, now, outgoing)
1820                .await?;
1821        }
1822        Ok(())
1823    }
1824
1825    /// A worker uploads a parse result (unary call).
1826    ///
1827    /// # Errors
1828    ///
1829    /// [`CoreError::BadMessage`] for a result missing its root or with DAG JSON that doesn't
1830    /// read; a database failure.
1831    pub async fn upload(
1832        &mut self,
1833        result: pb::ParseResult,
1834        now: Timestamp,
1835    ) -> Result<(), CoreError> {
1836        let bad = |reason: String| CoreError::BadMessage {
1837            worker_id: result.worker_id.clone(),
1838            reason,
1839        };
1840        let root = result
1841            .root
1842            .clone()
1843            .ok_or_else(|| bad("a parse result without its root".to_owned()))?;
1844        let files = result
1845            .files
1846            .iter()
1847            .cloned()
1848            .map(parsed_file_from_proto)
1849            .collect::<Result<Vec<_>, _>>()
1850            .map_err(|e| bad(e.to_string()))?;
1851        self.discovery
1852            .parse_uploaded(
1853                ParseUpload {
1854                    worker_id: result.worker_id.clone(),
1855                    key: ParseKey {
1856                        kind: root.kind(),
1857                        root: root.root,
1858                        content_hash: root.content_hash,
1859                        schedr_version: result.schedr_version.clone(),
1860                    },
1861                    files,
1862                    secret_storages: self
1863                        .connections
1864                        .get(&result.worker_id)
1865                        .and_then(|c| c.secret_storages.clone()),
1866                },
1867                now,
1868            )
1869            .await?;
1870        self.sync_code();
1871        Ok(())
1872    }
1873
1874    /// An open attempt's inputs as JSON (`FetchInputs`); `None` for an unknown or ended one.
1875    ///
1876    /// # Errors
1877    ///
1878    /// [`CoreError::Dispatch`] if the database fails.
1879    pub async fn inputs(&self, attempt_id: &str) -> Result<Option<Vec<u8>>, CoreError> {
1880        Ok(self.dispatcher.attempt_inputs(attempt_id).await?)
1881    }
1882
1883    /// What a worker message's handling comes to: its result when stored; when its commit was
1884    /// cut off and attempt `id` (or its absence) reads back as `landed` (see
1885    /// [`crate::dispatch::ReadBack`]), `Ok(None)`: stored after all, memory kept; otherwise
1886    /// the error, memory put back. A read that fails tells nothing.
1887    /// A worker's `Finished` stored in one transaction (see [`Self::settle`]).
1888    async fn finished(
1889        &mut self,
1890        worker_id: &str,
1891        finished: &pb::Finished,
1892        now: Timestamp,
1893    ) -> Result<Option<Outgoing>, CoreError> {
1894        let (db, memory) = (self.db.clone(), self.dispatcher.memory());
1895        let handled =
1896            Box::pin(db.atomically(self.dispatcher.finished(worker_id, finished, now))).await;
1897        self.settle(handled, memory, &finished.attempt_id, |a| {
1898            a.is_some_and(|a| a.status.is_some())
1899        })
1900        .await
1901    }
1902
1903    /// A turn's `Started`s, then its `Finished`s (M4B.3, decision 397): one transaction, one
1904    /// lease check and one commit, with one memory snapshot for the group (B48). Counts, wakes
1905    /// and `arrivals` only once it is stored. A commit cut off is read back once, by the last
1906    /// message: the group lands whole or not at all.
1907    ///
1908    /// # Errors
1909    ///
1910    /// The group handed back, its memory put back and nothing of it counted, when it failed
1911    /// (any message's error, the lease, the commit): the caller handles its messages one by
1912    /// one, which decides each one's fate as before.
1913    pub async fn handle_group(
1914        &mut self,
1915        worker_id: &str,
1916        group: Group,
1917        now: Timestamp,
1918    ) -> Result<Vec<Outgoing>, Group> {
1919        self.heard_from(worker_id, now).await;
1920        let (db, memory) = (self.db.clone(), self.dispatcher.memory());
1921        self.metrics.stage();
1922        self.dispatcher.take_witnesses();
1923        let dispatcher = &mut self.dispatcher;
1924        // What the group sends, kept for a commit whose answer is lost: stored, it is all sent
1925        // (Grok's review: a `Started` that started nothing is answered with a cancel).
1926        let mut out = Vec::new();
1927        let handled = Box::pin(db.atomically(async {
1928            if !group.started.is_empty() {
1929                out.extend(
1930                    dispatcher
1931                        .started_group(worker_id, &group.started, now)
1932                        .await?,
1933                );
1934            }
1935            if !group.finished.is_empty() {
1936                out.extend(
1937                    dispatcher
1938                        .finished_group(worker_id, &group.finished, now)
1939                        .await?,
1940                );
1941            }
1942            Ok::<_, DispatchError>(())
1943        }))
1944        .await;
1945        match handled {
1946            Ok(()) => {}
1947            // Read back by the first attempt its writes started or ended (they land together).
1948            Err(DispatchError::Db(DbError::CommitUnknown)) if self.group_landed().await => {}
1949            Err(error) => {
1950                self.metrics.drop_staged();
1951                self.dispatcher.undo(memory, &error);
1952                tracing::warn!(
1953                    worker_id,
1954                    %error,
1955                    messages = group.started.len() + group.finished.len(),
1956                    "a turn's group of messages failed: handled one by one"
1957                );
1958                return Err(group);
1959            }
1960        }
1961        self.metrics.count_staged();
1962        for id in group.attempt_ids() {
1963            self.arrivals.start_handled(id);
1964        }
1965        Ok(out)
1966    }
1967
1968    /// Whether a group whose commit was cut off was stored: by the first attempt its writes
1969    /// started or ended (all of them land or none). With none, it changed no attempt and is
1970    /// redone one by one, which changes nothing twice.
1971    async fn group_landed(&mut self) -> bool {
1972        let Some((id, witness)) = self.dispatcher.take_witnesses().into_iter().next() else {
1973            return false;
1974        };
1975        self.settings
1976            .read_back
1977            .stored(|| async {
1978                self.db.attempt(&id).await.is_ok_and(|attempt| {
1979                    attempt.is_some_and(|a| match witness {
1980                        crate::dispatch::Witness::Started => a.started,
1981                        crate::dispatch::Witness::Ended => a.status.is_some(),
1982                    })
1983                })
1984            })
1985            .await
1986    }
1987
1988    async fn settle<T>(
1989        &mut self,
1990        handled: Result<T, DispatchError>,
1991        memory: crate::dispatch::Memory,
1992        id: &str,
1993        landed: impl Fn(Option<&schedr_db::attempts::StoredAttempt>) -> bool,
1994    ) -> Result<Option<T>, CoreError> {
1995        match handled {
1996            Ok(done) => Ok(Some(done)),
1997            Err(DispatchError::Db(DbError::CommitUnknown))
1998                if self
1999                    .settings
2000                    .read_back
2001                    .stored(|| async {
2002                        self.db
2003                            .attempt(id)
2004                            .await
2005                            .is_ok_and(|attempt| landed(attempt.as_ref()))
2006                    })
2007                    .await =>
2008            {
2009                Ok(None)
2010            }
2011            Err(error) => {
2012                self.dispatcher.undo(memory, &error);
2013                Err(error.into())
2014            }
2015        }
2016    }
2017
2018    /// A registered worker's version, maintenance drain and roots: its reports replace what it
2019    /// reported before. Returns the parse jobs to send.
2020    async fn report_roots(
2021        &mut self,
2022        register: &pb::Register,
2023        now: Timestamp,
2024    ) -> Result<Vec<Outgoing>, CoreError> {
2025        let worker_id = register.worker_id.as_str();
2026        let mut outgoing = Vec::new();
2027        // Before anything hands jobs out, so one going back to it goes once (B235).
2028        let released = self.discovery.release_jobs(worker_id);
2029        self.dispatcher
2030            .set_worker_version(worker_id, register.schedr_version.parse().ok());
2031        // Drained for maintenance stays drained, whatever restarted (until resumed).
2032        if self.db.worker_drained(worker_id).await? {
2033            self.dispatcher.set_drained(worker_id);
2034            let moved = self.discovery.stop_parsing(worker_id, now);
2035            outgoing.extend(moved.into_iter().map(assign_parse));
2036        } else {
2037            outgoing.extend(
2038                self.discovery
2039                    .allow_parsing(worker_id, now)
2040                    .await?
2041                    .into_iter()
2042                    .map(assign_parse),
2043            );
2044        }
2045        // Its reports replace what it reported before: a root it no longer has stops counting.
2046        let keys: Vec<ParseKey> = register
2047            .roots
2048            .iter()
2049            .filter(|root| parsed_kind(root))
2050            .map(|root| {
2051                self.dispatcher
2052                    .report_root(worker_id, &root.root, &root.content_hash);
2053                ParseKey {
2054                    kind: root.kind(),
2055                    root: root.root.clone(),
2056                    content_hash: root.content_hash.clone(),
2057                    schedr_version: register.schedr_version.clone(),
2058                }
2059            })
2060            .collect();
2061        let jobs = self.discovery.registered(worker_id, keys, now).await?;
2062        outgoing.extend(jobs.into_iter().map(assign_parse));
2063        let handed = self.discovery.hand_out(&released, now);
2064        outgoing.extend(handed.into_iter().map(assign_parse));
2065        self.sync_code();
2066        Ok(outgoing)
2067    }
2068
2069    /// A worker's `CodeVersionChanged`, its writes one transaction.
2070    async fn code_version_changed(
2071        &mut self,
2072        worker_id: &str,
2073        root: &pb::RootHash,
2074        now: Timestamp,
2075    ) -> Result<Vec<Outgoing>, CoreError> {
2076        let (db, memory) = (self.db.clone(), self.discovery.memory());
2077        let handled = Box::pin(db.atomically(self.root_reported(worker_id, root, now))).await;
2078        if handled.is_err() {
2079            // Rolled back, discovery's memory too: a retry decides afresh, and records the
2080            // switch again (B91).
2081            self.discovery.restore(memory);
2082            self.sync_code();
2083        }
2084        handled
2085    }
2086
2087    async fn root_reported(
2088        &mut self,
2089        worker_id: &str,
2090        root: &pb::RootHash,
2091        now: Timestamp,
2092    ) -> Result<Vec<Outgoing>, CoreError> {
2093        if !parsed_kind(root) {
2094            return Ok(Vec::new());
2095        }
2096        if root.content_hash.is_empty() {
2097            // Withdrawn (decision 303).
2098            self.dispatcher.withdraw_root(worker_id, &root.root);
2099            self.discovery
2100                .root_withdrawn(worker_id, &root.root, now)
2101                .await?;
2102            self.sync_code();
2103            return Ok(Vec::new());
2104        }
2105        let version = self
2106            .connections
2107            .get(worker_id)
2108            .map(|c| c.schedr_version.clone())
2109            .unwrap_or_default();
2110        let key = ParseKey {
2111            kind: root.kind(),
2112            root: root.root.clone(),
2113            content_hash: root.content_hash.clone(),
2114            schedr_version: version,
2115        };
2116        self.dispatcher
2117            .report_root(worker_id, &root.root, &root.content_hash);
2118        let assignment = self.discovery.root_reported(worker_id, key, now).await?;
2119        self.sync_code();
2120        Ok(assignment.into_iter().map(assign_parse).collect())
2121    }
2122
2123    async fn journal_decision(
2124        &mut self,
2125        worker_id: &str,
2126        entry: &pb::JournalEntry,
2127        now: Timestamp,
2128    ) -> Result<(pb::AttemptDecision, u32, Option<Outgoing>), CoreError> {
2129        let Some(mut attempt) = self.db.attempt(&entry.attempt_id).await? else {
2130            return Ok((pb::AttemptDecision::Kill, 0, None));
2131        };
2132        let finished = entry.state == i32::from(pb::JournalState::Finished);
2133        if attempt.worker_id.is_empty()
2134            && attempt.status.is_none()
2135            && self.db.cleanup_moved_from(&attempt.id).await?.as_deref() == Some(worker_id)
2136        {
2137            // A cleanup that ended while its worker was away, waiting to move: its
2138            // `Finished`, sent again, counts and the move is dropped (decision 282). Not
2139            // adopted: nothing of it runs any more.
2140            if finished {
2141                return Ok((pb::AttemptDecision::Continue, 0, None));
2142            }
2143            // One not ended, holding handles the master never got: the only worker with all
2144            // of them gets it back, adopted below, and nothing else cleans them (B169).
2145            if entry.handles > self.known_handles(&attempt.id).await?
2146                && self.take_back(&attempt, worker_id).await?
2147            {
2148                attempt.worker_id = worker_id.to_owned();
2149            }
2150        }
2151        if attempt.worker_id != worker_id {
2152            // Its cleanup moved from this worker, which may hold handles the master never got
2153            // (registered while it was cut off): it cleans those itself, and its result is
2154            // added to the attempt's (B169). One that ended is sent again for that.
2155            if self.db.rest_owed_by(&attempt.id).await?.as_deref() == Some(worker_id) {
2156                if finished {
2157                    return Ok((pb::AttemptDecision::Continue, 0, None));
2158                }
2159                let known = self.known_handles(&attempt.id).await?;
2160                if entry.handles > known {
2161                    return Ok((pb::AttemptDecision::CleanRest, known, None));
2162                }
2163            }
2164            return Ok((pb::AttemptDecision::Kill, 0, None));
2165        }
2166        let (decision, outgoing) = match (attempt.status, finished) {
2167            // The master stored its result: the worker can forget it.
2168            (Some(_), true) => (pb::AttemptDecision::Ack, None),
2169            // The master ended it (lost, expired) while the worker still runs it.
2170            (Some(_), false) => (pb::AttemptDecision::Kill, None),
2171            // Still open: keep running (or send its `Finished` again). A cancel sent while
2172            // the worker was away was dropped, so it is sent again: the run's or the task's
2173            // (B43).
2174            (None, _) => {
2175                self.dispatcher.adopt(worker_id, &attempt.id, now).await?;
2176                let cancelling = self
2177                    .db
2178                    .run_tasks(&attempt.run_id)
2179                    .await?
2180                    .is_some_and(|run| run.cancels_instance(&attempt.instance_id));
2181                // A poke on a worker drained while it was away missed being moved.
2182                let moving = !cancelling
2183                    && self.db.worker_drained(worker_id).await?
2184                    && self.dispatcher.is_poke(worker_id, &attempt.id);
2185                let cancel = (cancelling || moving).then(|| Outgoing {
2186                    worker_id: worker_id.to_owned(),
2187                    message: pb::MasterMessage {
2188                        message: Some(master_message::Message::CancelAttempt(pb::CancelAttempt {
2189                            interrupted: moving,
2190                            attempt_id: attempt.id.clone(),
2191                        })),
2192                        clock: None,
2193                    },
2194                });
2195                (pb::AttemptDecision::Continue, cancel)
2196            }
2197        };
2198        Ok((decision, 0, outgoing))
2199    }
2200
2201    /// Undoes a waiting cleanup's move back to `worker_id` (B169). The task's result the
2202    /// move kept is the master's own `lost` when the task ran there: dropped, the worker
2203    /// reports its own.
2204    async fn take_back(
2205        &self,
2206        attempt: &schedr_db::attempts::StoredAttempt,
2207        worker_id: &str,
2208    ) -> Result<bool, CoreError> {
2209        let lost_kept = attempt.cleanup_moves == 1
2210            && self
2211                .db
2212                .task_result(&attempt.id)
2213                .await?
2214                .and_then(|kept| <pb::Finished as prost::Message>::decode(kept.as_slice()).ok())
2215                .is_some_and(|kept| kept.status == i32::from(pb::AttemptStatus::Lost));
2216        Ok(self
2217            .db
2218            .take_back_cleanup(&attempt.id, worker_id, lost_kept)
2219            .await?)
2220    }
2221
2222    /// How many of an attempt's cleanup handles the master has, from the first without a gap.
2223    async fn known_handles(&self, attempt_id: &str) -> Result<u32, CoreError> {
2224        Ok(self.db.cleanup_handles_unbroken(attempt_id).await?)
2225    }
2226
2227    /// A worker's state and the end of its attempts, in one transaction, memory put back if it
2228    /// fails.
2229    async fn store_gone(
2230        &mut self,
2231        worker_id: &str,
2232        state: WorkerState,
2233        results: KeptResults,
2234        now: Timestamp,
2235    ) -> Result<(), CoreError> {
2236        let (db, memory) = (self.db.clone(), self.dispatcher.memory());
2237        let stored = Box::pin(db.atomically(async {
2238            self.db.set_worker_state(worker_id, state, now).await?;
2239            self.dispatcher.worker_lost(worker_id, results, now).await?;
2240            Ok::<(), CoreError>(())
2241        }))
2242        .await;
2243        if let Err(error) = stored {
2244            self.dispatcher.restore(memory);
2245            if matches!(error, CoreError::Db(DbError::CommitUnknown))
2246                || matches!(&error, CoreError::Dispatch(e) if e.commit_unknown())
2247            {
2248                self.dispatcher.recount();
2249            }
2250            return Err(error);
2251        }
2252        Ok(())
2253    }
2254
2255    /// A worker deregistered (`Offline`) or is lost (`Lost`): its attempts end `lost`, its
2256    /// parse jobs move on, and the registry keeps it listed in that state.
2257    async fn forget(
2258        &mut self,
2259        worker_id: &str,
2260        state: WorkerState,
2261        now: Timestamp,
2262        outgoing: &mut Vec<Outgoing>,
2263    ) -> Result<(), CoreError> {
2264        // Its state and the end of its attempts in one transaction, memory put back if it
2265        // fails, and the connection dropped only once everything below is stored: a failure
2266        // anywhere is retried whole by the next tick's lease check, which looks only at
2267        // connections (B42); each step can be done again. (`worker_lost` joins this
2268        // transaction; the snapshot here covers its memory too.)
2269        let stored = self
2270            .store_gone(worker_id, state, KeptResults::Used, now)
2271            .await;
2272        match stored {
2273            // A kept result the database refuses would hold the worker, and those after it,
2274            // for ever: this time without it.
2275            Err(error) if error.is_data_fault() => {
2276                tracing::error!(worker_id, %error, "a kept result the database refuses");
2277                self.store_gone(worker_id, state, KeptResults::Refused, now)
2278                    .await?;
2279            }
2280            stored => stored?,
2281        }
2282        // Moved in memory: sent whatever fails after (B7).
2283        let moved = self.discovery.jobs_mut().worker_lost(worker_id, now);
2284        outgoing.extend(moved.into_iter().map(assign_parse));
2285        self.discovery.worker_gone(worker_id, now).await?;
2286        self.sync_code();
2287        self.connections.remove(worker_id);
2288        self.arrivals.forget(worker_id);
2289        self.stopping_triggers
2290            .retain(|_, (worker, _)| worker != worker_id);
2291        // After what is retried: its failure is logged, the CLI giving up after its timeout.
2292        if let Err(error) = self
2293            .connection_jobs_lost(
2294                worker_id,
2295                &format!("worker `{worker_id}` went away before answering"),
2296            )
2297            .await
2298        {
2299            tracing::warn!(worker_id, %error, "a lost worker's connection jobs not marked lost");
2300        }
2301        Ok(())
2302    }
2303
2304    /// A worker deregistered: forgotten as `Offline`. A failure is retried by the lease check
2305    /// (the connection stays); the parse jobs already moved go out either way, or they'd wait
2306    /// for their timeout.
2307    async fn deregistered(&mut self, worker_id: &str, now: Timestamp) -> Vec<Outgoing> {
2308        let mut outgoing = Vec::new();
2309        if let Err(error) = self
2310            .forget(worker_id, WorkerState::Offline, now, &mut outgoing)
2311            .await
2312        {
2313            tracing::error!(worker_id, %error, "a deregistered worker not forgotten yet");
2314        }
2315        outgoing
2316    }
2317
2318    /// Tells the dispatcher each root's current code, as discovery decided it.
2319    fn sync_code(&mut self) {
2320        let mut parsed = BTreeMap::new();
2321        for (root, hash, accepted, version) in self.discovery.current_code() {
2322            self.dispatcher.set_current_code(root, accepted, version);
2323            parsed.insert(root.to_owned(), hash.to_owned());
2324        }
2325        self.dispatcher
2326            .set_connections(self.discovery.registries(), &parsed);
2327    }
2328}
2329
2330impl MasterCore {
2331    /// The script roots each DAG root uses, as workers fold them: those no alive worker has
2332    /// reported for `script_root_grace` (since this master started, for one never reported)
2333    /// left out. No worker could fold one, so all would withdraw the DAG root and a fix to it
2334    /// would never be parsed; a reference to it stays an import error (295). The grace keeps a
2335    /// restart of the workers having it, or of the master, from dropping it meanwhile.
2336    fn script_uses_at(&mut self, now: Timestamp) -> crate::discovery::ScriptUses {
2337        let (seen, started) = &mut self.script_roots_seen;
2338        let started = *started.get_or_insert(now);
2339        for root in self.discovery.reported_script_roots() {
2340            seen.insert(root, now);
2341        }
2342        let grace = jiff::SignedDuration::try_from(self.settings.script_root_grace)
2343            .unwrap_or(jiff::SignedDuration::MAX);
2344        let present = |script: &str| {
2345            let since = seen.get(script).copied().unwrap_or(started);
2346            now.duration_since(since) < grace
2347        };
2348        self.discovery
2349            .script_uses()
2350            .iter()
2351            .filter_map(|(root, used)| {
2352                let used: BTreeSet<String> = used.iter().filter(|s| present(s)).cloned().collect();
2353                (!used.is_empty()).then(|| (root.clone(), used))
2354            })
2355            .collect()
2356    }
2357
2358    /// Sends every live worker the script roots each DAG root uses when they changed since
2359    /// they were last sent (decision 304).
2360    fn send_uses(&mut self, outgoing: &mut Vec<Outgoing>, now: Timestamp) {
2361        let uses = self.script_uses_at(now);
2362        if uses == self.sent_uses {
2363            return;
2364        }
2365        self.sent_uses = uses;
2366        let roots = root_uses(&self.sent_uses);
2367        for (worker_id, connection) in &self.connections {
2368            if connection.live {
2369                outgoing.push(Outgoing {
2370                    worker_id: worker_id.clone(),
2371                    message: pb::MasterMessage {
2372                        message: Some(master_message::Message::ScriptUses(pb::ScriptUses {
2373                            roots: roots.clone(),
2374                        })),
2375                        clock: None,
2376                    },
2377                });
2378            }
2379        }
2380    }
2381}
2382
2383/// The script roots each DAG root uses, as the protocol sends them (decision 304).
2384fn root_uses(uses: &crate::discovery::ScriptUses) -> Vec<pb::RootUses> {
2385    uses.iter()
2386        .map(|(root, used)| pb::RootUses {
2387            root: root.clone(),
2388            script_roots: used.iter().cloned().collect(),
2389        })
2390        .collect()
2391}
2392
2393fn assign_parse(assignment: ParseAssignment) -> Outgoing {
2394    Outgoing {
2395        worker_id: assignment.worker_id,
2396        message: pb::MasterMessage {
2397            message: Some(master_message::Message::AssignParse(pb::AssignParse {
2398                parse_job_id: assignment.job_id,
2399                root: Some(pb::RootHash {
2400                    kind: assignment.key.kind.into(),
2401                    root: assignment.key.root,
2402                    content_hash: assignment.key.content_hash,
2403                }),
2404            })),
2405            clock: None,
2406        },
2407    }
2408}
2409
2410/// A root the master has parsed: DAG roots, and script roots for their `schedr.toml` files
2411/// (M4.9); not one of a kind it doesn't know.
2412fn parsed_kind(root: &pb::RootHash) -> bool {
2413    matches!(root.kind(), pb::RootKind::Dag | pb::RootKind::Script)
2414}
2415
2416fn millis(duration: Duration) -> u64 {
2417    u64::try_from(duration.as_millis()).unwrap_or(u64::MAX)
2418}