Skip to main content

mz_adapter/
peek_registry.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//! Connection-partitioned tracking for frontend-owned peeks.
11
12use std::collections::{BTreeMap, BTreeSet};
13use std::sync::{Arc, Mutex, Weak};
14
15use mz_adapter_types::connection::ConnectionId;
16use mz_compute_client::controller::peek_lifecycle::PeekLifecycle;
17use mz_compute_client::protocol::response::{PeekError, PeekResponse};
18use mz_controller_types::ClusterId;
19use mz_repr::GlobalId;
20use uuid::Uuid;
21
22use crate::coord::peek::DroppedDependency;
23
24/// The global index is used only for connection management and catalog teardown.
25/// Ordinary registration and completion touch only their connection partition.
26#[derive(Debug, Default)]
27pub(crate) struct PeekRegistry {
28    connections: Mutex<BTreeMap<ConnectionId, Arc<ConnectionPeeks>>>,
29}
30
31#[derive(Debug, Default)]
32pub(crate) struct ConnectionPeeks {
33    state: Mutex<ConnectionState>,
34}
35
36#[derive(Debug, Default)]
37struct ConnectionState {
38    closed: bool,
39    cancellation_epoch: u64,
40    peeks: BTreeMap<Uuid, RegisteredPeek>,
41}
42
43#[derive(Debug)]
44pub(crate) struct RegisteredPeek {
45    pub cluster_id: ClusterId,
46    pub depends_on: BTreeSet<GlobalId>,
47    pub lifecycle: Weak<PeekLifecycle>,
48}
49
50#[derive(Debug, PartialEq, Eq)]
51pub(crate) enum RegisterError {
52    CatalogChanged,
53    Canceled,
54}
55
56impl PeekRegistry {
57    /// Returns the connection's partition, creating it if needed. It stays
58    /// indexed until [`Self::close_connection`].
59    pub(crate) fn connection(&self, id: ConnectionId) -> Arc<ConnectionPeeks> {
60        Arc::clone(
61            self.connections
62                .lock()
63                .expect("peek registry lock poisoned")
64                .entry(id)
65                .or_default(),
66        )
67    }
68
69    /// Cancels the connection's peeks and rejects its later registrations.
70    /// Returns the number of peeks canceled.
71    pub(crate) fn close_connection(&self, id: &ConnectionId) -> usize {
72        let connection = self
73            .connections
74            .lock()
75            .expect("peek registry lock poisoned")
76            .remove(id);
77        connection.map_or(0, |connection| connection.cancel_all(true))
78    }
79
80    /// Cancels the connection's peeks. Returns the number of peeks canceled.
81    pub(crate) fn cancel_connection(&self, id: &ConnectionId) -> usize {
82        let connection = self
83            .connections
84            .lock()
85            .expect("peek registry lock poisoned")
86            .get(id)
87            .cloned();
88        connection.map_or(0, |connection| connection.cancel_all(false))
89    }
90
91    /// Catalog invalidation must be published before taking this snapshot.
92    /// Each partition then rejects stale registration or includes it in the
93    /// invalidation scan. No catalog or lifecycle callback runs under the index lock.
94    pub(crate) fn invalidate(
95        &self,
96        relations: &BTreeMap<GlobalId, String>,
97        clusters: &BTreeMap<ClusterId, String>,
98    ) {
99        let connections: Vec<_> = self
100            .connections
101            .lock()
102            .expect("peek registry lock poisoned")
103            .values()
104            .cloned()
105            .collect();
106        for connection in connections {
107            connection.invalidate(relations, clusters);
108        }
109    }
110}
111
112impl ConnectionPeeks {
113    pub(crate) fn cancellation_epoch(&self) -> u64 {
114        self.state
115            .lock()
116            .expect("connection peek lock poisoned")
117            .cancellation_epoch
118    }
119
120    /// Checks catalog freshness under the invalidation scan's lock.
121    /// The caller must refresh and validate dependencies after CatalogChanged,
122    /// not turn an unrelated catalog edit into a SQL error.
123    pub(crate) fn register(
124        &self,
125        uuid: Uuid,
126        peek: RegisteredPeek,
127        cancellation_epoch: u64,
128        catalog_is_current: impl FnOnce() -> bool,
129    ) -> Result<(), RegisterError> {
130        let mut state = self.state.lock().expect("connection peek lock poisoned");
131        if state.closed || state.cancellation_epoch != cancellation_epoch {
132            return Err(RegisterError::Canceled);
133        }
134        if !catalog_is_current() {
135            return Err(RegisterError::CatalogChanged);
136        }
137        let previous = state.peeks.insert(uuid, peek);
138        assert!(previous.is_none(), "peek registered twice");
139        Ok(())
140    }
141
142    pub(crate) fn remove(&self, uuid: &Uuid) {
143        self.state
144            .lock()
145            .expect("connection peek lock poisoned")
146            .peeks
147            .remove(uuid);
148    }
149
150    pub(crate) fn cancel(&self) {
151        self.cancel_all(false);
152    }
153
154    fn cancel_all(&self, close: bool) -> usize {
155        let peeks = {
156            let mut state = self.state.lock().expect("connection peek lock poisoned");
157            state.closed |= close;
158            state.cancellation_epoch = state
159                .cancellation_epoch
160                .checked_add(1)
161                .expect("peek cancellation epoch overflow");
162            std::mem::take(&mut state.peeks)
163        };
164        let canceled = peeks.len();
165        for peek in peeks.into_values() {
166            if let Some(lifecycle) = peek.lifecycle.upgrade() {
167                lifecycle.cancel(PeekResponse::Canceled);
168            }
169        }
170        canceled
171    }
172
173    fn invalidate(
174        &self,
175        relations: &BTreeMap<GlobalId, String>,
176        clusters: &BTreeMap<ClusterId, String>,
177    ) {
178        let canceled = {
179            let mut state = self.state.lock().expect("connection peek lock poisoned");
180            let affected: Vec<_> = state
181                .peeks
182                .iter()
183                .filter_map(|(uuid, peek)| {
184                    let dependency = peek
185                        .depends_on
186                        .iter()
187                        .find_map(|id| relations.get(id))
188                        .map(|name| DroppedDependency::Relation { name: name.clone() })
189                        .or_else(|| {
190                            clusters
191                                .get(&peek.cluster_id)
192                                .map(|name| DroppedDependency::Cluster { name: name.clone() })
193                        });
194                    dependency.map(|dependency| (*uuid, dependency))
195                })
196                .collect();
197            affected
198                .into_iter()
199                .map(|(uuid, dependency)| {
200                    (
201                        state.peeks.remove(&uuid).expect("affected peek exists"),
202                        dependency,
203                    )
204                })
205                .collect::<Vec<_>>()
206        };
207        for (peek, dependency) in canceled {
208            if let Some(lifecycle) = peek.lifecycle.upgrade() {
209                lifecycle.cancel(PeekResponse::Error(PeekError::unstructured(
210                    dependency.query_terminated_error(),
211                )));
212            }
213        }
214    }
215}
216
217#[cfg(test)]
218mod tests {
219    use std::collections::{BTreeMap, BTreeSet};
220    use std::sync::atomic::{AtomicBool, Ordering};
221    use std::sync::{Arc, Barrier, Mutex};
222
223    use mz_compute_client::controller::PeekNotification;
224    use mz_compute_client::controller::peek_lifecycle::PeekLifecycle;
225    use mz_controller_types::ClusterId;
226    use mz_repr::GlobalId;
227    use uuid::Uuid;
228
229    use super::{ConnectionPeeks, PeekRegistry, RegisterError, RegisteredPeek};
230
231    fn peek(lifecycle: &Arc<PeekLifecycle>) -> RegisteredPeek {
232        RegisteredPeek {
233            cluster_id: ClusterId::User(1),
234            depends_on: BTreeSet::from([GlobalId::User(1)]),
235            lifecycle: Arc::downgrade(lifecycle),
236        }
237    }
238
239    #[mz_ore::test]
240    fn stale_catalog_does_not_publish_peek() {
241        let connection = ConnectionPeeks::default();
242        let lifecycle = Arc::new(PeekLifecycle::new(|_| panic!("unregistered peek retired")));
243        let uuid = Uuid::new_v4();
244        assert_eq!(
245            connection.register(uuid, peek(&lifecycle), 0, || false),
246            Err(RegisterError::CatalogChanged)
247        );
248        assert!(
249            connection
250                .state
251                .lock()
252                .expect("test lock poisoned")
253                .peeks
254                .is_empty()
255        );
256        assert_eq!(
257            connection.register(uuid, peek(&lifecycle), 0, || true),
258            Ok(())
259        );
260        connection.remove(&uuid);
261    }
262
263    #[mz_ore::test]
264    fn cancel_before_registration_rejects_old_execution_epoch() {
265        let connection = ConnectionPeeks::default();
266        let lifecycle = Arc::new(PeekLifecycle::new(|_| panic!("unregistered peek retired")));
267        let epoch = connection.cancellation_epoch();
268        connection.cancel();
269        let uuid = Uuid::new_v4();
270        assert_eq!(
271            connection.register(uuid, peek(&lifecycle), epoch, || true),
272            Err(RegisterError::Canceled)
273        );
274        assert_eq!(
275            connection.register(
276                uuid,
277                peek(&lifecycle),
278                connection.cancellation_epoch(),
279                || true
280            ),
281            Ok(())
282        );
283        connection.remove(&uuid);
284    }
285
286    #[mz_ore::test]
287    fn closed_connection_never_registers_again() {
288        let connection = ConnectionPeeks::default();
289        connection.cancel_all(true);
290        let lifecycle = Arc::new(PeekLifecycle::new(|_| panic!("unregistered peek retired")));
291        assert_eq!(
292            connection.register(
293                Uuid::new_v4(),
294                peek(&lifecycle),
295                connection.cancellation_epoch(),
296                || true
297            ),
298            Err(RegisterError::Canceled)
299        );
300    }
301
302    #[mz_ore::test]
303    fn dependency_invalidation_retires_only_matching_peeks() {
304        let registry = PeekRegistry::default();
305        let connection = registry.connection(mz_ore::id_gen::IdHandle::Static(1));
306        let outcomes = Arc::new(Mutex::new(Vec::new()));
307        let retired = Arc::clone(&outcomes);
308        let lifecycle = Arc::new(PeekLifecycle::new(move |outcome| {
309            retired.lock().expect("test lock poisoned").push(outcome)
310        }));
311        connection
312            .register(Uuid::new_v4(), peek(&lifecycle), 0, || true)
313            .expect("test operation failed");
314        registry.invalidate(
315            &BTreeMap::from([(GlobalId::User(2), "other".into())]),
316            &BTreeMap::new(),
317        );
318        assert!(outcomes.lock().expect("test lock poisoned").is_empty());
319        registry.invalidate(
320            &BTreeMap::from([(GlobalId::User(1), "t".into())]),
321            &BTreeMap::new(),
322        );
323        registry.invalidate(
324            &BTreeMap::new(),
325            &BTreeMap::from([(ClusterId::User(1), "c".into())]),
326        );
327        assert_eq!(
328            *outcomes.lock().expect("test lock poisoned"),
329            vec![PeekNotification::Canceled]
330        );
331        assert!(
332            connection
333                .state
334                .lock()
335                .expect("test lock poisoned")
336                .peeks
337                .is_empty()
338        );
339    }
340
341    #[mz_ore::test]
342    fn retirement_callback_can_remove_registration() {
343        let connection = Arc::new(ConnectionPeeks::default());
344        let retired = Arc::clone(&connection);
345        let uuid = Uuid::new_v4();
346        let lifecycle = Arc::new(PeekLifecycle::new(move |_| retired.remove(&uuid)));
347        connection
348            .register(uuid, peek(&lifecycle), 0, || true)
349            .expect("test operation failed");
350        connection.cancel();
351        assert!(
352            connection
353                .state
354                .lock()
355                .expect("test lock poisoned")
356                .peeks
357                .is_empty()
358        );
359    }
360
361    #[mz_ore::test]
362    fn drop_racing_catalog_check_sees_published_registration() {
363        let registry = PeekRegistry::default();
364        let connection = registry.connection(mz_ore::id_gen::IdHandle::Static(1));
365        let outcomes = Arc::new(Mutex::new(Vec::new()));
366        let retired = Arc::clone(&outcomes);
367        let lifecycle = Arc::new(PeekLifecycle::new(move |outcome| {
368            retired.lock().expect("test lock poisoned").push(outcome)
369        }));
370        let checked = Barrier::new(2);
371        let published = Barrier::new(2);
372        let current = AtomicBool::new(true);
373        std::thread::scope(|scope| {
374            let registering = scope.spawn(|| {
375                connection.register(Uuid::new_v4(), peek(&lifecycle), 0, || {
376                    let result = current.load(Ordering::SeqCst);
377                    checked.wait();
378                    published.wait();
379                    result
380                })
381            });
382            // Publish the catalog revision after the freshness check, while
383            // registration still holds the partition lock. Invalidation must
384            // wait for publication into that partition, then find the peek.
385            checked.wait();
386            current.store(false, Ordering::SeqCst);
387            published.wait();
388            registry.invalidate(
389                &BTreeMap::from([(GlobalId::User(1), "t".into())]),
390                &BTreeMap::new(),
391            );
392            assert_eq!(registering.join().expect("test thread panicked"), Ok(()));
393        });
394        assert_eq!(
395            *outcomes.lock().expect("test lock poisoned"),
396            vec![PeekNotification::Canceled]
397        );
398        assert!(
399            connection
400                .state
401                .lock()
402                .expect("test lock poisoned")
403                .peeks
404                .is_empty()
405        );
406    }
407}