Skip to main content

mz_storage/
healthcheck.rs

1// Copyright Materialize, Inc. and contributors. All rights reserved.
2//
3// Use of this software is governed by the Business Source License
4// included in the LICENSE file.
5//
6// As of the Change Date specified in that file, in accordance with
7// the Business Source License, use of this software will be governed
8// by the Apache License, Version 2.0.
9
10//! Healthcheck common
11
12use std::cell::RefCell;
13use std::collections::btree_map::Entry;
14use std::collections::{BTreeMap, BTreeSet};
15use std::fmt;
16use std::fmt::Debug;
17use std::rc::Rc;
18use std::time::Duration;
19
20use chrono::{DateTime, Utc};
21use differential_dataflow::Hashable;
22use futures::StreamExt;
23use mz_ore::cast::CastFrom;
24use mz_ore::now::NowFn;
25use mz_repr::GlobalId;
26use mz_storage_client::client::{Status, StatusUpdate};
27use mz_timely_util::builder_async::{
28    Event as AsyncEvent, OperatorBuilder as AsyncOperatorBuilder, PressOnDropButton,
29};
30use timely::dataflow::channels::pact::Exchange;
31use timely::dataflow::operators::vec::Map;
32use timely::dataflow::{Scope, StreamVec};
33use timely::progress::Timestamp;
34use tracing::{error, info};
35
36use crate::internal_control::{InternalCommandSender, InternalStorageCommand};
37
38/// The namespace of the update. The `Ord` impl matter here, later variants are
39/// displayed over earlier ones.
40///
41/// Some namespaces (referred to as "sidechannels") can come from any worker_id,
42/// and `Running` statuses from them do not mark the entire object as running.
43///
44/// Ensure you update `is_sidechannel` when adding variants.
45#[derive(
46    Copy,
47    Clone,
48    Debug,
49    Serialize,
50    Deserialize,
51    PartialEq,
52    Eq,
53    PartialOrd,
54    Ord
55)]
56pub enum StatusNamespace {
57    /// A normal status namespaces. Any `Running` status from any worker will mark the object
58    /// `Running`.
59    Generator,
60    Kafka,
61    Postgres,
62    MySql,
63    SqlServer,
64    Ssh,
65    Upsert,
66    Decode,
67    Iceberg,
68    Internal,
69}
70
71impl StatusNamespace {
72    fn is_sidechannel(&self) -> bool {
73        matches!(self, StatusNamespace::Ssh)
74    }
75}
76
77impl fmt::Display for StatusNamespace {
78    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
79        use StatusNamespace::*;
80        match self {
81            Generator => write!(f, "generator"),
82            Kafka => write!(f, "kafka"),
83            Postgres => write!(f, "postgres"),
84            MySql => write!(f, "mysql"),
85            SqlServer => write!(f, "sql-server"),
86            Ssh => write!(f, "ssh"),
87            Upsert => write!(f, "upsert"),
88            Decode => write!(f, "decode"),
89            Internal => write!(f, "internal"),
90            Iceberg => write!(f, "iceberg"),
91        }
92    }
93}
94
95#[derive(Debug)]
96struct PerWorkerHealthStatus {
97    pub(crate) errors_by_worker: Vec<BTreeMap<StatusNamespace, HealthStatusUpdate>>,
98}
99
100impl PerWorkerHealthStatus {
101    fn merge_update(
102        &mut self,
103        worker: usize,
104        namespace: StatusNamespace,
105        update: HealthStatusUpdate,
106        only_greater: bool,
107    ) {
108        let errors = &mut self.errors_by_worker[worker];
109        match errors.entry(namespace) {
110            Entry::Vacant(v) => {
111                v.insert(update);
112            }
113            Entry::Occupied(mut o) => {
114                if !only_greater || o.get() < &update {
115                    o.insert(update);
116                }
117            }
118        }
119    }
120
121    fn decide_status(&self) -> OverallStatus {
122        let mut output_status = OverallStatus::Starting;
123        let mut namespaced_errors: BTreeMap<StatusNamespace, String> = BTreeMap::new();
124        let mut hints: BTreeSet<String> = BTreeSet::new();
125
126        for status in self.errors_by_worker.iter() {
127            for (ns, ns_status) in status.iter() {
128                match ns_status {
129                    // HealthStatusUpdate::Ceased is currently unused, so just
130                    // treat it as if it were a normal error.
131                    //
132                    // TODO: redesign ceased status database-issues#7687
133                    HealthStatusUpdate::Ceased { error } => {
134                        if Some(error) > namespaced_errors.get(ns).as_deref() {
135                            namespaced_errors.insert(*ns, error.to_string());
136                        }
137                    }
138                    HealthStatusUpdate::Stalled { error, hint, .. } => {
139                        if Some(error) > namespaced_errors.get(ns).as_deref() {
140                            namespaced_errors.insert(*ns, error.to_string());
141                        }
142
143                        if let Some(hint) = hint {
144                            hints.insert(hint.to_string());
145                        }
146                    }
147                    HealthStatusUpdate::Running => {
148                        if !ns.is_sidechannel() {
149                            output_status = OverallStatus::Running;
150                        }
151                    }
152                }
153            }
154        }
155
156        if !namespaced_errors.is_empty() {
157            // Pick the most important error.
158            let (ns, err) = namespaced_errors.last_key_value().unwrap();
159            output_status = OverallStatus::Stalled {
160                error: format!("{}: {}", ns, err),
161                hints,
162                namespaced_errors,
163            }
164        }
165
166        output_status
167    }
168}
169
170#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
171pub enum OverallStatus {
172    Starting,
173    Running,
174    Stalled {
175        error: String,
176        hints: BTreeSet<String>,
177        namespaced_errors: BTreeMap<StatusNamespace, String>,
178    },
179    Ceased {
180        error: String,
181    },
182}
183
184impl OverallStatus {
185    /// The user-readable error string, if there is one.
186    pub(crate) fn error(&self) -> Option<&str> {
187        match self {
188            OverallStatus::Starting | OverallStatus::Running => None,
189            OverallStatus::Stalled { error, .. } | OverallStatus::Ceased { error, .. } => {
190                Some(error)
191            }
192        }
193    }
194
195    /// A set of namespaced errors, if there are any.
196    pub(crate) fn errors(&self) -> Option<&BTreeMap<StatusNamespace, String>> {
197        match self {
198            OverallStatus::Starting | OverallStatus::Running | OverallStatus::Ceased { .. } => None,
199            OverallStatus::Stalled {
200                namespaced_errors, ..
201            } => Some(namespaced_errors),
202        }
203    }
204
205    /// A set of hints, if there are any.
206    pub(crate) fn hints(&self) -> BTreeSet<String> {
207        match self {
208            OverallStatus::Starting | OverallStatus::Running | OverallStatus::Ceased { .. } => {
209                BTreeSet::new()
210            }
211            OverallStatus::Stalled { hints, .. } => hints.clone(),
212        }
213    }
214}
215
216impl<'a> From<&'a OverallStatus> for Status {
217    fn from(val: &'a OverallStatus) -> Self {
218        match val {
219            OverallStatus::Starting => Status::Starting,
220            OverallStatus::Running => Status::Running,
221            OverallStatus::Stalled { .. } => Status::Stalled,
222            OverallStatus::Ceased { .. } => Status::Ceased,
223        }
224    }
225}
226
227#[derive(Debug)]
228struct HealthState {
229    healths: PerWorkerHealthStatus,
230    last_reported_status: Option<OverallStatus>,
231    halt_with: Option<(StatusNamespace, HealthStatusUpdate)>,
232}
233
234impl HealthState {
235    fn new(worker_count: usize) -> HealthState {
236        HealthState {
237            healths: PerWorkerHealthStatus {
238                errors_by_worker: vec![Default::default(); worker_count],
239            },
240            last_reported_status: None,
241            halt_with: None,
242        }
243    }
244}
245
246/// A trait that lets a user configure the `health_operator` with custom
247/// behavior. This is mostly useful for testing, and the [`DefaultWriter`]
248/// should be the correct implementation for everyone.
249pub trait HealthOperator {
250    /// Record a new status.
251    fn record_new_status(
252        &self,
253        collection_id: GlobalId,
254        ts: DateTime<Utc>,
255        new_status: Status,
256        new_error: Option<&str>,
257        hints: &BTreeSet<String>,
258        namespaced_errors: &BTreeMap<StatusNamespace, String>,
259        // TODO(guswynn): not urgent:
260        // Ideally this would be entirely included in the `DefaultWriter`, but that
261        // requires a fairly heavy change to the `health_operator`, which hardcodes
262        // some use of persist. For now we just leave it and ignore it in tests.
263        write_namespaced_map: bool,
264    );
265    fn send_halt(&self, id: GlobalId, error: Option<(StatusNamespace, HealthStatusUpdate)>);
266    fn send_suspend(&self, id: GlobalId, error: Option<(StatusNamespace, HealthStatusUpdate)>);
267
268    /// Optionally override the chosen worker index. Default is semi-random.
269    /// Only useful for tests.
270    fn chosen_worker(&self) -> Option<usize> {
271        None
272    }
273}
274
275/// A default `HealthOperator` for use in normal cases.
276pub struct DefaultWriter {
277    pub command_tx: InternalCommandSender,
278    pub updates: Rc<RefCell<Vec<StatusUpdate>>>,
279    /// The epoch of the dataflow rendering this operator is part of.
280    pub epoch: u64,
281}
282
283impl HealthOperator for DefaultWriter {
284    fn record_new_status(
285        &self,
286        collection_id: GlobalId,
287        ts: DateTime<Utc>,
288        status: Status,
289        new_error: Option<&str>,
290        hints: &BTreeSet<String>,
291        namespaced_errors: &BTreeMap<StatusNamespace, String>,
292        write_namespaced_map: bool,
293    ) {
294        self.updates.borrow_mut().push(StatusUpdate {
295            id: collection_id,
296            timestamp: ts,
297            status,
298            error: new_error.map(|e| e.to_string()),
299            hints: hints.clone(),
300            namespaced_errors: if write_namespaced_map {
301                namespaced_errors
302                    .iter()
303                    .map(|(ns, val)| (ns.to_string(), val.clone()))
304                    .collect()
305            } else {
306                BTreeMap::new()
307            },
308            replica_id: None,
309        });
310    }
311
312    fn send_halt(&self, id: GlobalId, error: Option<(StatusNamespace, HealthStatusUpdate)>) {
313        self.command_tx
314            .send(InternalStorageCommand::SuspendAndRestart {
315                // Suspend and restart is expected to operate on the primary object and
316                // not any of the sub-objects
317                id,
318                reason: format!("{:?}", error),
319            });
320    }
321
322    fn send_suspend(&self, id: GlobalId, error: Option<(StatusNamespace, HealthStatusUpdate)>) {
323        self.command_tx.send(InternalStorageCommand::Suspend {
324            id,
325            epoch: self.epoch,
326            reason: format!("{:?}", error),
327        });
328    }
329}
330
331/// A health message consumed by the `health_operator`.
332#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
333pub struct HealthStatusMessage {
334    /// The object that this status message is about. When None, it refers to the entire ingestion
335    /// as a whole. When Some, it refers to a specific subsource.
336    pub id: Option<GlobalId>,
337    /// The namespace of the health update.
338    pub namespace: StatusNamespace,
339    /// The update itself.
340    pub update: HealthStatusUpdate,
341}
342
343/// Writes updates that come across `health_stream` to the collection's status shards, as identified
344/// by their `CollectionMetadata`.
345///
346/// Only one worker will be active and write to the status shard.
347///
348/// The `OutputIndex` values that come across `health_stream` must be a strict subset of those in
349/// `configs`'s keys.
350pub(crate) fn health_operator<'scope, T: Timestamp, P>(
351    scope: Scope<'scope, T>,
352    now: NowFn,
353    // A set of id's that should be marked as `HealthStatusUpdate::starting()` during startup.
354    mark_starting: BTreeSet<GlobalId>,
355    // An id that is allowed to halt the dataflow. Others are ignored, and panic during debug
356    // mode.
357    halting_id: GlobalId,
358    // A description of the object type we are writing status updates about. Used in log lines.
359    object_type: &'static str,
360    // An indexed stream of health updates. Indexes are configured in `configs`.
361    health_stream: StreamVec<'scope, T, HealthStatusMessage>,
362    // An impl of `HealthOperator` that configures the output behavior of this operator.
363    health_operator_impl: P,
364    // Whether or not we should actually write namespaced errors in the `details` column.
365    write_namespaced_map: bool,
366    // How long to wait before initiating a `SuspendAndRestart` command, to
367    // prevent hot restart loops.
368    suspend_and_restart_delay: Duration,
369) -> PressOnDropButton
370where
371    P: HealthOperator + 'static,
372{
373    // Derived config options
374    let healthcheck_worker_id = scope.index();
375    let worker_count = scope.peers();
376
377    // Inject the originating worker id to each item before exchanging to the chosen worker
378    let health_stream = health_stream.map(move |status| (healthcheck_worker_id, status));
379
380    let chosen_worker_id = if let Some(index) = health_operator_impl.chosen_worker() {
381        index
382    } else {
383        // We'll route all the work to a single arbitrary worker;
384        // there's not much to do, and we need a global view.
385        usize::cast_from(mark_starting.iter().next().hashed()) % worker_count
386    };
387
388    let is_active_worker = chosen_worker_id == healthcheck_worker_id;
389
390    let operator_name = format!("healthcheck({})", healthcheck_worker_id);
391    let mut health_op = AsyncOperatorBuilder::new(operator_name, scope.clone());
392
393    let mut input = health_op.new_disconnected_input(
394        health_stream,
395        Exchange::new(move |_| u64::cast_from(chosen_worker_id)),
396    );
397
398    let button = health_op.build(move |mut _capabilities| async move {
399        let mut health_states: BTreeMap<_, _> = mark_starting
400            .iter()
401            .copied()
402            .chain([halting_id])
403            .map(|id| (id, HealthState::new(worker_count)))
404            .collect();
405
406        // Write the initial starting state to the status shard for all managed objects
407        if is_active_worker {
408            for (id, state) in health_states.iter_mut() {
409                let status = OverallStatus::Starting;
410                let timestamp = mz_ore::now::to_datetime(now());
411                health_operator_impl.record_new_status(
412                    *id,
413                    timestamp,
414                    (&status).into(),
415                    status.error(),
416                    &status.hints(),
417                    status.errors().unwrap_or(&BTreeMap::new()),
418                    write_namespaced_map,
419                );
420
421                state.last_reported_status = Some(status);
422            }
423        }
424
425        let mut outputs_seen = BTreeMap::<GlobalId, BTreeSet<_>>::new();
426        while let Some(event) = input.next().await {
427            if let AsyncEvent::Data(_cap, rows) = event {
428                for (worker_id, message) in rows {
429                    let HealthStatusMessage {
430                        id,
431                        namespace: ns,
432                        update: health_event,
433                    } = message;
434                    let id = id.unwrap_or(halting_id);
435                    let HealthState {
436                        healths, halt_with, ..
437                    } = match health_states.get_mut(&id) {
438                        Some(health) => health,
439                        // This is a health status update for a sub-object_type that we did not request to
440                        // be generated, which means it doesn't have a GlobalId and should not be
441                        // propagated to the shard.
442                        None => continue,
443                    };
444
445                    // Its important to track `new_round` per-namespace, so namespaces are reasoned
446                    // about in `merge_update` independently.
447                    let new_round = outputs_seen
448                        .entry(id)
449                        .or_insert_with(BTreeSet::new)
450                        .insert(ns.clone());
451
452                    if !is_active_worker {
453                        error!(
454                            "Health messages for {object_type} {id} passed to \
455                              an unexpected worker id: {healthcheck_worker_id}"
456                        )
457                    }
458
459                    if health_event.stall_action() != StallAction::Continue {
460                        *halt_with = Some((ns.clone(), health_event.clone()));
461                    }
462
463                    healths.merge_update(worker_id, ns, health_event, !new_round);
464                }
465
466                let mut halt_with_outer = None;
467
468                while let Some((id, _)) = outputs_seen.pop_first() {
469                    let HealthState {
470                        healths,
471                        last_reported_status,
472                        halt_with,
473                    } = health_states.get_mut(&id).expect("known to exist");
474
475                    let new_status = healths.decide_status();
476
477                    if Some(&new_status) != last_reported_status.as_ref() {
478                        info!(
479                            "Health transition for {object_type} {id}: \
480                                  {last_reported_status:?} -> {:?}",
481                            Some(&new_status)
482                        );
483
484                        let timestamp = mz_ore::now::to_datetime(now());
485                        health_operator_impl.record_new_status(
486                            id,
487                            timestamp,
488                            (&new_status).into(),
489                            new_status.error(),
490                            &new_status.hints(),
491                            new_status.errors().unwrap_or(&BTreeMap::new()),
492                            write_namespaced_map,
493                        );
494
495                        *last_reported_status = Some(new_status.clone());
496                    }
497
498                    // Set halt with if None.
499                    if halt_with_outer.is_none() && halt_with.is_some() {
500                        halt_with_outer = Some((id, halt_with.clone()));
501                    }
502                }
503
504                // TODO(aljoscha): Instead of threading through the
505                // `should_halt` bit, we can give an internal command sender
506                // directly to the places where `should_halt = true` originates.
507                // We should definitely do that, but this is okay for a PoC.
508                if let Some((id, halt_with)) = halt_with_outer {
509                    mz_ore::soft_assert_or_log!(
510                        id == halting_id,
511                        "sub{object_type}s should not produce \
512                        halting errors, however {:?} halted while primary \
513                                            {object_type} is {:?}",
514                        id,
515                        halting_id
516                    );
517
518                    let action = halt_with.as_ref().map(|(_, update)| update.stall_action());
519                    if action == Some(StallAction::Suspend) {
520                        info!("Broadcasting suspend command because of {:?}", halt_with);
521                        health_operator_impl.send_suspend(id, halt_with);
522                    } else {
523                        info!(
524                            "Broadcasting suspend-and-restart \
525                            command because of {:?} after {:?} delay",
526                            halt_with, suspend_and_restart_delay
527                        );
528                        tokio::time::sleep(suspend_and_restart_delay).await;
529                        health_operator_impl.send_halt(id, halt_with);
530                    }
531                }
532            }
533        }
534    });
535
536    button.press_on_drop()
537}
538
539use serde::{Deserialize, Serialize};
540
541/// NB: we derive Ord here, so the enum order matters. Generally, statuses later in the list
542/// take precedence over earlier ones: so if one worker is stalled, we'll consider the entire
543/// source to be stalled.
544#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
545pub enum HealthStatusUpdate {
546    Running,
547    Stalled {
548        error: String,
549        hint: Option<String>,
550        action: StallAction,
551    },
552    Ceased {
553        error: String,
554    },
555}
556
557/// What the health operator does to a dataflow after recording its stall.
558#[derive(
559    Clone,
560    Copy,
561    Debug,
562    Serialize,
563    Deserialize,
564    PartialEq,
565    Eq,
566    PartialOrd,
567    Ord
568)]
569pub enum StallAction {
570    /// The dataflow keeps running and can report a recovery.
571    Continue,
572    /// The dataflow is torn down and rendered again.
573    Restart,
574    /// The dataflow is torn down and stays down until its run command is issued again.
575    Suspend,
576}
577
578impl HealthStatusUpdate {
579    /// Generates a running [`HealthStatusUpdate`].
580    pub(crate) fn running() -> Self {
581        HealthStatusUpdate::Running
582    }
583
584    /// Generates a non-halting [`HealthStatusUpdate`] with `update`.
585    pub(crate) fn stalled(error: String, hint: Option<String>) -> Self {
586        HealthStatusUpdate::Stalled {
587            error,
588            hint,
589            action: StallAction::Continue,
590        }
591    }
592
593    /// Generates a halting [`HealthStatusUpdate`] with `update`.
594    pub(crate) fn halting(error: String, hint: Option<String>) -> Self {
595        HealthStatusUpdate::Stalled {
596            error,
597            hint,
598            action: StallAction::Restart,
599        }
600    }
601
602    /// Generates a suspending [`HealthStatusUpdate`] with `update`, for an error that a restart
603    /// cannot fix.
604    ///
605    /// NOTE: an operator that only wedges after such an error keeps buffering its input, so the
606    /// dataflow has to be torn down to bound its memory.
607    pub(crate) fn suspending(error: String, hint: Option<String>) -> Self {
608        HealthStatusUpdate::Stalled {
609            error,
610            hint,
611            action: StallAction::Suspend,
612        }
613    }
614
615    // TODO: redesign ceased status database-issues#7687
616    // Generates a ceasing [`HealthStatusUpdate`] with `update`.
617    // pub(crate) fn ceasing(error: String) -> Self {
618    //     HealthStatusUpdate::Ceased { error }
619    // }
620
621    /// What should happen to the dataflow instance once this update is recorded.
622    pub(crate) fn stall_action(&self) -> StallAction {
623        match self {
624            HealthStatusUpdate::Running |
625            // HealthStatusUpdate::Ceased should never halt because it can occur
626            // at the subsource level and should not cause the entire dataflow
627            // to halt. Instead, the dataflow itself should handle shutting
628            // itself down if need be.
629            HealthStatusUpdate::Ceased { .. } => StallAction::Continue,
630            HealthStatusUpdate::Stalled { action, .. } => *action,
631        }
632    }
633}
634
635#[cfg(test)]
636mod tests {
637    use super::*;
638    use itertools::Itertools;
639
640    // Actual timely tests for `health_operator`.
641
642    #[mz_ore::test]
643    #[cfg_attr(miri, ignore)] // unsupported operation: returning ready events from epoll_wait is not yet implemented
644    fn test_health_operator_basic() {
645        use Step::*;
646
647        // Test 2 inputs across 2 workers.
648        health_operator_runner(
649            2,
650            2,
651            true,
652            vec![
653                AssertStatus(vec![
654                    // Assert both inputs started.
655                    StatusToAssert {
656                        collection_index: 0,
657                        status: Status::Starting,
658                        ..Default::default()
659                    },
660                    StatusToAssert {
661                        collection_index: 1,
662                        status: Status::Starting,
663                        ..Default::default()
664                    },
665                ]),
666                // Update and assert one is running.
667                Update(TestUpdate {
668                    worker_id: 1,
669                    namespace: StatusNamespace::Generator,
670                    id: None,
671                    update: HealthStatusUpdate::running(),
672                }),
673                AssertStatus(vec![StatusToAssert {
674                    collection_index: 0,
675                    status: Status::Running,
676                    ..Default::default()
677                }]),
678                // Assert the other can be stalled by 1 worker.
679                //
680                // TODO(guswynn): ideally we could push these updates
681                // at the same time, but because they are coming from separately
682                // workers, they could end up in different rounds, causing flakes.
683                // For now, we just do this.
684                Update(TestUpdate {
685                    worker_id: 1,
686                    namespace: StatusNamespace::Generator,
687                    id: Some(GlobalId::User(1)),
688                    update: HealthStatusUpdate::running(),
689                }),
690                AssertStatus(vec![StatusToAssert {
691                    collection_index: 1,
692                    status: Status::Running,
693                    ..Default::default()
694                }]),
695                Update(TestUpdate {
696                    worker_id: 0,
697                    namespace: StatusNamespace::Generator,
698                    id: Some(GlobalId::User(1)),
699                    update: HealthStatusUpdate::stalled("uhoh".to_string(), None),
700                }),
701                AssertStatus(vec![StatusToAssert {
702                    collection_index: 1,
703                    status: Status::Stalled,
704                    error: Some("generator: uhoh".to_string()),
705                    errors: Some("generator: uhoh".to_string()),
706                    ..Default::default()
707                }]),
708                // And that it can recover.
709                Update(TestUpdate {
710                    worker_id: 0,
711                    namespace: StatusNamespace::Generator,
712                    id: Some(GlobalId::User(1)),
713                    update: HealthStatusUpdate::running(),
714                }),
715                AssertStatus(vec![StatusToAssert {
716                    collection_index: 1,
717                    status: Status::Running,
718                    ..Default::default()
719                }]),
720            ],
721        );
722    }
723
724    #[mz_ore::test]
725    #[cfg_attr(miri, ignore)] // unsupported operation: returning ready events from epoll_wait is not yet implemented
726    fn test_health_operator_write_namespaced_map() {
727        use Step::*;
728
729        // Test 2 inputs across 2 workers.
730        health_operator_runner(
731            2,
732            2,
733            // testing this
734            false,
735            vec![
736                AssertStatus(vec![
737                    // Assert both inputs started.
738                    StatusToAssert {
739                        collection_index: 0,
740                        status: Status::Starting,
741                        ..Default::default()
742                    },
743                    StatusToAssert {
744                        collection_index: 1,
745                        status: Status::Starting,
746                        ..Default::default()
747                    },
748                ]),
749                Update(TestUpdate {
750                    worker_id: 0,
751                    namespace: StatusNamespace::Generator,
752                    id: Some(GlobalId::User(1)),
753                    update: HealthStatusUpdate::stalled("uhoh".to_string(), None),
754                }),
755                AssertStatus(vec![StatusToAssert {
756                    collection_index: 1,
757                    status: Status::Stalled,
758                    error: Some("generator: uhoh".to_string()),
759                    errors: None,
760                    ..Default::default()
761                }]),
762            ],
763        )
764    }
765
766    #[mz_ore::test]
767    #[cfg_attr(miri, ignore)] // unsupported operation: returning ready events from epoll_wait is not yet implemented
768    fn test_health_operator_namespaces() {
769        use Step::*;
770
771        // Test 2 inputs across 2 workers.
772        health_operator_runner(
773            2,
774            1,
775            true,
776            vec![
777                AssertStatus(vec![
778                    // Assert both inputs started.
779                    StatusToAssert {
780                        collection_index: 0,
781                        status: Status::Starting,
782                        ..Default::default()
783                    },
784                ]),
785                // Assert that we merge namespaced errors correctly.
786                //
787                // Note that these all happen on the same worker id.
788                Update(TestUpdate {
789                    worker_id: 0,
790                    namespace: StatusNamespace::Generator,
791                    id: None,
792                    update: HealthStatusUpdate::stalled("uhoh".to_string(), None),
793                }),
794                AssertStatus(vec![StatusToAssert {
795                    collection_index: 0,
796                    status: Status::Stalled,
797                    error: Some("generator: uhoh".to_string()),
798                    errors: Some("generator: uhoh".to_string()),
799                    ..Default::default()
800                }]),
801                Update(TestUpdate {
802                    worker_id: 0,
803                    namespace: StatusNamespace::Kafka,
804                    id: None,
805                    update: HealthStatusUpdate::stalled("uhoh".to_string(), None),
806                }),
807                AssertStatus(vec![StatusToAssert {
808                    collection_index: 0,
809                    status: Status::Stalled,
810                    error: Some("kafka: uhoh".to_string()),
811                    errors: Some("generator: uhoh, kafka: uhoh".to_string()),
812                    ..Default::default()
813                }]),
814                // And that it can recover.
815                Update(TestUpdate {
816                    worker_id: 0,
817                    namespace: StatusNamespace::Kafka,
818                    id: None,
819                    update: HealthStatusUpdate::running(),
820                }),
821                AssertStatus(vec![StatusToAssert {
822                    collection_index: 0,
823                    status: Status::Stalled,
824                    error: Some("generator: uhoh".to_string()),
825                    errors: Some("generator: uhoh".to_string()),
826                    ..Default::default()
827                }]),
828                Update(TestUpdate {
829                    worker_id: 0,
830                    namespace: StatusNamespace::Generator,
831                    id: None,
832                    update: HealthStatusUpdate::running(),
833                }),
834                AssertStatus(vec![StatusToAssert {
835                    collection_index: 0,
836                    status: Status::Running,
837                    ..Default::default()
838                }]),
839            ],
840        );
841    }
842
843    #[mz_ore::test]
844    #[cfg_attr(miri, ignore)] // unsupported operation: returning ready events from epoll_wait is not yet implemented
845    fn test_health_operator_namespace_side_channel() {
846        use Step::*;
847
848        health_operator_runner(
849            2,
850            1,
851            true,
852            vec![
853                AssertStatus(vec![
854                    // Assert both inputs started.
855                    StatusToAssert {
856                        collection_index: 0,
857                        status: Status::Starting,
858                        ..Default::default()
859                    },
860                ]),
861                // Assert that sidechannel namespaces don't downgrade the status
862                //
863                // Note that these all happen on the same worker id.
864                Update(TestUpdate {
865                    worker_id: 0,
866                    namespace: StatusNamespace::Ssh,
867                    id: None,
868                    update: HealthStatusUpdate::stalled("uhoh".to_string(), None),
869                }),
870                AssertStatus(vec![StatusToAssert {
871                    collection_index: 0,
872                    status: Status::Stalled,
873                    error: Some("ssh: uhoh".to_string()),
874                    errors: Some("ssh: uhoh".to_string()),
875                    ..Default::default()
876                }]),
877                Update(TestUpdate {
878                    worker_id: 0,
879                    namespace: StatusNamespace::Ssh,
880                    id: None,
881                    update: HealthStatusUpdate::stalled("uhoh2".to_string(), None),
882                }),
883                AssertStatus(vec![StatusToAssert {
884                    collection_index: 0,
885                    status: Status::Stalled,
886                    error: Some("ssh: uhoh2".to_string()),
887                    errors: Some("ssh: uhoh2".to_string()),
888                    ..Default::default()
889                }]),
890                Update(TestUpdate {
891                    worker_id: 0,
892                    namespace: StatusNamespace::Ssh,
893                    id: None,
894                    update: HealthStatusUpdate::running(),
895                }),
896                // We haven't starting running yet, as a `Default` namespace hasn't told us.
897                AssertStatus(vec![StatusToAssert {
898                    collection_index: 0,
899                    status: Status::Starting,
900                    ..Default::default()
901                }]),
902                Update(TestUpdate {
903                    worker_id: 0,
904                    namespace: StatusNamespace::Generator,
905                    id: None,
906                    update: HealthStatusUpdate::running(),
907                }),
908                AssertStatus(vec![StatusToAssert {
909                    collection_index: 0,
910                    status: Status::Running,
911                    ..Default::default()
912                }]),
913            ],
914        );
915    }
916
917    #[mz_ore::test]
918    #[cfg_attr(miri, ignore)] // unsupported operation: returning ready events from epoll_wait is not yet implemented
919    fn test_health_operator_hints() {
920        use Step::*;
921
922        health_operator_runner(
923            2,
924            1,
925            true,
926            vec![
927                AssertStatus(vec![
928                    // Assert both inputs started.
929                    StatusToAssert {
930                        collection_index: 0,
931                        status: Status::Starting,
932                        ..Default::default()
933                    },
934                ]),
935                // Note that these all happen across worker ids.
936                Update(TestUpdate {
937                    worker_id: 0,
938                    namespace: StatusNamespace::Generator,
939                    id: None,
940                    update: HealthStatusUpdate::stalled(
941                        "uhoh".to_string(),
942                        Some("hint1".to_string()),
943                    ),
944                }),
945                AssertStatus(vec![StatusToAssert {
946                    collection_index: 0,
947                    status: Status::Stalled,
948                    error: Some("generator: uhoh".to_string()),
949                    errors: Some("generator: uhoh".to_string()),
950                    hint: Some("hint1".to_string()),
951                }]),
952                Update(TestUpdate {
953                    worker_id: 1,
954                    namespace: StatusNamespace::Generator,
955                    id: None,
956                    update: HealthStatusUpdate::stalled(
957                        "uhoh2".to_string(),
958                        Some("hint2".to_string()),
959                    ),
960                }),
961                AssertStatus(vec![StatusToAssert {
962                    collection_index: 0,
963                    status: Status::Stalled,
964                    // Note the error sorts later so we just use that.
965                    error: Some("generator: uhoh2".to_string()),
966                    errors: Some("generator: uhoh2".to_string()),
967                    hint: Some("hint1, hint2".to_string()),
968                }]),
969                // Update one of the hints
970                Update(TestUpdate {
971                    worker_id: 1,
972                    namespace: StatusNamespace::Generator,
973                    id: None,
974                    update: HealthStatusUpdate::stalled(
975                        "uhoh2".to_string(),
976                        Some("hint3".to_string()),
977                    ),
978                }),
979                AssertStatus(vec![StatusToAssert {
980                    collection_index: 0,
981                    status: Status::Stalled,
982                    // Note the error sorts later so we just use that.
983                    error: Some("generator: uhoh2".to_string()),
984                    errors: Some("generator: uhoh2".to_string()),
985                    hint: Some("hint1, hint3".to_string()),
986                }]),
987                // Assert recovery.
988                Update(TestUpdate {
989                    worker_id: 0,
990                    namespace: StatusNamespace::Generator,
991                    id: None,
992                    update: HealthStatusUpdate::running(),
993                }),
994                AssertStatus(vec![StatusToAssert {
995                    collection_index: 0,
996                    status: Status::Stalled,
997                    // Note the error sorts later so we just use that.
998                    error: Some("generator: uhoh2".to_string()),
999                    errors: Some("generator: uhoh2".to_string()),
1000                    hint: Some("hint3".to_string()),
1001                }]),
1002                Update(TestUpdate {
1003                    worker_id: 1,
1004                    namespace: StatusNamespace::Generator,
1005                    id: None,
1006                    update: HealthStatusUpdate::running(),
1007                }),
1008                AssertStatus(vec![StatusToAssert {
1009                    collection_index: 0,
1010                    status: Status::Running,
1011                    ..Default::default()
1012                }]),
1013            ],
1014        );
1015    }
1016
1017    // The below is ALL test infrastructure for the above
1018
1019    use mz_ore::assert_err;
1020    use timely::container::CapacityContainerBuilder;
1021    use timely::dataflow::Scope;
1022    use timely::dataflow::operators::Enter;
1023    use timely::dataflow::operators::exchange::Exchange;
1024    use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender, unbounded_channel};
1025
1026    /// A status to assert.
1027    #[derive(Debug, Clone, PartialEq, Eq)]
1028    struct StatusToAssert {
1029        collection_index: usize,
1030        status: Status,
1031        error: Option<String>,
1032        errors: Option<String>,
1033        hint: Option<String>,
1034    }
1035
1036    impl Default for StatusToAssert {
1037        fn default() -> Self {
1038            StatusToAssert {
1039                collection_index: Default::default(),
1040                status: Status::Running,
1041                error: Default::default(),
1042                errors: Default::default(),
1043                hint: Default::default(),
1044            }
1045        }
1046    }
1047
1048    /// An update to push into the operator.
1049    /// Can come from any worker, and from any input.
1050    #[derive(Debug, Clone)]
1051    struct TestUpdate {
1052        worker_id: u64,
1053        namespace: StatusNamespace,
1054        id: Option<GlobalId>,
1055        update: HealthStatusUpdate,
1056    }
1057
1058    #[derive(Debug, Clone)]
1059    enum Step {
1060        /// Insert a new health update.
1061        Update(TestUpdate),
1062        /// Assert a set of outputs. Note that these should
1063        /// have unique `collection_index`'s
1064        AssertStatus(Vec<StatusToAssert>),
1065    }
1066
1067    struct TestWriter {
1068        sender: UnboundedSender<StatusToAssert>,
1069        input_mapping: BTreeMap<GlobalId, usize>,
1070    }
1071
1072    impl HealthOperator for TestWriter {
1073        fn record_new_status(
1074            &self,
1075            collection_id: GlobalId,
1076            _ts: DateTime<Utc>,
1077            status: Status,
1078            new_error: Option<&str>,
1079            hints: &BTreeSet<String>,
1080            namespaced_errors: &BTreeMap<StatusNamespace, String>,
1081            write_namespaced_map: bool,
1082        ) {
1083            let _ = self.sender.send(StatusToAssert {
1084                collection_index: *self.input_mapping.get(&collection_id).unwrap(),
1085                status,
1086                error: new_error.map(str::to_string),
1087                errors: if !namespaced_errors.is_empty() && write_namespaced_map {
1088                    Some(
1089                        namespaced_errors
1090                            .iter()
1091                            .map(|(ns, err)| format!("{}: {}", ns, err))
1092                            .join(", "),
1093                    )
1094                } else {
1095                    None
1096                },
1097                hint: if !hints.is_empty() {
1098                    Some(hints.iter().join(", "))
1099                } else {
1100                    None
1101                },
1102            });
1103        }
1104
1105        fn send_halt(&self, _id: GlobalId, _error: Option<(StatusNamespace, HealthStatusUpdate)>) {
1106            // Not yet unit-tested
1107            unimplemented!()
1108        }
1109
1110        fn send_suspend(
1111            &self,
1112            _id: GlobalId,
1113            _error: Option<(StatusNamespace, HealthStatusUpdate)>,
1114        ) {
1115            // Not yet unit-tested
1116            unimplemented!()
1117        }
1118
1119        fn chosen_worker(&self) -> Option<usize> {
1120            // We input and assert outputs on the first worker.
1121            Some(0)
1122        }
1123    }
1124
1125    /// Setup a `health_operator` with a set number of workers and inputs, and the
1126    /// steps on the first worker.
1127    fn health_operator_runner(
1128        workers: usize,
1129        inputs: usize,
1130        write_namespaced_map: bool,
1131        steps: Vec<Step>,
1132    ) {
1133        let tokio_runtime = tokio::runtime::Runtime::new().unwrap();
1134        let tokio_handle = tokio_runtime.handle().clone();
1135
1136        let inputs: BTreeMap<GlobalId, usize> = (0..inputs)
1137            .map(|index| (GlobalId::User(u64::cast_from(index)), index))
1138            .collect();
1139
1140        timely::execute::execute(
1141            timely::execute::Config {
1142                communication: timely::CommunicationConfig::Process(workers),
1143                worker: Default::default(),
1144            },
1145            move |worker| {
1146                let steps = steps.clone();
1147                let inputs = inputs.clone();
1148
1149                let _tokio_guard = tokio_handle.enter();
1150                let (in_tx, in_rx) = unbounded_channel();
1151                let (out_tx, mut out_rx) = unbounded_channel();
1152
1153                worker.dataflow::<(), _, _>(|root_scope| {
1154                    root_scope
1155                        .clone()
1156                        .scoped::<mz_repr::Timestamp, _, _>("gus", |scope| {
1157                            let input = producer(root_scope.clone(), in_rx).enter(scope);
1158                            Box::leak(Box::new(health_operator(
1159                                scope,
1160                                mz_ore::now::SYSTEM_TIME.clone(),
1161                                inputs.keys().copied().collect(),
1162                                *inputs.first_key_value().unwrap().0,
1163                                "source_test",
1164                                input,
1165                                TestWriter {
1166                                    sender: out_tx,
1167                                    input_mapping: inputs,
1168                                },
1169                                write_namespaced_map,
1170                                Duration::from_secs(5),
1171                            )));
1172                        });
1173                });
1174
1175                // We arbitrarily do all the testing on the first worker.
1176                if worker.index() == 0 {
1177                    use Step::*;
1178                    for step in steps {
1179                        match step {
1180                            Update(update) => {
1181                                let _ = in_tx.send(update);
1182                            }
1183                            AssertStatus(mut statuses) => loop {
1184                                match out_rx.try_recv() {
1185                                    Err(_) => {
1186                                        worker.step();
1187                                        // This makes testing easier.
1188                                        std::thread::sleep(std::time::Duration::from_millis(50));
1189                                    }
1190                                    Ok(update) => {
1191                                        let pos = statuses
1192                                            .iter()
1193                                            .position(|s| {
1194                                                s.collection_index == update.collection_index
1195                                            })
1196                                            .unwrap();
1197
1198                                        let status_to_assert = &statuses[pos];
1199                                        assert_eq!(&update, status_to_assert);
1200
1201                                        statuses.remove(pos);
1202                                        if statuses.is_empty() {
1203                                            break;
1204                                        }
1205                                    }
1206                                }
1207                            },
1208                        }
1209                    }
1210
1211                    // Assert that nothing is left in the channel.
1212                    assert_err!(out_rx.try_recv());
1213                }
1214            },
1215        )
1216        .unwrap();
1217    }
1218
1219    /// Produces (input_index, HealthStatusUpdate)'s based on the input channel.
1220    ///
1221    /// Only the first worker is used, all others immediately drop their capabilities and channels.
1222    /// After the channel is empty on the first worker, then the frontier will go to [].
1223    /// Also ensures that updates are routed to the correct worker based on the `TestUpdate`
1224    /// using an exchange.
1225    fn producer<'scope>(
1226        scope: Scope<'scope, ()>,
1227        mut input: UnboundedReceiver<TestUpdate>,
1228    ) -> StreamVec<'scope, (), HealthStatusMessage> {
1229        let mut iterator = AsyncOperatorBuilder::new("iterator".to_string(), scope.clone());
1230        let (output_handle, output) = iterator.new_output::<CapacityContainerBuilder<Vec<_>>>();
1231
1232        let index = scope.index();
1233        iterator.build(|mut caps| async move {
1234            // We input and assert outputs on the first worker.
1235            if index != 0 {
1236                return;
1237            }
1238            let mut capability = Some(caps.pop().unwrap());
1239            while let Some(element) = input.recv().await {
1240                output_handle.give(
1241                    capability.as_ref().unwrap(),
1242                    (
1243                        element.worker_id,
1244                        element.id,
1245                        element.namespace,
1246                        element.update,
1247                    ),
1248                );
1249            }
1250
1251            capability.take();
1252        });
1253
1254        let output = output.exchange(|d| d.0).map(|d| HealthStatusMessage {
1255            id: d.1,
1256            namespace: d.2,
1257            update: d.3,
1258        });
1259
1260        output
1261    }
1262}