Skip to main content

schedr_master/
service.rs

1//! The master's gRPC service and its loop: workers' `Control` streams, parse uploads and
2//! `FetchInputs`, over [`MasterCore`] (see archive/PROJECT.md, Master–worker protocol).
3//!
4//! A [`Hub`] holds the core and each live worker's outgoing stream; whatever the core decides
5//! to send (assignments, cancels, acknowledgements) is delivered through it, from a stream's
6//! messages and from the loop's ticks alike.
7
8use std::collections::{BTreeMap, VecDeque};
9use std::sync::Arc;
10use std::sync::atomic::{AtomicU64, Ordering};
11use std::time::Duration;
12
13use jiff::Timestamp;
14use schedr_db::commands::CommandNotifications;
15use schedr_db::{Database, DbError};
16use schedr_model::beat::Beat;
17use schedr_proto::convert::ParseUpload;
18use schedr_proto::pb::master_server::{Master, MasterServer};
19use schedr_proto::pb::{self, master_message, worker_message};
20use tokio::sync::{Mutex, mpsc, watch};
21use tokio_stream::wrappers::ReceiverStream;
22use tonic::{Request, Response, Status, Streaming};
23
24use crate::core::task_api::ApiCallPlan;
25use crate::core::{Arrivals, CoreError, Group, MasterCore, RoundPart};
26use crate::dispatch::Outgoing;
27use crate::lease::{Leadership, Renewal};
28use crate::metrics::MasterMetrics;
29use crate::problems::{ProblemKind, Problems};
30
31#[cfg(test)]
32mod tests;
33
34/// The size of one `FetchInputs` chunk.
35pub const INPUT_CHUNK: usize = 1024 * 1024;
36
37/// How many messages wait for a worker before it is taken for one that stopped reading.
38pub const STREAM_BUFFER: usize = 1024;
39
40/// A worker's stream of messages. Sending never waits (see [`Hub::deliver`]).
41/// A worker's stream to it (B240): each message's `MasterClock.sequence` is taken and the
42/// message queued under one lock, by the core's deliveries and the reader's answers alike, so
43/// the numbers leave in order; `id` tells it from the worker's other streams.
44#[derive(Debug, Clone)]
45struct Outbound {
46    sender: mpsc::Sender<Result<pb::MasterMessage, Status>>,
47    /// The last number used.
48    numbers: Arc<std::sync::Mutex<u64>>,
49    id: u64,
50}
51
52impl Outbound {
53    fn new(sender: mpsc::Sender<Result<pb::MasterMessage, Status>>, id: u64) -> Self {
54        Self {
55            sender,
56            numbers: Arc::default(),
57            id,
58        }
59    }
60
61    fn same_channel(&self, other: &Self) -> bool {
62        self.sender.same_channel(&other.sender)
63    }
64
65    /// Numbers `message` (stamped already) and queues it: its number. Not queued, the number
66    /// isn't used, and the message is dropped.
67    fn send(&self, message: pb::MasterMessage) -> Result<u64, mpsc::error::TrySendError<()>> {
68        numbered_send(&self.numbers, &self.sender, message)
69    }
70
71    /// Ends the stream with `status` (unnumbered: no message).
72    fn end(&self, status: Status) {
73        let _ = self.sender.try_send(Err(status));
74    }
75}
76
77/// Numbers `message` past the last of `numbers` and queues it on `sender`, under the lock.
78fn numbered_send(
79    numbers: &std::sync::Mutex<u64>,
80    sender: &mpsc::Sender<Result<pb::MasterMessage, Status>>,
81    mut message: pb::MasterMessage,
82) -> Result<u64, mpsc::error::TrySendError<()>> {
83    let mut last = numbers
84        .lock()
85        .unwrap_or_else(std::sync::PoisonError::into_inner);
86    let number = *last + 1;
87    if let Some(clock) = message.clock.as_mut() {
88        clock.sequence = number;
89    }
90    // The unsent message isn't wanted back: only whether the stream is full or closed.
91    sender.try_send(Ok(message)).map_err(|error| match error {
92        mpsc::error::TrySendError::Full(_) => mpsc::error::TrySendError::Full(()),
93        mpsc::error::TrySendError::Closed(_) => mpsc::error::TrySendError::Closed(()),
94    })?;
95    *last = number;
96    Ok(number)
97}
98
99/// The core and the workers' outgoing streams.
100#[derive(Debug, Clone)]
101pub struct Hub {
102    core: Arc<Mutex<MasterCore>>,
103    /// Each worker's current stream. Held only briefly (a send never waits), so the core's
104    /// lock, which can be held while waiting for it, never waits on a slow worker; a delivery
105    /// goes out whole under it, one after another.
106    streams: Arc<Mutex<BTreeMap<String, Outbound>>>,
107    /// Set when the master stops: each stream's server lets its sender go, for the stream to
108    /// end even when full (B200's review).
109    closing: Arc<watch::Sender<bool>>,
110    clock: fn() -> Timestamp,
111    /// When the loop last turned (the master's liveness).
112    beat: Beat,
113    metrics: MasterMetrics,
114    db: Database,
115    /// The longest a gauge refresh may take before it is abandoned.
116    refresh_limit: Duration,
117    /// The largest message a worker may send (a parse upload's file, a `Finished` with its
118    /// output): the core's `Settings::max_message_size`, which `Registered` also announces.
119    max_message_size: usize,
120    /// The most messages of one worker in a turn of the core's lock
121    /// (`SCHEDR_HIDDEN__MASTER__MESSAGES_PER_TURN`, M4B.3).
122    messages_per_turn: usize,
123    /// The most messages of a failed group handled one by one in a turn (decision 493).
124    alone_per_turn: usize,
125    /// The messages that wait for a worker before it is taken for one that stopped reading.
126    stream_buffer: usize,
127    /// When each worker's latest message arrived (the core's).
128    arrivals: Arrivals,
129    /// How often to try listening for commands again while the loop has no notifications
130    /// because starting them failed (see [`Hub::with_listen_retry`]).
131    listen_retry: Option<Duration>,
132    /// Whether this master leads (holds the lease, see [`crate::lease`]): worker messages,
133    /// registrations and uploads wait while it doesn't.
134    leading: Arc<watch::Sender<bool>>,
135    /// Told when a worker's `Finished` was recorded: a round runs at once instead of at the
136    /// next tick, its downstream tasks ready (decision 42B; [`ROUND_GAP`] after the last).
137    finished: Arc<tokio::sync::Notify>,
138    /// Told when the trigger loop must look (decision 486): a trigger's stored moment came
139    /// (the tick's probe), a named event was announced.
140    triggers_due: Arc<tokio::sync::Notify>,
141    /// Set when a trigger pass failed: the next tick wakes the loop again, as a failed round
142    /// is tried again at the next (Grok's review of M5.1f2).
143    triggers_failed: Arc<std::sync::atomic::AtomicBool>,
144    /// Its problems now, written with its row (decision 129).
145    problems: Problems,
146    /// How its loop is paced.
147    timings: crate::core::MasterTimings,
148    /// Master time (see [`crate::clock`]), stamped on every message.
149    steady: crate::clock::Steady,
150    /// The lease epoch this master leads with (decision 444), on every message's stamp.
151    epoch: i64,
152    /// The heartbeats heard on each worker's current stream: the latest's number goes on every
153    /// message to it (`MasterClock.heard_sequence`). One count per stream, so a replaced
154    /// stream's reader can't put its numbers on the new one's messages.
155    heard: Counters,
156}
157
158/// Another master took the lease over: this one's view is stale, and it must end.
159#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
160#[error("another master took the lease over: this one stops (restarted, it waits as a standby)")]
161pub struct LeaseLost;
162
163/// What woke the master's loop.
164enum Wake {
165    Stop,
166    Tick,
167    Command,
168    Finished,
169    RoundDue,
170    NotificationsFailed(DbError),
171    Alive,
172    Refresh,
173    LeaseLost,
174    ListenAgain,
175}
176
177impl Hub {
178    /// A hub over `core`, with the system clock.
179    #[must_use]
180    pub fn new(core: MasterCore) -> Self {
181        Self::with_clock(
182            core.with_steady(crate::clock::monotonic)
183                .with_wall(Timestamp::now),
184            Timestamp::now,
185        )
186    }
187
188    /// A hub over `core` with another clock (tests).
189    #[must_use]
190    pub fn with_clock(core: MasterCore, clock: fn() -> Timestamp) -> Self {
191        let core_steady = core.steady_clock();
192        Self {
193            beat: Beat::default(),
194            refresh_limit: DEFAULT_REFRESH_LIMIT,
195            max_message_size: core.settings().max_message_size,
196            messages_per_turn: core.settings().messages_per_turn.max(1),
197            alone_per_turn: core.settings().failed_group_messages_per_turn.max(1),
198            stream_buffer: core.settings().worker_stream_buffer.max(1),
199            timings: core.settings().timings,
200            metrics: core.metrics().clone(),
201            db: core.db().clone(),
202            arrivals: core.arrivals(),
203            leading: Arc::new(watch::Sender::new(true)),
204            finished: Arc::new(tokio::sync::Notify::new()),
205            // The dispatcher's: a trigger's state changing in memory wakes the loop too.
206            triggers_due: core.dispatcher().trigger_wake(),
207            triggers_failed: Arc::default(),
208            problems: Problems::default(),
209            listen_retry: None,
210            core: Arc::new(Mutex::new(core)),
211            streams: Arc::new(Mutex::new(BTreeMap::new())),
212            closing: Arc::new(watch::channel(false).0),
213            steady: core_steady,
214            epoch: 0,
215            heard: Arc::default(),
216            clock,
217        }
218    }
219
220    /// The hub trying to listen for commands again every `period` while its loop runs without
221    /// notifications (starting them failed: the database too slow to check for a pooler, or
222    /// unreachable), polling meanwhile; it stops trying once they start, or once they are found
223    /// off or behind a pooler.
224    #[must_use]
225    pub const fn with_listen_retry(mut self, period: Duration) -> Self {
226        self.listen_retry = Some(period);
227        self
228    }
229
230    /// The hub stamping `epoch`, its lease's, on every message (decision 444).
231    #[must_use]
232    pub const fn with_epoch(mut self, epoch: i64) -> Self {
233        self.epoch = epoch;
234        self
235    }
236
237    /// The hub reporting its problems to `problems` (its heartbeat writes them).
238    #[must_use]
239    pub fn with_problems(mut self, problems: Problems) -> Self {
240        self.problems = problems;
241        self
242    }
243
244    /// The hub abandoning a gauge refresh that takes longer than `limit` (it only reads, so
245    /// abandoning it is safe; a tick is never abandoned: see archive/PROJECT.md, Observability).
246    #[must_use]
247    pub const fn with_refresh_limit(mut self, limit: Duration) -> Self {
248        self.refresh_limit = limit;
249        self
250    }
251
252    /// Whether this master leads: false while paused (its lease not renewed) or after another
253    /// took it over; readiness follows it (B165).
254    #[must_use]
255    pub fn leading(&self) -> watch::Receiver<bool> {
256        self.leading.subscribe()
257    }
258
259    /// When the loop last turned: every tick, and at least every [`ALIVE_INTERVAL`] while it
260    /// waits, never while a tick is stuck.
261    #[must_use]
262    pub fn beat(&self) -> Beat {
263        self.beat.clone()
264    }
265
266    /// Records whether this master leads, telling the waiting worker messages and the log
267    /// when that changes.
268    fn set_leading(&self, leads: bool) {
269        let changed = self.leading.send_if_modified(|leading| {
270            let changed = *leading != leads;
271            *leading = leads;
272            changed
273        });
274        self.metrics.leading.set(i64::from(leads));
275        if changed && leads {
276            tracing::info!("the master's lease is renewed: leading again");
277            self.problems.clear(ProblemKind::Lease);
278        } else if changed {
279            tracing::warn!("the master's lease isn't renewed in time: pausing until it is");
280            self.problems.set(
281                ProblemKind::Lease,
282                false,
283                "its lease isn't renewed in time: paused until it is",
284            );
285        }
286    }
287
288    /// Waits until this master leads (at once when it does).
289    async fn while_leading(&self) {
290        let mut leading = self.leading.subscribe();
291        let _ = leading.wait_for(|leads| *leads).await;
292    }
293
294    /// Waits while this master doesn't lead, as [`Self::while_leading`]; false when it closes
295    /// its streams first (it stops): a call waiting would hold tonic's graceful shutdown
296    /// (B219's review).
297    async fn leading_unless_closing(&self) -> bool {
298        let mut closing = self.closing.subscribe();
299        tokio::select! {
300            () = self.while_leading() => true,
301            _ = closing.wait_for(|closing| *closing) => false,
302        }
303    }
304
305    /// Delivers the outbox through `sender` while this master leads (decision 410): a pass
306    /// every `poll`, at once again after a full one, until `stop` completes. A failing pass is
307    /// logged; the next one goes on.
308    pub async fn run_sender(
309        &self,
310        sender: crate::notifications::sender::Sender,
311        poll: Duration,
312        stop: impl Future<Output = ()>,
313    ) {
314        tokio::pin!(stop);
315        loop {
316            tokio::select! {
317                () = &mut stop => return,
318                () = self.while_leading() => {}
319            }
320            // Housekeeping: nothing a trigger depends on (decision 486).
321            let full = match self
322                .db
323                .quietly(sender.pass((self.clock)(), || *self.leading.borrow()))
324                .await
325            {
326                Ok(pass) => {
327                    pass.sent + pass.retried + pass.dropped
328                        >= crate::notifications::sender::BATCH as usize
329                }
330                Err(error) => {
331                    tracing::warn!(%error, "can't deliver notifications; trying again");
332                    false
333                }
334            };
335            if full {
336                continue;
337            }
338            tokio::select! {
339                () = &mut stop => return,
340                () = tokio::time::sleep(poll) => {}
341            }
342        }
343    }
344
345    /// Deletes what `[retention]` no longer keeps while this master leads (decisions
346    /// 430-435): a pass at once, then one every `settings.interval`, until `stop` completes. A
347    /// failing pass is logged; the next one goes on.
348    pub async fn run_retention(
349        &self,
350        settings: crate::retention::RetentionSettings,
351        stop: impl Future<Output = ()>,
352    ) {
353        let nothing = crate::retention::RetentionSettings {
354            interval: settings.interval,
355            batch: settings.batch,
356            ..Default::default()
357        };
358        if settings == nothing {
359            return;
360        }
361        tokio::pin!(stop);
362        loop {
363            tokio::select! {
364                () = &mut stop => return,
365                () = self.while_leading() => {}
366            }
367            let leading = || *self.leading.borrow();
368            // Housekeeping: what it deletes is past anything a trigger waits for (decision 486).
369            match self
370                .db
371                .quietly(crate::retention::pass(
372                    &self.db,
373                    &settings,
374                    (self.clock)(),
375                    leading,
376                    &self.metrics,
377                ))
378                .await
379            {
380                Ok(pass) if pass.any() => tracing::info!(
381                    runs = pass.runs,
382                    outputs = pass.outputs,
383                    events = pass.events,
384                    commands = pass.commands,
385                    dags = pass.dags,
386                    versions = pass.versions,
387                    "retention deleted what [retention] no longer keeps"
388                ),
389                Ok(_) => {}
390                Err(error) => {
391                    tracing::warn!(%error, "retention failed; trying again at its next pass");
392                }
393            }
394            tokio::select! {
395                () = &mut stop => return,
396                () = tokio::time::sleep(settings.interval) => {}
397            }
398        }
399    }
400
401    /// Samples each process a minute while this master leads (decision 464): its masters and
402    /// workers, one row per process (`process_id`, this master's own, gets its webserver role
403    /// with `with_webserver`), the rollups and deletes once a window closes, until `stop`
404    /// completes. A failing pass is logged; the next one goes on.
405    pub async fn run_samples(
406        &self,
407        settings: crate::samples::SampleSettings,
408        (process_id, with_webserver): (String, bool),
409        stop: impl Future<Output = ()>,
410    ) {
411        tokio::pin!(stop);
412        let mut sampler = crate::samples::Sampler::default();
413        let also_runs: std::collections::BTreeMap<String, String> = if with_webserver {
414            std::collections::BTreeMap::from([("webserver".to_owned(), process_id.clone())])
415        } else {
416            std::collections::BTreeMap::new()
417        };
418        loop {
419            tokio::select! {
420                () = &mut stop => return,
421                () = self.while_leading() => {}
422            }
423            let own = (!also_runs.is_empty()).then_some((process_id.as_str(), &also_runs));
424            // Housekeeping: nothing a trigger depends on (decision 486).
425            if let Err(error) = self
426                .db
427                .quietly(sampler.pass(&self.db, &settings, (self.clock)(), own))
428                .await
429            {
430                tracing::warn!(%error, "sampling the processes failed; trying again in a minute");
431            }
432            tokio::select! {
433                () = &mut stop => return,
434                () = tokio::time::sleep(settings.interval) => {}
435            }
436        }
437    }
438
439    /// Refreshes the gauges taken from the database; a failure is logged (the gauges keep
440    /// their last values).
441    pub async fn refresh_gauges(&self) {
442        match tokio::time::timeout(self.refresh_limit, self.db.state_counts()).await {
443            Ok(Ok(counts)) => self.metrics.set_counts(&counts),
444            Ok(Err(error)) => tracing::warn!(%error, "can't count runs, tasks and workers"),
445            Err(_) => tracing::warn!("counting runs, tasks and workers took too long; abandoned"),
446        }
447    }
448
449    /// The core, for status and tests.
450    #[must_use]
451    pub fn core(&self) -> Arc<Mutex<MasterCore>> {
452        Arc::clone(&self.core)
453    }
454
455    /// The gRPC service for a tonic server.
456    #[must_use]
457    pub fn service(&self) -> MasterServer<Self> {
458        MasterServer::new(self.clone()).max_decoding_message_size(self.max_message_size)
459    }
460
461    /// The core's lock, the wait for it recorded by who asked (`by`: M5.1a's profile).
462    async fn core_for(&self, by: &str) -> tokio::sync::MutexGuard<'_, MasterCore> {
463        let asked = std::time::Instant::now();
464        let core = self.core.lock().await;
465        self.metrics.core_lock_waited(by, asked.elapsed());
466        core
467    }
468
469    /// Reads the worker registry back (see [`MasterCore::restore`]) at the hub's clock, the
470    /// one its lease checks use.
471    ///
472    /// # Errors
473    ///
474    /// The core's failure.
475    pub async fn restore(&self) -> Result<usize, CoreError> {
476        let now = (self.clock)();
477        self.core_for("restore").await.restore(now).await
478    }
479
480    /// One tick of the master's loop, its messages delivered; its probe looks no time ahead.
481    ///
482    /// # Errors
483    ///
484    /// The core's failure (the next tick goes on).
485    pub async fn tick(&self) -> Result<(), CoreError> {
486        self.tick_ahead(Duration::ZERO).await
487    }
488
489    /// As [`Self::tick`], its probe looking `ahead` (the loop's tick interval: what comes due
490    /// before the next tick is found, so the round's parts share one probe, decision 485).
491    ///
492    /// # Errors
493    ///
494    /// The core's failure (the next tick goes on).
495    pub async fn tick_ahead(&self, ahead: Duration) -> Result<(), CoreError> {
496        // The lock taken for each part on its own, so a worker's turn gets in between them
497        // (decision 469), each part at the time it runs. What a part built before a failure is
498        // delivered too (B7); a failed part ends the round, as before. The round's reads the
499        // probe finds empty are skipped (decision 485): an idle tick is one statement.
500        Box::pin(self.db.in_round((self.clock)(), ahead, async {
501            // The trigger pass is the trigger loop's (decision 486): woken when a trigger's
502            // stored moment has come, or its last pass failed.
503            if self
504                .triggers_failed
505                .swap(false, std::sync::atomic::Ordering::SeqCst)
506                || !self
507                    .db
508                    .skipped_at(schedr_db::probe::Check::TriggersDue, (self.clock)())
509                    .await?
510            {
511                self.triggers_due.notify_one();
512            }
513            for part in RoundPart::ALL {
514                if part == RoundPart::Triggers {
515                    continue;
516                }
517                if part == RoundPart::Commands {
518                    self.commands().await?;
519                    continue;
520                }
521                let mut outgoing = Vec::new();
522                let result = self
523                    .core_for("round")
524                    .await
525                    .round_part(part, (self.clock)(), &mut outgoing)
526                    .await;
527                self.deliver(outgoing).await;
528                result?;
529            }
530            Ok(())
531        }))
532        .await
533    }
534
535    /// The round's commands part, the core's lock taken for each command on its own (decision
536    /// 483): each command is one transaction, so a worker's turn waits for one at most. Timed
537    /// as the part's time under the lock.
538    async fn commands(&self) -> Result<(), CoreError> {
539        let mut held = std::time::Duration::ZERO;
540        let mut outgoing = Vec::new();
541        let pending = {
542            let mut core = self.core_for("round").await;
543            let began = std::time::Instant::now();
544            let pending = core.commands_to_apply(&mut outgoing, (self.clock)()).await;
545            held += began.elapsed();
546            pending
547        };
548        self.deliver(std::mem::take(&mut outgoing)).await;
549        let mut failed = Ok(());
550        for command in pending? {
551            let applied = {
552                let mut core = self.core_for("round").await;
553                let began = std::time::Instant::now();
554                let applied = core
555                    .apply_command(command, &mut outgoing, (self.clock)())
556                    .await;
557                held += began.elapsed();
558                applied
559            };
560            self.deliver(std::mem::take(&mut outgoing)).await;
561            if applied.is_err() {
562                failed = applied;
563                break;
564            }
565        }
566        {
567            let mut core = self.core_for("round").await;
568            let began = std::time::Instant::now();
569            core.commands_done(&mut outgoing, (self.clock)()).await;
570            held += began.elapsed();
571        }
572        self.deliver(outgoing).await;
573        self.metrics
574            .round_part_done(RoundPart::Commands.name(), held);
575        failed
576    }
577
578    /// Runs the master's loop: a tick every `interval` until `stop` completes, and at once when
579    /// a new command is announced (`notifications`, Postgres; notifications that arrived
580    /// meanwhile are taken by the same tick, and the tick interval starts again after it). A
581    /// failing tick is logged; the next one goes on. When notifications fail (the database is
582    /// unreachable), they are tried again after [`NOTIFICATION_RETRY`]; polling goes on.
583    pub async fn run(
584        &self,
585        interval: Duration,
586        notifications: Option<CommandNotifications>,
587        stop: impl Future<Output = ()>,
588    ) {
589        let _ = self.run_with(interval, notifications, None, stop).await;
590    }
591
592    /// As [`Self::run`], leading by `leadership`'s lease (see [`crate::lease`]): renewed every
593    /// third of its period by a task of its own (a long round doesn't hold renewals up); while
594    /// it isn't fresh enough the master pauses (no rounds, worker messages wait) and resumes
595    /// once renewed; it is given up when `stop` completes. The hub's core must write through
596    /// [`Leadership::fenced_db`].
597    ///
598    /// # Errors
599    ///
600    /// [`LeaseLost`] when another master took it over.
601    pub async fn run_leading(
602        &self,
603        interval: Duration,
604        notifications: Option<CommandNotifications>,
605        leadership: Leadership,
606        stop: impl Future<Output = ()>,
607    ) -> Result<(), LeaseLost> {
608        self.run_with(interval, notifications, Some(leadership), stop)
609            .await
610    }
611
612    /// Tries to listen for commands again: `Some` once decided (listening, or found off or
613    /// behind a pooler), `None` to try later.
614    async fn listen_again(&self) -> Option<Option<CommandNotifications>> {
615        match self.db.command_notifications().await {
616            Ok(started) => {
617                if started.is_some() {
618                    tracing::info!("listening for commands now");
619                }
620                self.problems.clear(ProblemKind::Notifications);
621                Some(started)
622            }
623            Err(error) => {
624                tracing::warn!(
625                    %error,
626                    "still can't listen for commands; polling, trying again in {} min",
627                    self.listen_retry.unwrap_or_default().as_secs() / 60
628                );
629                None
630            }
631        }
632    }
633
634    /// Command notifications failed with `error`: logged and reported as a problem; until
635    /// the moment returned, the master polls.
636    fn notifications_failed(&self, error: &DbError) -> tokio::time::Instant {
637        tracing::warn!(
638            %error,
639            "command notifications failed; polling, trying again in {}s",
640            self.timings.notification_retry.as_secs()
641        );
642        self.problems.set(
643            ProblemKind::Notifications,
644            false,
645            format!("its command notifications failed ({error}): polling"),
646        );
647        tokio::time::Instant::now() + self.timings.notification_retry
648    }
649
650    async fn run_with(
651        &self,
652        interval: Duration,
653        mut notifications: Option<CommandNotifications>,
654        leadership: Option<Leadership>,
655        stop: impl Future<Output = ()>,
656    ) -> Result<(), LeaseLost> {
657        let (release, released) = tokio::sync::oneshot::channel();
658        let mut keeper = leadership.map(|leadership| {
659            self.set_leading(leadership.leads(std::time::Instant::now()));
660            let hub = self.clone();
661            // The lease's writes are housekeeping (decision 486).
662            tokio::spawn(async move {
663                let db = hub.db.clone();
664                db.quietly(hub.keep_leading(leadership, released)).await;
665            })
666        });
667        // Ends with this loop, however it returns.
668        let _triggers = self.start_triggers();
669        let mut ticks = tokio::time::interval(interval);
670        ticks.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
671        let mut alive = tokio::time::interval(self.timings.alive);
672        let mut refresh = tokio::time::interval(self.timings.gauge_refresh);
673        refresh.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
674        let mut paused_until: Option<tokio::time::Instant> = None;
675        let mut last_round: Option<tokio::time::Instant> = None;
676        // A round finished tasks asked for, held back by the gap after the last one: waited for
677        // here, so a stop or a lost lease doesn't wait for it.
678        let mut round_due: Option<tokio::time::Instant> = None;
679        let mut listen_again = self
680            .listen_retry
681            .filter(|_| notifications.is_none())
682            .map(|period| tokio::time::interval_at(tokio::time::Instant::now() + period, period));
683        tokio::pin!(stop);
684        loop {
685            let wake = tokio::select! {
686                () = &mut stop => Wake::Stop,
687                _ = ticks.tick() => Wake::Tick,
688                () = self.finished.notified() => Wake::Finished,
689                () = async { tokio::time::sleep_until(round_due.expect("guarded")).await },
690                    if round_due.is_some() => Wake::RoundDue,
691                listened = next_command(
692                    notifications.as_mut(), &mut paused_until, &self.problems, &self.triggers_due,
693                ) => {
694                    match listened {
695                        Listened::Command => Wake::Command,
696                        Listened::Failed(error) => Wake::NotificationsFailed(error),
697                    }
698                }
699                _ = alive.tick() => Wake::Alive,
700                _ = refresh.tick() => Wake::Refresh,
701                _ = async { keeper.as_mut().expect("guarded").await }, if keeper.is_some() => {
702                    Wake::LeaseLost
703                }
704                _ = async { listen_again.as_mut().expect("guarded").tick().await },
705                    if listen_again.is_some() => Wake::ListenAgain,
706            };
707            self.beat.beat();
708            let leads = *self.leading.borrow();
709            match wake {
710                Wake::Stop => {
711                    let _ = release.send(());
712                    if let Some(keeper) = keeper {
713                        // It gives the lease up.
714                        let _ = keeper.await;
715                    }
716                    return Ok(());
717                }
718                Wake::LeaseLost => return Err(LeaseLost),
719                Wake::Alive => continue,
720                Wake::ListenAgain => {
721                    if let Some(started) = self.listen_again().await {
722                        notifications = started;
723                        listen_again = None;
724                    }
725                    continue;
726                }
727                // Paused: no rounds until the lease is renewed.
728                Wake::Tick | Wake::Command | Wake::Finished | Wake::RoundDue if !leads => {
729                    round_due = None;
730                    continue;
731                }
732                Wake::Refresh => {
733                    self.refresh_gauges().await;
734                    continue;
735                }
736                Wake::Command => {
737                    paused_until = None;
738                    self.command_announced(notifications.as_mut()).await;
739                    ticks.reset();
740                }
741                Wake::NotificationsFailed(error) => {
742                    paused_until = Some(self.notifications_failed(&error));
743                    continue;
744                }
745                Wake::Finished => {
746                    // At most one round every ROUND_GAP: under a stream of finishes each
747                    // round takes what arrived meanwhile, and the lease's renewals and the
748                    // workers' messages get their turns.
749                    let due = last_round.map(|ended| ended + self.timings.round_gap);
750                    if let Some(due) = due.filter(|due| *due > tokio::time::Instant::now()) {
751                        round_due = Some(due);
752                        continue;
753                    }
754                    ticks.reset();
755                }
756                Wake::RoundDue => ticks.reset(),
757                Wake::Tick => {}
758            }
759            self.timed_tick(interval).await;
760            round_due = None;
761            last_round = Some(tokio::time::Instant::now());
762        }
763    }
764
765    /// A command was announced: notifications work again, and those already arrived are taken
766    /// with it (one round for a burst); an event among them wakes the trigger loop.
767    async fn command_announced(&self, notifications: Option<&mut CommandNotifications>) {
768        self.problems.clear(ProblemKind::Notifications);
769        if let Some(notifications) = notifications
770            && notifications.skip_arrived().await
771        {
772            self.triggers_due.notify_one();
773        }
774    }
775
776    /// Starts the trigger loop beside the master's loop: it stops when what this returns is
777    /// dropped.
778    fn start_triggers(&self) -> impl Drop {
779        let (stop, stopped) = watch::channel(false);
780        let hub = self.clone();
781        let task = tokio::spawn(async move { Box::pin(hub.run_triggers(stopped)).await });
782        scopeguard_stop(stop, task)
783    }
784
785    /// The trigger loop (decisions 485 and 486): the trigger pass at once, then again whenever
786    /// a write ended elsewhere in this process, a trigger's stored moment came (the tick's
787    /// probe) or a named event was announced, at most once every [`ROUND_GAP`] and only while
788    /// this master leads, until `stop` turns true. A pass is skipped by one `EXISTS` when no
789    /// trigger it looks after is switched on or running; its own writes wake nothing of it, and
790    /// a pass that wrote (a run queued) wakes the round, as a recorded `Finished` does.
791    async fn run_triggers(&self, mut stop: watch::Receiver<bool>) {
792        let mut last: Option<tokio::time::Instant> = None;
793        loop {
794            if let Some(last) = last {
795                tokio::select! {
796                    _ = stop.changed() => return,
797                    () = tokio::time::sleep_until(last + self.timings.round_gap) => {}
798                }
799            }
800            if *stop.borrow() {
801                return;
802            }
803            if *self.leading.borrow() {
804                Box::pin(self.trigger_pass()).await;
805                last = Some(tokio::time::Instant::now());
806            }
807            loop {
808                tokio::select! {
809                    _ = stop.changed() => return,
810                    () = self.db.changed() => break,
811                    () = self.triggers_due.notified() => break,
812                    // Steps a post in this process woke are the round's (decision 487): no
813                    // pass for them.
814                    () = self.db.waits_due() => self.finished.notify_one(),
815                    // Leading again after a pause: what changed meanwhile is looked at.
816                    () = async {
817                        let mut leading = self.leading.subscribe();
818                        let _ = leading.wait_for(|leads| *leads).await;
819                    }, if !*self.leading.borrow() => break,
820                }
821            }
822        }
823    }
824
825    /// One pass of the trigger loop, its messages delivered.
826    async fn trigger_pass(&self) {
827        let now = (self.clock)();
828        match self.db.exists(schedr_db::probe::Check::Triggers, now).await {
829            Ok(false) => return,
830            Ok(true) => {}
831            Err(error) => {
832                tracing::warn!(%error, "the trigger pass failed; trying again at the next tick");
833                self.triggers_failed
834                    .store(true, std::sync::atomic::Ordering::SeqCst);
835                return;
836            }
837        }
838        let before = self.db.writes_ended();
839        let mut outgoing = Vec::new();
840        let result = self
841            .db
842            .quietly(async {
843                Box::pin(self.core_for("triggers").await.round_part(
844                    RoundPart::Triggers,
845                    (self.clock)(),
846                    &mut outgoing,
847                ))
848                .await
849            })
850            .await;
851        self.deliver(outgoing).await;
852        if self.db.writes_ended() != before {
853            // A run queued, a trigger started or stopped: the round starts what it can.
854            self.finished.notify_one();
855        }
856        if let Err(error) = result {
857            tracing::warn!(%error, "the trigger pass failed; trying again at the next tick");
858            self.triggers_failed
859                .store(true, std::sync::atomic::Ordering::SeqCst);
860        }
861    }
862
863    /// A round, its duration observed.
864    async fn timed_tick(&self, ahead: Duration) {
865        let started = std::time::Instant::now();
866        match self.tick_ahead(ahead).await {
867            Ok(()) => self.problems.clear(ProblemKind::Round),
868            Err(error) => {
869                tracing::error!(%error, "master tick failed");
870                self.problems
871                    .set(ProblemKind::Round, true, format!("a round failed: {error}"));
872            }
873        }
874        self.metrics
875            .tick_duration
876            .observe(started.elapsed().as_secs_f64());
877    }
878
879    /// Renews `leadership` every third of its period, pausing the master when its last
880    /// renewal is no longer recent enough and resuming it when renewed, until another master
881    /// took the lease over (returned then) or `give_up` (the lease given up, a standby takes
882    /// over at once).
883    async fn keep_leading(
884        &self,
885        mut leadership: Leadership,
886        mut give_up: tokio::sync::oneshot::Receiver<()>,
887    ) {
888        let mut renew = tokio::time::interval(leadership.period() / 3);
889        renew.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
890        renew.reset();
891        loop {
892            let until = tokio::time::Instant::from_std(leadership.until());
893            let leading = *self.leading.borrow();
894            tokio::select! {
895                biased;
896                _ = &mut give_up => {
897                    leadership.release().await;
898                    // Not leading from now on: a stream offered while stopping is refused, and
899                    // no heartbeat is answered (B200).
900                    self.set_leading(false);
901                    return;
902                }
903                _ = renew.tick() => {
904                    if leadership.renew(std::time::Instant::now()).await == Renewal::TakenOver {
905                        self.set_leading(false);
906                        tracing::error!("{LeaseLost}");
907                        return;
908                    }
909                }
910                () = tokio::time::sleep_until(until), if leading => {}
911            }
912            self.set_leading(leadership.leads(std::time::Instant::now()));
913        }
914    }
915
916    /// Sends messages to their workers' streams; one for a worker without a live stream is
917    /// dropped (an assignment then recorded as never sent, so it is taken back without a retry
918    /// once the worker registers again or is lost; a cancel is sent again when the worker
919    /// comes back and reports the attempt in its journal).
920    ///
921    /// A send never waits: a worker [`STREAM_BUFFER`] messages behind has stopped reading.
922    /// Its stream is dropped and the worker disconnected, so it registers again and its
923    /// journal is reconciled; it never holds up the master's rounds, registrations or other
924    /// workers' messages, nor its messages pile up.
925    ///
926    /// Each is stamped with the master's clock as it is sent (B225).
927    async fn deliver(&self, outgoing: Vec<Outgoing>) {
928        let mut stuck = Vec::new();
929        let mut streams = self.streams.lock().await;
930        for Outgoing {
931            worker_id,
932            mut message,
933        } in outgoing
934        {
935            let assigned = match &message.message {
936                Some(master_message::Message::AssignTask(assign)) => {
937                    Some(assign.attempt_id.clone())
938                }
939                _ => None,
940            };
941            // An assignment that doesn't leave never started there (Grok's review of B240).
942            let unsent = |attempt: Option<&String>| {
943                if let Some(attempt_id) = attempt {
944                    self.arrivals.unsent(&worker_id, attempt_id);
945                }
946            };
947            let Some(stream) = streams.get(&worker_id) else {
948                tracing::warn!(worker_id, "no stream for worker; message dropped");
949                unsent(assigned.as_ref());
950                continue;
951            };
952            message.clock = Some(self.stamp(self.heard_on(&worker_id)));
953            match stream.send(message) {
954                Ok(number) => {
955                    if let Some(attempt_id) = assigned {
956                        self.arrivals
957                            .assigned(&worker_id, stream.id, &attempt_id, number);
958                    }
959                }
960                Err(mpsc::error::TrySendError::Full(())) => {
961                    unsent(assigned.as_ref());
962                    tracing::error!(
963                        worker_id,
964                        "worker doesn't read its stream ({} messages waiting): \
965                         disconnected",
966                        self.stream_buffer
967                    );
968                    streams.remove(&worker_id);
969                    stuck.push(worker_id);
970                }
971                Err(mpsc::error::TrySendError::Closed(())) => {
972                    unsent(assigned.as_ref());
973                    tracing::warn!(worker_id, "worker stream closed; message dropped");
974                }
975            }
976        }
977        drop(streams);
978        for worker_id in stuck {
979            // Not here: the caller may hold the core's lock.
980            tokio::spawn(self.clone().disconnect_stuck(worker_id));
981        }
982    }
983
984    /// The master's clock to stamp on a message (B225), `heard` the latest heartbeat heard on
985    /// the worker's stream.
986    fn stamp(&self, heard: u64) -> pb::MasterClock {
987        stamp_of((self.clock, self.steady), heard, self.epoch)
988    }
989
990    /// The latest heartbeat heard on `worker_id`'s current stream (0: none yet, or no stream).
991    fn heard_on(&self, worker_id: &str) -> u64 {
992        lock_heard(&self.heard)
993            .get(worker_id)
994            .map_or(0, |heard| heard.load(Ordering::SeqCst))
995    }
996
997    /// Disconnects a worker whose stream was dropped for not being read, unless it has
998    /// registered again since. (Its stream's reader stops at its next message, which ends
999    /// the worker's side.)
1000    async fn disconnect_stuck(self, worker_id: String) {
1001        let mut core = self.core_for("stream").await;
1002        if self.streams.lock().await.contains_key(&worker_id) {
1003            return;
1004        }
1005        if let Err(error) = core.disconnected(&worker_id, (self.clock)()).await {
1006            tracing::error!(worker_id, %error, "worker disconnect not recorded");
1007        }
1008    }
1009
1010    /// A worker's message handled; a task's API call checked here and run outside the lock (a
1011    /// request may take a while; M4.11h), its answer delivered when it comes.
1012    async fn handle(
1013        &self,
1014        core: &mut MasterCore,
1015        worker_id: &str,
1016        message: worker_message::Message,
1017    ) -> Result<Vec<Outgoing>, CoreError> {
1018        let worker_message::Message::ApiCall(call) = message else {
1019            return core.handle(worker_id, message, (self.clock)()).await;
1020        };
1021        match core.plan_api_call(worker_id, call, (self.clock)()).await? {
1022            ApiCallPlan::Answered(answer) => Ok(vec![*answer]),
1023            ApiCallPlan::Run(job) => {
1024                let hub = self.clone();
1025                tokio::spawn(async move {
1026                    let answer = job.run().await;
1027                    hub.deliver(vec![answer]).await;
1028                });
1029                Ok(Vec::new())
1030            }
1031        }
1032    }
1033
1034    /// The worker's next message, once this master leads (not while paused: another master
1035    /// may be leading), unless the master closes its streams first.
1036    async fn next_to_handle(
1037        &self,
1038        queued: &mut mpsc::UnboundedReceiver<worker_message::Message>,
1039        closing: &mut watch::Receiver<bool>,
1040    ) -> Next {
1041        let next = async {
1042            let Some(message) = queued.recv().await else {
1043                return Next::Ended;
1044            };
1045            self.while_leading().await;
1046            Next::Message(Box::new(message))
1047        };
1048        tokio::select! {
1049            next = next => next,
1050            _ = closing.wait_for(|closing| *closing) => Next::Closing,
1051        }
1052    }
1053
1054    /// One turn of a worker's messages (M4B.3, decision 397): its `Started`s and `Finished`s as
1055    /// one group, stored together, heartbeats and warnings after it; any other message ends the
1056    /// group (it is stored first) and is handled alone. A group that fails is redone one by one,
1057    /// [`ALONE_PER_TURN`] now and the rest first in the next turn, with what this turn hadn't
1058    /// reached. The core's lock is taken for each transaction on its own (the `Started` group,
1059    /// the `Finished` group, each message alone) and its stream checked again each time, so
1060    /// rounds and other workers' turns get in between (decision 480); what each sends goes out
1061    /// at once.
1062    async fn turn(
1063        &self,
1064        (worker_id, stream): (&str, &Outbound),
1065        turn: Vec<Turned>,
1066        carried: &mut VecDeque<Turned>,
1067    ) -> TurnEnd {
1068        let mut group = Group::default();
1069        let mut after = Vec::new();
1070        let mut messages = turn.into_iter();
1071        let mut barrier = None;
1072        loop {
1073            let next = messages.next();
1074            match next {
1075                Some(Turned::Grouped(worker_message::Message::Started(started))) => {
1076                    group.started.push(started);
1077                    continue;
1078                }
1079                Some(Turned::Grouped(worker_message::Message::Finished(finished))) => {
1080                    group.finished.push(finished);
1081                    continue;
1082                }
1083                Some(Turned::Grouped(
1084                    message @ (worker_message::Message::Heartbeat(_)
1085                    | worker_message::Message::Warnings(_)),
1086                )) => {
1087                    after.push(message);
1088                    continue;
1089                }
1090                Some(Turned::Grouped(message) | Turned::Alone(message)) => barrier = Some(message),
1091                None => {}
1092            }
1093            // The groups so far (`Started`s, then `Finished`s: each kind its own transaction,
1094            // decision 397), then what waited for them, then the barrier.
1095            let results = Group {
1096                started: Vec::new(),
1097                finished: std::mem::take(&mut group.finished),
1098            };
1099            let mut kinds = VecDeque::from([std::mem::take(&mut group), results]);
1100            while let Some(kind) = kinds.pop_front() {
1101                if kind.is_empty() {
1102                    continue;
1103                }
1104                let wakes = !kind.finished.is_empty();
1105                let (part, count) = if kind.started.is_empty() {
1106                    ("finished", kind.finished.len())
1107                } else {
1108                    ("started", kind.started.len())
1109                };
1110                let Some(mut core) = self.served_core(worker_id, stream).await else {
1111                    return TurnEnd::Dropped;
1112                };
1113                let began = std::time::Instant::now();
1114                let handled = core.handle_group(worker_id, kind, (self.clock)()).await;
1115                self.metrics.turn_part_done(part, count, began.elapsed());
1116                drop(core);
1117                match handled {
1118                    Ok(out) => self.sent(out, wakes).await,
1119                    Err(failed) => {
1120                        let mut failed = failed.into_messages().into_iter();
1121                        for message in failed.by_ref().take(self.alone_per_turn) {
1122                            let (end, _) = self.alone_served(worker_id, stream, message).await;
1123                            if !matches!(end, TurnEnd::Goes) {
1124                                return end;
1125                            }
1126                        }
1127                        // The rest in order: a `Finished` never stored before its `Started`.
1128                        carried.extend(failed.map(Turned::Alone));
1129                        carried.extend(
1130                            kinds
1131                                .into_iter()
1132                                .flat_map(Group::into_messages)
1133                                .map(Turned::Grouped),
1134                        );
1135                        carried.extend(after.drain(..).map(Turned::Grouped));
1136                        carried.extend(barrier.take().map(Turned::Alone));
1137                        carried.extend(messages);
1138                        return TurnEnd::Goes;
1139                    }
1140                }
1141            }
1142            let rest = after.len() + usize::from(barrier.is_some());
1143            let mut held = std::time::Duration::ZERO;
1144            for message in after.drain(..) {
1145                let (end, took) = self.alone_served(worker_id, stream, message).await;
1146                held += took;
1147                if !matches!(end, TurnEnd::Goes) {
1148                    self.metrics.turn_part_done("rest", rest, held);
1149                    return end;
1150                }
1151            }
1152            let end = match barrier.take() {
1153                Some(message) => {
1154                    let (end, took) = self.alone_served(worker_id, stream, message).await;
1155                    held += took;
1156                    Some(end)
1157                }
1158                None => None,
1159            };
1160            if rest > 0 {
1161                self.metrics.turn_part_done("rest", rest, held);
1162            }
1163            match end {
1164                // The barrier handled: on to the messages after it.
1165                Some(TurnEnd::Goes) => {}
1166                Some(end) => return end,
1167                None => return TurnEnd::Goes,
1168            }
1169        }
1170    }
1171
1172    /// The core, locked, if `stream` still carries its worker's messages (see
1173    /// [`Self::still_served`]); none when it doesn't, and the stream is let go.
1174    async fn served_core(
1175        &self,
1176        worker_id: &str,
1177        stream: &Outbound,
1178    ) -> Option<tokio::sync::MutexGuard<'_, MasterCore>> {
1179        let core = self.core_for("turn").await;
1180        self.still_served(&core, worker_id, stream)
1181            .await
1182            .then_some(core)
1183    }
1184
1185    /// `message` handled alone, under the core's lock taken for it ([`Self::alone`]), what it
1186    /// sends delivered after the lock is let go; with how long the lock was held.
1187    async fn alone_served(
1188        &self,
1189        worker_id: &str,
1190        stream: &Outbound,
1191        message: worker_message::Message,
1192    ) -> (TurnEnd, std::time::Duration) {
1193        let Some(mut core) = self.served_core(worker_id, stream).await else {
1194            return (TurnEnd::Dropped, std::time::Duration::ZERO);
1195        };
1196        let began = std::time::Instant::now();
1197        let mut done = TurnDone::default();
1198        let goes_on = self.alone(&mut core, worker_id, message, &mut done).await;
1199        let took = began.elapsed();
1200        drop(core);
1201        self.sent(done.outgoing, done.finished).await;
1202        let end = if goes_on && !done.unhandled {
1203            TurnEnd::Goes
1204        } else {
1205            TurnEnd::Unhandled
1206        };
1207        (end, took)
1208    }
1209
1210    /// Delivers what a transaction of a turn sends, waking a round if it stored a `Finished`.
1211    async fn sent(&self, outgoing: Vec<Outgoing>, finished: bool) {
1212        if finished {
1213            self.finished.notify_one();
1214        }
1215        self.deliver(outgoing).await;
1216    }
1217
1218    /// One message handled on its own, as every message was before M4B.3; whether the turn
1219    /// goes on (not: the stream ends).
1220    async fn alone(
1221        &self,
1222        core: &mut MasterCore,
1223        worker_id: &str,
1224        message: worker_message::Message,
1225        done: &mut TurnDone,
1226    ) -> bool {
1227        let is_finished = matches!(message, worker_message::Message::Finished(_));
1228        match self.handle(core, worker_id, message).await {
1229            // A round wakes for a `Finished` recorded, not one dropped or whose handling ended
1230            // the stream (B191, decision 42).
1231            Ok(out) => {
1232                done.finished |= is_finished;
1233                done.outgoing.extend(out);
1234                true
1235            }
1236            // Refused for its data, it would be refused again after a reconnect, and the
1237            // worker's later messages with it: dropped, the stream goes on (B106; a `Finished`
1238            // is stored as the attempt's failure instead).
1239            Err(error) if error.is_data_fault() => {
1240                tracing::error!(
1241                    worker_id,
1242                    %error,
1243                    "worker message dropped: the database refuses its data"
1244                );
1245                true
1246            }
1247            Err(error) => {
1248                // Not sent again on this stream (a code report is sent once): ended, so the
1249                // worker registers again and reports afresh (B101).
1250                tracing::error!(
1251                    worker_id,
1252                    %error,
1253                    "worker message not handled: its stream is ended, so the worker registers \
1254                     again"
1255                );
1256                done.unhandled = true;
1257                false
1258            }
1259        }
1260    }
1261
1262    /// Whether `stream` still carries its worker's messages (under the core's lock); not, it
1263    /// is let go.
1264    async fn still_served(&self, core: &MasterCore, worker_id: &str, stream: &Outbound) -> bool {
1265        if !self.is_current(worker_id, stream).await {
1266            // Replaced by a newer stream of the worker: what this one still says is out of
1267            // date, and must not change the newer one's state (B44).
1268            tracing::warn!(worker_id, "messages of a replaced stream dropped");
1269            return false;
1270        }
1271        if !core.is_live(worker_id) {
1272            // The worker was taken for lost (its lease) while this stream stayed open: ended,
1273            // so it registers again and its journal is reconciled; meanwhile its messages
1274            // change nothing.
1275            self.streams.lock().await.remove(worker_id);
1276            tracing::warn!(worker_id, "stream of a worker taken for lost ended");
1277            return false;
1278        }
1279        true
1280    }
1281
1282    async fn serve_stream(
1283        self,
1284        worker_id: String,
1285        stream: Outbound,
1286        inbound: Streaming<pb::WorkerMessage>,
1287        heard: Arc<AtomicU64>,
1288    ) {
1289        // Read apart from handling: while the master is stuck behind its lock, the worker's
1290        // messages still arrive, are recorded and wait in order (B6).
1291        let (queue, mut queued) = mpsc::unbounded_channel();
1292        let reader = tokio::spawn(read_stream(
1293            worker_id.clone(),
1294            inbound,
1295            self.arrivals.clone(),
1296            queue,
1297            HeartbeatAcks {
1298                stream: stream.sender.downgrade(),
1299                numbers: Arc::clone(&stream.numbers),
1300                stream_id: stream.id,
1301                leading: self.leading.subscribe(),
1302                clocks: (self.clock, self.steady),
1303                heard,
1304                epoch: self.epoch,
1305                current: (worker_id.clone(), Arc::clone(&self.heard)),
1306            },
1307        ));
1308        let mut closing = self.closing.subscribe();
1309        // A failed group's messages not redone in its turn, first in the next (M4B.3).
1310        let mut carried: VecDeque<Turned> = VecDeque::new();
1311        loop {
1312            let first = if let Some(first) = carried.pop_front() {
1313                // As `next_to_handle`: the master stopping lets the stream go (Grok's review).
1314                if !self.leading_unless_closing().await {
1315                    reader.abort();
1316                    return;
1317                }
1318                first
1319            } else {
1320                match self.next_to_handle(&mut queued, &mut closing).await {
1321                    Next::Message(first) => Turned::Grouped(*first),
1322                    Next::Ended => break,
1323                    // The master stopping: this stream's sender let go, its worker not written
1324                    // as disconnected (the lease is given back), as the master's end.
1325                    Next::Closing => {
1326                        reader.abort();
1327                        return;
1328                    }
1329                }
1330            };
1331            // Everything already queued, up to the turn's limit, in one turn of the lock: one
1332            // message per turn left a worker's messages behind every round in between (B12).
1333            let turn = fill_turn(
1334                first,
1335                &mut carried,
1336                &mut queued,
1337                (self.messages_per_turn, self.alone_per_turn),
1338            );
1339            match self.turn((&worker_id, &stream), turn, &mut carried).await {
1340                TurnEnd::Goes => {}
1341                TurnEnd::Dropped => {
1342                    reader.abort();
1343                    return;
1344                }
1345                TurnEnd::Unhandled => {
1346                    reader.abort();
1347                    break;
1348                }
1349            }
1350        }
1351        if let Err(error) = reader.await
1352            && !error.is_cancelled()
1353        {
1354            tracing::error!(worker_id, %error, "worker stream reader failed");
1355        }
1356        // Only the worker's current stream ending disconnects it: a replaced one's end says
1357        // nothing of the newer stream (B44). Checked and removed under the core's lock, which
1358        // a registration holds while it puts its stream in place.
1359        let mut core = self.core_for("stream").await;
1360        let mut streams = self.streams.lock().await;
1361        if !streams
1362            .get(&worker_id)
1363            .is_some_and(|s| s.same_channel(&stream))
1364        {
1365            return;
1366        }
1367        streams.remove(&worker_id);
1368        drop(streams);
1369        let now = (self.clock)();
1370        if let Err(error) = core.disconnected(&worker_id, now).await {
1371            tracing::error!(worker_id, %error, "worker disconnect not recorded");
1372        }
1373    }
1374
1375    /// Registers a worker on its stream, and serves the stream from then on. Not to be cancelled
1376    /// half-way: it changes the core's state in steps (B171).
1377    async fn open_stream(
1378        self,
1379        register: pb::Register,
1380        inbound: Streaming<pb::WorkerMessage>,
1381    ) -> Result<Response<ReceiverStream<Result<pb::MasterMessage, Status>>>, Status> {
1382        // A sign of life as it arrives, before it waits for the lock (B6: a reconnect during
1383        // a stall); and the attempts its journal reports have started, so none is taken back
1384        // for want of a `Started` meanwhile (B50: lost with the old stream). Adopted, they are
1385        // marked started, after which the reconciliation's decision stands.
1386        self.arrivals
1387            .arrived(&register.worker_id, (self.steady)((self.clock)()));
1388        let added: Vec<&str> = register
1389            .journal
1390            .iter()
1391            .filter(|entry| {
1392                self.arrivals
1393                    .start_known(&register.worker_id, &entry.attempt_id)
1394            })
1395            .map(|entry| entry.attempt_id.as_str())
1396            .collect();
1397        let leads = self.leading_unless_closing().await;
1398        let mut core = self.core_for("register").await;
1399        // Paused while it waited for the lock (behind a round), or stopping: refused as
1400        // above, what it added gone.
1401        if !leads || !*self.leading.borrow() {
1402            drop(core);
1403            for attempt_id in &added {
1404                self.arrivals.start_handled(attempt_id);
1405            }
1406            return Err(Status::unavailable(NOT_LEADING));
1407        }
1408        // The worker's old stream, no longer live (a live one refuses this registration), is
1409        // answered no more from here (decision 443): a replaced incarnation's lease runs out
1410        // from this registration, the master's last word to it, whatever the old process
1411        // still sends.
1412        if !core.is_live(&register.worker_id) {
1413            lock_heard(&self.heard).remove(&register.worker_id);
1414        }
1415        let registered = core.register(&register, (self.clock)()).await;
1416        match &registered {
1417            // Its journal is the whole truth now: what it reports is adopted (started) or
1418            // ended, and a start known of an attempt it doesn't report (a `Started` that
1419            // couldn't be stored, its process gone with a restart) protects nothing any more:
1420            // never started, it expires.
1421            Ok(_) => self.arrivals.forget_starts(&register.worker_id),
1422            // Never to be registered as it is: what it added goes; a start known before (a
1423            // `Started` that couldn't be stored, its stream still live) stays.
1424            Err(CoreError::Refused(_)) => {
1425                for attempt_id in &added {
1426                    self.arrivals.start_handled(attempt_id);
1427                }
1428            }
1429            // A database failure: the worker registers again with the same journal; kept
1430            // till then (and gone with the worker if it never comes back, by its lease).
1431            Err(_) => {}
1432        }
1433        let (registered, outgoing) = registered.map_err(|error| match error {
1434            CoreError::Refused(reason) => Status::failed_precondition(reason),
1435            other => Status::internal(other.to_string()),
1436        })?;
1437        // Room for the registration's own messages (`Registered` and a parse for each new
1438        // root, all sent before the worker reads any) on top of the usual buffer (B45).
1439        let own = outgoing
1440            .iter()
1441            .filter(|message| message.worker_id == register.worker_id)
1442            .count();
1443        let (sender, receiver) = mpsc::channel(self.stream_buffer + 1 + own);
1444        // Under the core's lock, as the registration: what an older stream's reader still
1445        // records is of another stream (B240).
1446        let stream = Outbound::new(sender, self.arrivals.new_stream(&register.worker_id));
1447        // A new count of heartbeats for the new stream: its `Register` is heartbeat 0.
1448        let heard = Arc::new(AtomicU64::new(0));
1449        let first = pb::MasterMessage {
1450            message: Some(master_message::Message::Registered(registered)),
1451            clock: Some(self.stamp(0)),
1452        };
1453        stream
1454            .send(first)
1455            .map_err(|_| Status::internal("the stream closed at once"))?;
1456        // The worker's stream from now on, put in place before the lock is let go: a message
1457        // of the old stream handled after this registration is known to be the old one's
1458        // (B44).
1459        {
1460            let mut streams = self.streams.lock().await;
1461            // Checked under the streams' lock: a master stopping meanwhile (no longer leading,
1462            // then closing its streams under that lock) either closes this one or refuses it,
1463            // never leaving it open for its graceful shutdown to wait for (B200's review).
1464            if !*self.leading.borrow() {
1465                return Err(Status::unavailable(NOT_LEADING));
1466            }
1467            streams.insert(register.worker_id.clone(), stream.clone());
1468            lock_heard(&self.heard).insert(register.worker_id.clone(), Arc::clone(&heard));
1469        }
1470        drop(core);
1471        self.deliver(outgoing).await;
1472        tokio::spawn(
1473            self.clone()
1474                .serve_stream(register.worker_id, stream, inbound, heard),
1475        );
1476        Ok(Response::new(ReceiverStream::new(receiver)))
1477    }
1478
1479    /// Ends every worker's stream with `UNAVAILABLE`, for the master to stop: tonic's graceful
1480    /// shutdown waits for open calls, which a worker's stream never ends by itself, and each
1481    /// worker connects again, to the master that leads (B200).
1482    pub async fn close_streams(&self) {
1483        // Each stream's server lets its sender go: a full one ends once its worker read it.
1484        self.closing.send_replace(true);
1485        let streams = std::mem::take(&mut *self.streams.lock().await);
1486        for stream in streams.into_values() {
1487            // Full, the worker isn't reading: its stream ends when its other senders go.
1488            stream.end(Status::unavailable(STOPPING));
1489        }
1490    }
1491
1492    /// Whether `stream` is still `worker_id`'s stream (not replaced by a newer registration).
1493    async fn is_current(&self, worker_id: &str, stream: &Outbound) -> bool {
1494        self.streams
1495            .lock()
1496            .await
1497            .get(worker_id)
1498            .is_some_and(|s| s.same_channel(stream))
1499    }
1500}
1501
1502/// What a worker's stream's server does next.
1503/// A turn from `first`: the carried messages first, then what is queued, up to `limit`; a
1504/// failed group's messages, each alone, at most `alone_limit` ([`ALONE_PER_TURN`] by default;
1505/// Grok's review of M4B.3: the carried ones took a whole turn's).
1506fn fill_turn(
1507    first: Turned,
1508    carried: &mut VecDeque<Turned>,
1509    queued: &mut mpsc::UnboundedReceiver<worker_message::Message>,
1510    (limit, alone_limit): (usize, usize),
1511) -> Vec<Turned> {
1512    let mut alone = usize::from(matches!(first, Turned::Alone(_)));
1513    let mut turn = vec![first];
1514    while turn.len() < limit {
1515        if alone >= alone_limit && matches!(carried.front(), Some(Turned::Alone(_))) {
1516            break;
1517        }
1518        let Some(next) = carried
1519            .pop_front()
1520            .or_else(|| queued.try_recv().ok().map(Turned::Grouped))
1521        else {
1522            break;
1523        };
1524        alone += usize::from(matches!(next, Turned::Alone(_)));
1525        turn.push(next);
1526    }
1527    turn
1528}
1529
1530/// A message of a turn: grouped with the others like it, or (a failed group's, M4B.3) handled
1531/// alone.
1532#[derive(Debug)]
1533enum Turned {
1534    Grouped(worker_message::Message),
1535    Alone(worker_message::Message),
1536}
1537
1538/// What a turn came to.
1539#[derive(Debug, Default)]
1540struct TurnDone {
1541    outgoing: Vec<Outgoing>,
1542    /// A `Finished` was stored: a round wakes.
1543    finished: bool,
1544    /// A message wasn't handled: the stream ends.
1545    unhandled: bool,
1546}
1547
1548/// How a turn ended.
1549enum TurnEnd {
1550    /// The stream goes on.
1551    Goes,
1552    /// The stream no longer carries its worker's messages (replaced, or the worker taken for
1553    /// lost): let go, the worker not written as disconnected.
1554    Dropped,
1555    /// A message wasn't handled: the stream ends, the worker disconnected.
1556    Unhandled,
1557}
1558
1559enum Next {
1560    /// Handles this message (boxed: a message is far larger than the other cases).
1561    Message(Box<worker_message::Message>),
1562    /// The worker's stream ended.
1563    Ended,
1564    /// The master closes its streams.
1565    Closing,
1566}
1567
1568/// Why a worker's stream ends when this master stops.
1569const STOPPING: &str = "this master is stopping: connect again";
1570
1571impl Hub {
1572    /// The refusal of a stream while this master doesn't lead, naming the master that holds
1573    /// the lease and until when, for whoever reads the worker's log (decision 452); as before
1574    /// when the database doesn't say within [`LEADER_LOOKUP`].
1575    async fn not_leading(&self) -> Status {
1576        let held = tokio::time::timeout(LEADER_LOOKUP, self.db.lease_held()).await;
1577        let message = match held {
1578            Ok(Ok(Some((holder, until)))) => {
1579                format!("{NOT_LEADING}; the lease is held by `{holder}` until {until}")
1580            }
1581            Ok(Ok(None)) => format!("{NOT_LEADING}; no master holds the lease now"),
1582            Ok(Err(_)) | Err(_) => NOT_LEADING.to_owned(),
1583        };
1584        Status::unavailable(message)
1585    }
1586}
1587
1588/// The longest a refusal waits to name the leader.
1589const LEADER_LOOKUP: Duration = Duration::from_secs(1);
1590
1591/// Why a stream opened while this master doesn't lead is refused.
1592const NOT_LEADING: &str = "this master isn't leading (its database lease isn't renewed, or another \
1593     master took it over): connect again";
1594
1595/// The master's clock to stamp on a message (B225): this process's timeline, master time
1596/// and the wall clock now, the latest heartbeat heard on the worker's stream, and the lease
1597/// epoch it leads with (decision 444).
1598fn stamp_of(
1599    (wall, steady): (fn() -> Timestamp, crate::clock::Steady),
1600    heard: u64,
1601    epoch: i64,
1602) -> pb::MasterClock {
1603    let wall = wall();
1604    pb::MasterClock {
1605        timeline: crate::clock::timeline(),
1606        master_ms: steady(wall).as_millisecond(),
1607        heard_sequence: heard,
1608        wall_ms: wall.as_millisecond(),
1609        lease_epoch: epoch,
1610        // Its number, set as it is queued on its stream (B240).
1611        sequence: 0,
1612    }
1613}
1614
1615fn lock_heard(
1616    heard: &std::sync::Mutex<BTreeMap<String, Arc<AtomicU64>>>,
1617) -> std::sync::MutexGuard<'_, BTreeMap<String, Arc<AtomicU64>>> {
1618    heard
1619        .lock()
1620        .unwrap_or_else(std::sync::PoisonError::into_inner)
1621}
1622
1623/// Each worker's current stream's heartbeat counter (B225), shared by the hub and the
1624/// streams' readers.
1625type Counters = Arc<std::sync::Mutex<BTreeMap<String, Arc<AtomicU64>>>>;
1626
1627/// Answers a worker's heartbeats as they arrive, before they wait for the lock: a busy master
1628/// isn't a lost one. Not while paused: another master may be leading, and may count the worker
1629/// lost. The stream is held weakly, for this reader not to keep it open.
1630struct HeartbeatAcks {
1631    stream: mpsc::WeakSender<Result<pb::MasterMessage, Status>>,
1632    /// The stream's numbering, shared with its [`Outbound`] (B240).
1633    numbers: Arc<std::sync::Mutex<u64>>,
1634    /// The stream's ID, for [`Arrivals::read`].
1635    stream_id: u64,
1636    leading: watch::Receiver<bool>,
1637    /// The master's wall clock and master time, for the stamp.
1638    clocks: (fn() -> Timestamp, crate::clock::Steady),
1639    /// The heartbeats heard on this stream: the latest's number.
1640    heard: Arc<AtomicU64>,
1641    /// The lease epoch on the stamp.
1642    epoch: i64,
1643    /// Its worker and the hub's counters of the current streams: answered only while `heard`
1644    /// is its worker's current one (decision 443).
1645    current: (String, Counters),
1646}
1647
1648impl HeartbeatAcks {
1649    /// The message numbered `sequence` arrived: noted (the latest's number goes on the
1650    /// master's next stamps, B225), and a heartbeat answered with it on the answer's stamp.
1651    fn heard(&self, sequence: u64, heartbeat: bool) {
1652        let heard = self
1653            .heard
1654            .fetch_max(sequence, Ordering::SeqCst)
1655            .max(sequence);
1656        if heartbeat
1657            && *self.leading.borrow()
1658            && self.is_current()
1659            && let Some(stream) = self.stream.upgrade()
1660        {
1661            let ack = pb::MasterMessage {
1662                message: Some(master_message::Message::HeartbeatAck(pb::HeartbeatAck {})),
1663                clock: Some(stamp_of(self.clocks, heard, self.epoch)),
1664            };
1665            // Full, the worker isn't reading: the next heartbeat tries again.
1666            let _ = numbered_send(&self.numbers, &stream, ack);
1667        }
1668    }
1669
1670    /// Whether this is its worker's current stream: one replaced by a registration (a new
1671    /// incarnation, or the same reconnecting) is answered no more.
1672    fn is_current(&self) -> bool {
1673        let (worker_id, streams) = &self.current;
1674        lock_heard(streams)
1675            .get(worker_id)
1676            .is_some_and(|heard| Arc::ptr_eq(heard, &self.heard))
1677    }
1678
1679    /// Master time now (a message's arrival).
1680    fn steady_now(&self) -> Timestamp {
1681        (self.clocks.1)((self.clocks.0)())
1682    }
1683}
1684
1685/// Reads a worker's stream until it ends: records when each message arrived and queues it
1686/// for handling.
1687async fn read_stream(
1688    worker_id: String,
1689    mut inbound: Streaming<pb::WorkerMessage>,
1690    arrivals: Arrivals,
1691    queue: mpsc::UnboundedSender<worker_message::Message>,
1692    acks: HeartbeatAcks,
1693) {
1694    loop {
1695        match inbound.message().await {
1696            Ok(Some(message)) => {
1697                arrivals.arrived(&worker_id, acks.steady_now());
1698                // A heartbeat is answered whatever it carries; its numbers count when stamped.
1699                let heartbeat =
1700                    matches!(message.message, Some(worker_message::Message::Heartbeat(_)));
1701                acks.heard(message.clock.as_ref().map_or(0, |c| c.sequence), heartbeat);
1702                if let Some(clock) = &message.clock {
1703                    arrivals.read(&worker_id, acks.stream_id, clock.heard_sequence);
1704                }
1705                if let Some(
1706                    worker_message::Message::Started(pb::Started { attempt_id, .. })
1707                    | worker_message::Message::Finished(pb::Finished { attempt_id, .. }),
1708                ) = &message.message
1709                {
1710                    arrivals.start_arrived(&worker_id, attempt_id);
1711                    arrivals.answered(&worker_id, attempt_id);
1712                }
1713                if let Some(worker_message::Message::Rejected(pb::Rejected {
1714                    attempt_id, ..
1715                })) = &message.message
1716                {
1717                    arrivals.answered(&worker_id, attempt_id);
1718                }
1719                if let Some(message) = message.message
1720                    && let Err(mpsc::error::SendError(unsent)) = queue.send(message)
1721                {
1722                    // Never to be handled: its start mustn't keep protecting the attempt.
1723                    if let worker_message::Message::Started(pb::Started { attempt_id, .. })
1724                    | worker_message::Message::Finished(pb::Finished { attempt_id, .. }) =
1725                        &unsent
1726                    {
1727                        arrivals.start_handled(attempt_id);
1728                    }
1729                    return;
1730                }
1731            }
1732            Ok(None) => return,
1733            Err(status) => {
1734                tracing::warn!(worker_id, %status, "worker stream failed");
1735                return;
1736            }
1737        }
1738    }
1739}
1740
1741#[tonic::async_trait]
1742impl Master for Hub {
1743    type ControlStream = ReceiverStream<Result<pb::MasterMessage, Status>>;
1744    type FetchInputsStream = ReceiverStream<Result<pb::InputChunk, Status>>;
1745
1746    async fn control(
1747        &self,
1748        request: Request<Streaming<pb::WorkerMessage>>,
1749    ) -> Result<Response<Self::ControlStream>, Status> {
1750        let mut inbound = request.into_inner();
1751        // Not waited for once the master stops: a stream that never sends `Register` would
1752        // keep tonic's graceful shutdown waiting (B219).
1753        let mut closing = self.closing.subscribe();
1754        let first = tokio::select! {
1755            first = inbound.message() => first?,
1756            _ = closing.wait_for(|closing| *closing) => {
1757                return Err(Status::unavailable(STOPPING));
1758            }
1759        }
1760        .ok_or_else(|| Status::invalid_argument("the stream ended before `Register`"))?;
1761        let Some(worker_message::Message::Register(register)) = first.message else {
1762            return Err(Status::invalid_argument(
1763                "the first message must be `Register`",
1764            ));
1765        };
1766        // Not while paused: another master may be leading. Refused at once rather than held
1767        // (B165), before anything is noted of it: the worker connects again, through the
1768        // Service, to the master that leads.
1769        if !*self.leading.borrow() {
1770            return Err(self.not_leading().await);
1771        }
1772        // Apart from this call, which ends when the worker resets its stream (giving up on a
1773        // slow master): stopped half-way, the worker would stay live with no stream behind it,
1774        // refused from then on (B171). Finished, its stream's end disconnects it as usual.
1775        tokio::spawn(self.clone().open_stream(register, inbound))
1776            .await
1777            .map_err(|e| Status::internal(format!("the registration failed: {e}")))?
1778    }
1779
1780    async fn upload_parse_result(
1781        &self,
1782        request: Request<Streaming<pb::ParseResultPart>>,
1783    ) -> Result<Response<pb::ParseResultAck>, Status> {
1784        // The header, then a file a message (B35): read whole before the lock is taken.
1785        let mut parts = request.into_inner();
1786        let mut upload = ParseUpload::default();
1787        // Not waited for once the master stops, as `control`'s `Register` isn't (B219's review).
1788        let mut closing = self.closing.subscribe();
1789        loop {
1790            let part = tokio::select! {
1791                part = parts.message() => part?,
1792                _ = closing.wait_for(|closing| *closing) => {
1793                    return Err(Status::unavailable(STOPPING));
1794                }
1795            };
1796            let Some(part) = part else { break };
1797            upload
1798                .add(part)
1799                .map_err(|e| Status::invalid_argument(e.to_string()))?;
1800        }
1801        let result = upload
1802            .finish()
1803            .map_err(|e| Status::invalid_argument(e.to_string()))?;
1804        // Apart from this call, as a registration is: a reset stream doesn't stop it half-way.
1805        let hub = self.clone();
1806        let uploaded = tokio::spawn(async move {
1807            if !hub.leading_unless_closing().await {
1808                return None;
1809            }
1810            Some(
1811                hub.core_for("upload")
1812                    .await
1813                    .upload(result, (hub.clock)())
1814                    .await,
1815            )
1816        })
1817        .await
1818        .map_err(|e| Status::internal(format!("the upload failed: {e}")))?
1819        .ok_or_else(|| Status::unavailable(STOPPING))?;
1820        match uploaded {
1821            Ok(()) => Ok(Response::new(pb::ParseResultAck {})),
1822            Err(error @ CoreError::BadMessage { .. }) => {
1823                Err(Status::invalid_argument(error.to_string()))
1824            }
1825            Err(error) => Err(Status::internal(error.to_string())),
1826        }
1827    }
1828
1829    async fn fetch_inputs(
1830        &self,
1831        request: Request<pb::FetchInputsRequest>,
1832    ) -> Result<Response<Self::FetchInputsStream>, Status> {
1833        let attempt_id = request.into_inner().attempt_id;
1834        // Read without the master's lock: a busy master doesn't hold a task's start up (B11).
1835        let inputs = crate::dispatch::attempt_inputs(&self.db, &attempt_id)
1836            .await
1837            .map_err(|e| Status::internal(e.to_string()))?
1838            .ok_or_else(|| Status::not_found(format!("no open attempt `{attempt_id}`")))?;
1839        let chunks: Vec<Vec<u8>> = inputs.chunks(INPUT_CHUNK).map(<[u8]>::to_vec).collect();
1840        let (sender, receiver) = mpsc::channel(chunks.len().max(1));
1841        for data in chunks {
1842            // The channel holds every chunk, so sending never waits.
1843            let _ = sender.try_send(Ok(pb::InputChunk { data }));
1844        }
1845        Ok(Response::new(ReceiverStream::new(receiver)))
1846    }
1847}
1848
1849/// The most messages of one worker handled in one turn of the master's lock: what is queued
1850/// gets through together, and a long queue doesn't hold rounds and other workers up for long
1851/// (at most this many `Finished`, each a few writes; the rest waits for the next turn). 80 from
1852/// M5.1e's stress runs (decision 484): bursts recorded fastest, steady throughput unchanged.
1853pub const MESSAGES_PER_TURN: usize = 80;
1854
1855/// The most messages of a failed group handled one by one in a turn (M4B.3): the rest wait for
1856/// the next, so a failing group doesn't hold the lock for 40 transactions.
1857pub const ALONE_PER_TURN: usize = 10;
1858
1859/// The least time between the end of a round and one a worker's `Finished` wakes (decision
1860/// 42B): none when the master was idle, so a finish starts its downstream tasks at once; under
1861/// a stream of finishes at most 20 rounds a second, each taking what arrived meanwhile.
1862pub const ROUND_GAP: Duration = Duration::from_millis(50);
1863
1864/// How long the master waits before listening again after notifications failed.
1865pub const NOTIFICATION_RETRY: Duration = Duration::from_secs(30);
1866
1867/// The longest a gauge refresh may take unless set otherwise.
1868pub const DEFAULT_REFRESH_LIMIT: Duration = Duration::from_secs(30);
1869
1870/// The largest message from a worker unless set otherwise (`[grpc] max_message_size`'s
1871/// default; gRPC's own, 4 MiB, is too small for a large root's parse upload).
1872pub const DEFAULT_MAX_MESSAGE_SIZE: usize = 64 << 20;
1873
1874/// How often the loop beats while it waits between ticks (liveness, see [`Hub::beat`]).
1875pub const ALIVE_INTERVAL: Duration = Duration::from_secs(5);
1876
1877/// What waiting for command notifications gave.
1878#[derive(Debug)]
1879enum Listened {
1880    /// A command was announced.
1881    Command,
1882    /// Listening failed.
1883    Failed(DbError),
1884}
1885
1886/// The next command notification, never without notifications. Paused after a failure
1887/// until `paused_until`; once that passes, listening resumes and the failure's problem is
1888/// cleared (set again if it fails again): a listener that reconnected by itself would
1889/// otherwise report it for good.
1890async fn next_command(
1891    notifications: Option<&mut CommandNotifications>,
1892    paused_until: &mut Option<tokio::time::Instant>,
1893    problems: &Problems,
1894    triggers_due: &tokio::sync::Notify,
1895) -> Listened {
1896    if let Some(until) = *paused_until {
1897        tokio::time::sleep_until(until).await;
1898        *paused_until = None;
1899        problems.clear(ProblemKind::Notifications);
1900    }
1901    let Some(notifications) = notifications else {
1902        return std::future::pending().await;
1903    };
1904    loop {
1905        return match notifications.next().await {
1906            Ok(schedr_db::commands::Notified::Command) => Listened::Command,
1907            // For the trigger loop (decision 486), and the round only when steps wait for it
1908            // (decision 487).
1909            Ok(schedr_db::commands::Notified::Event { triggers, waiters }) => {
1910                if triggers {
1911                    triggers_due.notify_one();
1912                }
1913                if !waiters {
1914                    continue;
1915                }
1916                Listened::Command
1917            }
1918            Err(error) => Listened::Failed(error),
1919        };
1920    }
1921}
1922
1923/// Stops the trigger loop when dropped: `stop` turned true. A pass under way ends first (cut
1924/// off halfway, its transaction and the core's memory would be left in between); the loop
1925/// then returns at its next wait.
1926fn scopeguard_stop(stop: watch::Sender<bool>, task: tokio::task::JoinHandle<()>) -> impl Drop {
1927    struct Guard(
1928        watch::Sender<bool>,
1929        #[expect(dead_code, reason = "detached on drop")] tokio::task::JoinHandle<()>,
1930    );
1931    impl Drop for Guard {
1932        fn drop(&mut self) {
1933            let _ = self.0.send(true);
1934        }
1935    }
1936    Guard(stop, task)
1937}