Skip to main content

micromegas/servers/
maintenance.rs

1use anyhow::{Context, Result, anyhow};
2use async_trait::async_trait;
3use chrono::{DateTime, DurationRound};
4use chrono::{TimeDelta, Utc};
5use futures::stream::FuturesUnordered;
6use futures::{FutureExt, StreamExt};
7use micromegas_analytics::audience::audience_column_mismatch;
8use micromegas_analytics::delete::delete_old_data;
9use micromegas_analytics::lakehouse::batch_update::materialize_partition_range;
10use micromegas_analytics::lakehouse::lakehouse_context::LakehouseContext;
11use micromegas_analytics::lakehouse::partition_cache::PartitionCache;
12use micromegas_analytics::lakehouse::temp::delete_expired_temporary_files;
13use micromegas_analytics::lakehouse::view::View;
14use micromegas_analytics::lakehouse::view_factory::ViewFactory;
15use micromegas_analytics::lakehouse::view_registry::ViewRegistry;
16use micromegas_analytics::response_writer::ResponseWriter;
17use micromegas_analytics::time::TimeRange;
18use micromegas_tracing::prelude::*;
19use std::future::Future;
20use std::num::NonZeroUsize;
21use std::sync::Arc;
22use std::time::Duration;
23use tokio::task::{AbortHandle, JoinError, JoinSet};
24
25use super::cron_task::{CronTask, TaskCallback};
26use super::pg_stats::PgStatsTask;
27use crate::settings::{ServiceRole, SettingsDataFusionConfig, SettingsSource, resolve_u64_env};
28
29/// Resolves and sorts the view-carrying task's per-tick view list from `registry.current()`: the
30/// base plus every DDL-defined view with an `update_group`, sorted by that group. Computed fresh
31/// on every tick (rather than once at `daemon()` startup, as before DDL-defined views existed)
32/// so a newly created or dropped view set is picked up without a restart.
33fn sorted_views_from_registry(registry: &ViewRegistry) -> Arc<Vec<Arc<dyn View>>> {
34    let mut views = get_global_views_with_update_group(&registry.current());
35    views.sort_by_key(|v| v.get_update_group().unwrap_or(i32::MAX));
36    Arc::new(views)
37}
38
39/// Aborts the spawned tasks it tracks when dropped, so cancelling a pass cancels its in-flight work.
40struct AbortOnDrop(Vec<AbortHandle>);
41
42impl Drop for AbortOnDrop {
43    fn drop(&mut self) {
44        for handle in &self.0 {
45            handle.abort();
46        }
47    }
48}
49
50/// Runs `run` over `items`, grouped by contiguous runs of equal `group_of`, with at most
51/// `concurrency` items in flight. Each group starts after the previous one has fully finished,
52/// and gets a fresh `fetch_group_context()` result.
53///
54/// Each item runs as its own spawned task so CPU-bound work spreads across runtime workers;
55/// items start in input order and dropping the returned future aborts the in-flight tasks.
56/// A task that panics is reported as a failure of its item, like an `Err`.
57/// Returns per-item failures (global index, error) in input order. A `fetch_group_context`
58/// error aborts the pass.
59pub async fn run_update_groups<T, K, C, FetchFut, RunFut>(
60    items: &[T],
61    group_of: impl Fn(&T) -> K,
62    concurrency: NonZeroUsize,
63    mut fetch_group_context: impl FnMut() -> FetchFut,
64    run: impl Fn(&T, Arc<C>) -> RunFut,
65) -> Result<Vec<(usize, anyhow::Error)>>
66where
67    K: PartialEq,
68    C: Send + Sync + 'static,
69    FetchFut: Future<Output = Result<C>>,
70    RunFut: Future<Output = Result<()>> + Send + 'static,
71{
72    let mut failures = Vec::new();
73    let mut offset = 0;
74    for group in items.chunk_by(|a, b| group_of(a) == group_of(b)) {
75        let ctx = Arc::new(fetch_group_context().await?);
76        // Build the futures eagerly so the queue holds no closure borrowing `items`/`run`
77        // across awaits, which breaks the `Send` proof for spawned callers.
78        let mut queue = group
79            .iter()
80            .enumerate()
81            .map(|(i, item)| (offset + i, run(item, ctx.clone())))
82            .collect::<Vec<_>>()
83            .into_iter();
84        let mut guard = AbortOnDrop(Vec::new());
85        let mut running = FuturesUnordered::new();
86        instrument_named!(
87            async {
88                loop {
89                    while running.len() < concurrency.get() {
90                        let Some((i, fut)) = queue.next() else {
91                            break;
92                        };
93                        let handle = spawn_with_context(fut);
94                        guard.0.push(handle.abort_handle());
95                        running.push(handle.map(move |r| (i, r)));
96                    }
97                    match running.next().await {
98                        Some((_, Ok(Ok(())))) => {}
99                        Some((i, Ok(Err(e)))) => failures.push((i, e)),
100                        Some((i, Err(e))) => {
101                            failures.push((i, anyhow!("update task failed: {e}")));
102                        }
103                        None => break,
104                    }
105                }
106            },
107            "update_group"
108        )
109        .await;
110        offset += group.len();
111    }
112    // Items complete in any order; sorting keeps the error text deterministic.
113    failures.sort_by_key(|(i, _)| *i);
114    Ok(failures)
115}
116
117/// Materializes all views within a given time range.
118///
119/// This function iterates through the provided views, materializing partitions
120/// for each view within the specified `insert_range` and `partition_time_delta`.
121/// Views within an update group may run concurrently, up to `concurrency`; the
122/// group boundary is a barrier.
123///
124/// Per-view failures are isolated: a view whose `materialize_partition_range`
125/// call errors is logged, counted (`materialize_view_failure`), and skipped —
126/// every other view, in the same update group or a later one, still gets its
127/// own materialization attempt this pass. This is a deliberate cross-group
128/// policy ("continue anyway"): materialization is idempotent and re-attempted
129/// every tick, so letting later groups proceed even after an earlier-group
130/// failure can't corrupt anything, and it avoids reintroducing the
131/// group-granularity starvation this isolation is meant to fix. If any view
132/// failed, the pass still returns a single aggregated `Err` listing every
133/// failed view, so `CronTask`/`log_task_result` continues to record the pass
134/// as failed.
135#[span_fn]
136pub async fn materialize_all_views(
137    lakehouse: Arc<LakehouseContext>,
138    views: Arc<Vec<Arc<dyn View>>>,
139    insert_range: TimeRange,
140    partition_time_delta: TimeDelta,
141    concurrency: NonZeroUsize,
142) -> Result<()> {
143    let null_response_writer = Arc::new(ResponseWriter::new(None));
144    // Views in the same update group have no inter-dependencies: built-in factories are
145    // restricted to earlier-group sources and `validate_view_definition` rejects a DDL view
146    // reading a view of its own or a later group, so same-group views can be materialized
147    // independently, in any order, with one's failure isolated from the other's.
148    let failed = run_update_groups(
149        &views,
150        |v| v.get_update_group(),
151        concurrency,
152        || PartitionCache::fetch_overlapping_insert_range(&lakehouse.lake().db_pool, insert_range),
153        |view, partitions_all_views| {
154            let view = view.clone();
155            let lakehouse = lakehouse.clone();
156            let null_response_writer = null_response_writer.clone();
157            async move {
158                let view_set_name = view.get_view_set_name();
159                let view_instance_id = view.get_view_instance_id();
160                let res = materialize_partition_range(
161                    partitions_all_views,
162                    lakehouse,
163                    view,
164                    insert_range,
165                    partition_time_delta,
166                    null_response_writer,
167                )
168                .await;
169                if let Err(e) = &res {
170                    error!(
171                        "materialize_all_views: {view_set_name} {view_instance_id} failed: {e:?}"
172                    );
173                    imetric!(
174                        "materialize_view_failure",
175                        "count",
176                        view_set_name = view_set_name,
177                        view_instance_id = view_instance_id,
178                        1
179                    );
180                }
181                res
182            }
183        },
184    )
185    .await?;
186    if !failed.is_empty() {
187        let failures: Vec<String> = failed
188            .iter()
189            .map(|(i, _)| {
190                let view = &views[*i];
191                format!(
192                    "{} {}",
193                    view.get_view_set_name(),
194                    view.get_view_instance_id()
195                )
196            })
197            .collect();
198        anyhow::bail!(
199            "materialize_all_views: {} view(s) failed:\n{}",
200            failures.len(),
201            failures.join("\n")
202        );
203    }
204    Ok(())
205}
206
207/// task running once a day to materialize older partitions
208pub struct EveryDayTask {
209    pub lakehouse: Arc<LakehouseContext>,
210    pub view_registry: Arc<ViewRegistry>,
211}
212
213#[async_trait]
214impl TaskCallback for EveryDayTask {
215    #[span_fn]
216    async fn run(&self, task_scheduled_time: DateTime<Utc>) -> Result<()> {
217        let partition_time_delta = TimeDelta::days(1);
218        let trunc_task_time = task_scheduled_time.duration_trunc(partition_time_delta)?;
219        let begin_range = trunc_task_time - (partition_time_delta * 2);
220        let end_range = trunc_task_time;
221        let views = sorted_views_from_registry(&self.view_registry);
222        materialize_all_views(
223            self.lakehouse.clone(),
224            views,
225            TimeRange::new(begin_range, end_range),
226            partition_time_delta,
227            NonZeroUsize::MIN,
228        )
229        .await
230    }
231}
232
233/// Counts `blocks` rows whose `process_id` disagrees with their stream's own `process_id`,
234/// over the last hour. A block's own `audience` column governs its label regardless of
235/// `process_id`, so this is a plain data-integrity check rather than a security one, run from
236/// the maintenance role so it costs nothing on the hot ingestion path. Reported via
237/// `imetric!("block_stream_process_id_mismatch", "count", n)` and a `warn!` when non-zero --
238/// the healthy baseline is a flat zero.
239async fn measure_block_stream_process_id_mismatch(
240    pool: &sqlx::PgPool,
241    since: DateTime<Utc>,
242) -> Result<()> {
243    let count: i64 = sqlx::query_scalar(
244        "SELECT count(*) FROM blocks b
245         JOIN streams s ON s.stream_id = b.stream_id
246         WHERE b.process_id <> s.process_id
247         AND b.insert_time >= $1",
248    )
249    .bind(since)
250    .fetch_one(pool)
251    .await
252    .with_context(|| "counting block_stream_process_id_mismatch")?;
253    if count > 0 {
254        warn!(
255            "block_stream_process_id_mismatch: {count} block(s) in the last hour disagree with their stream's process_id"
256        );
257    }
258    imetric!("block_stream_process_id_mismatch", "count", count as u64);
259    Ok(())
260}
261
262/// Counts `blocks` rows whose own `audience` disagrees with their stream's or process's
263/// `audience`, over the last hour -- the live-Postgres counterpart to the per-partition
264/// `block_audience_mismatch_excluded` metric. Built from [`audience_column_mismatch`], the
265/// same comparison `blocks_view.rs`'s exclusion predicate uses, so the two can never drift
266/// apart. A non-zero reading is not necessarily a bug (it may be a re-pointed ingestion
267/// credential), but it always means telemetry was silently dropped from `blocks` and its
268/// downstream views, so it is worth a `warn!` regardless. Reported as
269/// `imetric!("block_audience_mismatch_rows", "count", n)`.
270async fn measure_block_audience_mismatch_rows(
271    pool: &sqlx::PgPool,
272    since: DateTime<Utc>,
273) -> Result<()> {
274    let predicate = format!(
275        "({} OR {})",
276        audience_column_mismatch("b", "s"),
277        audience_column_mismatch("b", "p"),
278    );
279    let sql = format!(
280        "SELECT count(*) FROM blocks b
281         JOIN streams s ON s.stream_id = b.stream_id
282         JOIN processes p ON p.process_id = b.process_id
283         WHERE {predicate}
284         AND b.insert_time >= $1"
285    );
286    let count: i64 = sqlx::query_scalar(&sql)
287        .bind(since)
288        .fetch_one(pool)
289        .await
290        .with_context(|| "counting block_audience_mismatch_rows")?;
291    if count > 0 {
292        warn!(
293            "block_audience_mismatch_rows: {count} block(s) in the last hour disagree with their \
294             stream's or process's audience -- silently dropped from blocks/log_entries/measures/otel_histograms/log_stats \
295             by the audience-mismatch predicate"
296        );
297    }
298    imetric!("block_audience_mismatch_rows", "count", count as u64);
299    Ok(())
300}
301
302/// task running once an hour to materialize recent partitions
303pub struct EveryHourTask {
304    pub lakehouse: Arc<LakehouseContext>,
305    pub view_registry: Arc<ViewRegistry>,
306    pub settings: Arc<SettingsSource>,
307}
308
309#[async_trait]
310impl TaskCallback for EveryHourTask {
311    #[span_fn]
312    async fn run(&self, task_scheduled_time: DateTime<Utc>) -> Result<()> {
313        // A settings failure must not fall back to the default horizon: that would delete blocks
314        // an override is keeping. Skip deletion and let the rest of the hourly task run.
315        match self.settings.payload_retention().await {
316            Ok(retention) => delete_old_data(self.lakehouse.lake(), &retention).await?,
317            Err(e) => error!("skipping payload deletion, could not load retention settings: {e:#}"),
318        }
319        delete_expired_temporary_files(self.lakehouse.lake().clone()).await?;
320
321        let since = task_scheduled_time - TimeDelta::hours(1);
322        measure_block_stream_process_id_mismatch(&self.lakehouse.lake().db_pool, since).await?;
323        measure_block_audience_mismatch_rows(&self.lakehouse.lake().db_pool, since).await?;
324
325        let partition_time_delta = TimeDelta::hours(1);
326        let trunc_task_time = task_scheduled_time.duration_trunc(partition_time_delta)?;
327        let begin_range = trunc_task_time - (partition_time_delta * 2);
328        let end_range = trunc_task_time;
329        let views = sorted_views_from_registry(&self.view_registry);
330        materialize_all_views(
331            self.lakehouse.clone(),
332            views,
333            TimeRange::new(begin_range, end_range),
334            partition_time_delta,
335            NonZeroUsize::MIN,
336        )
337        .await
338    }
339}
340
341/// task running once a minute to materialize recent partitions
342pub struct EveryMinuteTask {
343    pub lakehouse: Arc<LakehouseContext>,
344    pub view_registry: Arc<ViewRegistry>,
345}
346
347#[async_trait]
348impl TaskCallback for EveryMinuteTask {
349    #[span_fn]
350    async fn run(&self, task_scheduled_time: DateTime<Utc>) -> Result<()> {
351        let partition_time_delta = TimeDelta::minutes(1);
352        let trunc_task_time = task_scheduled_time.duration_trunc(partition_time_delta)?;
353        let begin_range = trunc_task_time - (partition_time_delta * 2);
354        // we only try to process a single partition per view
355        let end_range = trunc_task_time - partition_time_delta;
356        let views = sorted_views_from_registry(&self.view_registry);
357        materialize_all_views(
358            self.lakehouse.clone(),
359            views,
360            TimeRange::new(begin_range, end_range),
361            partition_time_delta,
362            NonZeroUsize::MIN,
363        )
364        .await
365    }
366}
367
368/// Environment variable bounding how many views of one update group the every-second pass
369/// materializes at once.
370pub const SECONDS_MATERIALIZATION_CONCURRENCY_ENV: &str =
371    "MICROMEGAS_SECONDS_MATERIALIZATION_CONCURRENCY";
372pub const DEFAULT_SECONDS_MATERIALIZATION_CONCURRENCY: u64 = 8;
373
374/// task running once a second to materialize newest partitions
375pub struct EverySecondTask {
376    pub lakehouse: Arc<LakehouseContext>,
377    pub view_registry: Arc<ViewRegistry>,
378    pub concurrency: NonZeroUsize,
379}
380
381#[async_trait]
382impl TaskCallback for EverySecondTask {
383    #[span_fn]
384    async fn run(&self, task_scheduled_time: DateTime<Utc>) -> Result<()> {
385        let delay = Utc::now() - task_scheduled_time;
386        imetric!(
387            "every_second_task_delay",
388            "ms",
389            delay.num_milliseconds() as u64
390        );
391        if delay > TimeDelta::seconds(10) {
392            // we don't want to accumulate too much delay - the minutes task will fill the missing data
393            warn!("skipping `seconds` task, delay={delay}");
394            return Ok(());
395        }
396        let partition_time_delta = TimeDelta::seconds(1);
397        let trunc_task_time = task_scheduled_time.duration_trunc(partition_time_delta)?;
398        let begin_range = trunc_task_time - (partition_time_delta * 2);
399        // we only try to process a single partition per view
400        let end_range = trunc_task_time - partition_time_delta;
401        let views = sorted_views_from_registry(&self.view_registry);
402        let pass_begin = Utc::now();
403        let res = materialize_all_views(
404            self.lakehouse.clone(),
405            views,
406            TimeRange::new(begin_range, end_range),
407            partition_time_delta,
408            self.concurrency,
409        )
410        .await;
411        let elapsed = Utc::now() - pass_begin;
412        imetric!(
413            "every_second_pass_duration",
414            "ms",
415            elapsed.num_milliseconds() as u64
416        );
417        res
418    }
419}
420
421/// Logs the outcome of a completed cron task.
422///
423/// The result is triply nested: the outer `JoinError` reports a panicked or
424/// cancelled task, the inner `JoinError` comes from the spawned future, and the
425/// innermost `Result` is the task callback's own outcome. Any error at any layer
426/// is logged; a fully successful run is a no-op.
427fn log_task_result(res: Result<Result<Result<()>, JoinError>, JoinError>) {
428    match res {
429        Ok(Ok(Ok(()))) => {}
430        Ok(Ok(Err(e))) => error!("{e:?}"),
431        Ok(Err(e)) => error!("{e:?}"),
432        Err(e) => error!("{e:?}"),
433    }
434}
435
436/// Awaits and logs every in-flight task, returning once the set is empty.
437///
438/// Used to drain currently running tasks before the loop exits on shutdown, so
439/// their work completes rather than being dropped.
440async fn drain_task_set(task_set: &mut JoinSet<Result<Result<()>, JoinError>>) {
441    while let Some(res) = task_set.join_next().await {
442        log_task_result(res);
443    }
444}
445
446/// Runs a collection of `CronTask`s until `shutdown` fires.
447///
448/// When `shutdown` completes, the loop stops scheduling new tasks and drains
449/// any currently running tasks before returning.
450pub async fn run_tasks_forever<F>(mut tasks: Vec<CronTask>, max_parallelism: usize, shutdown: F)
451where
452    F: Future<Output = ()>,
453{
454    tokio::pin!(shutdown);
455    let mut task_set = JoinSet::new();
456    loop {
457        let mut next_task_run = Utc::now() + TimeDelta::days(2);
458        for task in &mut tasks {
459            if task.get_next_run() < Utc::now() {
460                task_set.spawn(task.spawn().await);
461                if task_set.len() >= max_parallelism {
462                    tokio::select! {
463                        res = task_set.join_next() => {
464                            if let Some(res) = res {
465                                log_task_result(res);
466                            }
467                        }
468                        _ = &mut shutdown => {
469                            drain_task_set(&mut task_set).await;
470                            return;
471                        }
472                    }
473                }
474            }
475            let task_next_run = task.get_next_run();
476            if task_next_run < next_task_run {
477                next_task_run = task_next_run;
478            }
479        }
480        let time_until_next_task = next_task_run - Utc::now();
481        if time_until_next_task > TimeDelta::zero() {
482            match time_until_next_task
483                .to_std()
484                .with_context(|| "delay.to_std")
485            {
486                Ok(wait) => {
487                    tokio::select! {
488                        _ = tokio::time::sleep(wait) => {}
489                        _ = &mut shutdown => {
490                            drain_task_set(&mut task_set).await;
491                            return;
492                        }
493                    }
494                }
495                Err(e) => warn!("{e:?}"),
496            }
497        } else {
498            // No sleep needed, but still poll the shutdown future so the loop
499            // can exit even when tasks run longer than their period.
500            tokio::select! {
501                biased;
502                _ = &mut shutdown => {
503                    drain_task_set(&mut task_set).await;
504                    return;
505                }
506                _ = tokio::task::yield_now() => {}
507            }
508        }
509    }
510}
511
512/// Retrieves a list of global views that have an associated update group.
513///
514/// This function filters the global views provided by the `view_factory`,
515/// returning only those that are part of an update group.
516pub fn get_global_views_with_update_group(view_factory: &ViewFactory) -> Vec<Arc<dyn View>> {
517    view_factory
518        .get_global_views()
519        .iter()
520        .filter(|v| v.get_update_group().is_some())
521        .cloned()
522        .collect()
523}
524
525/// Starts the maintenance daemon, which runs various scheduled tasks.
526///
527/// This function initializes and spawns several `CronTask`s for daily, hourly, minute,
528/// and second-based maintenance operations, such as data materialization and cleanup,
529/// plus a once-a-minute collector that samples the metadata Postgres's `pg_stat_*`
530/// views for self-observability. All runner loops react to `shutdown`: they stop
531/// scheduling and drain in-flight tasks. A deadline arm forces return after `grace`
532/// even if tasks haven't drained.
533///
534/// # Arguments
535///
536/// * `lakehouse` - The lakehouse context with shared metadata cache.
537/// * `view_registry` - The shared registry (base views plus every DDL-defined global view);
538///   each view-carrying task resolves and sorts its own view list from `view_registry.current()`
539///   fresh on every tick, so a view set created or dropped after the daemon started is picked up
540///   without a restart.
541/// * `settings` - Source of the payload retention policy, read on every hourly pass, and of the
542///   `datafusion_config_maintenance` overrides applied to every session the daemon builds.
543/// * `shutdown` - Future that completes when the process should begin shutting down.
544/// * `grace` - Maximum time to wait for in-flight tasks after the shutdown signal.
545pub async fn daemon<F>(
546    lakehouse: Arc<LakehouseContext>,
547    view_registry: Arc<ViewRegistry>,
548    settings: Arc<SettingsSource>,
549    shutdown: F,
550    grace: Duration,
551) -> Result<()>
552where
553    F: Future<Output = ()> + Send + 'static,
554{
555    use super::shutdown::ShutdownFanout;
556
557    // Wrapped before `lakehouse` is cloned into the cron tasks so every materialization and
558    // merge session applies the maintenance overrides.
559    let lakehouse = lakehouse.with_datafusion_config(Arc::new(SettingsDataFusionConfig::new(
560        settings.clone(),
561        ServiceRole::Maintenance,
562    )));
563
564    // Loaded once, synchronously, before the cron tasks are spawned -- failing startup on error,
565    // the way `migrate_lakehouse` already does -- so the daemon never materializes with a
566    // DDL-defined view set (or the now-seeded `log_stats`) silently missing from `current()`.
567    view_registry
568        .reload()
569        .await
570        .with_context(|| "initial view_registry reload")?;
571
572    let every_day = CronTask::new(
573        String::from("every_day"),
574        TimeDelta::days(1),
575        TimeDelta::hours(4),
576        Arc::new(EveryDayTask {
577            lakehouse: lakehouse.clone(),
578            view_registry: view_registry.clone(),
579        }),
580    )?;
581    let every_hour = CronTask::new(
582        String::from("every_hour"),
583        TimeDelta::hours(1),
584        TimeDelta::minutes(10),
585        Arc::new(EveryHourTask {
586            lakehouse: lakehouse.clone(),
587            view_registry: view_registry.clone(),
588            settings,
589        }),
590    )?;
591    let every_minute = CronTask::new(
592        String::from("every minute"),
593        TimeDelta::minutes(1),
594        TimeDelta::seconds(30),
595        Arc::new(EveryMinuteTask {
596            lakehouse: lakehouse.clone(),
597            view_registry: view_registry.clone(),
598        }),
599    )?;
600    let pg_stats = CronTask::new(
601        String::from("pg_stats"),
602        TimeDelta::minutes(1),
603        TimeDelta::seconds(15), // staggered from the materialization tasks' 30s offset
604        Arc::new(PgStatsTask {
605            lakehouse: lakehouse.clone(),
606        }),
607    )?;
608    let seconds_concurrency = NonZeroUsize::new(resolve_u64_env(
609        SECONDS_MATERIALIZATION_CONCURRENCY_ENV,
610        DEFAULT_SECONDS_MATERIALIZATION_CONCURRENCY,
611    ) as usize)
612    .unwrap_or(NonZeroUsize::MIN);
613    let every_second = CronTask::new(
614        String::from("every second"),
615        TimeDelta::seconds(1),
616        TimeDelta::milliseconds(500),
617        Arc::new(EverySecondTask {
618            lakehouse,
619            view_registry: view_registry.clone(),
620            concurrency: seconds_concurrency,
621        }),
622    )?;
623
624    let fanout = ShutdownFanout::new(shutdown);
625    let grace_secs = grace.as_secs();
626
627    // Keeps `view_registry.current()` fresh for every task above, independent of their own
628    // schedules.
629    view_registry.spawn_refresh_task(fanout.subscribe());
630
631    let mut runners = tokio::task::JoinSet::new();
632    runners.spawn(run_tasks_forever(vec![every_day], 1, fanout.subscribe()));
633    runners.spawn(run_tasks_forever(vec![every_hour], 1, fanout.subscribe()));
634    runners.spawn(run_tasks_forever(vec![every_minute], 5, fanout.subscribe()));
635    runners.spawn(run_tasks_forever(vec![every_second], 5, fanout.subscribe()));
636    runners.spawn(run_tasks_forever(vec![pg_stats], 1, fanout.subscribe()));
637
638    let deadline = {
639        let d = fanout.subscribe();
640        async move {
641            d.await;
642            tokio::time::sleep(grace).await;
643        }
644    };
645
646    tokio::select! {
647        _ = runners.join_all() => {
648            info!("daemon drain completed");
649        }
650        _ = deadline => {
651            warn!("daemon grace period of {grace_secs}s elapsed with work still in flight");
652        }
653    }
654    Ok(())
655}