Skip to main content

mz_storage/
storage_state.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//! Worker-local state for storage timely instances.
7//!
8//! One instance of a [`Worker`], along with its contained [`StorageState`], is
9//! part of an ensemble of storage workers that all run inside the same timely
10//! cluster. We call this worker a _storage worker_ to disambiguate it from
11//! other kinds of workers, potentially other components that might be sharing
12//! the same timely cluster.
13//!
14//! ## Controller and internal communication
15//!
16//! A worker receives _external_ [`StorageCommands`](StorageCommand) from the
17//! storage controller, via a channel. Storage workers also share an _internal_
18//! control/command fabric ([`internal_control`]). Internal commands go through
19//! a sequencer dataflow that ensures that all workers receive all commands in
20//! the same consistent order.
21//!
22//! We need to make sure that commands that cause dataflows to be rendered are
23//! processed in the same consistent order across all workers because timely
24//! requires this. To achieve this, we make sure that only internal commands can
25//! cause dataflows to be rendered. External commands (from the controller)
26//! cause internal commands to be broadcast (by only one worker), to get
27//! dataflows rendered.
28//!
29//! The internal command fabric is also used to broadcast messages from a local
30//! operator/worker to all workers. For example, when we need to tear down and
31//! restart a dataflow on all workers when an error is encountered.
32//!
33//! ## Async Storage Worker
34//!
35//! The storage worker has a companion [`AsyncStorageWorker`] that must be used
36//! when running code that requires `async`. This is needed because a timely
37//! main loop cannot run `async` code.
38//!
39//! ## Example flow of commands for `RunIngestion`
40//!
41//! With external commands, internal commands, and the async worker,
42//! understanding where and how commands from the controller are realized can
43//! get complicated. We will follow the complete flow for `RunIngestion`, as an
44//! example:
45//!
46//! 1. Worker receives a [`StorageCommand::RunIngestion`] command from the
47//!    controller.
48//! 2. This command is processed in [`StorageState::handle_storage_command`].
49//!    This step cannot render dataflows, because it does not have access to the
50//!    timely worker. It will only set up state that stays over the whole
51//!    lifetime of the source, such as the `reported_frontier`. Putting in place
52//!    this reported frontier will enable frontier reporting for that source. We
53//!    will not start reporting when we only see an internal command for
54//!    rendering a dataflow, which can "overtake" the external `RunIngestion`
55//!    command.
56//! 3. During processing of that command, we call
57//!    [`AsyncStorageWorker::update_ingestion_frontiers`], which causes a command to
58//!    be sent to the async worker.
59//! 4. We eventually get a response from the async worker:
60//!    [`AsyncStorageWorkerResponse::IngestionFrontiersUpdated`].
61//! 5. This response is handled in [`Worker::handle_async_worker_response`].
62//! 6. Handling that response causes a
63//!    [`InternalStorageCommand::CreateIngestionDataflow`] to be broadcast to
64//!    all workers via the internal command fabric.
65//! 7. This message will be processed (on each worker) in
66//!    [`Worker::handle_internal_storage_command`]. This is what will cause the
67//!    required dataflow to be rendered on all workers.
68//!
69//! The process described above assumes that the `RunIngestion` is _not_ an
70//! update, i.e. it is in response to a `CREATE SOURCE`-like statement.
71//!
72//! The primary distinction when handling a `RunIngestion` that represents an
73//! update, is that it might fill out new internal state in the mid-level
74//! clients on the way toward being run.
75
76use std::cell::RefCell;
77use std::collections::{BTreeMap, BTreeSet, VecDeque};
78use std::path::PathBuf;
79use std::rc::Rc;
80use std::sync::Arc;
81use std::thread;
82use std::time::Duration;
83
84use differential_dataflow::lattice::Lattice;
85use fail::fail_point;
86use mz_ore::now::NowFn;
87use mz_ore::soft_assert_or_log;
88use mz_ore::tracing::TracingHandle;
89use mz_persist_client::batch::ProtoBatch;
90use mz_persist_client::cache::PersistClientCache;
91use mz_persist_client::operators::shard_source::ErrorHandler;
92use mz_repr::{GlobalId, Timestamp};
93use mz_rocksdb::config::SharedWriteBufferManager;
94use mz_storage_client::client::{
95    RunIngestionCommand, StatusUpdate, StorageCommand, StorageResponse,
96};
97use mz_storage_types::AlterCompatible;
98use mz_storage_types::configuration::StorageConfiguration;
99use mz_storage_types::connections::ConnectionContext;
100use mz_storage_types::controller::CollectionMetadata;
101use mz_storage_types::dyncfgs::STORAGE_SERVER_MAINTENANCE_INTERVAL;
102use mz_storage_types::oneshot_sources::OneshotIngestionDescription;
103use mz_storage_types::sinks::StorageSinkDesc;
104use mz_storage_types::sources::IngestionDescription;
105use mz_timely_util::builder_async::PressOnDropButton;
106use mz_txn_wal::operator::TxnsContext;
107use timely::order::PartialOrder;
108use timely::progress::Timestamp as _;
109use timely::progress::frontier::Antichain;
110use timely::worker::Worker as TimelyWorker;
111use tokio::sync::mpsc::error::TryRecvError;
112use tokio::sync::{mpsc, watch};
113use tokio::time::Instant;
114use tracing::{debug, info, trace, warn};
115use uuid::Uuid;
116
117use crate::internal_control::{
118    self, DataflowParameters, InternalCommandReceiver, InternalCommandSender,
119    InternalStorageCommand,
120};
121use crate::metrics::StorageMetrics;
122use crate::statistics::{AggregatedStatistics, SinkStatistics, SourceStatistics};
123use crate::storage_state::async_storage_worker::{AsyncStorageWorker, AsyncStorageWorkerResponse};
124
125pub mod async_storage_worker;
126
127type CommandReceiver = mpsc::UnboundedReceiver<StorageCommand>;
128type ResponseSender = mpsc::UnboundedSender<StorageResponse>;
129
130/// State maintained for each worker thread.
131///
132/// Much of this state can be viewed as local variables for the worker thread,
133/// holding state that persists across function calls.
134pub struct Worker<'w> {
135    /// The underlying Timely worker.
136    ///
137    /// NOTE: This is `pub` for testing.
138    pub timely_worker: &'w mut TimelyWorker,
139    /// The channel over which communication handles for newly connected clients
140    /// are delivered.
141    pub client_rx: mpsc::UnboundedReceiver<(Uuid, CommandReceiver, ResponseSender)>,
142    /// The state associated with collection ingress and egress.
143    pub storage_state: StorageState,
144}
145
146impl<'w> Worker<'w> {
147    /// Creates new `Worker` state from the given components.
148    pub fn new(
149        timely_worker: &'w mut TimelyWorker,
150        client_rx: mpsc::UnboundedReceiver<(Uuid, CommandReceiver, ResponseSender)>,
151        metrics: StorageMetrics,
152        now: NowFn,
153        connection_context: ConnectionContext,
154        instance_context: StorageInstanceContext,
155        persist_clients: Arc<PersistClientCache>,
156        txns_ctx: TxnsContext,
157        tracing_handle: Arc<TracingHandle>,
158        shared_rocksdb_write_buffer_manager: SharedWriteBufferManager,
159    ) -> Self {
160        // It is very important that we only create the internal control
161        // flow/command sequencer once because a) the worker state is re-used
162        // when a new client connects and b) dataflows that have already been
163        // rendered into the timely worker are reused as well.
164        //
165        // If we created a new sequencer every time we get a new client (likely
166        // because the controller re-started and re-connected), dataflows that
167        // were rendered before would still hold a handle to the old sequencer
168        // but we would not read their commands anymore.
169        let (internal_cmd_tx, internal_cmd_rx) =
170            internal_control::setup_command_sequencer(timely_worker);
171
172        let storage_state = StorageState::new_guest(
173            timely_worker.index(),
174            timely_worker.peers(),
175            internal_cmd_tx,
176            Some(internal_cmd_rx),
177            metrics,
178            now,
179            connection_context,
180            instance_context,
181            persist_clients,
182            txns_ctx,
183            tracing_handle,
184            shared_rocksdb_write_buffer_manager,
185        );
186
187        // TODO(aljoscha): We might want `async_worker` and `internal_cmd_tx` to
188        // be fields of `Worker` instead of `StorageState`, but at least for the
189        // command flow sources and sinks need access to that. We can refactor
190        // this once we have a clearer boundary between what sources/sinks need
191        // and the full "power" of the internal command flow, which should stay
192        // internal to the worker/not be exposed to source/sink implementations.
193        Self {
194            timely_worker,
195            client_rx,
196            storage_state,
197        }
198    }
199}
200
201impl StorageState {
202    /// Creates per-worker storage state, for hosting on any Timely worker.
203    ///
204    /// The caller provides the internal command channel endpoints: the native storage worker wires
205    /// them to the sequencer dataflow, a foreign host wires the sender to its own sequencing
206    /// channel and passes no receiver, since it dispatches internal commands itself.
207    /// Must be called on the hosting worker's thread, because the async worker unparks the
208    /// creating thread.
209    pub fn new_guest(
210        timely_worker_index: usize,
211        timely_worker_peers: usize,
212        internal_cmd_tx: InternalCommandSender,
213        internal_cmd_rx: Option<InternalCommandReceiver>,
214        metrics: StorageMetrics,
215        now: NowFn,
216        connection_context: ConnectionContext,
217        instance_context: StorageInstanceContext,
218        persist_clients: Arc<PersistClientCache>,
219        txns_ctx: TxnsContext,
220        tracing_handle: Arc<TracingHandle>,
221        shared_rocksdb_write_buffer_manager: SharedWriteBufferManager,
222    ) -> Self {
223        let storage_configuration =
224            StorageConfiguration::new(connection_context, mz_dyncfgs::all_dyncfgs());
225
226        // We always initialize as read_only=true. Only when we're explicitly
227        // allowed do we switch to doing writes.
228        let (read_only_tx, read_only_rx) = watch::channel(true);
229
230        // Similar to the internal command sequencer, it is very important that
231        // we only create the async worker once because a) the worker state is
232        // re-used when a new client connects and b) commands that have already
233        // been sent and might yield a response will be lost if a new iteration
234        // of `run_client` creates a new async worker.
235        //
236        // If we created a new async worker every time we get a new client
237        // (likely because the controller re-started and re-connected), we can
238        // get into an inconsistent state where we think that a dataflow has
239        // been rendered, for example because there is an entry in
240        // `StorageState::ingestions`, while there is not yet a dataflow. This
241        // happens because the dataflow only gets rendered once we get a
242        // response from the async worker and send off an internal command.
243        //
244        // The core idea is that both the sequencer and the async worker are
245        // part of the per-worker state, and must be treated as such, meaning
246        // they must survive between invocations of `run_client`.
247
248        // TODO(aljoscha): This thread unparking business seems brittle, but that's
249        // also how the command channel works currently. We can wrap it inside a
250        // struct that holds both a channel and a `Thread`, but I don't
251        // think that would help too much.
252        let async_worker = async_storage_worker::AsyncStorageWorker::new(
253            thread::current(),
254            Arc::clone(&persist_clients),
255        );
256        let cluster_memory_limit = instance_context.cluster_memory_limit;
257
258        let storage_state = StorageState {
259            source_uppers: BTreeMap::new(),
260            source_tokens: BTreeMap::new(),
261            metrics,
262            reported_frontiers: BTreeMap::new(),
263            ingestions: BTreeMap::new(),
264            exports: BTreeMap::new(),
265            oneshot_ingestions: BTreeMap::new(),
266            now,
267            timely_worker_index,
268            timely_worker_peers,
269            instance_context,
270            persist_clients,
271            txns_ctx,
272            sink_tokens: BTreeMap::new(),
273            rendered_dataflows: 0,
274            dataflow_epochs: BTreeMap::new(),
275            sink_write_frontiers: BTreeMap::new(),
276            dropped_ids: Vec::new(),
277            aggregated_statistics: AggregatedStatistics::new(
278                timely_worker_index,
279                timely_worker_peers,
280            ),
281            shared_status_updates: Default::default(),
282            latest_status_updates: Default::default(),
283            initial_status_reported: Default::default(),
284            internal_cmd_tx,
285            internal_cmd_rx,
286            read_only_tx,
287            read_only_rx,
288            async_worker,
289            storage_configuration,
290            dataflow_parameters: DataflowParameters::new(
291                shared_rocksdb_write_buffer_manager,
292                cluster_memory_limit,
293            ),
294            tracing_handle,
295            server_maintenance_interval: Duration::ZERO,
296        };
297
298        storage_state
299    }
300}
301
302/// Worker-local state related to the ingress or egress of collections of data.
303pub struct StorageState {
304    /// The highest observed upper frontier for collection.
305    ///
306    /// This is shared among all source instances, so that they can jointly advance the
307    /// frontier even as other instances are created and dropped. Ideally, the Storage
308    /// module would eventually provide one source of truth on this rather than multiple,
309    /// and we should aim for that but are not there yet.
310    pub source_uppers: BTreeMap<GlobalId, Rc<RefCell<Antichain<mz_repr::Timestamp>>>>,
311    /// Handles to created sources, keyed by ID
312    /// NB: The type of the tokens must not be changed to something other than `PressOnDropButton`
313    /// to prevent usage of custom shutdown tokens that are tricky to get right.
314    pub source_tokens: BTreeMap<GlobalId, Vec<PressOnDropButton>>,
315    /// Metrics for storage objects.
316    pub metrics: StorageMetrics,
317    /// Tracks the conditional write frontiers we have reported.
318    pub reported_frontiers: BTreeMap<GlobalId, Antichain<Timestamp>>,
319    /// Descriptions of each installed ingestion.
320    pub ingestions: BTreeMap<GlobalId, IngestionDescription<CollectionMetadata>>,
321    /// Descriptions of each installed export.
322    pub exports: BTreeMap<GlobalId, StorageSinkDesc<CollectionMetadata, mz_repr::Timestamp>>,
323    /// Descriptions of oneshot ingestions that are currently running.
324    pub oneshot_ingestions: BTreeMap<uuid::Uuid, OneshotIngestionDescription<ProtoBatch>>,
325    /// Undocumented
326    pub now: NowFn,
327    /// Index of the associated timely dataflow worker.
328    pub timely_worker_index: usize,
329    /// Peers in the associated timely dataflow worker.
330    pub timely_worker_peers: usize,
331    /// Other configuration for sources and sinks.
332    pub instance_context: StorageInstanceContext,
333    /// A process-global cache of (blob_uri, consensus_uri) -> PersistClient.
334    /// This is intentionally shared between workers
335    pub persist_clients: Arc<PersistClientCache>,
336    /// Context necessary for rendering txn-wal operators.
337    pub txns_ctx: TxnsContext,
338    /// Tokens that should be dropped when a dataflow is dropped to clean up
339    /// associated state.
340    /// NB: The type of the tokens must not be changed to something other than `PressOnDropButton`
341    /// to prevent usage of custom shutdown tokens that are tricky to get right.
342    pub sink_tokens: BTreeMap<GlobalId, Vec<PressOnDropButton>>,
343    /// The number of dataflows rendered so far, equal on all workers because they render in the
344    /// order of the sequenced internal commands.
345    pub rendered_dataflows: u64,
346    /// The epoch of the current rendering of each dataflow.
347    pub dataflow_epochs: BTreeMap<GlobalId, u64>,
348    /// Frontier of sink writes (all subsequent writes will be at times at or
349    /// equal to this frontier)
350    pub sink_write_frontiers: BTreeMap<GlobalId, Rc<RefCell<Antichain<Timestamp>>>>,
351    /// Collection ids that have been dropped but not yet reported as dropped
352    pub dropped_ids: Vec<GlobalId>,
353
354    /// Statistics for sources and sinks.
355    pub aggregated_statistics: AggregatedStatistics,
356
357    /// A place shared with running dataflows, so that health operators, can
358    /// report status updates back to us.
359    ///
360    /// **NOTE**: Operators that append to this collection should take care to only add new
361    /// status updates if the status of the ingestion/export in question has _changed_.
362    pub shared_status_updates: Rc<RefCell<Vec<StatusUpdate>>>,
363
364    /// The latest status update for each object.
365    pub latest_status_updates: BTreeMap<GlobalId, StatusUpdate>,
366
367    /// Whether we have reported the initial status after connecting to a new client.
368    /// This is reset to false when a new client connects.
369    pub initial_status_reported: bool,
370
371    /// Sender for cluster-internal storage commands. These can be sent from
372    /// within workers/operators and will be distributed to all workers. For
373    /// example, for shutting down an entire dataflow from within a
374    /// operator/worker.
375    pub internal_cmd_tx: InternalCommandSender,
376    /// Receiver for cluster-internal storage commands. `None` when the state is hosted outside
377    /// the storage server, whose host dispatches internal commands itself.
378    pub internal_cmd_rx: Option<InternalCommandReceiver>,
379
380    /// When this replica/cluster is in read-only mode it must not affect any
381    /// changes to external state. This flag can only be changed by a
382    /// [StorageCommand::AllowWrites].
383    ///
384    /// Everything running on this replica/cluster must obey this flag. At the
385    /// time of writing, nothing currently looks at this flag.
386    /// TODO(benesch): fix this.
387    ///
388    /// NOTE: In the future, we might want a more complicated flag, for example
389    /// something that tells us after which timestamp we are allowed to write.
390    /// In this first version we are keeping things as simple as possible!
391    pub read_only_rx: watch::Receiver<bool>,
392
393    /// Send-side for read-only state.
394    pub read_only_tx: watch::Sender<bool>,
395
396    /// Async worker companion, used for running code that requires async, which
397    /// the timely main loop cannot do.
398    pub async_worker: AsyncStorageWorker<mz_repr::Timestamp>,
399
400    /// Configuration for source and sink connections.
401    pub storage_configuration: StorageConfiguration,
402    /// Dynamically configurable parameters that control how dataflows are rendered.
403    /// NOTE(guswynn): we should consider moving these into `storage_configuration`.
404    pub dataflow_parameters: DataflowParameters,
405
406    /// A process-global handle to tracing configuration.
407    pub tracing_handle: Arc<TracingHandle>,
408
409    /// Interval at which to perform server maintenance tasks. Set to a zero interval to
410    /// perform maintenance with every `step_or_park` invocation.
411    pub server_maintenance_interval: Duration,
412}
413
414impl StorageState {
415    /// Starts the epoch of a new rendering of the dataflow for `id` and returns it.
416    pub fn next_dataflow_epoch(&mut self, id: GlobalId) -> u64 {
417        self.rendered_dataflows += 1;
418        self.dataflow_epochs.insert(id, self.rendered_dataflows);
419        self.rendered_dataflows
420    }
421
422    /// Return an error handler that triggers a suspend and restart of the corresponding storage
423    /// dataflow.
424    pub fn error_handler(&self, context: &'static str, id: GlobalId) -> ErrorHandler {
425        let tx = self.internal_cmd_tx.clone();
426        ErrorHandler::signal(move |e| {
427            tx.send(InternalStorageCommand::SuspendAndRestart {
428                id,
429                reason: format!("{context}: {e:#}"),
430            })
431        })
432    }
433}
434
435/// Extra context for a storage instance.
436/// This is extra information that is used when rendering source
437/// and sinks that is not tied to the source/connection configuration itself.
438#[derive(Clone)]
439pub struct StorageInstanceContext {
440    /// A directory that can be used for scratch work.
441    pub scratch_directory: Option<PathBuf>,
442    /// The memory limit of the materialize cluster replica. This will
443    /// be used to calculate and configure the maximum inflight bytes for backpressure
444    pub cluster_memory_limit: Option<usize>,
445    /// Whether the replica can swap.
446    pub swap_available: bool,
447}
448
449impl StorageInstanceContext {
450    /// Build a new `StorageInstanceContext`.
451    pub fn new(
452        scratch_directory: Option<PathBuf>,
453        cluster_memory_limit: Option<usize>,
454        swap_available: bool,
455    ) -> Self {
456        Self {
457            scratch_directory,
458            cluster_memory_limit,
459            swap_available,
460        }
461    }
462
463    /// Returns a `rocksdb::Env` for a new RocksDB instance.
464    ///
465    /// With a scratch directory this is the default `Env`, which stores data
466    /// on the host filesystem. Without one, RocksDB runs in memory, and every
467    /// call returns a fresh in-memory `Env`. State written through an `Env`
468    /// is only reachable through that same `Env`, so a per-instance `Env`
469    /// isolates instances from each other and from previous incarnations of
470    /// themselves. Background threads are process-wide either way, both
471    /// variants delegate them to the default `Env`.
472    pub fn rocksdb_env(&self) -> Result<rocksdb::Env, rocksdb::Error> {
473        if self.scratch_directory.is_some() {
474            rocksdb::Env::new()
475        } else {
476            rocksdb::Env::mem_env()
477        }
478    }
479}
480
481impl<'w> Worker<'w> {
482    /// Waits for client connections and runs them to completion.
483    pub fn run(&mut self) {
484        while let Some((_nonce, rx, tx)) = self.client_rx.blocking_recv() {
485            self.run_client(rx, tx);
486        }
487    }
488
489    /// Runs this (timely) storage worker until the given `command_rx` is
490    /// disconnected.
491    ///
492    /// See the [module documentation](crate::storage_state) for this
493    /// workers responsibilities, how it communicates with the other workers and
494    /// how commands flow from the controller and through the workers.
495    fn run_client(&mut self, mut command_rx: CommandReceiver, response_tx: ResponseSender) {
496        // At this point, all workers are still reading from the command flow.
497        if self.reconcile(&mut command_rx).is_err() {
498            return;
499        }
500
501        // The last time we reported statistics.
502        let mut last_stats_time = Instant::now();
503
504        // The last time we did periodic maintenance.
505        let mut last_maintenance = std::time::Instant::now();
506
507        let mut disconnected = false;
508        while !disconnected {
509            let config = &self.storage_state.storage_configuration;
510            let stats_interval = config.parameters.statistics_collection_interval;
511
512            let maintenance_interval = self.storage_state.server_maintenance_interval;
513
514            let now = std::time::Instant::now();
515            // Determine if we need to perform maintenance, which is true if `maintenance_interval`
516            // time has passed since the last maintenance.
517            let sleep_duration;
518            if now >= last_maintenance + maintenance_interval {
519                last_maintenance = now;
520                sleep_duration = None;
521
522                self.report_frontier_progress(&response_tx);
523            } else {
524                // We didn't perform maintenance, sleep until the next maintenance interval.
525                let next_maintenance = last_maintenance + maintenance_interval;
526                sleep_duration = Some(next_maintenance.saturating_duration_since(now))
527            }
528
529            // Ask Timely to execute a unit of work.
530            //
531            // If there are no pending commands or responses from the async
532            // worker, we ask Timely to park the thread if there's nothing to
533            // do. We rely on another thread unparking us when there's new work
534            // to be done, e.g., when sending a command or when new Kafka
535            // messages have arrived.
536            //
537            // It is critical that we allow Timely to park iff there are no
538            // pending commands or responses. The command may have already been
539            // consumed by the call to `client_rx.recv`. See:
540            // https://github.com/MaterializeInc/materialize/pull/13973#issuecomment-1200312212
541            if command_rx.is_empty() && self.storage_state.async_worker.is_empty() {
542                // Make sure we wake up again to report any pending statistics updates.
543                let mut park_duration = stats_interval.saturating_sub(last_stats_time.elapsed());
544                if let Some(sleep_duration) = sleep_duration {
545                    park_duration = std::cmp::min(sleep_duration, park_duration);
546                }
547                self.timely_worker.step_or_park(Some(park_duration));
548            } else {
549                self.timely_worker.step();
550            }
551
552            // Rerport any dropped ids
553            for id in std::mem::take(&mut self.storage_state.dropped_ids) {
554                self.send_storage_response(&response_tx, StorageResponse::DroppedId(id));
555            }
556
557            self.process_oneshot_ingestions(&response_tx);
558
559            self.report_status_updates(&response_tx);
560
561            if last_stats_time.elapsed() >= stats_interval {
562                self.report_storage_statistics(&response_tx);
563                last_stats_time = Instant::now();
564            }
565
566            // Handle any received commands.
567            loop {
568                match command_rx.try_recv() {
569                    Ok(cmd) => self.storage_state.handle_storage_command(cmd),
570                    Err(TryRecvError::Empty) => break,
571                    Err(TryRecvError::Disconnected) => {
572                        disconnected = true;
573                        break;
574                    }
575                }
576            }
577
578            // Handle responses from the async worker.
579            while let Ok(response) = self.storage_state.async_worker.try_recv() {
580                self.handle_async_worker_response(response);
581            }
582
583            // Handle any received commands.
584            while let Some(command) = self
585                .storage_state
586                .internal_cmd_rx
587                .as_ref()
588                .expect("storage server always wires a receiver")
589                .try_recv()
590            {
591                self.handle_internal_storage_command(command);
592            }
593        }
594    }
595
596    /// Entry point for applying a response from the async storage worker.
597    pub fn handle_async_worker_response(
598        &self,
599        async_response: AsyncStorageWorkerResponse<mz_repr::Timestamp>,
600    ) {
601        // NOTE: If we want to share the load of async processing we
602        // have to change `handle_storage_command` and change this
603        // assert.
604        assert_eq!(
605            self.timely_worker.index(),
606            0,
607            "only worker #0 is doing async processing"
608        );
609        match async_response {
610            AsyncStorageWorkerResponse::IngestionFrontiersUpdated {
611                id,
612                ingestion_description,
613                as_of,
614                resume_uppers,
615                source_resume_uppers,
616            } => {
617                self.storage_state.internal_cmd_tx.send(
618                    InternalStorageCommand::CreateIngestionDataflow {
619                        id,
620                        ingestion_description,
621                        as_of,
622                        resume_uppers,
623                        source_resume_uppers,
624                    },
625                );
626            }
627            AsyncStorageWorkerResponse::ExportUpperFetched { id, upper } => {
628                let Some(mut description) = self.storage_state.exports.get(&id).cloned() else {
629                    return;
630                };
631                // Choose an as-of frontier for this execution of the sink. If the write frontier
632                // of the sink is strictly larger than its read hold, it must have at least written
633                // out its snapshot, and we can skip reading it; otherwise assume we may have to
634                // replay from the beginning.
635                let mut as_of = Antichain::from_iter(
636                    upper
637                        .iter()
638                        .map(|t| t.step_back().unwrap_or_else(Timestamp::minimum)),
639                );
640                as_of.join_assign(&description.as_of);
641                description.with_snapshot = description.with_snapshot
642                    && !PartialOrder::less_than(&description.as_of, &upper);
643                description.as_of = as_of;
644                self.storage_state
645                    .internal_cmd_tx
646                    .send(InternalStorageCommand::RunSinkDataflow(id, description));
647            }
648            AsyncStorageWorkerResponse::DropDataflow(id) => {
649                self.storage_state
650                    .internal_cmd_tx
651                    .send(InternalStorageCommand::DropDataflow(vec![id]));
652            }
653        }
654    }
655
656    /// Entry point for applying an internal storage command.
657    pub fn handle_internal_storage_command(&mut self, internal_cmd: InternalStorageCommand) {
658        match internal_cmd {
659            InternalStorageCommand::SuspendAndRestart { id, reason } => {
660                info!(
661                    "worker {}/{} initiating suspend-and-restart for {id} because of: {reason}",
662                    self.timely_worker.index(),
663                    self.timely_worker.peers(),
664                );
665
666                let maybe_ingestion = self.storage_state.ingestions.get(&id).cloned();
667                if let Some(ingestion_description) = maybe_ingestion {
668                    // Yank the token of the previously existing source dataflow.Note that this
669                    // token also includes any source exports/subsources.
670                    let maybe_token = self.storage_state.source_tokens.remove(&id);
671                    if maybe_token.is_none() {
672                        // Something has dropped the source. Make sure we don't
673                        // accidentally re-create it.
674                        return;
675                    }
676
677                    // This needs to be done by one worker, which will
678                    // broadcasts a `CreateIngestionDataflow` command to all
679                    // workers based on the response that contains the
680                    // resumption upper.
681                    //
682                    // Doing this separately on each worker could lead to
683                    // differing resume_uppers which might lead to all kinds of
684                    // mayhem.
685                    //
686                    // TODO(aljoscha): If we ever become worried that this is
687                    // putting undue pressure on worker 0 we can pick the
688                    // designated worker for a source/sink based on `id.hash()`.
689                    if self.timely_worker.index() == 0 {
690                        for (id, _) in ingestion_description.source_exports.iter() {
691                            self.storage_state
692                                .aggregated_statistics
693                                .advance_global_epoch(*id);
694                        }
695                        self.storage_state
696                            .async_worker
697                            .update_ingestion_frontiers(id, ingestion_description);
698                    }
699
700                    // Continue with other commands.
701                    return;
702                }
703
704                let maybe_sink = self.storage_state.exports.get(&id).cloned();
705                if let Some(sink_description) = maybe_sink {
706                    // Yank the token of the previously existing sink
707                    // dataflow.
708                    let maybe_token = self.storage_state.sink_tokens.remove(&id);
709
710                    if maybe_token.is_none() {
711                        // Something has dropped the sink. Make sure we don't
712                        // accidentally re-create it.
713                        return;
714                    }
715
716                    // This needs to be broadcast by one worker and go through
717                    // the internal command fabric, to ensure consistent
718                    // ordering of dataflow rendering across all workers.
719                    if self.timely_worker.index() == 0 {
720                        self.storage_state
721                            .aggregated_statistics
722                            .advance_global_epoch(id);
723                        self.storage_state
724                            .async_worker
725                            .update_sink_frontiers(id, sink_description);
726                    }
727
728                    // Continue with other commands.
729                    return;
730                }
731
732                if !self
733                    .storage_state
734                    .ingestions
735                    .values()
736                    .any(|v| v.source_exports.contains_key(&id))
737                {
738                    // Our current approach to dropping a source results in a race between shard
739                    // finalization (which happens in the controller) and dataflow shutdown (which
740                    // happens in clusterd). If a source is created and dropped fast enough -or the
741                    // two commands get sufficiently delayed- then it's possible to receive a
742                    // SuspendAndRestart command for an unknown source. We cannot assert that this
743                    // never happens but we log an error here to track how often this happens.
744                    warn!(
745                        "got InternalStorageCommand::SuspendAndRestart for something that is not a source or sink: {id}"
746                    );
747                }
748            }
749            InternalStorageCommand::Suspend { id, epoch, reason } => {
750                // NOTE: a stale `Suspend` must not stop a newer rendering of this dataflow, because
751                // that rendering would be torn down and never restarted.
752                if self.storage_state.dataflow_epochs.get(&id) != Some(&epoch) {
753                    info!(
754                        "worker {}/{} ignoring suspend for {id} from stale epoch {epoch}",
755                        self.timely_worker.index(),
756                        self.timely_worker.peers(),
757                    );
758                    return;
759                }
760                // Nothing brings the dataflow back on its own, so this is louder than a restart.
761                warn!(
762                    "worker {}/{} suspending {id} because of: {reason}",
763                    self.timely_worker.index(),
764                    self.timely_worker.peers(),
765                );
766                self.storage_state.source_tokens.remove(&id);
767                self.storage_state.sink_tokens.remove(&id);
768            }
769            InternalStorageCommand::CreateIngestionDataflow {
770                id: ingestion_id,
771                mut ingestion_description,
772                as_of,
773                mut resume_uppers,
774                mut source_resume_uppers,
775            } => {
776                info!(
777                    ?as_of,
778                    ?resume_uppers,
779                    "worker {}/{} trying to (re-)start ingestion {ingestion_id}",
780                    self.timely_worker.index(),
781                    self.timely_worker.peers(),
782                );
783
784                // We initialize statistics before we prune finished exports. We
785                // still want to export statistics for these, plus the rendering
786                // machinery will get confused if there are not at least
787                // statistics for the "main" source.
788                for (export_id, export) in ingestion_description.source_exports.iter() {
789                    let resume_upper = resume_uppers[export_id].clone();
790                    self.storage_state.aggregated_statistics.initialize_source(
791                        *export_id,
792                        ingestion_id,
793                        resume_upper.clone(),
794                        as_of.clone(),
795                        || {
796                            SourceStatistics::new(
797                                *export_id,
798                                self.storage_state.timely_worker_index,
799                                &self.storage_state.metrics.source_statistics,
800                                ingestion_id,
801                                &export.storage_metadata.data_shard,
802                                export.data_config.envelope.clone(),
803                                resume_upper,
804                                as_of.clone(),
805                            )
806                        },
807                    );
808                }
809
810                let finished_exports: BTreeSet<GlobalId> = resume_uppers
811                    .iter()
812                    .filter(|(_, frontier)| frontier.is_empty())
813                    .map(|(id, _)| *id)
814                    .collect();
815
816                resume_uppers.retain(|id, _| !finished_exports.contains(id));
817                source_resume_uppers.retain(|id, _| !finished_exports.contains(id));
818                ingestion_description
819                    .source_exports
820                    .retain(|id, _| !finished_exports.contains(id));
821
822                for id in ingestion_description.collection_ids() {
823                    // If there is already a shared upper, we re-use it, to make
824                    // sure that parties that are already using the shared upper
825                    // can continue doing so.
826                    let source_upper = self
827                        .storage_state
828                        .source_uppers
829                        .entry(id.clone())
830                        .or_insert_with(|| {
831                            Rc::new(RefCell::new(Antichain::from_elem(Timestamp::minimum())))
832                        });
833
834                    let mut source_upper = source_upper.borrow_mut();
835                    if !source_upper.is_empty() {
836                        source_upper.clear();
837                        source_upper.insert(mz_repr::Timestamp::minimum());
838                    }
839                }
840
841                // If all subsources of the source are finished, we can skip rendering entirely.
842                // Also, if `as_of` is empty, the dataflow has been finalized, so we can skip it as
843                // well.
844                //
845                // TODO(guswynn|petrosagg): this is a bit hacky, and is a consequence of storage state
846                // management being a bit of a mess. we should clean this up and remove weird if
847                // statements like this.
848                if resume_uppers.values().all(|frontier| frontier.is_empty()) || as_of.is_empty() {
849                    info!(
850                        ?resume_uppers,
851                        ?as_of,
852                        "worker {}/{} skipping building ingestion dataflow \
853                        for {ingestion_id} because the ingestion is finished",
854                        self.timely_worker.index(),
855                        self.timely_worker.peers(),
856                    );
857                    return;
858                }
859
860                crate::render::build_ingestion_dataflow(
861                    self.timely_worker,
862                    &mut self.storage_state,
863                    ingestion_id,
864                    ingestion_description,
865                    as_of,
866                    resume_uppers,
867                    source_resume_uppers,
868                );
869            }
870            InternalStorageCommand::RunOneshotIngestion {
871                ingestion_id,
872                collection_id,
873                collection_meta,
874                request,
875            } => {
876                crate::render::build_oneshot_ingestion_dataflow(
877                    self.timely_worker,
878                    &mut self.storage_state,
879                    ingestion_id,
880                    collection_id,
881                    collection_meta,
882                    request,
883                );
884            }
885            InternalStorageCommand::RunSinkDataflow(sink_id, sink_description) => {
886                info!(
887                    "worker {}/{} trying to (re-)start sink {sink_id}",
888                    self.timely_worker.index(),
889                    self.timely_worker.peers(),
890                );
891
892                {
893                    // If there is already a shared write frontier, we re-use it, to
894                    // make sure that parties that are already using the shared
895                    // frontier can continue doing so.
896                    let sink_write_frontier = self
897                        .storage_state
898                        .sink_write_frontiers
899                        .entry(sink_id.clone())
900                        .or_insert_with(|| Rc::new(RefCell::new(Antichain::new())));
901
902                    let mut sink_write_frontier = sink_write_frontier.borrow_mut();
903                    sink_write_frontier.clear();
904                    // The controller holds back the sink's input based on the reported write
905                    // frontier, so a sink that is not rendered must report the empty frontier.
906                    if !sink_description.as_of.is_empty() {
907                        sink_write_frontier.insert(mz_repr::Timestamp::minimum());
908                    }
909                }
910
911                // A restart takes its as-of from the upper of the sink's shard, which is empty
912                // once the sink has written all of its input, or once it was dropped and the
913                // shard finalized. A replica that lost its controller never hears about the
914                // drop, so the as-of is the only signal here, and `persist_source` panics on an
915                // empty one.
916                if sink_description.as_of.is_empty() {
917                    info!(
918                        "worker {}/{} skipping building sink dataflow for {sink_id} \
919                        because its as-of is empty",
920                        self.timely_worker.index(),
921                        self.timely_worker.peers(),
922                    );
923                    return;
924                }
925
926                self.storage_state
927                    .aggregated_statistics
928                    .initialize_sink(sink_id, || {
929                        SinkStatistics::new(
930                            sink_id,
931                            self.storage_state.timely_worker_index,
932                            &self.storage_state.metrics.sink_statistics,
933                        )
934                    });
935
936                crate::render::build_export_dataflow(
937                    self.timely_worker,
938                    &mut self.storage_state,
939                    sink_id,
940                    sink_description,
941                );
942            }
943            InternalStorageCommand::DropDataflow(ids) => {
944                for id in &ids {
945                    // Clean up per-source / per-sink state.
946                    self.storage_state.source_uppers.remove(id);
947                    self.storage_state.source_tokens.remove(id);
948
949                    self.storage_state.sink_tokens.remove(id);
950                    self.storage_state.sink_write_frontiers.remove(id);
951                    self.storage_state.dataflow_epochs.remove(id);
952
953                    self.storage_state.aggregated_statistics.deinitialize(*id);
954                }
955            }
956            InternalStorageCommand::UpdateConfiguration { storage_parameters } => {
957                self.storage_state
958                    .dataflow_parameters
959                    .update(storage_parameters.clone());
960                self.storage_state
961                    .storage_configuration
962                    .update(storage_parameters);
963
964                // Clear out the updates as we no longer forward them to anyone else to process.
965                // We clone `StorageState::storage_configuration` many times during rendering
966                // and want to avoid cloning these unused updates.
967                self.storage_state
968                    .storage_configuration
969                    .parameters
970                    .dyncfg_updates = Default::default();
971
972                // Remember the maintenance interval locally to avoid reading it from the config set on
973                // every server iteration.
974                self.storage_state.server_maintenance_interval =
975                    STORAGE_SERVER_MAINTENANCE_INTERVAL
976                        .get(self.storage_state.storage_configuration.config_set());
977
978                // Apply storage's upsert spill flag to the storage chunk spill
979                // gate. The buffer pool and its budget are the shared ones
980                // configured by compute's `apply_worker_config` (compute and
981                // storage run in the same process).
982                //
983                // The flag is replica-scoped: the storage controller merges
984                // per-replica overrides into the `UpdateConfiguration`
985                // commands it sends, so reading this worker's `ConfigSet`
986                // here observes them.
987                {
988                    use mz_storage_types::dyncfgs::ENABLE_UPSERT_PAGED_SPILL;
989
990                    let enabled = ENABLE_UPSERT_PAGED_SPILL
991                        .get(self.storage_state.storage_configuration.config_set());
992                    debug!(
993                        worker = self.timely_worker.index(),
994                        enabled, "upsert stash spill: applying gate",
995                    );
996                    crate::upsert::upsert_stash_spill::set_enabled(enabled);
997                }
998            }
999            InternalStorageCommand::StatisticsUpdate { sources, sinks } => self
1000                .storage_state
1001                .aggregated_statistics
1002                .ingest(sources, sinks),
1003        }
1004    }
1005
1006    /// Emit information about write frontier progress, along with information that should
1007    /// be made durable for this to be the case.
1008    ///
1009    /// The write frontier progress is "conditional" in that it is not until the information is made
1010    /// durable that the data are emitted to downstream workers, and indeed they should not rely on
1011    /// the completeness of what they hear until the information is made durable.
1012    ///
1013    /// Specifically, this sends information about new timestamp bindings created by dataflow workers,
1014    /// with the understanding if that if made durable (and ack'd back to the workers) the source will
1015    /// in fact progress with this write frontier.
1016    pub fn report_frontier_progress(&mut self, response_tx: &ResponseSender) {
1017        let mut new_uppers = Vec::new();
1018
1019        // Check if any observed frontier should advance the reported frontiers.
1020        for (id, frontier) in self
1021            .storage_state
1022            .source_uppers
1023            .iter()
1024            .chain(self.storage_state.sink_write_frontiers.iter())
1025        {
1026            let Some(reported_frontier) = self.storage_state.reported_frontiers.get_mut(id) else {
1027                // Frontier reporting has not yet been started for this object.
1028                // Potentially because this timely worker has not yet seen the
1029                // `CreateSources` command.
1030                continue;
1031            };
1032
1033            let observed_frontier = frontier.borrow();
1034
1035            // Only do a thing if it *advances* the frontier, not just *changes* the frontier.
1036            // This is protection against `frontier` lagging behind what we have conditionally reported.
1037            if PartialOrder::less_than(reported_frontier, &observed_frontier) {
1038                new_uppers.push((*id, observed_frontier.clone()));
1039                reported_frontier.clone_from(&observed_frontier);
1040            }
1041        }
1042
1043        for (id, upper) in new_uppers {
1044            self.send_storage_response(response_tx, StorageResponse::FrontierUpper(id, upper));
1045        }
1046    }
1047
1048    /// Pumps latest status updates from the buffer shared with operators and
1049    /// reports any updates that need reporting.
1050    pub fn report_status_updates(&mut self, response_tx: &ResponseSender) {
1051        // If we haven't done the initial status report, report all current statuses
1052        if !self.storage_state.initial_status_reported {
1053            // We pull initially reported status updates to "now", so that they
1054            // sort as the latest update in internal status collections. This
1055            // makes it so that a newly bootstrapped envd can append status
1056            // updates to internal status collections that report an accurate
1057            // view as of the time when they came up.
1058            let now_ts = mz_ore::now::to_datetime((self.storage_state.now)());
1059            let status_updates = self
1060                .storage_state
1061                .latest_status_updates
1062                .values()
1063                .cloned()
1064                .map(|mut update| {
1065                    update.timestamp = now_ts.clone();
1066                    update
1067                });
1068            for update in status_updates {
1069                self.send_storage_response(response_tx, StorageResponse::StatusUpdate(update));
1070            }
1071            self.storage_state.initial_status_reported = true;
1072        }
1073
1074        // Pump updates into our state and stage them for reporting.
1075        for shared_update in self.storage_state.shared_status_updates.take() {
1076            self.send_storage_response(
1077                response_tx,
1078                StorageResponse::StatusUpdate(shared_update.clone()),
1079            );
1080
1081            self.storage_state
1082                .latest_status_updates
1083                .insert(shared_update.id, shared_update);
1084        }
1085    }
1086
1087    /// Report source statistics back to the controller.
1088    pub fn report_storage_statistics(&mut self, response_tx: &ResponseSender) {
1089        let (sources, sinks) = self.storage_state.aggregated_statistics.emit_local();
1090        if !sources.is_empty() || !sinks.is_empty() {
1091            self.storage_state
1092                .internal_cmd_tx
1093                .send(InternalStorageCommand::StatisticsUpdate { sources, sinks })
1094        }
1095
1096        let (sources, sinks) = self.storage_state.aggregated_statistics.snapshot();
1097        if !sources.is_empty() || !sinks.is_empty() {
1098            self.send_storage_response(
1099                response_tx,
1100                StorageResponse::StatisticsUpdates(sources, sinks),
1101            );
1102        }
1103    }
1104
1105    /// Send a response to the coordinator.
1106    pub fn send_storage_response(&self, response_tx: &ResponseSender, response: StorageResponse) {
1107        // Ignore send errors because the coordinator is free to ignore our
1108        // responses. This happens during shutdown.
1109        let _ = response_tx.send(response);
1110    }
1111
1112    /// Forward completed oneshot ingestion results to the coordinator.
1113    pub fn process_oneshot_ingestions(&mut self, response_tx: &ResponseSender) {
1114        for (ingestion_id, ingestion_state) in &mut self.storage_state.oneshot_ingestions {
1115            loop {
1116                match ingestion_state.results.try_recv() {
1117                    Ok(result) => {
1118                        let response = match result {
1119                            Ok(maybe_batch) => maybe_batch.into_iter().map(Result::Ok).collect(),
1120                            Err(err) => vec![Err(err)],
1121                        };
1122                        let staged_batches = BTreeMap::from([(*ingestion_id, response)]);
1123                        let _ = response_tx.send(StorageResponse::StagedBatches(staged_batches));
1124                    }
1125                    Err(TryRecvError::Empty) => {
1126                        break;
1127                    }
1128                    Err(TryRecvError::Disconnected) => {
1129                        break;
1130                    }
1131                }
1132            }
1133        }
1134    }
1135
1136    /// Extract commands until `InitializationComplete`, and make the worker
1137    /// reflect those commands. If the worker can not be made to reflect the
1138    /// commands, return an error.
1139    fn reconcile(&mut self, command_rx: &mut CommandReceiver) -> Result<(), ()> {
1140        // To initialize the connection, we want to drain all commands until we
1141        // receive a `StorageCommand::InitializationComplete` command to form a
1142        // target command state.
1143        let mut commands = vec![];
1144        loop {
1145            match command_rx.blocking_recv().ok_or(())? {
1146                StorageCommand::InitializationComplete => break,
1147                command => commands.push(command),
1148            }
1149        }
1150
1151        self.reconcile_commands(commands);
1152        Ok(())
1153    }
1154
1155    /// Reconciles the worker state with the given target command state,
1156    /// which the caller has drained from a new client connection up to (exclusive) the
1157    /// `InitializationComplete` marker.
1158    pub fn reconcile_commands(&mut self, mut commands: Vec<StorageCommand>) {
1159        let worker_id = self.timely_worker.index();
1160
1161        // Track which frontiers this envd expects; we will also set their
1162        // initial timestamp to the minimum timestamp to reset them as we don't
1163        // know what frontiers the new envd expects.
1164        let mut expected_objects = BTreeSet::new();
1165
1166        let mut drop_commands = BTreeSet::new();
1167        let mut running_ingestion_descriptions = self.storage_state.ingestions.clone();
1168        let mut running_exports_descriptions = self.storage_state.exports.clone();
1169
1170        let mut create_oneshot_ingestions: BTreeSet<Uuid> = BTreeSet::new();
1171        let mut cancel_oneshot_ingestions: BTreeSet<Uuid> = BTreeSet::new();
1172
1173        for command in &mut commands {
1174            match command {
1175                StorageCommand::Hello { .. } => {
1176                    panic!("Hello must be captured before")
1177                }
1178                StorageCommand::AllowCompaction(id, since) => {
1179                    info!(%worker_id, ?id, ?since, "reconcile: received AllowCompaction command");
1180
1181                    // collect all "drop commands". These are `AllowCompaction`
1182                    // commands that compact to the empty since. Then, later, we make sure
1183                    // we retain only those `Create*` commands that are not dropped. We
1184                    // assume that the `AllowCompaction` command is ordered after the
1185                    // `Create*` commands but don't assert that.
1186                    // WIP: Should we assert?
1187                    if since.is_empty() {
1188                        drop_commands.insert(*id);
1189                    }
1190                }
1191                StorageCommand::RunIngestion(ingestion) => {
1192                    info!(
1193                        %worker_id,
1194                        id = %ingestion.id,
1195                        "reconcile: received RunIngestion command"
1196                    );
1197                    trace!(%worker_id, ?ingestion, "reconcile: received RunIngestion command");
1198
1199                    // Ensure that ingestions are forward-rolling alter compatible.
1200                    let prev = running_ingestion_descriptions
1201                        .insert(ingestion.id, ingestion.description.clone());
1202
1203                    if let Some(prev_ingest) = prev {
1204                        // If the new ingestion is not exactly equal to the currently running
1205                        // ingestion, we must either track that we need to synthesize an update
1206                        // command to change the ingestion, or panic.
1207                        prev_ingest
1208                            .alter_compatible(ingestion.id, &ingestion.description)
1209                            .expect("only alter compatible ingestions permitted");
1210                    }
1211                }
1212                StorageCommand::RunSink(export) => {
1213                    info!(%worker_id, ?export, "reconcile: received RunSink command");
1214
1215                    // Ensure that exports are forward-rolling alter compatible.
1216                    let prev =
1217                        running_exports_descriptions.insert(export.id, export.description.clone());
1218
1219                    if let Some(prev_export) = prev {
1220                        prev_export
1221                            .alter_compatible(export.id, &export.description)
1222                            .expect("only alter compatible exports permitted");
1223                    }
1224                }
1225                StorageCommand::RunOneshotIngestion(ingestion) => {
1226                    info!(
1227                        %worker_id,
1228                        ingestion_id = %ingestion.ingestion_id,
1229                        collection_id = %ingestion.collection_id,
1230                        "reconcile: received RunOneshotIngestion command",
1231                    );
1232                    create_oneshot_ingestions.insert(ingestion.ingestion_id);
1233                }
1234                StorageCommand::CancelOneshotIngestion(uuid) => {
1235                    info!(%worker_id, %uuid, "reconcile: received CancelOneshotIngestion command");
1236                    cancel_oneshot_ingestions.insert(*uuid);
1237                }
1238                StorageCommand::InitializationComplete
1239                | StorageCommand::AllowWrites
1240                | StorageCommand::UpdateConfiguration(_) => (),
1241            }
1242        }
1243
1244        let mut seen_most_recent_definition = BTreeSet::new();
1245
1246        // We iterate over this backward to ensure that we keep only the most recent ingestion
1247        // description.
1248        let mut filtered_commands = VecDeque::new();
1249        for mut command in commands.into_iter().rev() {
1250            let mut should_keep = true;
1251            match &mut command {
1252                StorageCommand::Hello { .. } => {
1253                    panic!("Hello must be captured before")
1254                }
1255                StorageCommand::RunIngestion(ingestion) => {
1256                    // Subsources can be dropped independently of their
1257                    // primary source, so we evaluate them in a separate
1258                    // loop.
1259                    for export_id in ingestion
1260                        .description
1261                        .source_exports
1262                        .keys()
1263                        .filter(|export_id| **export_id != ingestion.id)
1264                    {
1265                        if drop_commands.remove(export_id) {
1266                            info!(%worker_id, %export_id, "reconcile: dropping subsource");
1267                            self.storage_state.dropped_ids.push(*export_id);
1268                        }
1269                    }
1270
1271                    if drop_commands.remove(&ingestion.id)
1272                        || self.storage_state.dropped_ids.contains(&ingestion.id)
1273                    {
1274                        info!(%worker_id, %ingestion.id, "reconcile: dropping ingestion");
1275
1276                        // If an ingestion is dropped, so too must all of
1277                        // its subsources (i.e. ingestion exports, as well
1278                        // as its progress subsource).
1279                        for id in ingestion.description.collection_ids() {
1280                            drop_commands.remove(&id);
1281                            self.storage_state.dropped_ids.push(id);
1282                        }
1283                        should_keep = false;
1284                    } else {
1285                        let most_recent_defintion =
1286                            seen_most_recent_definition.insert(ingestion.id);
1287
1288                        if most_recent_defintion {
1289                            // If this is the most recent definition, this
1290                            // is what we will be running when
1291                            // reconciliation completes. This definition
1292                            // must not include any dropped subsources.
1293                            ingestion.description.source_exports.retain(|export_id, _| {
1294                                !self.storage_state.dropped_ids.contains(export_id)
1295                            });
1296
1297                            // After clearing any dropped subsources, we can
1298                            // state that we expect all of these to exist.
1299                            expected_objects.extend(ingestion.description.collection_ids());
1300                        }
1301
1302                        let running_ingestion = self.storage_state.ingestions.get(&ingestion.id);
1303
1304                        // We keep only:
1305                        // - The most recent version of the ingestion, which
1306                        //   is why these commands are run in reverse.
1307                        // - Ingestions whose descriptions are not exactly
1308                        //   those that are currently running.
1309                        should_keep = most_recent_defintion
1310                            && running_ingestion != Some(&ingestion.description)
1311                    }
1312                }
1313                StorageCommand::RunSink(export) => {
1314                    if drop_commands.remove(&export.id)
1315                        // If there were multiple `RunSink` in the command
1316                        // stream, we want to ensure none of them are
1317                        // retained.
1318                        || self.storage_state.dropped_ids.contains(&export.id)
1319                    {
1320                        info!(%worker_id, %export.id, "reconcile: dropping sink");
1321
1322                        // Make sure that we report back that the ID was
1323                        // dropped.
1324                        self.storage_state.dropped_ids.push(export.id);
1325
1326                        should_keep = false
1327                    } else {
1328                        expected_objects.insert(export.id);
1329
1330                        let running_sink = self.storage_state.exports.get(&export.id);
1331
1332                        // We keep only:
1333                        // - The most recent version of the sink, which
1334                        //   is why these commands are run in reverse.
1335                        // - Sinks whose descriptions are not exactly
1336                        //   those that are currently running.
1337                        should_keep = seen_most_recent_definition.insert(export.id)
1338                            && running_sink != Some(&export.description);
1339                    }
1340                }
1341                StorageCommand::RunOneshotIngestion(ingestion) => {
1342                    let already_running = self
1343                        .storage_state
1344                        .oneshot_ingestions
1345                        .contains_key(&ingestion.ingestion_id);
1346                    let was_canceled = cancel_oneshot_ingestions.contains(&ingestion.ingestion_id);
1347
1348                    should_keep = !already_running && !was_canceled;
1349                }
1350                StorageCommand::CancelOneshotIngestion(ingestion_id) => {
1351                    let already_running = self
1352                        .storage_state
1353                        .oneshot_ingestions
1354                        .contains_key(ingestion_id);
1355                    should_keep = already_running;
1356                }
1357                StorageCommand::InitializationComplete
1358                | StorageCommand::AllowWrites
1359                | StorageCommand::UpdateConfiguration(_)
1360                | StorageCommand::AllowCompaction(_, _) => (),
1361            }
1362            if should_keep {
1363                filtered_commands.push_front(command);
1364            }
1365        }
1366        let commands = filtered_commands;
1367
1368        // Make sure all the "drop commands" matched up with a source or sink.
1369        // This is also what the regular handler logic for `AllowCompaction`
1370        // would do.
1371        soft_assert_or_log!(
1372            drop_commands.is_empty(),
1373            "AllowCompaction commands for non-existent IDs {:?}",
1374            drop_commands
1375        );
1376
1377        // Determine the ID of all objects we did _not_ see; these are
1378        // considered stale.
1379        let stale_objects = self
1380            .storage_state
1381            .ingestions
1382            .values()
1383            .map(|i| i.collection_ids())
1384            .flatten()
1385            .chain(self.storage_state.exports.keys().copied())
1386            // Objects are considered stale if we did not see them re-created.
1387            .filter(|id| !expected_objects.contains(id))
1388            .collect::<Vec<_>>();
1389        let stale_oneshot_ingestions = self
1390            .storage_state
1391            .oneshot_ingestions
1392            .keys()
1393            .filter(|ingestion_id| {
1394                let to_create = create_oneshot_ingestions.contains(ingestion_id);
1395                let to_drop = cancel_oneshot_ingestions.contains(ingestion_id);
1396                mz_ore::soft_assert_or_log!(
1397                    !(!to_create && to_drop),
1398                    "attempting to drop oneshot source {ingestion_id} that is not expected to be created during reconciliation"
1399                );
1400                !to_create && !to_drop
1401            })
1402            .copied()
1403            .collect::<Vec<_>>();
1404
1405        info!(
1406            %worker_id, ?expected_objects, ?stale_objects, ?stale_oneshot_ingestions,
1407            "reconcile: modifing storage state to match expected objects",
1408        );
1409
1410        for id in stale_objects {
1411            self.storage_state.drop_collection(id);
1412        }
1413        for id in stale_oneshot_ingestions {
1414            self.storage_state.drop_oneshot_ingestion(id);
1415        }
1416
1417        // Do not report dropping any objects that do not belong to expected
1418        // objects.
1419        self.storage_state
1420            .dropped_ids
1421            .retain(|id| expected_objects.contains(id));
1422
1423        // Do not report any frontiers that do not belong to expected objects.
1424        // Note that this set of objects can differ from the set of sources and
1425        // sinks.
1426        self.storage_state
1427            .reported_frontiers
1428            .retain(|id, _| expected_objects.contains(id));
1429
1430        // Reset the reported frontiers for the remaining objects.
1431        for (_, frontier) in &mut self.storage_state.reported_frontiers {
1432            *frontier = Antichain::from_elem(<_>::minimum());
1433        }
1434
1435        // Reset the initial status reported flag when a new client connects
1436        self.storage_state.initial_status_reported = false;
1437
1438        // Execute the modified commands.
1439        for command in commands {
1440            self.storage_state.handle_storage_command(command);
1441        }
1442    }
1443}
1444
1445impl StorageState {
1446    /// Entry point for applying a storage command.
1447    ///
1448    /// NOTE: This does not have access to the timely worker and therefore
1449    /// cannot render dataflows. For dataflow rendering, this needs to either
1450    /// send asynchronous command to the `async_worker` or internal
1451    /// commands to the `internal_cmd_tx`.
1452    pub fn handle_storage_command(&mut self, cmd: StorageCommand) {
1453        match cmd {
1454            StorageCommand::Hello { .. } => panic!("Hello must be captured before"),
1455            StorageCommand::InitializationComplete => (),
1456            StorageCommand::AllowWrites => {
1457                self.read_only_tx
1458                    .send(false)
1459                    .expect("we're holding one other end");
1460                self.persist_clients.cfg().enable_compaction();
1461            }
1462            StorageCommand::UpdateConfiguration(params) => {
1463                // These can be done from all workers safely.
1464                debug!("Applying configuration update: {params:?}");
1465
1466                // We serialize the dyncfg updates in StorageParameters, but configure
1467                // persist separately.
1468                self.persist_clients
1469                    .cfg()
1470                    .apply_from(&params.dyncfg_updates);
1471
1472                params.tracing.apply(self.tracing_handle.as_ref());
1473
1474                if let Some(log_filter) = &params.tracing.log_filter {
1475                    self.storage_configuration
1476                        .connection_context
1477                        .librdkafka_log_level =
1478                        mz_ore::tracing::crate_level(&log_filter.clone().into(), "librdkafka");
1479                }
1480
1481                // This needs to be broadcast by one worker and go through
1482                // the internal command fabric, to ensure consistent
1483                // ordering of dataflow rendering across all workers.
1484                if self.timely_worker_index == 0 {
1485                    self.internal_cmd_tx
1486                        .send(InternalStorageCommand::UpdateConfiguration {
1487                            storage_parameters: *params,
1488                        })
1489                }
1490            }
1491            StorageCommand::RunIngestion(ingestion) => {
1492                let RunIngestionCommand { id, description } = *ingestion;
1493
1494                // Remember the ingestion description to facilitate possible
1495                // reconciliation later.
1496                self.ingestions.insert(id, description.clone());
1497
1498                // Initialize shared frontier reporting.
1499                for id in description.collection_ids() {
1500                    self.reported_frontiers
1501                        .entry(id)
1502                        .or_insert_with(|| Antichain::from_elem(mz_repr::Timestamp::minimum()));
1503                }
1504
1505                // This needs to be done by one worker, which will broadcasts a
1506                // `CreateIngestionDataflow` command to all workers based on the response that
1507                // contains the resumption upper.
1508                //
1509                // Doing this separately on each worker could lead to differing resume_uppers
1510                // which might lead to all kinds of mayhem.
1511                //
1512                // n.b. the ingestion on each worker uses the description from worker 0––not the
1513                // ingestion in the local storage state. This is something we might have
1514                // interest in fixing in the future, e.g. materialize#19907
1515                if self.timely_worker_index == 0 {
1516                    self.async_worker
1517                        .update_ingestion_frontiers(id, description);
1518                }
1519            }
1520            StorageCommand::RunOneshotIngestion(oneshot) => {
1521                if self.timely_worker_index == 0 {
1522                    self.internal_cmd_tx
1523                        .send(InternalStorageCommand::RunOneshotIngestion {
1524                            ingestion_id: oneshot.ingestion_id,
1525                            collection_id: oneshot.collection_id,
1526                            collection_meta: oneshot.collection_meta,
1527                            request: oneshot.request,
1528                        });
1529                }
1530            }
1531            StorageCommand::CancelOneshotIngestion(id) => {
1532                self.drop_oneshot_ingestion(id);
1533            }
1534            StorageCommand::RunSink(export) => {
1535                // Remember the sink description to facilitate possible
1536                // reconciliation later.
1537                let prev = self.exports.insert(export.id, export.description.clone());
1538
1539                // New sink, add state.
1540                if prev.is_none() {
1541                    self.reported_frontiers.insert(
1542                        export.id,
1543                        Antichain::from_elem(mz_repr::Timestamp::minimum()),
1544                    );
1545                }
1546
1547                // This needs to be broadcast by one worker and go through the internal command
1548                // fabric, to ensure consistent ordering of dataflow rendering across all
1549                // workers.
1550                if self.timely_worker_index == 0 {
1551                    self.internal_cmd_tx
1552                        .send(InternalStorageCommand::RunSinkDataflow(
1553                            export.id,
1554                            export.description,
1555                        ));
1556                }
1557            }
1558            StorageCommand::AllowCompaction(id, frontier) => {
1559                soft_assert_or_log!(
1560                    self.exports.contains_key(&id) || self.reported_frontiers.contains_key(&id),
1561                    "AllowCompaction command for non-existent {id}"
1562                );
1563
1564                if frontier.is_empty() {
1565                    // Indicates that we may drop `id`, as there are no more valid times to read.
1566                    self.drop_collection(id);
1567                }
1568            }
1569        }
1570    }
1571
1572    /// Drop the identified storage collection from the storage state.
1573    fn drop_collection(&mut self, id: GlobalId) {
1574        fail_point!("crash_on_drop");
1575
1576        self.ingestions.remove(&id);
1577        self.exports.remove(&id);
1578
1579        let _ = self.latest_status_updates.remove(&id);
1580
1581        // This will stop reporting of frontiers.
1582        //
1583        // If this object still has its frontiers reported, we will notify the
1584        // client envd of the drop.
1585        if self.reported_frontiers.remove(&id).is_some() {
1586            // The only actions left are internal cleanup, so we can commit to
1587            // the client that these objects have been dropped.
1588            //
1589            // This must be done now rather than in response to `DropDataflow`,
1590            // otherwise we introduce the possibility of a timing issue where:
1591            // - We remove all tracking state from the storage state and send
1592            //   `DropDataflow` (i.e. this block).
1593            // - While waiting to process that command, we reconcile with a new
1594            //   envd. That envd has already committed to its catalog that this
1595            //   object no longer exists.
1596            // - We process the `DropDataflow` command, and identify that this
1597            //   object has been dropped.
1598            // - The next time `dropped_ids` is processed, we send a response
1599            //   that this ID has been dropped, but the upstream state has no
1600            //   record of that object having ever existed.
1601            self.dropped_ids.push(id);
1602        }
1603
1604        // Send through async worker for correct ordering with RunIngestion, and
1605        // dropping the dataflow is done on async worker response.
1606        if self.timely_worker_index == 0 {
1607            self.async_worker.drop_dataflow(id);
1608        }
1609    }
1610
1611    /// Drop the identified oneshot ingestion from the storage state.
1612    fn drop_oneshot_ingestion(&mut self, ingestion_id: uuid::Uuid) {
1613        let prev = self.oneshot_ingestions.remove(&ingestion_id);
1614        info!(%ingestion_id, existed = %prev.is_some(), "dropping oneshot ingestion");
1615    }
1616}