Skip to main content

mz_compute_client/controller/
peek_lifecycle.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//! Ordering of compute issue, cancellation, and frontend-owned retirement.
11
12use std::sync::Mutex;
13
14use crate::controller::PeekNotification;
15use crate::protocol::response::PeekResponse;
16
17enum State {
18    /// `cancel` is set once compute work is issued.
19    Pending {
20        retire: Box<dyn FnOnce(PeekNotification) + Send>,
21        cancel: Option<Box<dyn FnOnce(PeekResponse) + Send>>,
22    },
23    /// Holds the response for an issue attempt that arrives after retirement.
24    Retired(PeekResponse),
25}
26
27/// A peek's exactly-once retirement, ordered against compute issue and cancellation.
28///
29/// Dropping the handle does not retire the peek. The owner must call
30/// [`Self::complete`] or [`Self::cancel`] on every path where compute will not.
31/// Callbacks run synchronously on the retiring thread, which can be the compute
32/// instance task, so they must not block on that task.
33#[derive(derivative::Derivative)]
34#[derivative(Debug)]
35pub struct PeekLifecycle {
36    #[derivative(Debug = "ignore")]
37    state: Mutex<State>,
38}
39
40impl PeekLifecycle {
41    /// Creates an unissued peek that reports its terminal notification to `retire`.
42    pub fn new(retire: impl FnOnce(PeekNotification) + Send + 'static) -> Self {
43        Self {
44            state: Mutex::new(State::Pending {
45                retire: Box::new(retire),
46                cancel: None,
47            }),
48        }
49    }
50
51    /// Runs `issue` unless the peek is already retired.
52    ///
53    /// `issue` runs under the lifecycle lock and must not call back into this
54    /// handle. It must return `Err` only if no compute peek was issued. In that
55    /// case the peek stays unissued and the caller still owes retirement.
56    ///
57    /// Returns `Ok(None)` once issued. A later [`Self::cancel`] then passes its
58    /// response to `cancel`. If already retired, calls neither callback and
59    /// returns the response to send on the peek's result channel.
60    ///
61    /// # Panics
62    ///
63    /// Panics if the peek is already issued.
64    pub(super) fn issue<E>(
65        &self,
66        issue: impl FnOnce() -> Result<(), E>,
67        cancel: impl FnOnce(PeekResponse) + Send + 'static,
68    ) -> Result<Option<PeekResponse>, E> {
69        let mut state = self.state.lock().expect("peek lifecycle lock poisoned");
70        match &mut *state {
71            State::Retired(response) => Ok(Some(response.clone())),
72            State::Pending { cancel: slot, .. } => {
73                assert!(slot.is_none(), "peek issued twice");
74                issue()?;
75                *slot = Some(Box::new(cancel));
76                Ok(None)
77            }
78        }
79    }
80
81    /// Retires the peek with `outcome` without canceling compute. No-op if already
82    /// retired.
83    pub fn complete(&self, outcome: PeekNotification) {
84        self.retire(outcome, None);
85    }
86
87    /// Retires the peek as canceled. No-op if already retired.
88    ///
89    /// `response` is what the query receives: `Canceled`, or `Error` for a dropped
90    /// dependency. The retirement callback receives `PeekNotification::Canceled`
91    /// in both cases. An unissued peek is never issued. An issued peek gets a
92    /// queued compute cancellation and can still deliver its result first.
93    ///
94    /// # Panics
95    ///
96    /// Panics if `response` is neither `Canceled` nor `Error`.
97    pub fn cancel(&self, response: PeekResponse) {
98        assert!(
99            matches!(&response, PeekResponse::Canceled | PeekResponse::Error(_)),
100            "peek canceled with a non-cancellation response"
101        );
102        self.retire(PeekNotification::Canceled, Some(response));
103    }
104
105    /// Retires the peek with `outcome` unless already retired. A `cancellation`
106    /// response additionally cancels compute if the peek was issued.
107    fn retire(&self, outcome: PeekNotification, cancellation: Option<PeekResponse>) {
108        let previous = {
109            let mut state = self.state.lock().expect("peek lifecycle lock poisoned");
110            if matches!(&*state, State::Retired(_)) {
111                return;
112            }
113            let response = cancellation.clone().unwrap_or(PeekResponse::Canceled);
114            std::mem::replace(&mut *state, State::Retired(response))
115        };
116        let State::Pending { retire, cancel } = previous else {
117            unreachable!("retired state returns above");
118        };
119        // The callbacks remove registry entries and enqueue compute commands.
120        // Running them under the lifecycle lock would invert lock order with
121        // those structures.
122        if let (Some(cancel), Some(response)) = (cancel, cancellation) {
123            cancel(response);
124        }
125        retire(outcome);
126    }
127}
128
129#[cfg(test)]
130mod tests {
131    use std::sync::{Arc, Barrier, Mutex};
132
133    use crate::controller::PeekNotification;
134    use crate::protocol::response::{PeekError, PeekResponse};
135
136    use super::PeekLifecycle;
137
138    fn success() -> PeekNotification {
139        PeekNotification::Success {
140            rows: 1,
141            result_size: 8,
142        }
143    }
144
145    #[mz_ore::test]
146    fn cancellation_before_issue_prevents_issue() {
147        let outcomes = Arc::new(Mutex::new(Vec::new()));
148        let captured = Arc::clone(&outcomes);
149        let lifecycle = PeekLifecycle::new(move |outcome| {
150            captured.lock().expect("test lock poisoned").push(outcome)
151        });
152        lifecycle.cancel(PeekResponse::Canceled);
153        let result = lifecycle.issue::<()>(
154            || panic!("canceled peek issued"),
155            |_| panic!("unissued peek canceled"),
156        );
157        assert_eq!(result, Ok(Some(PeekResponse::Canceled)));
158        lifecycle.complete(success());
159        assert_eq!(
160            *outcomes.lock().expect("test lock poisoned"),
161            vec![PeekNotification::Canceled]
162        );
163    }
164
165    #[mz_ore::test]
166    fn cancellation_after_issue_cancels_compute_once() {
167        let events = Arc::new(Mutex::new(Vec::new()));
168        let retired = Arc::clone(&events);
169        let lifecycle =
170            PeekLifecycle::new(move |_| retired.lock().expect("test lock poisoned").push("retire"));
171        let issued = Arc::clone(&events);
172        let canceled = Arc::clone(&events);
173        assert_eq!(
174            lifecycle.issue::<()>(
175                move || {
176                    issued.lock().expect("test lock poisoned").push("issue");
177                    Ok(())
178                },
179                move |_| canceled.lock().expect("test lock poisoned").push("cancel")
180            ),
181            Ok(None)
182        );
183        lifecycle.cancel(PeekResponse::Canceled);
184        lifecycle.cancel(PeekResponse::Canceled);
185        lifecycle.complete(success());
186        assert_eq!(
187            *events.lock().expect("test lock poisoned"),
188            vec!["issue", "cancel", "retire"]
189        );
190    }
191
192    #[mz_ore::test]
193    fn completion_prevents_late_cancellation() {
194        let outcomes = Arc::new(Mutex::new(Vec::new()));
195        let captured = Arc::clone(&outcomes);
196        let lifecycle = PeekLifecycle::new(move |outcome| {
197            captured.lock().expect("test lock poisoned").push(outcome)
198        });
199        assert_eq!(
200            lifecycle.issue::<()>(|| Ok(()), |_| panic!("completed peek canceled")),
201            Ok(None)
202        );
203        lifecycle.complete(success());
204        lifecycle.cancel(PeekResponse::Canceled);
205        lifecycle.complete(success());
206        assert_eq!(
207            *outcomes.lock().expect("test lock poisoned"),
208            vec![success()]
209        );
210    }
211
212    #[mz_ore::test]
213    fn failed_issue_preserves_retirement_obligation() {
214        let outcomes = Arc::new(Mutex::new(Vec::new()));
215        let captured = Arc::clone(&outcomes);
216        let lifecycle = PeekLifecycle::new(move |outcome| {
217            captured.lock().expect("test lock poisoned").push(outcome)
218        });
219        assert_eq!(
220            lifecycle.issue(|| Err("issue failed"), |_| panic!("failed peek canceled")),
221            Err("issue failed")
222        );
223        let error = PeekNotification::Error("issue failed".into());
224        lifecycle.complete(error.clone());
225        lifecycle.cancel(PeekResponse::Canceled);
226        assert_eq!(*outcomes.lock().expect("test lock poisoned"), vec![error]);
227    }
228
229    #[mz_ore::test]
230    fn cancellation_racing_issue_is_ordered_after_issue() {
231        let entered = Arc::new(Barrier::new(2));
232        let release = Arc::new(Barrier::new(2));
233        let events = Arc::new(Mutex::new(Vec::new()));
234        let retired = Arc::clone(&events);
235        let lifecycle = Arc::new(PeekLifecycle::new(move |_| {
236            retired.lock().expect("test lock poisoned").push("retire")
237        }));
238        std::thread::scope(|scope| {
239            let issuing = Arc::clone(&lifecycle);
240            let entered_issue = Arc::clone(&entered);
241            let release_issue = Arc::clone(&release);
242            let issued = Arc::clone(&events);
243            let canceled = Arc::clone(&events);
244            let issue = scope.spawn(move || {
245                issuing.issue::<()>(
246                    move || {
247                        entered_issue.wait();
248                        release_issue.wait();
249                        issued.lock().expect("test lock poisoned").push("issue");
250                        Ok(())
251                    },
252                    move |_| canceled.lock().expect("test lock poisoned").push("cancel"),
253                )
254            });
255            entered.wait();
256            let (locked_tx, locked_rx) = std::sync::mpsc::channel();
257            let canceling = &lifecycle;
258            let cancel = scope.spawn(move || {
259                let locked = matches!(
260                    canceling.state.try_lock(),
261                    Err(std::sync::TryLockError::WouldBlock)
262                );
263                locked_tx.send(locked).expect("issue thread alive");
264                canceling.cancel(PeekResponse::Canceled);
265            });
266            let locked = locked_rx.recv().expect("cancellation thread alive");
267            release.wait();
268            assert!(locked, "issue must hold the lifecycle lock");
269            assert_eq!(issue.join().expect("test thread panicked"), Ok(None));
270            cancel.join().expect("test thread panicked");
271        });
272        assert_eq!(
273            *events.lock().expect("test lock poisoned"),
274            vec!["issue", "cancel", "retire"]
275        );
276    }
277
278    #[mz_ore::test]
279    fn dependency_drop_returns_error_but_logs_cancellation() {
280        let outcomes = Arc::new(Mutex::new(Vec::new()));
281        let captured = Arc::clone(&outcomes);
282        let lifecycle = PeekLifecycle::new(move |outcome| {
283            captured.lock().expect("test lock poisoned").push(outcome)
284        });
285        let response = PeekResponse::Error(PeekError::unstructured("dependency dropped"));
286        lifecycle.cancel(response.clone());
287        assert_eq!(
288            lifecycle.issue::<()>(
289                || panic!("dropped peek issued"),
290                |_| panic!("unissued peek canceled")
291            ),
292            Ok(Some(response))
293        );
294        assert_eq!(
295            *outcomes.lock().expect("test lock poisoned"),
296            vec![PeekNotification::Canceled]
297        );
298    }
299}