Skip to main content

mz_compute/
server.rs

1// Copyright Materialize, Inc. and contributors. All rights reserved.
2//
3// Use of this software is governed by the Business Source License
4// included in the LICENSE file.
5//
6// As of the Change Date specified in that file, in accordance with
7// the Business Source License, use of this software will be governed
8// by the Apache License, Version 2.0.
9
10//! An interactive dataflow server.
11
12use std::cell::RefCell;
13use std::collections::{BTreeMap, BTreeSet};
14use std::convert::Infallible;
15use std::fmt::Debug;
16use std::path::PathBuf;
17use std::rc::Rc;
18use std::sync::{Arc, Mutex};
19use std::task::{Context, Poll};
20use std::thread::Thread;
21use std::time::{Duration, Instant};
22
23use anyhow::Error;
24use mz_cluster::client::{ClusterClient, ClusterSpec, GuestClusterClient};
25use mz_cluster_client::client::TimelyConfig;
26use mz_compute_client::protocol::command::ComputeCommand;
27use mz_compute_client::protocol::history::ComputeCommandHistory;
28use mz_compute_client::protocol::response::ComputeResponse;
29use mz_ore::halt;
30use mz_ore::metrics::MetricsRegistry;
31use mz_ore::now::NowFn;
32use mz_ore::tracing::TracingHandle;
33use mz_persist_client::cache::PersistClientCache;
34use mz_rocksdb::config::SharedWriteBufferManager;
35use mz_service::client::GenericClient;
36use mz_storage::internal_control::{InternalCommandSender, InternalStorageCommand};
37use mz_storage::metrics::StorageMetrics;
38use mz_storage::storage_state::{StorageInstanceContext, StorageState, Worker as StorageWorker};
39use mz_storage_client::client::{StorageCommand, StorageResponse};
40use mz_storage_operators::persist::SharedBatches;
41use mz_storage_types::connections::ConnectionContext;
42use mz_txn_wal::operator::TxnsContext;
43use timely::progress::Antichain;
44use timely::worker::Worker as TimelyWorker;
45use tokio::sync::mpsc;
46use tokio::sync::mpsc::error::SendError;
47use tracing::{info, trace, warn};
48use uuid::Uuid;
49
50use crate::command_channel::{self, StorageLaneInput, UnifiedCommand};
51use crate::compute_state::{
52    ActiveComputeState, ComputeState, PeekPermits, PendingPeek, ReportedFrontier,
53};
54use crate::metrics::{ComputeMetrics, WorkerMetrics};
55
56/// Caller-provided configuration for compute.
57#[derive(Clone, Debug)]
58pub struct ComputeInstanceContext {
59    /// A directory that can be used for scratch work.
60    pub scratch_directory: Option<PathBuf>,
61    /// Whether to set core affinity for Timely workers.
62    pub worker_core_affinity: bool,
63    /// Whether the replica can swap.
64    pub swap_available: bool,
65    /// Context required to connect to an external sink from compute,
66    /// like the `CopyToS3OneshotSink` compute sink.
67    pub connection_context: ConnectionContext,
68}
69
70/// Which of a process's compute runtimes a given runtime is.
71///
72/// A clusterd process runs a single `Solo` runtime by default. When an interactive runtime is
73/// configured, the process instead runs a `Maintenance` and an `Interactive` runtime side by side.
74/// The named roles share per-process resources (persist cache, metrics registry, log spans). The
75/// role distinguishes them so that only the globals-owning runtime runs the non-idempotent
76/// process-global initializers, and so metric series and log spans do not collide.
77///
78/// `Solo` exists so the single-runtime default stays behaviorally identical to a deployment without
79/// a second runtime: no `role` metric label, and it owns the process globals just as the sole
80/// runtime always has.
81#[derive(Clone, Copy, Debug, PartialEq, Eq)]
82pub enum ComputeRuntimeRole {
83    /// The sole runtime of a single-runtime process. Owns index maintenance and the process-global
84    /// initializers.
85    Solo,
86    /// The maintenance runtime of a two-runtime process. Owns index maintenance and the
87    /// process-global initializers.
88    Maintenance,
89    /// The interactive runtime of a two-runtime process. Shares the process globals owned by
90    /// maintenance and serves reads.
91    ///
92    /// Test-only until the interactive runtime exists to construct it. It is present because the
93    /// `role` label's entire purpose is that two named roles register into one process registry
94    /// without colliding, and nothing else can express that: `Solo` registers the same metric names
95    /// with no `role` label, so prometheus rejects it alongside a named role for differing label
96    /// dimensions rather than treating it as a second series. Verifying non-collision therefore
97    /// needs a second *named* role.
98    ///
99    /// TODO: drop the `cfg` when the interactive runtime lands and constructs this.
100    #[cfg(test)]
101    Interactive,
102}
103
104impl ComputeRuntimeRole {
105    /// The `role` metric/log label for this role, or `None` for `Solo`.
106    ///
107    /// `Solo` omits the label so a single-runtime deployment registers exactly as it did before a
108    /// second runtime existed, keeping exact-match dashboards and alerts unchanged.
109    pub fn label(self) -> Option<&'static str> {
110        match self {
111            ComputeRuntimeRole::Solo => None,
112            ComputeRuntimeRole::Maintenance => Some("maintenance"),
113            #[cfg(test)]
114            ComputeRuntimeRole::Interactive => Some("interactive"),
115        }
116    }
117
118    /// Whether this role runs the non-idempotent, process-global initializers.
119    ///
120    /// `Solo` and `Maintenance` run them. An interactive runtime shares the same process and
121    /// inherits the globals maintenance installs, so re-running them would either double-apply a
122    /// non-idempotent effect or race maintenance.
123    ///
124    /// NOTE: every role a release build can construct owns the globals, so this is constantly true
125    /// outside tests. The distinction becomes load-bearing when the interactive runtime lands.
126    pub fn owns_process_globals(self) -> bool {
127        matches!(
128            self,
129            ComputeRuntimeRole::Solo | ComputeRuntimeRole::Maintenance
130        )
131    }
132}
133
134/// Configures the server with compute-specific metrics.
135#[derive(Clone)]
136struct Config {
137    /// `persist` client cache.
138    pub persist_clients: Arc<PersistClientCache>,
139    /// Shared persist batch state.
140    pub persist_batches: SharedBatches,
141    /// Context necessary for rendering txn-wal operators.
142    pub txns_ctx: TxnsContext,
143    /// A process-global handle to tracing configuration.
144    pub tracing_handle: Arc<TracingHandle>,
145    /// Metrics exposed by compute replicas.
146    pub metrics: ComputeMetrics,
147    /// Other configuration for compute.
148    pub context: ComputeInstanceContext,
149    /// The process-global metrics registry.
150    pub metrics_registry: MetricsRegistry,
151    /// The number of timely workers per process.
152    pub workers_per_process: usize,
153    /// Bounds how many offloaded peek walks run at once, shared by every worker this server runs.
154    ///
155    /// NOTE: per compute runtime, not global. A process running a maintenance and an interactive
156    /// runtime calls `serve` twice and admits the bound once per call.
157    pub peek_permits: Arc<PeekPermits>,
158    /// Configuration for hosting storage objects on this cluster, if enabled.
159    pub storage_guest: Option<Arc<StorageGuestConfig>>,
160}
161
162/// A per-worker channel delivering storage client connections.
163type StorageClientRx = mpsc::UnboundedReceiver<(
164    Uuid,
165    mpsc::UnboundedReceiver<StorageCommand>,
166    mpsc::UnboundedSender<StorageResponse>,
167)>;
168
169/// Configuration for hosting storage objects on the compute cluster.
170pub struct StorageGuestConfig {
171    /// Per-worker channels delivering storage client connections, indexed by local worker index.
172    client_rxs: Mutex<Vec<Option<StorageClientRx>>>,
173    /// Metrics for storage objects.
174    metrics: StorageMetrics,
175    /// Function to get wall time now.
176    now: NowFn,
177    /// Configuration for source and sink connections.
178    connection_context: ConnectionContext,
179    /// Other configuration for storage instances.
180    instance_context: StorageInstanceContext,
181    /// Shared rocksdb write buffer manager.
182    shared_rocksdb_write_buffer_manager: SharedWriteBufferManager,
183}
184
185/// Initiates a timely dataflow computation, processing compute commands.
186pub async fn serve(
187    timely_config: TimelyConfig,
188    role: ComputeRuntimeRole,
189    metrics_registry: &MetricsRegistry,
190    persist_clients: Arc<PersistClientCache>,
191    txns_ctx: TxnsContext,
192    tracing_handle: Arc<TracingHandle>,
193    context: ComputeInstanceContext,
194) -> Result<impl Fn() -> ComputeServerClient + use<>, Error> {
195    let workers_per_process = timely_config.workers;
196    let config = Config {
197        persist_batches: SharedBatches::new(),
198        persist_clients,
199        txns_ctx,
200        tracing_handle,
201        metrics: ComputeMetrics::register_with(metrics_registry, role),
202        context,
203        metrics_registry: metrics_registry.clone(),
204        workers_per_process,
205        peek_permits: Arc::new(PeekPermits::new(workers_per_process)),
206        storage_guest: None,
207    };
208
209    let (_worker_threads, client_builder) = serve_inner(config, timely_config).await?;
210    Ok(client_builder)
211}
212
213/// Initiates a timely dataflow computation that processes compute commands and additionally hosts
214/// storage objects, processing storage commands received over a separate client connection.
215///
216/// Returns client builders for both the compute and the storage side.
217pub async fn serve_unified(
218    timely_config: TimelyConfig,
219    role: ComputeRuntimeRole,
220    metrics_registry: &MetricsRegistry,
221    persist_clients: Arc<PersistClientCache>,
222    txns_ctx: TxnsContext,
223    tracing_handle: Arc<TracingHandle>,
224    context: ComputeInstanceContext,
225    now: NowFn,
226    storage_connection_context: ConnectionContext,
227    storage_instance_context: StorageInstanceContext,
228) -> Result<
229    (
230        impl Fn() -> ComputeServerClient + use<>,
231        impl Fn() -> GuestClusterClient<StorageCommand, StorageResponse> + use<>,
232    ),
233    Error,
234> {
235    let workers_per_process = timely_config.workers;
236
237    // Per-worker channels over which storage client connections are delivered.
238    let mut storage_client_txs = Vec::new();
239    let mut storage_client_rxs = Vec::new();
240    for _ in 0..workers_per_process {
241        let (tx, rx) = mpsc::unbounded_channel();
242        storage_client_txs.push(tx);
243        storage_client_rxs.push(Some(rx));
244    }
245
246    let storage_guest = StorageGuestConfig {
247        client_rxs: Mutex::new(storage_client_rxs),
248        metrics: StorageMetrics::register_with(metrics_registry),
249        now,
250        connection_context: storage_connection_context,
251        instance_context: storage_instance_context,
252        shared_rocksdb_write_buffer_manager: Default::default(),
253    };
254
255    let config = Config {
256        persist_batches: SharedBatches::new(),
257        persist_clients,
258        txns_ctx,
259        tracing_handle,
260        metrics: ComputeMetrics::register_with(metrics_registry, role),
261        context,
262        metrics_registry: metrics_registry.clone(),
263        workers_per_process,
264        peek_permits: Arc::new(PeekPermits::new(workers_per_process)),
265        storage_guest: Some(Arc::new(storage_guest)),
266    };
267
268    let (worker_threads, compute_client_builder) = serve_inner(config, timely_config).await?;
269
270    let storage_client_txs = Arc::new(storage_client_txs);
271    let storage_client_builder =
272        move || GuestClusterClient::new(Arc::clone(&storage_client_txs), worker_threads.clone());
273
274    Ok((compute_client_builder, storage_client_builder))
275}
276
277/// Builds the Timely cluster for the given config and returns its worker threads along with a
278/// builder for compute clients to it.
279async fn serve_inner(
280    config: Config,
281    timely_config: TimelyConfig,
282) -> Result<(Vec<Thread>, impl Fn() -> ComputeServerClient + use<>), Error> {
283    mz_timely_util::pool_config::metrics::register(&config.metrics_registry);
284    mz_cluster::client::register_exert_policy_metrics(&config.metrics_registry);
285
286    let tokio_executor = tokio::runtime::Handle::current();
287
288    let timely_container = config.build_cluster(timely_config, tokio_executor).await?;
289    let worker_threads = timely_container.worker_threads();
290    let timely_container = Arc::new(Mutex::new(timely_container));
291
292    let client_builder =
293        move || ComputeServerClient(ClusterClient::new(Arc::clone(&timely_container)));
294
295    Ok((worker_threads, client_builder))
296}
297
298/// A client to the Timely cluster of a compute server.
299#[derive(Debug)]
300pub struct ComputeServerClient(ClusterClient<Config>);
301
302impl GenericClient<ComputeCommand, ComputeResponse> for ComputeServerClient {
303    fn send(&mut self, cmd: ComputeCommand) -> impl Future<Output = Result<(), Error>> + Send {
304        self.0.send(cmd)
305    }
306
307    fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll<Result<Option<ComputeResponse>, Error>> {
308        self.0.poll_recv(cx)
309    }
310}
311
312/// Error type returned on connection nonce changes.
313///
314/// A nonce change informs workers that subsequent commands come a from a new client connection
315/// and therefore require reconciliation.
316struct NonceChange(Uuid);
317
318/// Endpoint used by workers to receive compute commands.
319///
320/// Observes nonce changes in the command stream and converts them into receive errors.
321struct CommandReceiver {
322    /// The channel supplying commands.
323    inner: command_channel::Receiver,
324    /// The ID of the Timely worker.
325    worker_id: usize,
326    /// The nonce identifying the current cluster protocol incarnation.
327    nonce: Option<Uuid>,
328    /// A stash to enable peeking the next command, used in `try_recv`.
329    stashed_command: Option<ComputeCommand>,
330}
331
332impl CommandReceiver {
333    fn new(inner: command_channel::Receiver, worker_id: usize) -> Self {
334        Self {
335            inner,
336            worker_id,
337            nonce: None,
338            stashed_command: None,
339        }
340    }
341
342    /// Receive the next pending command, if any.
343    ///
344    /// If the next compute command has a different nonce, this method instead returns an `Err`
345    /// containing the new nonce.
346    fn try_recv(&mut self) -> Result<Option<WorkerCommand>, NonceChange> {
347        if let Some(command) = self.stashed_command.take() {
348            return Ok(Some(WorkerCommand::Compute(command)));
349        }
350        let Some(message) = self.inner.try_recv() else {
351            return Ok(None);
352        };
353
354        let (command, nonce) = match message {
355            UnifiedCommand::Compute(command, nonce) => (command, nonce),
356            UnifiedCommand::Storage(command) => {
357                trace!(
358                    worker = self.worker_id,
359                    ?command,
360                    "received storage command"
361                );
362                return Ok(Some(WorkerCommand::Storage(command)));
363            }
364        };
365
366        trace!(worker = self.worker_id, %nonce, ?command, "received command");
367
368        if Some(nonce) == self.nonce {
369            Ok(Some(WorkerCommand::Compute(command)))
370        } else {
371            self.nonce = Some(nonce);
372            self.stashed_command = Some(command);
373            Err(NonceChange(nonce))
374        }
375    }
376}
377
378/// A command dispatched to the worker from the command channel.
379enum WorkerCommand {
380    /// A compute command.
381    Compute(ComputeCommand),
382    /// A storage-internal command, to be dispatched to the storage guest.
383    Storage(InternalStorageCommand),
384}
385
386/// Endpoint used by workers to send sending compute responses.
387///
388/// Tags responses with the current nonce, allowing receivers to filter out responses intended for
389/// previous client connections.
390pub(crate) struct ResponseSender {
391    /// The channel consuming responses.
392    inner: mpsc::UnboundedSender<(ComputeResponse, Uuid)>,
393    /// The ID of the Timely worker.
394    worker_id: usize,
395    /// The nonce identifying the current cluster protocol incarnation.
396    nonce: Option<Uuid>,
397}
398
399impl ResponseSender {
400    /// `pub(crate)` rather than private so the peek tests can build the sender a worker holds.
401    pub(crate) fn new(
402        inner: mpsc::UnboundedSender<(ComputeResponse, Uuid)>,
403        worker_id: usize,
404    ) -> Self {
405        Self {
406            inner,
407            worker_id,
408            nonce: None,
409        }
410    }
411
412    /// Set the cluster protocol nonce.
413    pub(crate) fn set_nonce(&mut self, nonce: Uuid) {
414        self.nonce = Some(nonce);
415    }
416
417    /// Send a compute response.
418    pub fn send(&self, response: ComputeResponse) -> Result<(), SendError<ComputeResponse>> {
419        let nonce = self.nonce.expect("nonce must be initialized");
420
421        trace!(worker = self.worker_id, %nonce, ?response, "sending response");
422        self.inner
423            .send((response, nonce))
424            .map_err(|SendError((resp, _))| SendError(resp))
425    }
426}
427
428/// State maintained for each worker thread.
429///
430/// Much of this state can be viewed as local variables for the worker thread,
431/// holding state that persists across function calls.
432struct Worker<'w> {
433    /// The underlying Timely worker.
434    timely_worker: &'w mut TimelyWorker,
435    /// The channel over which commands are received.
436    command_rx: CommandReceiver,
437    /// The channel over which responses are sent.
438    response_tx: ResponseSender,
439    compute_state: Option<ComputeState>,
440    /// Compute metrics.
441    metrics: WorkerMetrics,
442    /// A process-global cache of (blob_uri, consensus_uri) -> PersistClient.
443    /// This is intentionally shared between workers
444    persist_clients: Arc<PersistClientCache>,
445    persist_batches: SharedBatches,
446    /// Context necessary for rendering txn-wal operators.
447    txns_ctx: TxnsContext,
448    /// A process-global handle to tracing configuration.
449    tracing_handle: Arc<TracingHandle>,
450    context: ComputeInstanceContext,
451    /// The process-global metrics registry.
452    metrics_registry: MetricsRegistry,
453    /// The number of timely workers per process.
454    workers_per_process: usize,
455    /// Bounds how many offloaded peek walks run at once, shared by the workers of one `serve`
456    /// call rather than by the process.
457    peek_permits: Arc<PeekPermits>,
458    /// The hosted storage guest, if any.
459    storage: Option<StorageGuest>,
460}
461
462/// Per-worker state for hosting storage objects on the compute cluster.
463struct StorageGuest {
464    /// Channel delivering new storage client connections.
465    client_rx: StorageClientRx,
466    /// The current storage client connection, if any.
467    conn: Option<StorageConn>,
468    /// The hosted storage worker state.
469    storage_state: StorageState,
470    /// The last time storage maintenance ran.
471    last_maintenance: Instant,
472    /// The last time storage statistics were reported.
473    last_stats_time: Instant,
474}
475
476impl StorageGuest {
477    /// The longest the worker may park before the guest's next periodic duty (frontier reporting
478    /// or statistics collection) comes due, or `None` when no duty is pending.
479    ///
480    /// Mirrors the parking of storage's own server loop: the maintenance and statistics intervals
481    /// bound the park. A maintenance deadline in the past does not bound it, because maintenance
482    /// runs on the next wakeup anyway. The initial zero maintenance interval would otherwise turn
483    /// every park into a spin.
484    fn park_cap(&self) -> Option<Duration> {
485        // Periodic duties run only on a reconciled connection. Without one there is no deadline
486        // to meet, and connection and command arrivals unpark the worker.
487        let conn_serving = self
488            .conn
489            .as_ref()
490            .is_some_and(|conn| conn.reconcile_buf.is_none());
491        if !conn_serving {
492            return None;
493        }
494
495        let maintenance_interval = self.storage_state.server_maintenance_interval;
496        let stats_interval = self
497            .storage_state
498            .storage_configuration
499            .parameters
500            .statistics_collection_interval;
501
502        let next_maintenance =
503            (self.last_maintenance + maintenance_interval).checked_duration_since(Instant::now());
504        let next_stats = stats_interval.saturating_sub(self.last_stats_time.elapsed());
505        match next_maintenance {
506            Some(maintenance) => Some(maintenance.min(next_stats)),
507            None => Some(next_stats),
508        }
509    }
510}
511
512/// A storage client connection.
513struct StorageConn {
514    /// The channel over which storage commands are received.
515    command_rx: mpsc::UnboundedReceiver<StorageCommand>,
516    /// The channel over which storage responses are sent.
517    response_tx: mpsc::UnboundedSender<StorageResponse>,
518    /// Commands buffered for reconciliation, until `InitializationComplete` is received.
519    /// `None` once the connection is reconciled and serving.
520    reconcile_buf: Option<Vec<StorageCommand>>,
521}
522
523impl ClusterSpec for Config {
524    type Command = ComputeCommand;
525    type Response = ComputeResponse;
526
527    const NAME: &str = "compute";
528
529    fn run_worker(
530        &self,
531        timely_worker: &mut TimelyWorker,
532        client_rx: mpsc::UnboundedReceiver<(
533            Uuid,
534            mpsc::UnboundedReceiver<ComputeCommand>,
535            mpsc::UnboundedSender<ComputeResponse>,
536        )>,
537    ) {
538        if self.context.worker_core_affinity {
539            set_core_affinity(timely_worker.index());
540        }
541
542        let worker_id = timely_worker.index();
543        let metrics = self.metrics.for_worker(worker_id);
544
545        let local_index = worker_id % self.workers_per_process;
546
547        // Prepare the storage guest's inputs to the command channel, so
548        // storage-internal commands are sequenced through the same lane as compute commands.
549        let mut storage_lane_input = None;
550        let guest_setup = self.storage_guest.as_ref().map(|cfg| {
551            let storage_client_rx = cfg.client_rxs.lock().expect("poisoned")[local_index]
552                .take()
553                .expect("each worker takes its storage client_rx exactly once");
554            let (internal_tx, internal_rx) = std::sync::mpsc::channel();
555            let activator_slot = Rc::new(RefCell::new(None));
556            storage_lane_input = Some(StorageLaneInput {
557                rx: internal_rx,
558                activator_slot: Rc::clone(&activator_slot),
559            });
560            let internal_cmd_tx = InternalCommandSender::from_parts(internal_tx, activator_slot);
561            (Arc::clone(cfg), storage_client_rx, internal_cmd_tx)
562        });
563
564        // Create the command channel that broadcasts commands from worker 0 to other workers. We
565        // reuse this channel between client connections, to avoid bugs where different workers end
566        // up creating incompatible sides of the channel dataflow after reconnects.
567        // See database-issues#8964.
568        let (cmd_tx, cmd_rx) = command_channel::render(timely_worker, storage_lane_input);
569        let (resp_tx, resp_rx) = mpsc::unbounded_channel();
570
571        spawn_channel_adapter(client_rx, cmd_tx, resp_rx, worker_id);
572
573        // Create the storage guest state.
574        let storage = guest_setup.map(|(cfg, storage_client_rx, internal_cmd_tx)| {
575            let storage_state = StorageState::new_guest(
576                timely_worker.index(),
577                timely_worker.peers(),
578                internal_cmd_tx,
579                // The host dispatches internal commands from the unified command channel, so
580                // the guest reads no receiver of its own.
581                None,
582                cfg.metrics.clone(),
583                cfg.now.clone(),
584                cfg.connection_context.clone(),
585                cfg.instance_context.clone(),
586                Arc::clone(&self.persist_clients),
587                self.txns_ctx.clone(),
588                Arc::clone(&self.tracing_handle),
589                cfg.shared_rocksdb_write_buffer_manager.clone(),
590            );
591
592            StorageGuest {
593                client_rx: storage_client_rx,
594                conn: None,
595                storage_state,
596                last_maintenance: Instant::now(),
597                last_stats_time: Instant::now(),
598            }
599        });
600
601        Worker {
602            timely_worker,
603            command_rx: CommandReceiver::new(cmd_rx, worker_id),
604            response_tx: ResponseSender::new(resp_tx, worker_id),
605            metrics,
606            context: self.context.clone(),
607            persist_clients: Arc::clone(&self.persist_clients),
608            persist_batches: self.persist_batches.clone(),
609            txns_ctx: self.txns_ctx.clone(),
610            compute_state: None,
611            tracing_handle: Arc::clone(&self.tracing_handle),
612            metrics_registry: self.metrics_registry.clone(),
613            workers_per_process: self.workers_per_process,
614            peek_permits: Arc::clone(&self.peek_permits),
615            storage,
616        }
617        .run()
618    }
619}
620
621/// Set the current thread's core affinity, based on the given `worker_id`.
622#[cfg(not(target_os = "macos"))]
623fn set_core_affinity(worker_id: usize) {
624    use tracing::error;
625
626    let Some(mut core_ids) = core_affinity::get_core_ids() else {
627        error!(worker_id, "unable to get core IDs for setting affinity");
628        return;
629    };
630
631    // The `get_core_ids` docs don't say anything about a guaranteed order of the returned Vec,
632    // so sort it just to be safe.
633    core_ids.sort_unstable_by_key(|i| i.id);
634
635    // On multi-process replicas `worker_id` might be greater than the number of available cores.
636    // However, we assume that we always have at least as many cores as there are local workers.
637    // Violating this assumption is safe but might lead to degraded performance due to skew in core
638    // utilization.
639    let idx = worker_id % core_ids.len();
640    let core_id = core_ids[idx];
641
642    if core_affinity::set_for_current(core_id) {
643        info!(
644            worker_id,
645            core_id = core_id.id,
646            "set core affinity for worker"
647        );
648    } else {
649        error!(
650            worker_id,
651            core_id = core_id.id,
652            "failed to set core affinity for worker"
653        )
654    }
655}
656
657/// Set the current thread's core affinity, based on the given `worker_id`.
658#[cfg(target_os = "macos")]
659fn set_core_affinity(_worker_id: usize) {
660    // Setting core affinity is known to not work on Apple Silicon:
661    // https://github.com/Elzair/core_affinity_rs/issues/22
662    info!("setting core affinity is not supported on macOS");
663}
664
665impl<'w> Worker<'w> {
666    /// Runs a compute worker.
667    pub fn run(&mut self) {
668        // The command receiver is initialized without an nonce, so receiving the first command
669        // always triggers a nonce change.
670        let NonceChange(nonce) = self.recv_command().expect_err("change to first nonce");
671        self.set_nonce(nonce);
672
673        loop {
674            let Err(NonceChange(nonce)) = self.run_client();
675            self.set_nonce(nonce);
676        }
677    }
678
679    fn set_nonce(&mut self, nonce: Uuid) {
680        self.response_tx.set_nonce(nonce);
681    }
682
683    /// Handles commands for a client connection, returns when the nonce changes.
684    fn run_client(&mut self) -> Result<Infallible, NonceChange> {
685        self.reconcile()?;
686
687        // The last time we did periodic maintenance.
688        let mut last_maintenance = Instant::now();
689
690        // Commence normal operation.
691        loop {
692            // Get the maintenance interval, default to zero if we don't have a compute state.
693            let maintenance_interval = self
694                .compute_state
695                .as_ref()
696                .map_or(Duration::ZERO, |state| state.server_maintenance_interval);
697
698            let now = Instant::now();
699            // Determine if we need to perform maintenance, which is true if `maintenance_interval`
700            // time has passed since the last maintenance.
701            let sleep_duration;
702            if now >= last_maintenance + maintenance_interval {
703                last_maintenance = now;
704                sleep_duration = None;
705
706                // Report frontier information back the coordinator.
707                if let Some(mut compute_state) = self.activate_compute() {
708                    compute_state.compute_state.traces.maintenance();
709                    compute_state.report_frontiers();
710                    compute_state.report_metrics();
711                    compute_state.check_expiration();
712                }
713
714                self.metrics.record_shared_row_metrics();
715            } else {
716                // We didn't perform maintenance, sleep until the next maintenance interval.
717                let next_maintenance = last_maintenance + maintenance_interval;
718                sleep_duration = Some(next_maintenance.saturating_duration_since(now))
719            };
720
721            // Do not sleep while a peek waits for its turn. Only the sweep below gives it one,
722            // and nothing else leaves an activation behind to end the park.
723            let sleep_duration = match &self.compute_state {
724                Some(state) if state.peeks_awaiting_turn() => Some(Duration::ZERO),
725                _ => sleep_duration,
726            };
727
728            // With a storage guest, cap the park duration so the guest's periodic duties run on
729            // time.
730            let sleep_duration = match self.storage.as_ref().and_then(StorageGuest::park_cap) {
731                Some(cap) => Some(sleep_duration.map_or(cap, |d| d.min(cap))),
732                None => sleep_duration,
733            };
734
735            // Step the timely worker, recording the time taken.
736            let timer = self.metrics.timely_step_duration_seconds.start_timer();
737            if self.storage_guest_busy() {
738                self.timely_worker.step();
739            } else {
740                self.timely_worker.step_or_park(sleep_duration);
741            }
742            timer.observe_duration();
743
744            self.handle_pending_commands()?;
745
746            self.process_storage_guest();
747
748            if let Some(mut compute_state) = self.activate_compute() {
749                compute_state.process_peeks();
750                compute_state.process_subscribes();
751                compute_state.process_copy_tos();
752            }
753        }
754    }
755
756    fn handle_pending_commands(&mut self) -> Result<(), NonceChange> {
757        while let Some(cmd) = self.command_rx.try_recv()? {
758            match cmd {
759                WorkerCommand::Compute(cmd) => self.handle_command(cmd),
760                WorkerCommand::Storage(cmd) => self.handle_storage_internal_command(cmd),
761            }
762        }
763        Ok(())
764    }
765
766    /// Whether the storage guest has pending work that forbids parking.
767    ///
768    /// It is critical that we allow Timely to park iff there are no pending commands or async
769    /// worker responses, since those are delivered by other threads that only unpark us once, at
770    /// send time.
771    fn storage_guest_busy(&self) -> bool {
772        self.storage.as_ref().is_some_and(|guest| {
773            !guest.client_rx.is_empty()
774                || (!self.storage_commands_held()
775                    && guest
776                        .conn
777                        .as_ref()
778                        .is_some_and(|conn| !conn.command_rx.is_empty()))
779                || !guest.storage_state.async_worker.is_empty()
780        })
781    }
782
783    /// Whether the storage guest must leave external storage commands unread.
784    ///
785    /// Commands are held until compute's `CreateInstance` has initialized logging. Held commands
786    /// do not keep the worker busy. Handling `CreateInstance` releases them.
787    fn storage_commands_held(&self) -> bool {
788        // Storage commands render storage dataflows, and the loggers only observe operators
789        // created after their initialization, so a storage dataflow rendered earlier never
790        // appears in introspection. Nothing orders the storage and compute controller
791        // connections, so the storage controller can connect first. Every storage dataflow
792        // stems from an external storage command, so holding those back suffices.
793        self.compute_state.is_none()
794    }
795
796    /// Dispatch a storage-internal command from the command channel to
797    /// the storage guest. This is where all storage dataflow rendering happens.
798    fn handle_storage_internal_command(&mut self, cmd: InternalStorageCommand) {
799        let mut guest = self
800            .storage
801            .take()
802            .expect("the command channel carries storage commands only when a guest is hosted");
803
804        let mut worker = StorageWorker {
805            timely_worker: &mut *self.timely_worker,
806            client_rx: guest.client_rx,
807            storage_state: guest.storage_state,
808        };
809        worker.handle_internal_storage_command(cmd);
810
811        let StorageWorker {
812            timely_worker: _,
813            client_rx,
814            storage_state,
815        } = worker;
816        guest.client_rx = client_rx;
817        guest.storage_state = storage_state;
818        self.storage = Some(guest);
819    }
820
821    /// Process the storage guest's per-iteration duties: accept client
822    /// connections, handle external storage commands (buffering for reconciliation until
823    /// `InitializationComplete`), forward async worker responses, and report frontiers, dropped
824    /// collections, status updates, and statistics.
825    fn process_storage_guest(&mut self) {
826        let Some(mut guest) = self.storage.take() else {
827            return;
828        };
829
830        // Accept new client connections, replacing any current one. Every new connection starts
831        // with a reconciliation.
832        loop {
833            use tokio::sync::mpsc::error::TryRecvError;
834            match guest.client_rx.try_recv() {
835                Ok((_nonce, command_rx, response_tx)) => {
836                    guest.conn = Some(StorageConn {
837                        command_rx,
838                        response_tx,
839                        reconcile_buf: Some(Vec::new()),
840                    });
841                }
842                Err(TryRecvError::Empty | TryRecvError::Disconnected) => break,
843            }
844        }
845
846        let commands_held = self.storage_commands_held();
847        let mut worker = StorageWorker {
848            timely_worker: &mut *self.timely_worker,
849            client_rx: guest.client_rx,
850            storage_state: guest.storage_state,
851        };
852
853        // Handle responses from the async worker. Only worker 0 does async processing, so only
854        // worker 0 ever receives any. This must run with or without a client connection:
855        // storage-internal commands keep flowing through the command channel while the
856        // controller is away and can issue async work, and an undrained response queue keeps
857        // `storage_guest_busy` true, turning every park into a spin.
858        while let Ok(response) = worker.storage_state.async_worker.try_recv() {
859            worker.handle_async_worker_response(response);
860        }
861
862        let conn = if commands_held {
863            None
864        } else {
865            guest.conn.take()
866        };
867        let Some(mut conn) = conn else {
868            let StorageWorker {
869                timely_worker: _,
870                client_rx,
871                storage_state,
872            } = worker;
873            guest.client_rx = client_rx;
874            guest.storage_state = storage_state;
875            self.storage = Some(guest);
876            return;
877        };
878
879        // Drain external storage commands.
880        let mut disconnected = false;
881        loop {
882            use tokio::sync::mpsc::error::TryRecvError;
883            match conn.command_rx.try_recv() {
884                Ok(StorageCommand::InitializationComplete) if conn.reconcile_buf.is_some() => {
885                    let commands = conn.reconcile_buf.take().expect("checked above");
886                    worker.reconcile_commands(commands);
887                }
888                Ok(cmd) => match &mut conn.reconcile_buf {
889                    Some(buf) => buf.push(cmd),
890                    None => worker.storage_state.handle_storage_command(cmd),
891                },
892                Err(TryRecvError::Empty) => break,
893                Err(TryRecvError::Disconnected) => {
894                    disconnected = true;
895                    break;
896                }
897            }
898        }
899
900        // Response-producing duties run only on a reconciled connection.
901        if conn.reconcile_buf.is_none() {
902            let maintenance_interval = worker.storage_state.server_maintenance_interval;
903            let now = Instant::now();
904            if now >= guest.last_maintenance + maintenance_interval {
905                guest.last_maintenance = now;
906                worker.report_frontier_progress(&conn.response_tx);
907            }
908
909            for id in std::mem::take(&mut worker.storage_state.dropped_ids) {
910                worker.send_storage_response(&conn.response_tx, StorageResponse::DroppedId(id));
911            }
912
913            worker.process_oneshot_ingestions(&conn.response_tx);
914            worker.report_status_updates(&conn.response_tx);
915
916            let stats_interval = worker
917                .storage_state
918                .storage_configuration
919                .parameters
920                .statistics_collection_interval;
921            if guest.last_stats_time.elapsed() >= stats_interval {
922                worker.report_storage_statistics(&conn.response_tx);
923                guest.last_stats_time = Instant::now();
924            }
925        }
926
927        let StorageWorker {
928            timely_worker: _,
929            client_rx,
930            storage_state,
931        } = worker;
932        guest.client_rx = client_rx;
933        guest.storage_state = storage_state;
934        guest.conn = (!disconnected).then_some(conn);
935        self.storage = Some(guest);
936    }
937
938    fn handle_command(&mut self, cmd: ComputeCommand) {
939        if matches!(&cmd, ComputeCommand::CreateInstance(_)) {
940            self.compute_state = Some(ComputeState::new(
941                Arc::clone(&self.persist_clients),
942                self.persist_batches.clone(),
943                self.txns_ctx.clone(),
944                self.metrics.clone(),
945                Arc::clone(&self.tracing_handle),
946                self.context.clone(),
947                self.metrics_registry.clone(),
948                self.workers_per_process,
949                Arc::clone(&self.peek_permits),
950            ));
951        }
952        self.activate_compute().unwrap().handle_compute_command(cmd);
953    }
954
955    fn activate_compute(&mut self) -> Option<ActiveComputeState<'_>> {
956        if let Some(compute_state) = &mut self.compute_state {
957            Some(ActiveComputeState {
958                timely_worker: &mut *self.timely_worker,
959                compute_state,
960                response_tx: &mut self.response_tx,
961            })
962        } else {
963            None
964        }
965    }
966
967    /// Receive the next compute command.
968    ///
969    /// This method blocks if no command is currently available, but takes care to step the Timely
970    /// worker while doing so.
971    fn recv_command(&mut self) -> Result<ComputeCommand, NonceChange> {
972        loop {
973            if let Some(cmd) = self.command_rx.try_recv()? {
974                match cmd {
975                    WorkerCommand::Compute(cmd) => return Ok(cmd),
976                    // Storage-internal commands are dispatched even while
977                    // waiting for compute commands (e.g. during compute reconciliation), so
978                    // storage dataflow construction keeps its lane position on all workers.
979                    WorkerCommand::Storage(cmd) => {
980                        self.handle_storage_internal_command(cmd);
981                        continue;
982                    }
983                }
984            }
985
986            // Keep serving the storage guest while blocked on compute
987            // commands, and avoid unbounded parks that would stall its periodic duties.
988            self.process_storage_guest();
989            let park_cap = self.storage.as_ref().and_then(StorageGuest::park_cap);
990
991            let start = Instant::now();
992            if self.storage_guest_busy() {
993                self.timely_worker.step();
994            } else if let Some(cap) = park_cap {
995                self.timely_worker.step_or_park(Some(cap));
996            } else {
997                self.timely_worker.step_or_park(None);
998            }
999            self.metrics
1000                .timely_step_duration_seconds
1001                .observe(start.elapsed().as_secs_f64());
1002        }
1003    }
1004
1005    /// Extract commands until `InitializationComplete`, and make the worker reflect those commands.
1006    ///
1007    /// This method is meant to be a function of the commands received thus far (as recorded in the
1008    /// compute state command history) and the new commands from `command_rx`. It should not be a
1009    /// function of other characteristics, like whether the worker has managed to respond to a peek
1010    /// or not. Some effort goes in to narrowing our view to only the existing commands we can be sure
1011    /// are live at all other workers.
1012    ///
1013    /// The methodology here is to drain `command_rx` until an `InitializationComplete`, at which point
1014    /// the prior commands are "reconciled" in. Reconciliation takes each goal dataflow and looks for an
1015    /// existing "compatible" dataflow (per `compatible()`) it can repurpose, with some additional tests
1016    /// to be sure that we can cut over from one to the other (no additional compaction, no tails/sinks).
1017    /// With any connections established, old orphaned dataflows are allow to compact away, and any new
1018    /// dataflows are created from scratch. "Kept" dataflows are allowed to compact up to any new `as_of`.
1019    ///
1020    /// Some additional tidying happens, cleaning up pending peeks, reported frontiers, and creating a new
1021    /// subscribe response buffer. We will need to be vigilant with future modifications to `ComputeState` to
1022    /// line up changes there with clean resets here.
1023    fn reconcile(&mut self) -> Result<(), NonceChange> {
1024        // To initialize the connection, we want to drain all commands until we receive a
1025        // `ComputeCommand::InitializationComplete` command to form a target command state.
1026        let mut new_commands = Vec::new();
1027        loop {
1028            match self.recv_command()? {
1029                ComputeCommand::InitializationComplete => break,
1030                command => new_commands.push(command),
1031            }
1032        }
1033
1034        // Commands we will need to apply before entering normal service.
1035        // These commands may include dropping existing dataflows, compacting existing dataflows,
1036        // and creating new dataflows, in addition to standard peek and compaction commands.
1037        // The result should be the same as if dropping all dataflows and running `new_commands`.
1038        let mut todo_commands = Vec::new();
1039        // We only have a compute history if we are in an initialized state
1040        // (i.e. after a `CreateInstance`).
1041        // If this is not the case, just copy `new_commands` into `todo_commands`.
1042        if let Some(compute_state) = &mut self.compute_state {
1043            // Reduce the installed commands.
1044            // Importantly, act as if all peeks may have been retired (as we cannot know otherwise).
1045            compute_state.command_history.discard_peeks();
1046            compute_state.command_history.reduce();
1047
1048            // At this point, we need to sort out which of the *certainly installed* dataflows are
1049            // suitable replacements for the requested dataflows. A dataflow is "certainly installed"
1050            // as of a frontier if its compaction allows it to go no further. We ignore peeks for this
1051            // reasoning, as we cannot be certain that peeks still exist at any other worker.
1052
1053            // Having reduced our installed command history retaining no peeks (above), we should be able
1054            // to use track down installed dataflows we can use as surrogates for requested dataflows (which
1055            // have retained all of their peeks, creating a more demanding `as_of` requirement).
1056            // NB: installed dataflows may still be allowed to further compact, and we should double check
1057            // this before being too confident. It should be rare without peeks, but could happen with e.g.
1058            // multiple outputs of a dataflow.
1059
1060            // The values with which a prior `CreateInstance` was called, if it was.
1061            let mut old_instance_config = None;
1062            // Index dataflows by `export_ids().collect()`, as this is a precondition for their compatibility.
1063            let mut old_dataflows = BTreeMap::default();
1064            // Maintain allowed compaction, in case installed identifiers may have been allowed to compact.
1065            let mut old_frontiers = BTreeMap::default();
1066            for command in compute_state.command_history.iter() {
1067                match command {
1068                    ComputeCommand::CreateInstance(config) => {
1069                        old_instance_config = Some(config);
1070                    }
1071                    ComputeCommand::CreateDataflow(dataflow) => {
1072                        let export_ids = dataflow.export_ids().collect::<BTreeSet<_>>();
1073                        old_dataflows.insert(export_ids, dataflow);
1074                    }
1075                    ComputeCommand::AllowCompaction { id, frontier } => {
1076                        old_frontiers.insert(id, frontier);
1077                    }
1078                    _ => {
1079                        // Nothing to do in these cases.
1080                    }
1081                }
1082            }
1083
1084            // Compaction commands that can be applied to existing dataflows.
1085            let mut old_compaction = BTreeMap::default();
1086            // Exported identifiers from dataflows we retain.
1087            let mut retain_ids = BTreeSet::default();
1088
1089            // Traverse new commands, sorting out what remediation we can do.
1090            for command in new_commands.iter() {
1091                match command {
1092                    ComputeCommand::CreateDataflow(dataflow) => {
1093                        // Attempt to find an existing match for the dataflow.
1094                        let as_of = dataflow.as_of.as_ref().unwrap();
1095                        let export_ids = dataflow.export_ids().collect::<BTreeSet<_>>();
1096
1097                        if let Some(old_dataflow) = old_dataflows.get(&export_ids) {
1098                            let compatible = old_dataflow.compatible_with(dataflow);
1099                            let uncompacted = !export_ids
1100                                .iter()
1101                                .flat_map(|id| old_frontiers.get(id))
1102                                .any(|frontier| {
1103                                    !timely::PartialOrder::less_equal(
1104                                        *frontier,
1105                                        dataflow.as_of.as_ref().unwrap(),
1106                                    )
1107                                });
1108
1109                            // We cannot reconcile subscribe and copy-to sinks at the moment,
1110                            // because the response buffer is shared, and to a first approximation
1111                            // must be completely reformed.
1112                            let subscribe_free = dataflow.subscribe_ids().next().is_none();
1113                            let copy_to_free = dataflow.copy_to_ids().next().is_none();
1114
1115                            // If we have replaced any dependency of this dataflow, we need to
1116                            // replace this dataflow, to make it use the replacement.
1117                            let dependencies_retained = dataflow
1118                                .imported_index_ids()
1119                                .all(|id| retain_ids.contains(&id));
1120
1121                            if compatible
1122                                && uncompacted
1123                                && subscribe_free
1124                                && copy_to_free
1125                                && dependencies_retained
1126                            {
1127                                // Match found; remove the match from the deletion queue,
1128                                // and compact its outputs to the dataflow's `as_of`.
1129                                old_dataflows.remove(&export_ids);
1130                                for id in export_ids.iter() {
1131                                    old_compaction.insert(*id, as_of.clone());
1132                                }
1133                                retain_ids.extend(export_ids);
1134                            } else {
1135                                warn!(
1136                                    ?export_ids,
1137                                    ?compatible,
1138                                    ?uncompacted,
1139                                    ?subscribe_free,
1140                                    ?copy_to_free,
1141                                    ?dependencies_retained,
1142                                    old_as_of = ?old_dataflow.as_of,
1143                                    new_as_of = ?as_of,
1144                                    "dataflow reconciliation failed",
1145                                );
1146
1147                                // Dump the full dataflow plans if they are incompatible, to
1148                                // simplify debugging hard-to-reproduce reconciliation failures.
1149                                if !compatible {
1150                                    warn!(
1151                                        old = ?old_dataflow,
1152                                        new = ?dataflow,
1153                                        "incompatible dataflows in reconciliation",
1154                                    );
1155                                }
1156
1157                                todo_commands
1158                                    .push(ComputeCommand::CreateDataflow(dataflow.clone()));
1159                            }
1160
1161                            compute_state.metrics.record_dataflow_reconciliation(
1162                                compatible,
1163                                uncompacted,
1164                                subscribe_free,
1165                                copy_to_free,
1166                                dependencies_retained,
1167                            );
1168                        } else {
1169                            todo_commands.push(ComputeCommand::CreateDataflow(dataflow.clone()));
1170                        }
1171                    }
1172                    ComputeCommand::CreateInstance(config) => {
1173                        // Cluster creation should not be performed again!
1174                        if old_instance_config.map_or(false, |old| !old.compatible_with(config)) {
1175                            halt!(
1176                                "new instance configuration not compatible with existing instance configuration:\n{:?}\nvs\n{:?}",
1177                                config,
1178                                old_instance_config,
1179                            );
1180                        }
1181                    }
1182                    // All other commands we apply as requested.
1183                    command => {
1184                        todo_commands.push(command.clone());
1185                    }
1186                }
1187            }
1188
1189            // Issue compaction commands first to reclaim resources.
1190            for (_, dataflow) in old_dataflows.iter() {
1191                for id in dataflow.export_ids() {
1192                    // We want to drop anything that has not yet been dropped,
1193                    // and nothing that has already been dropped.
1194                    if old_frontiers.get(&id) != Some(&&Antichain::new()) {
1195                        old_compaction.insert(id, Antichain::new());
1196                    }
1197                }
1198            }
1199            todo_commands.splice(
1200                0..0,
1201                old_compaction.iter().rev().map(|(&id, frontier)| {
1202                    ComputeCommand::AllowCompaction {
1203                        id,
1204                        frontier: frontier.clone(),
1205                    }
1206                }),
1207            );
1208
1209            // Clean up worker-local state.
1210            //
1211            // Various aspects of `ComputeState` need to be either uninstalled, or return to a blank slate.
1212            // All dropped dataflows should clean up after themselves, as we plan to install new dataflows
1213            // re-using the same identifiers.
1214            // All re-used dataflows should roll back any believed communicated information (e.g. frontiers)
1215            // so that they recommunicate that information as if from scratch.
1216
1217            // Remove all peeks, whether they have started or are still awaiting a turn.
1218            let queued = std::mem::take(&mut compute_state.queued_peeks);
1219            let pending = std::mem::take(&mut compute_state.pending_peeks);
1220            for peek in queued.into_iter().map(PendingPeek::Index).chain(pending) {
1221                // Log dropping the peek request.
1222                if let Some(logger) = compute_state.compute_logger.as_mut() {
1223                    logger.log(&peek.as_log_event(false));
1224                }
1225            }
1226
1227            for (&id, collection) in compute_state.collections.iter_mut() {
1228                // Adjust reported frontiers:
1229                //  * For dataflows we continue to use, reset to ensure we report something not
1230                //    before the new `as_of` next.
1231                //  * For dataflows we drop, set to the empty frontier, to ensure we don't report
1232                //    anything for them.
1233                let retained = retain_ids.contains(&id);
1234                let compaction = old_compaction.remove(&id);
1235                let new_reported_frontier = match (retained, compaction) {
1236                    (true, Some(new_as_of)) => ReportedFrontier::NotReported { lower: new_as_of },
1237                    (true, None) => {
1238                        unreachable!("retained dataflows are compacted to the new as_of")
1239                    }
1240                    (false, Some(new_frontier)) => {
1241                        assert!(new_frontier.is_empty());
1242                        ReportedFrontier::Reported(new_frontier)
1243                    }
1244                    (false, None) => {
1245                        // Logging dataflows are implicitly retained and don't have a new as_of.
1246                        // Reset them to the minimal frontier.
1247                        ReportedFrontier::new()
1248                    }
1249                };
1250
1251                collection.reset_reported_frontiers(new_reported_frontier);
1252
1253                // Sink tokens should be retained for retained dataflows, and dropped for dropped
1254                // dataflows.
1255                //
1256                // Dropping the tokens of active subscribe and copy-tos makes them place
1257                // `DroppedAt` responses into the respective response buffer. We drop those buffers
1258                // in the next step, which ensures that we don't send out `DroppedAt` responses for
1259                // subscribe/copy-tos dropped during reconciliation.
1260                if !retained {
1261                    collection.sink_token = None;
1262                }
1263            }
1264
1265            // We must drop the response buffers as they are global across all subscribe/copy-tos.
1266            // If they were broken out by `GlobalId` then we could drop only the response buffers
1267            // of dataflows we drop.
1268            compute_state.subscribe_response_buffer = Rc::new(RefCell::new(Vec::new()));
1269            compute_state.copy_to_response_buffer = Rc::new(RefCell::new(Vec::new()));
1270
1271            // The controller expects the logging collections to be readable from the minimum time
1272            // initially. We cannot recreate the logging arrangements without restarting the
1273            // instance, but we can pad the compacted times with empty data. Doing so is sound
1274            // because logging collections from different replica incarnations are considered
1275            // distinct TVCs, so the controller doesn't expect any historical consistency from
1276            // these collections when it reconnects to a replica.
1277            //
1278            // TODO(database-issues#8152): Consider resolving this with controller-side reconciliation instead.
1279            if let Some(config) = old_instance_config {
1280                for id in config.logging.index_logs.values() {
1281                    let trace = compute_state
1282                        .traces
1283                        .remove(id)
1284                        .expect("logging trace exists");
1285                    let padded = trace.into_padded();
1286                    compute_state.traces.set(*id, padded);
1287                }
1288            }
1289        } else {
1290            todo_commands.clone_from(&new_commands);
1291        }
1292
1293        // Execute the commands to bring us to `new_commands`.
1294        for command in todo_commands.into_iter() {
1295            self.handle_command(command);
1296        }
1297
1298        // Overwrite `self.command_history` to reflect `new_commands`.
1299        // It is possible that there still isn't a compute state yet.
1300        if let Some(compute_state) = &mut self.compute_state {
1301            let mut command_history = ComputeCommandHistory::new(self.metrics.for_history());
1302            for command in new_commands.iter() {
1303                command_history.push(command.clone());
1304            }
1305            compute_state.command_history = command_history;
1306        }
1307        Ok(())
1308    }
1309}
1310
1311/// Spawn a task to bridge between [`ClusterClient`] and [`Worker`] channels.
1312///
1313/// The [`Worker`] expects a pair of persistent channels, with punctuation marking reconnects,
1314/// while the [`ClusterClient`] provides a new pair of channels on each reconnect.
1315fn spawn_channel_adapter(
1316    mut client_rx: mpsc::UnboundedReceiver<(
1317        Uuid,
1318        mpsc::UnboundedReceiver<ComputeCommand>,
1319        mpsc::UnboundedSender<ComputeResponse>,
1320    )>,
1321    command_tx: command_channel::Sender,
1322    mut response_rx: mpsc::UnboundedReceiver<(ComputeResponse, Uuid)>,
1323    worker_id: usize,
1324) {
1325    mz_ore::task::spawn(
1326        || format!("compute-channel-adapter-{worker_id}"),
1327        async move {
1328            // To make workers aware of the individual client connections, we tag forwarded
1329            // commands with the client nonce. Additionally, we use the nonce to filter out
1330            // responses with a different nonce, which are intended for different client
1331            // connections.
1332            //
1333            // It's possible that we receive responses with nonces from the past but also from the
1334            // future: Worker 0 might have received a new nonce before us and broadcasted it to our
1335            // Timely cluster. When we receive a response with a future nonce, we need to wait with
1336            // forwarding it until we have received the same nonce from a client connection.
1337            //
1338            // Nonces are not ordered so we don't know whether a response nonce is from the past or
1339            // the future. We thus assume that every response with an unknown nonce might be from
1340            // the future and stash them all. Every time we reconnect, we immediately send all
1341            // stashed responses with a matching nonce. Every time we receive a new response with a
1342            // nonce that matches our current one, we can discard the entire response stash as we
1343            // know that all stashed responses must be from the past.
1344            let mut stashed_responses = BTreeMap::<Uuid, Vec<ComputeResponse>>::new();
1345
1346            while let Some((nonce, mut command_rx, response_tx)) = client_rx.recv().await {
1347                // Send stashed responses for this client.
1348                if let Some(resps) = stashed_responses.remove(&nonce) {
1349                    for resp in resps {
1350                        let _ = response_tx.send(resp);
1351                    }
1352                }
1353
1354                // Wait for a new response while forwarding received commands.
1355                let mut serve_rx_channels = async || loop {
1356                    tokio::select! {
1357                        msg = command_rx.recv() => match msg {
1358                            Some(cmd) => command_tx.send((cmd, nonce)),
1359                            None => return Err(()),
1360                        },
1361                        msg = response_rx.recv() => {
1362                            return Ok(msg.expect("worker connected"));
1363                        }
1364                    }
1365                };
1366
1367                // Serve this connection until we see any of the channels disconnect.
1368                loop {
1369                    let Ok((resp, resp_nonce)) = serve_rx_channels().await else {
1370                        break;
1371                    };
1372
1373                    if resp_nonce == nonce {
1374                        // Response for the current connection; forward it.
1375                        stashed_responses.clear();
1376                        if response_tx.send(resp).is_err() {
1377                            break;
1378                        }
1379                    } else {
1380                        // Response for a past or future connection; stash it.
1381                        let stash = stashed_responses.entry(resp_nonce).or_default();
1382                        stash.push(resp);
1383                    }
1384                }
1385            }
1386        },
1387    );
1388}