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