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