Skip to main content

mz_storage/
internal_control.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//! Types for cluster-internal control messages that can be broadcast to all
7//! workers from individual operators/workers.
8
9use std::cell::RefCell;
10use std::collections::{BTreeMap, BTreeSet};
11use std::rc::Rc;
12use std::sync::mpsc;
13
14use mz_repr::{GlobalId, Row};
15use mz_rocksdb::config::SharedWriteBufferManager;
16use mz_storage_types::controller::CollectionMetadata;
17use mz_storage_types::oneshot_sources::OneshotIngestionRequest;
18use mz_storage_types::parameters::StorageParameters;
19use mz_storage_types::sinks::StorageSinkDesc;
20use mz_storage_types::sources::IngestionDescription;
21use mz_timely_util::scope_label::ScopeExt;
22use serde::{Deserialize, Serialize};
23use timely::dataflow::channels::pact::{Exchange, Pipeline};
24use timely::dataflow::operators::Operator;
25use timely::dataflow::operators::generic::source;
26use timely::dataflow::operators::vec::Broadcast;
27use timely::progress::Antichain;
28use timely::scheduling::Activator;
29use timely::worker::Worker as TimelyWorker;
30
31use crate::statistics::{SinkStatisticsRecord, SourceStatisticsRecord};
32
33/// _Dynamic_ storage instance configuration parameters that are used during dataflow rendering.
34/// Changes to these parameters are applied to `StorageWorker`s in a consistent order
35/// with source and sink creation.
36#[derive(Debug)]
37pub struct DataflowParameters {
38    /// Configuration/tuning for RocksDB. This also contains
39    /// some shared objects, which is why its separate.
40    pub upsert_rocksdb_tuning_config: mz_rocksdb::RocksDBConfig,
41}
42
43impl DataflowParameters {
44    /// Creates a new instance of `DataflowParameters` with given shared rocksdb write buffer manager
45    /// and the cluster memory limit
46    pub fn new(
47        shared_rocksdb_write_buffer_manager: SharedWriteBufferManager,
48        cluster_memory_limit: Option<usize>,
49    ) -> Self {
50        Self {
51            upsert_rocksdb_tuning_config: mz_rocksdb::RocksDBConfig::new(
52                shared_rocksdb_write_buffer_manager,
53                cluster_memory_limit,
54            ),
55        }
56    }
57    /// Update the `DataflowParameters` with new configuration.
58    pub fn update(&mut self, storage_parameters: StorageParameters) {
59        self.upsert_rocksdb_tuning_config
60            .apply(storage_parameters.upsert_rocksdb_tuning_config.clone());
61    }
62}
63
64/// Internal commands that can be sent by individual operators/workers that will
65/// be broadcast to all workers. The worker main loop will receive those and act
66/// on them.
67#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
68pub enum InternalStorageCommand {
69    /// Suspend and restart the dataflow identified by the `GlobalId`.
70    SuspendAndRestart {
71        /// The id of the dataflow that should be restarted.
72        id: GlobalId,
73        /// The reason for the restart request.
74        reason: String,
75    },
76    /// Suspend the dataflow identified by the `GlobalId` without restarting it. It stays down
77    /// until the controller issues its run command again.
78    Suspend {
79        /// The id of the dataflow that should be suspended.
80        id: GlobalId,
81        /// The epoch of the rendering that asked for this. A later rendering keeps running.
82        epoch: u64,
83        /// The reason for the suspend request.
84        reason: String,
85    },
86    /// Render an ingestion dataflow at the given resumption frontier.
87    CreateIngestionDataflow {
88        /// ID of the ingestion/sourve.
89        id: GlobalId,
90        /// The description of the ingestion/source.
91        ingestion_description: IngestionDescription<CollectionMetadata>,
92        /// The frontier beyond which ingested updates should be uncompacted. Inputs to the
93        /// ingestion are guaranteed to be readable at this frontier.
94        as_of: Antichain<mz_repr::Timestamp>,
95        /// A frontier in the Materialize time domain with the property that all updates not beyond
96        /// it have already been durably ingested.
97        resume_uppers: BTreeMap<GlobalId, Antichain<mz_repr::Timestamp>>,
98        /// A frontier in the source time domain with the property that all updates not beyond it
99        /// have already been durably ingested.
100        source_resume_uppers: BTreeMap<GlobalId, Vec<Row>>,
101    },
102    /// Render a oneshot ingestion dataflow that fetches data from an external system and stages
103    /// batches in Persist, that can later be appended to the shard.
104    RunOneshotIngestion {
105        /// ID of the running dataflow that is doing the ingestion.
106        ingestion_id: uuid::Uuid,
107        /// ID of the collection we'll create batches for.
108        collection_id: GlobalId,
109        /// Metadata of the collection we'll create batches for.
110        collection_meta: CollectionMetadata,
111        /// Description of the oneshot ingestion.
112        request: OneshotIngestionRequest,
113    },
114    /// Render a sink dataflow.
115    RunSinkDataflow(
116        GlobalId,
117        StorageSinkDesc<CollectionMetadata, mz_repr::Timestamp>,
118    ),
119    /// Drop all state and operators for a dataflow. This is a vec because some
120    /// dataflows have their state spread over multiple IDs (i.e. sources that
121    /// spawn subsources); this means that actions taken in response to this
122    /// command should be permissive about missing state.
123    DropDataflow(Vec<GlobalId>),
124
125    /// Update the configuration for rendering dataflows.
126    UpdateConfiguration {
127        /// The new configuration parameters.
128        storage_parameters: StorageParameters,
129    },
130    /// For moving statistics updates to worker 0.
131    StatisticsUpdate {
132        /// Local statistics, with their epochs.
133        sources: Vec<(usize, SourceStatisticsRecord)>,
134        /// Local statistics, with their epochs.
135        sinks: Vec<(usize, SinkStatisticsRecord)>,
136    },
137}
138
139/// A sender broadcasting [`InternalStorageCommand`]s to all workers.
140#[derive(Clone)]
141pub struct InternalCommandSender {
142    tx: mpsc::Sender<InternalStorageCommand>,
143    activator: Rc<RefCell<Option<Activator>>>,
144}
145
146impl InternalCommandSender {
147    /// Creates a sender from externally provided parts, for hosts that
148    /// route internal commands through their own sequencing channel instead of
149    /// `setup_command_sequencer`.
150    pub fn from_parts(
151        tx: mpsc::Sender<InternalStorageCommand>,
152        activator: Rc<RefCell<Option<Activator>>>,
153    ) -> Self {
154        Self { tx, activator }
155    }
156
157    /// Broadcasts the given command to all workers.
158    pub fn send(&self, cmd: InternalStorageCommand) {
159        if self.tx.send(cmd).is_err() {
160            panic!("internal command channel disconnected");
161        }
162
163        self.activator.borrow().as_ref().map(|a| a.activate());
164    }
165}
166
167/// A receiver for [`InternalStorageCommand`]s broadcasted by workers.
168pub struct InternalCommandReceiver {
169    rx: mpsc::Receiver<InternalStorageCommand>,
170}
171
172impl InternalCommandReceiver {
173    /// Returns the next available command, if any.
174    ///
175    /// This returns `None` when there are currently no commands but there might be commands again
176    /// in the future.
177    pub fn try_recv(&self) -> Option<InternalStorageCommand> {
178        match self.rx.try_recv() {
179            Ok(cmd) => Some(cmd),
180            Err(mpsc::TryRecvError::Empty) => None,
181            Err(mpsc::TryRecvError::Disconnected) => {
182                panic!("internal command channel disconnected")
183            }
184        }
185    }
186}
187
188pub(crate) fn setup_command_sequencer<'w>(
189    timely_worker: &'w mut TimelyWorker,
190) -> (InternalCommandSender, InternalCommandReceiver) {
191    let (input_tx, input_rx) = mpsc::channel();
192    let (output_tx, output_rx) = mpsc::channel();
193    let activator = Rc::new(RefCell::new(None));
194
195    timely_worker.dataflow_named::<(), _, _>("command_sequencer", {
196        let activator = Rc::clone(&activator);
197        move |scope| {
198            let scope = scope.with_label();
199            // Create a stream of commands received from `input_rx`.
200            //
201            // The output commands are tagged by worker ID and command index, allowing downstream
202            // operators to ensure their correct relative order.
203            let stream = source(scope, "command_sequencer::source", |cap, info| {
204                *activator.borrow_mut() = Some(scope.activator_for(info.address));
205
206                let worker_id = scope.index();
207                let mut cmd_index = 0;
208                let mut capability = Some(cap);
209
210                move |output| {
211                    let Some(cap) = capability.clone() else {
212                        return;
213                    };
214
215                    let mut session = output.session(&cap);
216                    loop {
217                        match input_rx.try_recv() {
218                            Ok(command) => {
219                                let cmd = IndexedCommand {
220                                    index: cmd_index,
221                                    command,
222                                };
223                                session.give((worker_id, cmd));
224                                cmd_index += 1;
225                            }
226                            Err(mpsc::TryRecvError::Empty) => break,
227                            Err(mpsc::TryRecvError::Disconnected) => {
228                                // Drop our capability to shut down.
229                                capability = None;
230                                break;
231                            }
232                        }
233                    }
234                }
235            });
236
237            // Sequence all commands through a single worker to establish a unique order.
238            //
239            // The output commands are tagged by a command index, allowing downstream operators to
240            // ensure their correct relative order.
241            let stream = stream.unary_frontier(
242                Exchange::new(|_| 0),
243                "command_sequencer::sequencer",
244                |cap, _info| {
245                    let mut cmd_index = 0;
246                    let mut capability = Some(cap);
247
248                    // For each worker, keep an ordered list of pending commands, as well as the
249                    // current index of the next command.
250                    let mut pending_commands = vec![(BTreeSet::new(), 0); scope.peers()];
251
252                    move |(input, frontier), output| {
253                        let Some(cap) = capability.clone() else {
254                            return;
255                        };
256
257                        input.for_each(|_time, data| {
258                            for (worker_id, cmd) in data.drain(..) {
259                                pending_commands[worker_id].0.insert(cmd);
260                            }
261                        });
262
263                        let mut session = output.session(&cap);
264                        for (commands, next_idx) in &mut pending_commands {
265                            while commands.first().is_some_and(|c| c.index == *next_idx) {
266                                let mut cmd = commands.pop_first().unwrap();
267                                cmd.index = cmd_index;
268                                session.give(cmd);
269
270                                *next_idx += 1;
271                                cmd_index += 1;
272                            }
273                        }
274
275                        let _ = session;
276
277                        if frontier.is_empty() {
278                            // Drop our capability to shut down.
279                            capability = None;
280                        }
281                    }
282                },
283            );
284
285            // Broadcast the ordered commands to all workers.
286            let stream = stream.broadcast();
287
288            // Sink the stream back into `output_tx`.
289            stream.sink(Pipeline, "command_sequencer::sink", {
290                // Keep an ordered list of pending commands, as well as the current index of the
291                // next command.
292                let mut pending_commands = BTreeSet::new();
293                let mut next_idx = 0;
294
295                move |(input, _frontier)| {
296                    input.for_each(|_time, data| {
297                        pending_commands.extend(data.drain(..));
298                    });
299
300                    while pending_commands
301                        .first()
302                        .is_some_and(|c| c.index == next_idx)
303                    {
304                        let cmd = pending_commands.pop_first().unwrap();
305                        let _ = output_tx.send(cmd.command);
306                        next_idx += 1;
307                    }
308                }
309            });
310        }
311    });
312
313    let tx = InternalCommandSender {
314        tx: input_tx,
315        activator,
316    };
317    let rx = InternalCommandReceiver { rx: output_rx };
318
319    (tx, rx)
320}
321
322// An [`InternalStorageCommand`] tagged with an index.
323//
324// This is a `(u64, InternalStorageCommand)` in spirit, but implements `Ord` (which
325// `InternalStorageCommand` doesn't) by looking only at the index.
326#[derive(Clone, Debug, Serialize, Deserialize)]
327struct IndexedCommand {
328    index: u64,
329    command: InternalStorageCommand,
330}
331
332impl PartialEq for IndexedCommand {
333    fn eq(&self, other: &Self) -> bool {
334        self.cmp(other).is_eq()
335    }
336}
337
338impl Eq for IndexedCommand {}
339
340impl PartialOrd for IndexedCommand {
341    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
342        Some(self.cmp(other))
343    }
344}
345
346impl Ord for IndexedCommand {
347    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
348        self.index.cmp(&other.index)
349    }
350}