Skip to main content

mz_adapter/coord/
consistency.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//! Internal consistency checks that validate invariants of [`Coordinator`].
11
12use super::Coordinator;
13use crate::catalog::consistency::CatalogInconsistencies;
14use mz_adapter_types::connection::ConnectionIdType;
15use mz_catalog::memory::objects::{CatalogItem, DataSourceDesc, Source, Table, TableDataSource};
16use mz_controller_types::{ClusterId, ReplicaId};
17use mz_ore::instrument;
18use mz_repr::{CatalogItemId, GlobalId};
19use mz_sql::catalog::{CatalogCluster, CatalogClusterReplica};
20use serde::Serialize;
21
22#[derive(Debug, Default, Serialize, PartialEq)]
23pub struct CoordinatorInconsistencies {
24    /// Inconsistencies found in the catalog.
25    catalog_inconsistencies: Box<CatalogInconsistencies>,
26    /// Inconsistencies found in read holds.
27    read_holds: Vec<ReadHoldsInconsistency>,
28    /// Inconsistencies found with our map of active webhooks.
29    active_webhooks: Vec<ActiveWebhookInconsistency>,
30    /// Inconsistencies found with our map of cluster statuses.
31    cluster_statuses: Vec<ClusterStatusInconsistency>,
32}
33
34impl CoordinatorInconsistencies {
35    pub fn is_empty(&self) -> bool {
36        self.catalog_inconsistencies.is_empty()
37            && self.read_holds.is_empty()
38            && self.active_webhooks.is_empty()
39            && self.cluster_statuses.is_empty()
40    }
41}
42
43impl Coordinator {
44    /// Checks the [`Coordinator`] to make sure we're internally consistent.
45    #[instrument(name = "coord::check_consistency")]
46    pub fn check_consistency(&mut self) -> Result<(), CoordinatorInconsistencies> {
47        let mut inconsistencies = CoordinatorInconsistencies::default();
48
49        // Without soft assertions only `/api/coordinator/check` gets here, and a cache would leave
50        // the coordinator holding the names and `create_sql` of every non-temporary user item.
51        let checked_sql =
52            mz_ore::assert::soft_assertions_enabled().then_some(&mut self.checked_create_sql);
53        if let Err(catalog_inconsistencies) = self
54            .catalog
55            .state()
56            .check_consistency_with_cache(checked_sql)
57        {
58            inconsistencies.catalog_inconsistencies = catalog_inconsistencies;
59        }
60
61        if let Err(read_holds) = self.check_read_holds() {
62            inconsistencies.read_holds = read_holds;
63        }
64
65        if let Err(active_webhooks) = self.check_active_webhooks() {
66            inconsistencies.active_webhooks = active_webhooks;
67        }
68
69        if let Err(cluster_statuses) = self.check_cluster_statuses() {
70            inconsistencies.cluster_statuses = cluster_statuses;
71        }
72
73        if inconsistencies.is_empty() {
74            Ok(())
75        } else {
76            Err(inconsistencies)
77        }
78    }
79
80    /// # Invariants:
81    ///
82    /// * Read holds should reference known objects.
83    ///
84    fn check_read_holds(&self) -> Result<(), Vec<ReadHoldsInconsistency>> {
85        let mut inconsistencies = Vec::new();
86
87        for timeline in self.global_timelines.values() {
88            for id in timeline.read_holds.storage_ids() {
89                if self.catalog().try_get_entry_by_global_id(&id).is_none() {
90                    inconsistencies.push(ReadHoldsInconsistency::Storage(id));
91                }
92            }
93            for (cluster_id, id) in timeline.read_holds.compute_ids() {
94                if self.catalog().try_get_cluster(cluster_id).is_none() {
95                    inconsistencies.push(ReadHoldsInconsistency::Cluster(cluster_id));
96                }
97                if !id.is_transient() && self.catalog().try_get_entry_by_global_id(&id).is_none() {
98                    inconsistencies.push(ReadHoldsInconsistency::Compute(id));
99                }
100            }
101        }
102
103        for conn_id in self.txn_read_holds.keys() {
104            if !self.active_conns.contains_key(conn_id) {
105                inconsistencies.push(ReadHoldsInconsistency::Transaction(conn_id.unhandled()));
106            }
107        }
108
109        if inconsistencies.is_empty() {
110            Ok(())
111        } else {
112            Err(inconsistencies)
113        }
114    }
115
116    /// # Invariants
117    ///
118    /// * All [`GlobalId`]s in the `active_webhooks` map should reference known webhook sources.
119    ///
120    fn check_active_webhooks(&self) -> Result<(), Vec<ActiveWebhookInconsistency>> {
121        let mut inconsistencies = vec![];
122        for (id, _) in &self.active_webhooks {
123            let is_webhook = self
124                .catalog()
125                .try_get_entry(id)
126                .map(|entry| entry.item())
127                .and_then(|item| {
128                    let data_source = match &item {
129                        CatalogItem::Source(Source { data_source, .. }) => data_source,
130                        CatalogItem::Table(Table {
131                            data_source: TableDataSource::DataSource { desc, .. },
132                            ..
133                        }) => desc,
134                        _ => return None,
135                    };
136                    Some(matches!(data_source, DataSourceDesc::Webhook { .. }))
137                })
138                .unwrap_or(false);
139            if !is_webhook {
140                inconsistencies.push(ActiveWebhookInconsistency::NonExistentWebhook(*id));
141            }
142        }
143
144        if inconsistencies.is_empty() {
145            Ok(())
146        } else {
147            Err(inconsistencies)
148        }
149    }
150
151    /// # Invariants
152    ///
153    /// * All [`ClusterId`]s in the `cluster_replica_statuses` map should reference known clusters.
154    /// * All [`ReplicaId`]s in the `cluster_replica_statuses` map should reference known cluster
155    /// replicas.
156    fn check_cluster_statuses(&self) -> Result<(), Vec<ClusterStatusInconsistency>> {
157        let mut inconsistencies = vec![];
158        for (cluster_id, replica_status) in &self.cluster_replica_statuses.0 {
159            if self.catalog().try_get_cluster(*cluster_id).is_none() {
160                inconsistencies.push(ClusterStatusInconsistency::NonExistentCluster(*cluster_id));
161            }
162            for replica_id in replica_status.keys() {
163                if self
164                    .catalog()
165                    .try_get_cluster_replica(*cluster_id, *replica_id)
166                    .is_none()
167                {
168                    inconsistencies.push(ClusterStatusInconsistency::NonExistentReplica(
169                        *cluster_id,
170                        *replica_id,
171                    ));
172                }
173            }
174        }
175        for cluster in self.catalog().clusters() {
176            if let Some(cluster_statuses) = self.cluster_replica_statuses.0.get(&cluster.id()) {
177                for replica in cluster.replicas() {
178                    if !cluster_statuses.contains_key(&replica.replica_id()) {
179                        inconsistencies.push(ClusterStatusInconsistency::NonExistentReplicaStatus(
180                            cluster.name.clone(),
181                            replica.name.clone(),
182                            cluster.id(),
183                            replica.replica_id(),
184                        ));
185                    }
186                }
187            } else {
188                inconsistencies.push(ClusterStatusInconsistency::NonExistentClusterStatus(
189                    cluster.name.clone(),
190                    cluster.id(),
191                ));
192            }
193        }
194        if inconsistencies.is_empty() {
195            Ok(())
196        } else {
197            Err(inconsistencies)
198        }
199    }
200}
201
202#[derive(Debug, Serialize, PartialEq, Eq)]
203enum ReadHoldsInconsistency {
204    Storage(GlobalId),
205    Compute(GlobalId),
206    Cluster(ClusterId),
207    Transaction(ConnectionIdType),
208}
209
210#[derive(Debug, Serialize, PartialEq, Eq)]
211enum ActiveWebhookInconsistency {
212    NonExistentWebhook(CatalogItemId),
213}
214
215#[derive(Debug, Serialize, PartialEq, Eq)]
216enum ClusterStatusInconsistency {
217    NonExistentCluster(ClusterId),
218    NonExistentReplica(ClusterId, ReplicaId),
219    NonExistentClusterStatus(String, ClusterId),
220    NonExistentReplicaStatus(String, String, ClusterId, ReplicaId),
221}