Skip to main content

mz_compute/
compute_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 compute timely instances.
7
8use std::any::Any;
9use std::cell::RefCell;
10use std::cmp::Ordering;
11use std::collections::{BTreeMap, BTreeSet, VecDeque};
12use std::num::NonZeroUsize;
13use std::rc::Rc;
14use std::sync::Arc;
15use std::time::{Duration, Instant};
16
17use differential_dataflow::Hashable;
18use differential_dataflow::lattice::Lattice;
19use differential_dataflow::trace::TraceReader;
20use mz_compute_client::logging::LoggingConfig;
21use mz_compute_client::protocol::command::{
22    ComputeCommand, ComputeParameters, InstanceConfig, Peek, PeekTarget,
23};
24use mz_compute_client::protocol::history::ComputeCommandHistory;
25use mz_compute_client::protocol::response::{
26    ComputeResponse, CopyToResponse, FrontiersResponse, PeekError, PeekResponse, SubscribeResponse,
27};
28use mz_compute_types::dataflows::RenderDataflowDescription;
29use mz_compute_types::dyncfgs::{
30    ENABLE_PEEK_RESPONSE_STASH, ENABLE_PEEK_ROW_ITERATION_LIMIT, PEEK_RESPONSE_STASH_BATCH_BYTES,
31    PEEK_RESPONSE_STASH_THRESHOLD_BYTES, PEEK_ROW_ITERATION_LIMIT,
32};
33use mz_dyncfg::{ConfigSet, ConfigValHandle};
34use mz_expr::SafeMfpPlan;
35use mz_expr::row::RowCollection;
36use mz_ore::cast::{CastFrom, CastLossy};
37use mz_ore::collections::CollectionExt;
38use mz_ore::metrics::{MetricsRegistry, UIntGauge};
39use mz_ore::now::EpochMillis;
40use mz_ore::soft_panic_or_log;
41use mz_ore::task::AbortOnDropHandle;
42use mz_ore::tracing::{OpenTelemetryContext, TracingHandle};
43use mz_persist_client::Diagnostics;
44use mz_persist_client::cache::PersistClientCache;
45use mz_persist_client::cfg::USE_CRITICAL_SINCE_SNAPSHOT;
46use mz_persist_client::read::ReadHandle;
47use mz_persist_types::PersistLocation;
48use mz_persist_types::codec_impls::UnitSchema;
49use mz_repr::{DatumVec, GlobalId, Row, RowArena, Timestamp};
50use mz_storage_operators::persist::SharedBatches;
51use mz_storage_operators::stats::StatsCursor;
52use mz_storage_types::StorageDiff;
53use mz_storage_types::controller::CollectionMetadata;
54use mz_storage_types::dyncfgs::ORE_OVERFLOWING_BEHAVIOR;
55use mz_storage_types::sources::SourceData;
56use mz_storage_types::time_dependence::TimeDependence;
57use mz_txn_wal::operator::TxnsContext;
58use mz_txn_wal::txn_cache::TxnsCache;
59use timely::dataflow::operators::probe;
60use timely::order::PartialOrder;
61use timely::progress::frontier::Antichain;
62use timely::worker::Worker as TimelyWorker;
63use tokio::sync::{oneshot, watch};
64use tracing::{Level, debug, error, info, span, trace, warn};
65use uuid::Uuid;
66
67use crate::arrangement::manager::{TraceBundle, TraceManager};
68use crate::compute_state::peek_budget::InlineBudget;
69use crate::compute_state::peek_metrics::{IndexPeekMetrics, PeekWalkMetrics};
70pub(crate) use crate::compute_state::peek_offload::PeekPermits;
71use crate::compute_state::peek_offload::{OffloadConfig, OffloadedPeek};
72use crate::compute_state::peek_scan::{
73    IndexPeekScan, PeekScan, ScanOutcome, StashBounds, entry_byte_len, rows_response,
74};
75use crate::logging;
76use crate::logging::compute::{CollectionLogging, ComputeEvent, PeekEvent};
77use crate::logging::initialize::LoggingTraces;
78use crate::metrics::{CollectionMetrics, WorkerMetrics};
79use crate::render::{LinearJoinSpec, StartSignal};
80use crate::server::{ComputeInstanceContext, ResponseSender};
81
82mod error_scan;
83mod peek_budget;
84mod peek_metrics;
85mod peek_offload;
86mod peek_result_iterator;
87mod peek_scan;
88mod peek_stash;
89
90/// Cheap handles on the dyncfgs that bound how many rows a peek may examine.
91///
92/// The limit is read through handles rather than captured once, because `UpdateConfiguration`
93/// applies to peeks that are already in flight.
94#[derive(Clone, Debug)]
95struct PeekRowIterationConfig {
96    enabled: ConfigValHandle<bool>,
97    limit: ConfigValHandle<usize>,
98}
99
100impl PeekRowIterationConfig {
101    fn new(config: &ConfigSet) -> Self {
102        Self {
103            enabled: ENABLE_PEEK_ROW_ITERATION_LIMIT.handle(config),
104            limit: PEEK_ROW_ITERATION_LIMIT.handle(config),
105        }
106    }
107
108    fn current_limit(&self) -> Option<usize> {
109        self.enabled.get().then(|| self.limit.get())
110    }
111}
112
113/// Counts the rows a peek has examined on this worker and fails it once that exceeds the limit.
114///
115/// A "row" here is a record the worker had to look at, not a record it returned. Records the MFP
116/// throws away, and records that consolidate to zero, cost scan time all the same, so they count
117/// too. A literal a trace does not hold reaches no record and so costs nothing here; the fuel
118/// budget is what bounds those seeks.
119///
120/// Exactly `limit` rows are allowed. The peek only fails when it asks for the row after that.
121#[derive(Debug)]
122pub(crate) struct PeekRowIterationTracker {
123    limit: Option<usize>,
124    rows_iterated: usize,
125}
126
127impl PeekRowIterationTracker {
128    fn new(limit: Option<usize>, rows_iterated: usize) -> Self {
129        Self {
130            limit,
131            rows_iterated,
132        }
133    }
134
135    /// Adopts a new limit without forgetting the rows already examined.
136    ///
137    /// Rows counted while the feature was off still count, so turning it on mid-scan accounts for
138    /// the work the peek has already caused.
139    fn set_limit(&mut self, limit: Option<usize>) {
140        self.limit = limit;
141    }
142
143    fn rows_iterated(&self) -> usize {
144        self.rows_iterated
145    }
146
147    /// Adds rows examined by a walk that ran before this one.
148    ///
149    /// The limit bounds a peek rather than a single walk, so a walk that continues another one
150    /// starts from the count that one reached.
151    fn add_rows_iterated(&mut self, rows_iterated: usize) {
152        self.rows_iterated = self.rows_iterated.saturating_add(rows_iterated);
153    }
154
155    fn track_next(&mut self) -> Result<(), PeekError> {
156        if let Some(limit) = self.limit
157            && self.rows_iterated >= limit
158        {
159            return Err(PeekError::RowIterationLimitExceeded { limit });
160        }
161
162        self.rows_iterated = self.rows_iterated.saturating_add(1);
163        Ok(())
164    }
165}
166
167fn peek_row_iteration_limit(config: &ConfigSet) -> Option<usize> {
168    ENABLE_PEEK_ROW_ITERATION_LIMIT
169        .get(config)
170        .then(|| PEEK_ROW_ITERATION_LIMIT.get(config))
171}
172
173/// Worker-local state that is maintained across dataflows.
174///
175/// This state is restricted to the COMPUTE state, the deterministic, idempotent work
176/// done between data ingress and egress.
177pub struct ComputeState {
178    /// State kept for each installed compute collection.
179    ///
180    /// Each collection has exactly one frontier.
181    /// How the frontier is communicated depends on the collection type:
182    ///  * Frontiers of indexes are equal to the frontier of their corresponding traces in the
183    ///    `TraceManager`.
184    ///  * Persist sinks store their current frontier in `CollectionState::sink_write_frontier`.
185    ///  * Subscribes report their frontiers through the `subscribe_response_buffer`.
186    pub collections: BTreeMap<GlobalId, CollectionState>,
187    /// The traces available for sharing across dataflows.
188    pub traces: TraceManager,
189    /// Shared buffer with SUBSCRIBE operator instances by which they can respond.
190    ///
191    /// The entries are pairs of sink identifier (to identify the subscribe instance)
192    /// and the response itself.
193    pub subscribe_response_buffer: Rc<RefCell<Vec<(GlobalId, SubscribeResponse)>>>,
194    /// Shared buffer with S3 oneshot operator instances by which they can respond.
195    ///
196    /// The entries are pairs of sink identifier (to identify the s3 oneshot instance)
197    /// and the response itself.
198    pub copy_to_response_buffer: Rc<RefCell<Vec<(GlobalId, CopyToResponse)>>>,
199    /// Index peeks awaiting their turn on the worker, in the order the sweep serves them.
200    ///
201    /// A sweep takes from the front and returns what it could not retire to the back, so a peek
202    /// it passed over is served before the peeks it served ahead of it, and a peek that arrives
203    /// later queues behind both. Keeping the order here spares the sweep a resume point.
204    pub queued_peeks: VecDeque<IndexPeek>,
205    /// Peeks a driver has taken over, awaiting the outcome that driver hands back.
206    ///
207    /// These are polled on every sweep and draw no budget, because the work they are waiting on is
208    /// not running on the worker.
209    pub pending_peeks: VecDeque<PendingPeek>,
210    /// The persist location where we can stash large peek results.
211    pub peek_stash_persist_location: Option<PersistLocation>,
212    /// The logger, from Timely's logging framework, if logs are enabled.
213    pub compute_logger: Option<logging::compute::Logger>,
214    /// A process-global cache of (blob_uri, consensus_uri) -> PersistClient.
215    /// This is intentionally shared between workers.
216    pub persist_clients: Arc<PersistClientCache>,
217    /// A process-global cache of shared persist batch writers. This allows
218    /// coalescing writes across local workers without explicit exchanges.
219    pub persist_batches: SharedBatches,
220    /// Context necessary for rendering txn-wal operators.
221    pub txns_ctx: TxnsContext,
222    /// History of commands received by this workers and all its peers.
223    pub command_history: ComputeCommandHistory<UIntGauge>,
224    /// Max size in bytes of any result.
225    max_result_size: u64,
226    /// Specification for rendering linear joins.
227    pub linear_join_spec: LinearJoinSpec,
228    /// Metrics for this worker.
229    pub metrics: WorkerMetrics,
230    /// A process-global handle to tracing configuration.
231    tracing_handle: Arc<TracingHandle>,
232    /// Other configuration for compute
233    pub context: ComputeInstanceContext,
234    /// Per-worker dynamic configuration.
235    ///
236    /// This is separate from the process-global `ConfigSet` and contains config options that need
237    /// to be applied consistently with compute command order.
238    ///
239    /// For example, for options that influence dataflow rendering it is important that all workers
240    /// render the same dataflow with the same options. If these options were stored in a global
241    /// `ConfigSet`, we couldn't guarantee that all workers observe changes to them at the same
242    /// point in the stream of compute commands. Storing per-worker configuration ensures that
243    /// because each worker's configuration is only updated once that worker observes the
244    /// respective `UpdateConfiguration` command.
245    ///
246    /// Reference-counted to avoid cloning for `Context`.
247    pub worker_config: Rc<ConfigSet>,
248
249    /// The process-global metrics registry.
250    pub metrics_registry: MetricsRegistry,
251
252    /// The number of timely workers per process.
253    pub workers_per_process: usize,
254
255    /// Bounds how many offloaded peek walks run at once, shared with the other workers of the same
256    /// `serve` call. A process running two compute runtime roles has one of these per role.
257    pub peek_permits: Arc<PeekPermits>,
258
259    /// The metrics an index peek walk reports, whichever driver runs it.
260    ///
261    /// Held here rather than assembled per peek, because an offload clones it into the task and
262    /// the inline driver reads it on every activation of every pending peek.
263    peek_walk_metrics: PeekWalkMetrics,
264
265    /// What this activation may spend walking index peeks on the worker, and what is left of it.
266    ///
267    /// Begun at the top of every sweep, but armed by the first peek that asks for a slice, which
268    /// may be one arriving between two sweeps. Such a peek draws from what the last sweep left, so
269    /// a batch of arrivals costs at most one more aggregate rather than one per peek.
270    peek_budget: InlineBudget,
271
272    /// Whether the last sweep passed a peek over for want of budget.
273    ///
274    /// Says only that such a peek exists, because [`ComputeState::queued_peeks`] already says
275    /// which one it is: the sweep left it at the front of the queue.
276    peek_passed_over: bool,
277
278    /// Collections awaiting schedule instruction by the controller.
279    ///
280    /// Each entry stores a reference to a token that can be dropped to unsuspend the collection's
281    /// dataflow. Multiple collections can reference the same token if they are exported by the
282    /// same dataflow.
283    suspended_collections: BTreeMap<GlobalId, Rc<dyn Any>>,
284
285    /// Interval at which to perform server maintenance tasks. Set to a zero interval to
286    /// perform maintenance with every `step_or_park` invocation.
287    pub server_maintenance_interval: Duration,
288
289    /// The [`mz_ore::now::SYSTEM_TIME`] at which the replica was started.
290    ///
291    /// Used to compute `replica_expiration`.
292    pub init_system_time: EpochMillis,
293
294    /// The maximum time for which the replica is expected to live. If not empty, dataflows in the
295    /// replica can drop diffs associated with timestamps beyond the replica expiration.
296    /// The replica will panic if such dataflows are not dropped before the replica has expired.
297    pub replica_expiration: Antichain<Timestamp>,
298}
299
300impl ComputeState {
301    /// Whether a peek is waiting on nothing but its next turn in the sweep.
302    ///
303    /// Read by the worker loop before it parks. The sweep that serves such a peek runs on the same
304    /// thread, so the loop steps without parking rather than waking itself.
305    pub(crate) fn peeks_awaiting_turn(&self) -> bool {
306        self.peek_passed_over
307    }
308
309    /// Construct a new `ComputeState`.
310    pub fn new(
311        persist_clients: Arc<PersistClientCache>,
312        persist_batches: SharedBatches,
313        txns_ctx: TxnsContext,
314        metrics: WorkerMetrics,
315        tracing_handle: Arc<TracingHandle>,
316        context: ComputeInstanceContext,
317        metrics_registry: MetricsRegistry,
318        workers_per_process: usize,
319        peek_permits: Arc<PeekPermits>,
320    ) -> Self {
321        let worker_config: Rc<ConfigSet> = mz_dyncfgs::all_dyncfgs().into();
322        let traces = TraceManager::new(metrics.clone());
323        let command_history = ComputeCommandHistory::new(metrics.for_history());
324        let peek_walk_metrics = PeekWalkMetrics::new(&metrics);
325        let peek_budget = InlineBudget::new(&worker_config);
326
327        Self {
328            collections: Default::default(),
329            traces,
330            subscribe_response_buffer: Default::default(),
331            copy_to_response_buffer: Default::default(),
332            queued_peeks: Default::default(),
333            pending_peeks: Default::default(),
334            peek_stash_persist_location: None,
335            compute_logger: None,
336            persist_clients,
337            persist_batches,
338            txns_ctx,
339            command_history,
340            max_result_size: u64::MAX,
341            linear_join_spec: Default::default(),
342            metrics,
343            tracing_handle,
344            context,
345            worker_config,
346            metrics_registry,
347            workers_per_process,
348            peek_permits,
349            peek_walk_metrics,
350            peek_budget,
351            peek_passed_over: false,
352            suspended_collections: Default::default(),
353            server_maintenance_interval: Duration::ZERO,
354            init_system_time: mz_ore::now::SYSTEM_TIME(),
355            replica_expiration: Antichain::default(),
356        }
357    }
358
359    /// Return a mutable reference to the identified collection.
360    ///
361    /// Panics if the collection doesn't exist.
362    pub fn expect_collection_mut(&mut self, id: GlobalId) -> &mut CollectionState {
363        self.collections
364            .get_mut(&id)
365            .expect("collection must exist")
366    }
367
368    /// Construct a new frontier probe for the given input and add it to the state of the given
369    /// collections.
370    ///
371    /// The caller is responsible for attaching the returned probe handle to the respective
372    /// dataflow input stream.
373    pub fn input_probe_for(
374        &mut self,
375        input_id: GlobalId,
376        collection_ids: impl Iterator<Item = GlobalId>,
377    ) -> probe::Handle<Timestamp> {
378        let probe = probe::Handle::default();
379        for id in collection_ids {
380            if let Some(collection) = self.collections.get_mut(&id) {
381                collection.input_probes.insert(input_id, probe.clone());
382            }
383        }
384        probe
385    }
386
387    /// Apply the current `worker_config` to the compute state.
388    fn apply_worker_config(&mut self) {
389        use mz_compute_types::dyncfgs::*;
390
391        let config = &self.worker_config;
392        // The one scratch path every scratch consumer below is fed from.
393        let scratch = self.context.scratch_directory.clone();
394
395        self.linear_join_spec = LinearJoinSpec::from_config(config);
396
397        if ENABLE_LGALLOC.get(config) {
398            if let Some(path) = &scratch {
399                let clear_bytes = LGALLOC_SLOW_CLEAR_BYTES.get(config);
400                let eager_return = ENABLE_LGALLOC_EAGER_RECLAMATION.get(config);
401                let file_growth_dampener = LGALLOC_FILE_GROWTH_DAMPENER.get(config);
402                let interval = LGALLOC_BACKGROUND_INTERVAL.get(config);
403                let local_buffer_bytes = LGALLOC_LOCAL_BUFFER_BYTES.get(config);
404                info!(
405                    ?path,
406                    backgrund_interval=?interval,
407                    clear_bytes,
408                    eager_return,
409                    file_growth_dampener,
410                    local_buffer_bytes,
411                    "enabling lgalloc"
412                );
413                let background_worker_config = lgalloc::BackgroundWorkerConfig {
414                    interval,
415                    clear_bytes,
416                };
417                lgalloc::lgalloc_set_config(
418                    lgalloc::LgAlloc::new()
419                        .enable()
420                        .with_path(path.clone())
421                        .with_background_config(background_worker_config)
422                        .eager_return(eager_return)
423                        .file_growth_dampener(file_growth_dampener)
424                        .local_buffer_bytes(local_buffer_bytes),
425                );
426            } else {
427                debug!("not enabling lgalloc, scratch directory not specified");
428            }
429        } else {
430            info!("disabling lgalloc");
431            lgalloc::lgalloc_set_config(lgalloc::LgAlloc::new().disable());
432        }
433
434        crate::memory_limiter::apply_limiter_config(config);
435
436        mz_ore::region::ENABLE_LGALLOC_REGION.store(
437            ENABLE_COLUMNATION_LGALLOC.get(config),
438            std::sync::atomic::Ordering::Relaxed,
439        );
440
441        // NB: arrangement dictionary compression is deliberately NOT applied here. Unlike the
442        // settings above, it is captured once at replica creation (see `handle_create_instance`
443        // and `InstanceConfig::arrangement_dictionary_compression`) and held fixed, so that
444        // flipping the flag does not retroactively change arrangements on existing replicas.
445
446        // Install and retune the process-wide buffer pool that backs chunk
447        // spilling. Installation is the gate. The pool is constructed, and its
448        // MAP_NORESERVE address space reserved and spill threads spawned, only
449        // when a config apply runs with a spill gate on, so a process that
450        // never enables spilling never mmaps the pool. Config application
451        // reruns on every UpdateConfiguration, so flipping a gate on installs
452        // the pool on the next tick. The pool is a process singleton with no
453        // teardown: once installed it stays active for the life of the process.
454        // Later ticks retune the installed instance in place even with every
455        // gate off. Consumers that rendered under a gate keep spilling into the
456        // pool after it turns off, so a skipped retune would leave them on the
457        // old budget and RSS target, with no error.
458        //
459        // Storage's stash shares the singleton and gates only participation,
460        // so its spill gate installs the pool too, on replicas where the
461        // upsert-v2 stash can render (see `swap_available`). The worker config
462        // set is the full dyncfg aggregate, which is what makes the storage
463        // flags readable here.
464        {
465            use mz_storage_types::dyncfgs::{ENABLE_UPSERT_PAGED_SPILL, ENABLE_UPSERT_V2};
466            use mz_timely_util::pool_config::{
467                ExtentBackend, PoolPagerConfig, apply_pool_config, global_pool_peek,
468                spill_threads_for_workers,
469            };
470
471            let compute_spill = ENABLE_COLUMN_PAGED_BATCHER_SPILL.get(config);
472            let storage_spill = ENABLE_UPSERT_PAGED_SPILL.get(config)
473                && ENABLE_UPSERT_V2.get(config)
474                && self.context.swap_available;
475            let sink_spill = ENABLE_CORRECTION_V2_SPILL.get(config);
476            // Storage's config application sets the storage chunk gate.
477            mz_timely_util::columnar::chunk::set_compute_spill_enabled(compute_spill);
478            mz_timely_util::columnar::chunk::set_sink_spill_enabled(sink_spill);
479            if !(compute_spill || storage_spill || sink_spill) && global_pool_peek().is_none() {
480                debug!("chunk spill: gates off, leaving the buffer pool uninstalled");
481            } else {
482                let spill_fraction = COLUMN_PAGED_BATCHER_SPILL_WORKER_FRACTION.get(config);
483                let spill_threads =
484                    spill_threads_for_workers(self.workers_per_process, spill_fraction);
485                let eager_backing = COLUMN_PAGED_BATCHER_EAGER_BACKING.get(config);
486
487                // Budget derivation: fraction of physical RAM, with a 128 MiB
488                // floor so the no-pressure case doesn't page per chunk.
489                // Resident budgets derive from RAM, never from the announced
490                // memory limit, which on swap-provisioned nodes deliberately
491                // includes swap for the memory limiter's purposes. Falls back
492                // to a 4 GiB assumption if detection fails.
493                const MIB: usize = 1024 * 1024;
494                const DEFAULT_RAM: usize = 4 * 1024 * MIB;
495                let ram = mz_ore::memory::physical_memory_bytes().unwrap_or(DEFAULT_RAM);
496                let of_ram =
497                    |fraction: f64| usize::cast_lossy(f64::cast_lossy(ram) * fraction.max(0.0));
498                let fraction = COLUMN_PAGED_BATCHER_BUDGET_FRACTION.get(config);
499                let total = of_ram(fraction).max(128 * MIB);
500                // No ordering is enforced between the target and the budget. A
501                // target at or below budget + warm cap leaves no compressed-tier
502                // headroom, which legally collapses the tier. Every backing
503                // write then pages out immediately, the pre-tier behavior.
504                let rss_target = of_ram(COLUMN_PAGED_BATCHER_POOL_RSS_TARGET_FRACTION.get(config));
505
506                // The file store lives in its own subdirectory so its files
507                // cannot collide with other scratch users. It sizes itself to
508                // the volume's free space, so it assumes no other writer fills
509                // the volume. lgalloc uses the same directory, but is not
510                // enabled alongside the store.
511                let backend = match &scratch {
512                    Some(scratch) if ENABLE_COLUMN_PAGED_BATCHER_FILE_EXTENTS.get(config) => {
513                        ExtentBackend::File {
514                            dir: scratch.join("pool"),
515                            capacity_bytes: None,
516                        }
517                    }
518                    _ => ExtentBackend::Swap,
519                };
520                let applied = apply_pool_config(
521                    PoolPagerConfig {
522                        budget_bytes: total,
523                        spill_threads,
524                        eager_backing,
525                        rss_target_bytes: rss_target,
526                        file_release_interval: COLUMN_PAGED_BATCHER_FILE_RELEASE_INTERVAL
527                            .get(config),
528                        file_release_bytes: COLUMN_PAGED_BATCHER_FILE_RELEASE_BYTES.get(config),
529                    },
530                    backend,
531                );
532                if applied {
533                    info!(
534                        compute_spill,
535                        storage_spill,
536                        fraction,
537                        ram,
538                        budget_bytes = total,
539                        spill_fraction,
540                        spill_threads,
541                        eager_backing,
542                        rss_target_bytes = rss_target,
543                        "chunk spill: applying buffer-pool config",
544                    );
545                } else {
546                    warn!("chunk spill: buffer pool unavailable; chunks stay resident");
547                }
548            }
549
550            // The generational depth floor below which spilled bodies store
551            // uncompressed. Subsystem-independent, so applied here alongside
552            // the rest of the process-wide chunk configuration.
553            let compress_min_depth =
554                u8::try_from(COLUMN_CHUNK_COMPRESS_MIN_DEPTH.get(config)).unwrap_or(u8::MAX);
555            mz_timely_util::columnar::chunk::set_compress_min_depth(compress_min_depth);
556            let sink_compress_min_depth =
557                u8::try_from(CORRECTION_V2_COMPRESS_MIN_DEPTH.get(config)).unwrap_or(u8::MAX);
558            mz_timely_util::columnar::chunk::set_sink_compress_min_depth(sink_compress_min_depth);
559        }
560
561        // Remember the maintenance interval locally to avoid reading it from the config set on
562        // every server iteration.
563        self.server_maintenance_interval = COMPUTE_SERVER_MAINTENANCE_INTERVAL.get(config);
564
565        let overflowing_behavior = ORE_OVERFLOWING_BEHAVIOR.get(config);
566        match overflowing_behavior.parse() {
567            Ok(behavior) => mz_ore::overflowing::set_behavior(behavior),
568            Err(err) => {
569                error!(
570                    err,
571                    overflowing_behavior, "Invalid value for ore_overflowing_behavior"
572                );
573            }
574        }
575    }
576
577    /// Apply the provided replica expiration `offset` by converting it to a frontier relative to
578    /// the replica's initialization system time.
579    ///
580    /// Only expected to be called once when creating the instance. Guards against calling it
581    /// multiple times by checking if the local expiration time is set.
582    pub fn apply_expiration_offset(&mut self, offset: Duration) {
583        if self.replica_expiration.is_empty() {
584            let offset: EpochMillis = offset
585                .as_millis()
586                .try_into()
587                .expect("duration must fit within u64");
588            let replica_expiration_millis = self.init_system_time + offset;
589            let replica_expiration = Timestamp::from(replica_expiration_millis);
590
591            info!(
592                offset = %offset,
593                replica_expiration_millis = %replica_expiration_millis,
594                replica_expiration_utc = %mz_ore::now::to_datetime(replica_expiration_millis),
595                "setting replica expiration",
596            );
597            self.replica_expiration = Antichain::from_elem(replica_expiration);
598
599            // Record the replica expiration in the metrics.
600            self.metrics
601                .replica_expiration_timestamp_seconds
602                .set(replica_expiration.into());
603        }
604    }
605
606    /// Returns the cc or non-cc version of "dataflow_max_inflight_bytes", as
607    /// appropriate to this replica.
608    pub fn dataflow_max_inflight_bytes(&self) -> Option<usize> {
609        use mz_compute_types::dyncfgs::{
610            DATAFLOW_MAX_INFLIGHT_BYTES, DATAFLOW_MAX_INFLIGHT_BYTES_CC,
611        };
612
613        if self.persist_clients.cfg.is_cc_active {
614            DATAFLOW_MAX_INFLIGHT_BYTES_CC.get(&self.worker_config)
615        } else {
616            DATAFLOW_MAX_INFLIGHT_BYTES.get(&self.worker_config)
617        }
618    }
619}
620
621/// A wrapper around [ComputeState] with a live timely worker and response channel.
622pub(crate) struct ActiveComputeState<'a> {
623    /// The underlying Timely worker.
624    pub timely_worker: &'a mut TimelyWorker,
625    /// The compute state itself.
626    pub compute_state: &'a mut ComputeState,
627    /// The channel over which frontier information is reported.
628    pub response_tx: &'a mut ResponseSender,
629}
630
631/// A token that keeps a sink alive.
632pub struct SinkToken(#[allow(dead_code)] Box<dyn Any>);
633
634impl SinkToken {
635    /// Create a new `SinkToken`.
636    pub fn new(t: Box<dyn Any>) -> Self {
637        Self(t)
638    }
639}
640
641impl<'a> ActiveComputeState<'a> {
642    /// Entrypoint for applying a compute command.
643    #[mz_ore::instrument(level = "debug")]
644    pub fn handle_compute_command(&mut self, cmd: ComputeCommand) {
645        use ComputeCommand::*;
646
647        self.compute_state.command_history.push(cmd.clone());
648
649        // Record the command duration, per worker and command kind.
650        let timer = self
651            .compute_state
652            .metrics
653            .handle_command_duration_seconds
654            .for_command(&cmd)
655            .start_timer();
656
657        match cmd {
658            Hello { .. } => panic!("Hello must be captured before"),
659            CreateInstance(instance_config) => self.handle_create_instance(*instance_config),
660            InitializationComplete => (),
661            UpdateConfiguration(params) => self.handle_update_configuration(*params),
662            CreateDataflow(dataflow) => self.handle_create_dataflow(*dataflow),
663            Schedule(id) => self.handle_schedule(id),
664            AllowCompaction { id, frontier } => self.handle_allow_compaction(id, frontier),
665            Peek(peek) => {
666                peek.otel_ctx.attach_as_parent();
667                self.handle_peek(*peek)
668            }
669            CancelPeek { uuid } => self.handle_cancel_peek(uuid),
670            AllowWrites(id) => {
671                self.handle_allow_writes(id);
672            }
673        }
674
675        timer.observe_duration();
676    }
677
678    fn handle_create_instance(&mut self, config: InstanceConfig) {
679        // Seed the worker configuration with the controller's snapshot before applying it, so
680        // create-time setup observes controller-synced values rather than dyncfg defaults. The
681        // same values arrive again in the following `UpdateConfiguration`, which applies globally
682        // and keeps the configuration current. An empty snapshot leaves the defaults in place.
683        config
684            .initial_config
685            .apply(&self.compute_state.worker_config);
686
687        // Ensure the state is consistent with the config before we initialize anything.
688        self.compute_state.apply_worker_config();
689
690        // Apply dictionary compression exactly once, here at instance creation, from the value the
691        // controller captured when the replica was created. We deliberately do NOT re-apply it on
692        // `handle_update_configuration`, so flipping the flag does not retroactively change this
693        // replica's arrangements. `DICTIONARY_COMPRESSION` is process-global and a replica process
694        // hosts a single instance, so this single store covers all of the replica's arrangements.
695        mz_row_spine::DICTIONARY_COMPRESSION.store(
696            config.arrangement_dictionary_compression,
697            std::sync::atomic::Ordering::Relaxed,
698        );
699
700        if let Some(offset) = config.expiration_offset {
701            self.compute_state.apply_expiration_offset(offset);
702        }
703
704        self.initialize_logging(config.logging);
705
706        self.compute_state.peek_stash_persist_location = Some(config.peek_stash_persist_location);
707    }
708
709    fn handle_update_configuration(&mut self, params: ComputeParameters) {
710        debug!("Applying configuration update: {params:?}");
711
712        let ComputeParameters {
713            workload_class,
714            max_result_size,
715            tracing,
716            grpc_client: _grpc_client,
717            dyncfg_updates,
718        } = params;
719
720        if let Some(v) = workload_class {
721            self.compute_state.metrics.set_workload_class(v);
722        }
723        if let Some(v) = max_result_size {
724            self.compute_state.max_result_size = v;
725        }
726
727        tracing.apply(self.compute_state.tracing_handle.as_ref());
728
729        dyncfg_updates.apply(&self.compute_state.worker_config);
730        self.compute_state
731            .persist_clients
732            .cfg()
733            .apply_from(&dyncfg_updates);
734
735        // Note: We're only updating mz_metrics from the compute state here, but not from the
736        // equivalent storage state. This is because they're running on the same process and
737        // share the metrics.
738        mz_metrics::update_dyncfg(&dyncfg_updates);
739
740        self.compute_state.apply_worker_config();
741    }
742
743    fn handle_create_dataflow(&mut self, dataflow: RenderDataflowDescription<CollectionMetadata>) {
744        let dataflow_index = Rc::new(self.timely_worker.next_dataflow_index());
745        let as_of = dataflow.as_of.clone().unwrap();
746
747        let dataflow_expiration = dataflow
748            .time_dependence
749            .as_ref()
750            .map(|time_dependence| {
751                self.determine_dataflow_expiration(time_dependence, &dataflow.until)
752            })
753            .unwrap_or_default();
754
755        // Add the dataflow expiration to `until`.
756        let until = dataflow.until.meet(&dataflow_expiration);
757
758        if dataflow.is_transient() {
759            debug!(
760                name = %dataflow.debug_name,
761                import_ids = %dataflow.display_import_ids(),
762                export_ids = %dataflow.display_export_ids(),
763                as_of = ?as_of.elements(),
764                time_dependence = ?dataflow.time_dependence,
765                expiration = ?dataflow_expiration.elements(),
766                expiration_datetime = ?dataflow_expiration
767                    .as_option()
768                    .map(|t| mz_ore::now::to_datetime(t.into())),
769                plan_until = ?dataflow.until.elements(),
770                until = ?until.elements(),
771                "creating dataflow",
772            );
773        } else {
774            info!(
775                name = %dataflow.debug_name,
776                import_ids = %dataflow.display_import_ids(),
777                export_ids = %dataflow.display_export_ids(),
778                as_of = ?as_of.elements(),
779                time_dependence = ?dataflow.time_dependence,
780                expiration = ?dataflow_expiration.elements(),
781                expiration_datetime = ?dataflow_expiration
782                    .as_option()
783                    .map(|t| mz_ore::now::to_datetime(t.into())),
784                plan_until = ?dataflow.until.elements(),
785                until = ?until.elements(),
786                "creating dataflow",
787            );
788        };
789
790        let subscribe_copy_ids: BTreeSet<_> = dataflow
791            .subscribe_ids()
792            .chain(dataflow.copy_to_ids())
793            .collect();
794
795        // `StartSignal` is attached only to imported sources and imported indexes, and
796        // `import_ids` is exactly those two sets, so a dataflow with no imports has nothing
797        // suspended and begins computing as soon as it is rendered. Such a dataflow can reach
798        // hydration before its `Schedule` arrives, and the controller sends one anyway to keep
799        // protocol communication predictable, so a `started_at` stamped only from
800        // `handle_schedule` would land after `hydrated_at`. Stamping it here also keeps the row
801        // truthful from the moment it appears, rather than reporting the object as queued while
802        // nothing is queueing it.
803        let starts_immediately = dataflow.import_ids().next().is_none();
804
805        // Initialize compute and logging state for each object.
806        for object_id in dataflow.export_ids() {
807            let is_subscribe_or_copy = subscribe_copy_ids.contains(&object_id);
808            let metrics = self.compute_state.metrics.for_collection(object_id);
809            let mut collection = CollectionState::new(
810                Rc::clone(&dataflow_index),
811                is_subscribe_or_copy,
812                as_of.clone(),
813                metrics,
814            );
815
816            if let Some(logger) = self.compute_state.compute_logger.clone() {
817                let logging = CollectionLogging::new(
818                    object_id,
819                    logger,
820                    *dataflow_index,
821                    dataflow.import_ids(),
822                );
823                if starts_immediately {
824                    logging.set_hydration_start();
825                }
826                collection.logging = Some(logging);
827            }
828
829            collection.reset_reported_frontiers(ReportedFrontier::NotReported {
830                lower: as_of.clone(),
831            });
832
833            let existing = self.compute_state.collections.insert(object_id, collection);
834            if existing.is_some() {
835                error!(
836                    id = ?object_id,
837                    "existing collection for newly created dataflow",
838                );
839            }
840        }
841
842        let (start_signal, suspension_token) = StartSignal::new();
843        for id in dataflow.export_ids() {
844            self.compute_state
845                .suspended_collections
846                .insert(id, Rc::clone(&suspension_token));
847        }
848
849        crate::render::build_compute_dataflow(
850            self.timely_worker,
851            self.compute_state,
852            dataflow,
853            start_signal,
854            until,
855            dataflow_expiration,
856        );
857    }
858
859    fn handle_schedule(&mut self, id: GlobalId) {
860        // A `Schedule` command instructs us to begin dataflow computation for a collection, so
861        // we should unsuspend it by dropping the corresponding suspension token. Note that a
862        // dataflow can export multiple collections and they all share one suspension token, so the
863        // computation of a dataflow will only start once all its exported collections have been
864        // scheduled.
865        let suspension_token = self.compute_state.suspended_collections.remove(&id);
866        drop(suspension_token);
867
868        if let Some(collection) = self.compute_state.collections.get(&id) {
869            if let Some(logging) = &collection.logging {
870                logging.set_hydration_start();
871            }
872        }
873    }
874
875    fn handle_allow_compaction(&mut self, id: GlobalId, frontier: Antichain<Timestamp>) {
876        if frontier.is_empty() {
877            // Indicates that we may drop `id`, as there are no more valid times to read.
878            self.drop_collection(id);
879        } else {
880            self.compute_state
881                .traces
882                .allow_compaction(id, frontier.borrow());
883        }
884    }
885
886    #[mz_ore::instrument(level = "debug")]
887    fn handle_peek(&mut self, peek: Peek) {
888        let pending = match &peek.target {
889            PeekTarget::Index { id } => {
890                // Acquire a copy of the trace suitable for fulfilling the peek.
891                let trace_bundle = self.compute_state.traces.get(id).unwrap().clone();
892                PendingPeek::index(peek, trace_bundle)
893            }
894            PeekTarget::Persist { metadata, .. } => {
895                let metadata = metadata.clone();
896                PendingPeek::persist(
897                    peek,
898                    Arc::clone(&self.compute_state.persist_clients),
899                    metadata,
900                    usize::cast_from(self.compute_state.max_result_size),
901                    self.timely_worker,
902                    PeekRowIterationConfig::new(&self.compute_state.worker_config),
903                )
904            }
905        };
906
907        // Log the receipt of the peek.
908        if let Some(logger) = self.compute_state.compute_logger.as_mut() {
909            logger.log(&pending.as_log_event(true));
910        }
911
912        match pending {
913            PendingPeek::Index(peek) => self.serve_index_peek(&mut Antichain::new(), peek),
914            pending => self.poll_pending_peek(pending),
915        }
916    }
917
918    fn handle_cancel_peek(&mut self, uuid: Uuid) {
919        let queued = &mut self.compute_state.queued_peeks;
920        if let Some(index) = queued.iter().position(|peek| peek.peek.uuid == uuid) {
921            let peek = queued.remove(index).expect("found above");
922            self.send_peek_response(PendingPeek::Index(peek), PeekResponse::Canceled);
923            return;
924        }
925
926        let pending = &mut self.compute_state.pending_peeks;
927        let Some(index) = pending.iter().position(|peek| peek.peek().uuid == uuid) else {
928            return;
929        };
930        let peek = pending.remove(index).expect("found above");
931        self.send_peek_response(peek, PeekResponse::Canceled);
932    }
933
934    fn handle_allow_writes(&mut self, id: GlobalId) {
935        // Enable persist compaction on any allow-writes command. We
936        // assume persist only compacts after making durable changes,
937        // such as appending a batch or advancing the upper.
938        self.compute_state.persist_clients.cfg().enable_compaction();
939
940        if let Some(collection) = self.compute_state.collections.get_mut(&id) {
941            collection.allow_writes();
942        } else {
943            soft_panic_or_log!("allow writes for unknown collection {id}");
944        }
945    }
946
947    /// Drop the given collection.
948    fn drop_collection(&mut self, id: GlobalId) {
949        let collection = self
950            .compute_state
951            .collections
952            .remove(&id)
953            .expect("dropped untracked collection");
954
955        // If this collection is an index, remove its trace.
956        self.compute_state.traces.remove(&id);
957        // If the collection is unscheduled, remove it from the list of waiting collections.
958        self.compute_state.suspended_collections.remove(&id);
959
960        // Drop the dataflow, if all its exports have been dropped.
961        if let Ok(index) = Rc::try_unwrap(collection.dataflow_index) {
962            self.timely_worker.drop_dataflow(index);
963        }
964
965        // The compute protocol requires us to send a `Frontiers` response with empty frontiers
966        // when a collection was dropped, unless:
967        //  * The frontier was already reported as empty previously, or
968        //  * The collection is a subscribe or copy-to.
969        if !collection.is_subscribe_or_copy {
970            let reported = collection.reported_frontiers;
971            let write_frontier = (!reported.write_frontier.is_empty()).then(Antichain::new);
972            let input_frontier = (!reported.input_frontier.is_empty()).then(Antichain::new);
973            let output_frontier = (!reported.output_frontier.is_empty()).then(Antichain::new);
974
975            let frontiers = FrontiersResponse {
976                write_frontier,
977                input_frontier,
978                output_frontier,
979            };
980            if frontiers.has_updates() {
981                self.send_compute_response(ComputeResponse::Frontiers(id, frontiers));
982            }
983        }
984    }
985
986    /// Initializes timely dataflow logging and publishes as a view.
987    pub fn initialize_logging(&mut self, config: LoggingConfig) {
988        if self.compute_state.compute_logger.is_some() {
989            panic!("dataflow server has already initialized logging");
990        }
991
992        let LoggingTraces {
993            traces,
994            dataflow_index,
995            compute_logger: logger,
996        } = logging::initialize(
997            self.timely_worker,
998            &config,
999            self.compute_state.metrics_registry.clone(),
1000            self.compute_state.metrics.for_logging(),
1001            Rc::clone(&self.compute_state.worker_config),
1002            self.compute_state.workers_per_process,
1003        );
1004
1005        let dataflow_index = Rc::new(dataflow_index);
1006        let mut log_index_ids = config.index_logs;
1007        for (log, trace) in traces {
1008            // Install trace as maintained index.
1009            let id = log_index_ids
1010                .remove(&log)
1011                .expect("`logging::initialize` does not invent logs");
1012            self.compute_state.traces.set(id, trace);
1013
1014            // Initialize compute and logging state for the logging index.
1015            let is_subscribe_or_copy = false;
1016            let as_of = Antichain::from_elem(Timestamp::MIN);
1017            let metrics = self.compute_state.metrics.for_collection(id);
1018            let mut collection = CollectionState::new(
1019                Rc::clone(&dataflow_index),
1020                is_subscribe_or_copy,
1021                as_of,
1022                metrics,
1023            );
1024
1025            let logging =
1026                CollectionLogging::new(id, logger.clone(), *dataflow_index, std::iter::empty());
1027            // Log collections are never suspended and the controller marks them scheduled
1028            // implicitly, so no `Schedule` command ever arrives for them. Record their hydration
1029            // start here, or they would sit permanently in the illegal state of being hydrated
1030            // without having started.
1031            logging.set_hydration_start();
1032            collection.logging = Some(logging);
1033
1034            let existing = self.compute_state.collections.insert(id, collection);
1035            if existing.is_some() {
1036                error!(
1037                    id = ?id,
1038                    "existing collection for newly initialized logging export",
1039                );
1040            }
1041        }
1042
1043        // Sanity check.
1044        assert!(
1045            log_index_ids.is_empty(),
1046            "failed to create requested logging indexes: {log_index_ids:?}",
1047        );
1048
1049        self.compute_state.compute_logger = Some(logger);
1050    }
1051
1052    /// Send progress information to the controller.
1053    pub fn report_frontiers(&mut self) {
1054        let mut responses = Vec::new();
1055
1056        // Maintain a single allocation for `new_frontier` to avoid allocating on every iteration.
1057        let mut new_frontier = Antichain::new();
1058
1059        for (&id, collection) in self.compute_state.collections.iter_mut() {
1060            // The compute protocol does not allow `Frontiers` responses for subscribe and copy-to
1061            // collections (database-issues#4701).
1062            if collection.is_subscribe_or_copy {
1063                continue;
1064            }
1065
1066            let reported = collection.reported_frontiers();
1067
1068            // Collect the write frontier and check for progress.
1069            new_frontier.clear();
1070            if let Some(traces) = self.compute_state.traces.get_mut(&id) {
1071                assert!(
1072                    collection.sink_write_frontier.is_none(),
1073                    "collection {id} has multiple frontiers"
1074                );
1075                traces.oks_mut().read_upper(&mut new_frontier);
1076            } else if let Some(frontier) = &collection.sink_write_frontier {
1077                new_frontier.clone_from(&frontier.borrow());
1078            } else {
1079                error!(id = ?id, "collection without write frontier");
1080                continue;
1081            }
1082            let new_write_frontier = reported
1083                .write_frontier
1084                .allows_reporting(&new_frontier)
1085                .then(|| new_frontier.clone());
1086
1087            // Collect the output frontier and check for progress.
1088            //
1089            // By default, the output frontier equals the write frontier (which is still stored in
1090            // `new_frontier`). If the collection provides a compute frontier, we construct the
1091            // output frontier by taking the meet of write and compute frontier, to avoid:
1092            //  * reporting progress through times we have not yet written
1093            //  * reporting progress through times we have not yet fully processed, for
1094            //    collections that jump their write frontiers into the future
1095            //
1096            // As a special case, in read-only mode we don't take the write frontier into account.
1097            // The dataflow doesn't have the ability to push it forward, so it can't be used as a
1098            // measure of dataflow progress.
1099            if let Some(probe) = &collection.compute_probe {
1100                if *collection.read_only_rx.borrow() {
1101                    new_frontier.clear();
1102                }
1103                probe.with_frontier(|frontier| new_frontier.extend(frontier.iter().copied()));
1104            }
1105            let new_output_frontier = reported
1106                .output_frontier
1107                .allows_reporting(&new_frontier)
1108                .then(|| new_frontier.clone());
1109
1110            // Collect the input frontier and check for progress.
1111            new_frontier.clear();
1112            for probe in collection.input_probes.values() {
1113                probe.with_frontier(|frontier| new_frontier.extend(frontier.iter().copied()));
1114            }
1115            let new_input_frontier = reported
1116                .input_frontier
1117                .allows_reporting(&new_frontier)
1118                .then(|| new_frontier.clone());
1119
1120            if let Some(frontier) = &new_write_frontier {
1121                collection
1122                    .set_reported_write_frontier(ReportedFrontier::Reported(frontier.clone()));
1123            }
1124            if let Some(frontier) = &new_input_frontier {
1125                collection
1126                    .set_reported_input_frontier(ReportedFrontier::Reported(frontier.clone()));
1127            }
1128            if let Some(frontier) = &new_output_frontier {
1129                collection
1130                    .set_reported_output_frontier(ReportedFrontier::Reported(frontier.clone()));
1131            }
1132
1133            let response = FrontiersResponse {
1134                write_frontier: new_write_frontier,
1135                input_frontier: new_input_frontier,
1136                output_frontier: new_output_frontier,
1137            };
1138            if response.has_updates() {
1139                responses.push((id, response));
1140            }
1141        }
1142
1143        for (id, frontiers) in responses {
1144            self.send_compute_response(ComputeResponse::Frontiers(id, frontiers));
1145        }
1146    }
1147
1148    /// Report per-worker metrics.
1149    pub(crate) fn report_metrics(&self) {
1150        if let Some(expiration) = self.compute_state.replica_expiration.as_option() {
1151            let now = Duration::from_millis(mz_ore::now::SYSTEM_TIME()).as_secs_f64();
1152            let expiration = Duration::from_millis(<u64>::from(expiration)).as_secs_f64();
1153            let remaining = expiration - now;
1154            self.compute_state
1155                .metrics
1156                .replica_expiration_remaining_seconds
1157                .set(remaining)
1158        }
1159    }
1160
1161    /// Gives `peek` a turn on the worker if this activation's budget has one left, and queues it
1162    /// for a later activation otherwise.
1163    fn serve_index_peek(&mut self, upper: &mut Antichain<Timestamp>, peek: IndexPeek) {
1164        match self.compute_state.peek_budget.grant() {
1165            Some(fuel) => self.walk_index_peek(upper, peek, fuel),
1166            None => {
1167                // A scan is opened by the slice that walks it, so passing a peek over costs it an
1168                // activation and nothing else.
1169                self.compute_state.peek_passed_over = true;
1170                self.compute_state.queued_peeks.push_back(peek);
1171            }
1172        }
1173    }
1174
1175    /// Walks `peek` for up to `fuel` cursor positions and either answers it, hands it to a driver
1176    /// that finishes it, or returns it to the queue for another turn.
1177    fn walk_index_peek(
1178        &mut self,
1179        upper: &mut Antichain<Timestamp>,
1180        mut peek: IndexPeek,
1181        fuel: usize,
1182    ) {
1183        let start = Instant::now();
1184
1185        let row_iteration_limit = peek_row_iteration_limit(&self.compute_state.worker_config);
1186
1187        let peek_stash_eligible = peek
1188            .peek
1189            .finishing
1190            .is_streamable(peek.peek.result_desc.arity());
1191
1192        // Whether a diverted peek has somewhere to write its rows. A flag here and the location
1193        // itself only where an offload needs it, because this runs for every peek the sweep gives
1194        // a turn, including the point lookups that answer inline and never reach the stash.
1195        let has_stash_location = {
1196            let enabled = ENABLE_PEEK_RESPONSE_STASH.get(&self.compute_state.worker_config);
1197            let located = self.compute_state.peek_stash_persist_location.is_some();
1198            if !located && enabled {
1199                error!("missing peek_stash_persist_location but peek stash is enabled");
1200            }
1201            enabled && located
1202        };
1203
1204        let stash = StashBounds {
1205            eligible: peek_stash_eligible && has_stash_location,
1206            threshold_bytes: PEEK_RESPONSE_STASH_THRESHOLD_BYTES
1207                .get(&self.compute_state.worker_config),
1208            batch_bytes: PEEK_RESPONSE_STASH_BATCH_BYTES.get(&self.compute_state.worker_config),
1209        };
1210
1211        let metrics = IndexPeekMetrics {
1212            seek_fulfillment_seconds: &self
1213                .compute_state
1214                .metrics
1215                .index_peek_seek_fulfillment_seconds,
1216            frontier_check_seconds: &self.compute_state.metrics.index_peek_frontier_check_seconds,
1217            walk: &self.compute_state.peek_walk_metrics,
1218        };
1219
1220        let mut unspent = fuel;
1221        let status = peek.seek_fulfillment(
1222            upper,
1223            self.compute_state.max_result_size,
1224            stash,
1225            row_iteration_limit,
1226            &mut unspent,
1227            &metrics,
1228        );
1229
1230        // Charged with what the slice walked rather than with what it was granted, so a peek that
1231        // answers in three positions leaves the activation's budget to the peeks behind it.
1232        self.compute_state
1233            .peek_budget
1234            .charge(fuel.saturating_sub(unspent));
1235
1236        self.compute_state
1237            .metrics
1238            .index_peek_total_seconds
1239            .observe(start.elapsed().as_secs_f64());
1240
1241        match status {
1242            PeekStatus::Ready(response) => {
1243                let _span =
1244                    span!(parent: &peek.span, Level::DEBUG, "process_peek_response").entered();
1245                self.send_peek_response(PendingPeek::Index(peek), response);
1246            }
1247            PeekStatus::NotReady => self.compute_state.queued_peeks.push_back(peek),
1248            PeekStatus::Offload(scan) => {
1249                let _span = span!(parent: &peek.span, Level::DEBUG, "offload_index_peek").entered();
1250
1251                let permits = Arc::clone(&self.compute_state.peek_permits);
1252                let config = OffloadConfig::new(&self.compute_state.worker_config);
1253                let walk_metrics = self.compute_state.peek_walk_metrics.clone();
1254                let worker = std::thread::current();
1255                // Read off the scan rather than decided again, so a walk that can offer a batch
1256                // always has somewhere to write it.
1257                let stash = self
1258                    .compute_state
1259                    .peek_stash_persist_location
1260                    .as_ref()
1261                    .filter(|_| scan.stash_eligible())
1262                    .cloned()
1263                    .map(|location| {
1264                        peek_stash::StashTarget::new(
1265                            &peek.peek,
1266                            Arc::clone(&self.compute_state.persist_clients),
1267                            location,
1268                        )
1269                    });
1270
1271                let offloaded = OffloadedPeek::start(
1272                    peek.peek,
1273                    scan,
1274                    stash,
1275                    permits,
1276                    config,
1277                    walk_metrics,
1278                    worker,
1279                );
1280
1281                self.compute_state
1282                    .pending_peeks
1283                    .push_back(PendingPeek::Offloaded(offloaded));
1284            }
1285        }
1286    }
1287
1288    /// Asks the driver that has taken `pending` over for its outcome, and sends the response when
1289    /// one is ready.
1290    fn poll_pending_peek(&mut self, mut pending: PendingPeek) {
1291        let response = match &mut pending {
1292            // An index peek reaches a driver only by leaving the queue, and the driver that takes
1293            // it over replaces it with a variant of its own.
1294            PendingPeek::Index(peek) => {
1295                soft_panic_or_log!(
1296                    "index peek on {} polled as if a driver had taken it over",
1297                    peek.peek.target.id()
1298                );
1299                None
1300            }
1301            PendingPeek::Persist(peek) => peek.result.try_recv().ok().map(|(result, duration)| {
1302                self.compute_state
1303                    .metrics
1304                    .persist_peek_seconds
1305                    .observe(duration.as_secs_f64());
1306                result
1307            }),
1308            PendingPeek::Offloaded(offloaded) => match offloaded.result.try_recv() {
1309                Ok((response, duration)) => {
1310                    // Covers the writing to the peek stash too, because the walk that produces the
1311                    // rows is the one that writes them.
1312                    self.compute_state
1313                        .metrics
1314                        .index_peek_offload_seconds
1315                        .observe(duration.as_secs_f64());
1316
1317                    trace!(?offloaded.peek, ?duration, "finished offloaded index peek walk");
1318                    Some(response)
1319                }
1320                Err(oneshot::error::TryRecvError::Empty) => None,
1321                // The task drops its sender without sending only on a cancellation, which removes
1322                // this entry, so an entry still here to be polled means the task died. Answering
1323                // keeps the peek from waiting forever on a walk nothing is running.
1324                //
1325                // NOTE: a walk dropped by a shutting-down tokio runtime arrives here the same way.
1326                // The worker is going away too, so the log line is noise rather than a lost signal.
1327                Err(oneshot::error::TryRecvError::Closed) => {
1328                    soft_panic_or_log!(
1329                        "offloaded walk of peek on {} ended without an outcome",
1330                        offloaded.peek.target.id()
1331                    );
1332                    Some(PeekResponse::Error(PeekError::unstructured(
1333                        "offloaded peek walk failed",
1334                    )))
1335                }
1336            },
1337        };
1338
1339        if let Some(response) = response {
1340            let _span =
1341                span!(parent: pending.span(), Level::DEBUG, "process_peek_response").entered();
1342            self.send_peek_response(pending, response)
1343        } else {
1344            self.compute_state.pending_peeks.push_back(pending);
1345        }
1346    }
1347
1348    /// Scan the peeks a driver is finishing and the peeks awaiting a turn, and attempt to retire
1349    /// each.
1350    ///
1351    /// The queue of peeks awaiting a turn is served from the front and each peek it cannot retire
1352    /// is returned to the back, so the next sweep resumes where this one ran out of budget without
1353    /// either of them recording where that was.
1354    pub fn process_peeks(&mut self) {
1355        // Above the early return because this is the only place an activation begins. A replica
1356        // whose peeks all answer inline leaves none pending, and beginning an activation only
1357        // where there is work would let the aggregate drain across its arrivals.
1358        self.compute_state.peek_budget.start_activation();
1359
1360        // Says what this sweep found, so it is cleared before the sweep rather than carried in
1361        // from the last one. A peek cancelled or dropped between two sweeps would otherwise leave
1362        // the worker spinning on a turn nothing is waiting for.
1363        self.compute_state.peek_passed_over = false;
1364
1365        // Runs on every iteration of the worker loop, and almost every one finds no peek at all.
1366        if self.compute_state.pending_peeks.is_empty() && self.compute_state.queued_peeks.is_empty()
1367        {
1368            return;
1369        }
1370
1371        let mut upper = Antichain::new();
1372
1373        // Both queues are taken out of the state for the sweep, because serving a peek borrows
1374        // `self` mutably. A peek the sweep returns for another turn lands in the emptied queue.
1375        let mut pending_peeks = std::mem::take(&mut self.compute_state.pending_peeks);
1376        while let Some(peek) = pending_peeks.pop_front() {
1377            self.poll_pending_peek(peek);
1378        }
1379
1380        // The aggregate does not refill within an activation, so the first peek the budget cannot
1381        // serve is also the last: every peek behind it would be passed over for the same reason.
1382        let mut queued_peeks = std::mem::take(&mut self.compute_state.queued_peeks);
1383        while let Some(peek) = queued_peeks.pop_front() {
1384            let Some(fuel) = self.compute_state.peek_budget.grant() else {
1385                queued_peeks.push_front(peek);
1386                break;
1387            };
1388            self.walk_index_peek(&mut upper, peek, fuel);
1389        }
1390
1391        // A peek the sweep never reached keeps its place ahead of the peeks it served, so the
1392        // queue rotates instead of starving its tail.
1393        self.compute_state.peek_passed_over = !queued_peeks.is_empty();
1394        let served = std::mem::replace(&mut self.compute_state.queued_peeks, queued_peeks);
1395        self.compute_state.queued_peeks.extend(served);
1396    }
1397
1398    /// Sends a response for this peek's resolution to the coordinator.
1399    ///
1400    /// Note that this function takes ownership of the `PendingPeek`, which is
1401    /// meant to prevent multiple responses to the same peek.
1402    #[mz_ore::instrument(level = "debug")]
1403    fn send_peek_response(&mut self, peek: PendingPeek, response: PeekResponse) {
1404        let log_event = peek.as_log_event(false);
1405        // Respond with the response.
1406        self.send_compute_response(ComputeResponse::PeekResponse(
1407            peek.peek().uuid,
1408            response,
1409            OpenTelemetryContext::obtain(),
1410        ));
1411
1412        // Log responding to the peek request.
1413        if let Some(logger) = self.compute_state.compute_logger.as_mut() {
1414            logger.log(&log_event);
1415        }
1416    }
1417
1418    /// Scan the shared subscribe response buffer, and forward results along.
1419    pub fn process_subscribes(&mut self) {
1420        let mut subscribe_responses = self.compute_state.subscribe_response_buffer.borrow_mut();
1421        for (sink_id, mut response) in subscribe_responses.drain(..) {
1422            // Update frontier logging for this subscribe.
1423            if let Some(collection) = self.compute_state.collections.get_mut(&sink_id) {
1424                let new_frontier = match &response {
1425                    SubscribeResponse::Batch(b) => b.upper.clone(),
1426                    SubscribeResponse::DroppedAt(_) => Antichain::new(),
1427                };
1428
1429                let reported = collection.reported_frontiers();
1430                assert!(
1431                    reported.write_frontier.allows_reporting(&new_frontier),
1432                    "subscribe write frontier regression: {:?} -> {:?}",
1433                    reported.write_frontier,
1434                    new_frontier,
1435                );
1436                assert!(
1437                    reported.input_frontier.allows_reporting(&new_frontier),
1438                    "subscribe input frontier regression: {:?} -> {:?}",
1439                    reported.input_frontier,
1440                    new_frontier,
1441                );
1442
1443                collection
1444                    .set_reported_write_frontier(ReportedFrontier::Reported(new_frontier.clone()));
1445                collection
1446                    .set_reported_input_frontier(ReportedFrontier::Reported(new_frontier.clone()));
1447                collection.set_reported_output_frontier(ReportedFrontier::Reported(new_frontier));
1448            } else {
1449                // Presumably tracking state for this subscribe was already dropped by
1450                // `drop_collection`. There is nothing left to do for logging.
1451            }
1452
1453            response
1454                .to_error_if_exceeds(usize::try_from(self.compute_state.max_result_size).unwrap());
1455            self.send_compute_response(ComputeResponse::SubscribeResponse(sink_id, response));
1456        }
1457    }
1458
1459    /// Scan the shared copy to response buffer, and forward results along.
1460    pub fn process_copy_tos(&self) {
1461        let mut responses = self.compute_state.copy_to_response_buffer.borrow_mut();
1462        for (sink_id, response) in responses.drain(..) {
1463            self.send_compute_response(ComputeResponse::CopyToResponse(sink_id, response));
1464        }
1465    }
1466
1467    /// Send a response to the coordinator.
1468    fn send_compute_response(&self, response: ComputeResponse) {
1469        // Ignore send errors because the coordinator is free to ignore our
1470        // responses. This happens during shutdown.
1471        let _ = self.response_tx.send(response);
1472    }
1473
1474    /// Checks for dataflow expiration. Panics if we're past the replica expiration time.
1475    pub(crate) fn check_expiration(&self) {
1476        let now = mz_ore::now::SYSTEM_TIME();
1477        if self.compute_state.replica_expiration.less_than(&now.into()) {
1478            let now_datetime = mz_ore::now::to_datetime(now);
1479            let expiration_datetime = self
1480                .compute_state
1481                .replica_expiration
1482                .as_option()
1483                .map(Into::into)
1484                .map(mz_ore::now::to_datetime);
1485
1486            // We error and assert separately to produce structured logs in anything that depends
1487            // on tracing.
1488            error!(
1489                now,
1490                now_datetime = ?now_datetime,
1491                expiration = ?self.compute_state.replica_expiration.elements(),
1492                expiration_datetime = ?expiration_datetime,
1493                "replica expired"
1494            );
1495
1496            // Repeat condition for better error message.
1497            assert!(
1498                !self.compute_state.replica_expiration.less_than(&now.into()),
1499                "replica expired. now: {now} ({now_datetime:?}), expiration: {:?} ({expiration_datetime:?})",
1500                self.compute_state.replica_expiration.elements(),
1501            );
1502        }
1503    }
1504
1505    /// Returns the dataflow expiration, i.e, the timestamp beyond which diffs can be
1506    /// dropped.
1507    ///
1508    /// Returns an empty timestamp if `replica_expiration` is unset or matches conditions under
1509    /// which dataflow expiration should be disabled.
1510    pub fn determine_dataflow_expiration(
1511        &self,
1512        time_dependence: &TimeDependence,
1513        until: &Antichain<Timestamp>,
1514    ) -> Antichain<Timestamp> {
1515        // Evaluate time dependence with respect to the expiration time.
1516        // * Step time forward to ensure the expiration time is different to the moment a dataflow
1517        //   can legitimately jump to.
1518        // * We cannot expire dataflow with an until that is less or equal to the expiration time.
1519        let iter = self
1520            .compute_state
1521            .replica_expiration
1522            .iter()
1523            .filter_map(|t| time_dependence.apply(*t))
1524            .filter_map(|t| Timestamp::try_step_forward(&t))
1525            .filter(|expiration| !until.less_equal(expiration));
1526        Antichain::from_iter(iter)
1527    }
1528}
1529
1530/// A peek against either an index or a Persist collection.
1531///
1532/// Note that `PendingPeek` intentionally does not implement or derive `Clone`,
1533/// as each `PendingPeek` is meant to be dropped after it's responded to.
1534pub enum PendingPeek {
1535    /// A peek against an index. (Possibly a temporary index created for the purpose.)
1536    Index(IndexPeek),
1537    /// A peek against a Persist-backed collection.
1538    Persist(PersistPeek),
1539    /// A peek against an index whose walk was offloaded from the worker and is running as an async
1540    /// task.
1541    Offloaded(OffloadedPeek),
1542}
1543
1544impl PendingPeek {
1545    /// Produces a corresponding log event.
1546    pub fn as_log_event(&self, installed: bool) -> ComputeEvent {
1547        let peek = self.peek();
1548        let (id, peek_type) = match &peek.target {
1549            PeekTarget::Index { id } => (*id, logging::compute::PeekType::Index),
1550            PeekTarget::Persist { id, .. } => (*id, logging::compute::PeekType::Persist),
1551        };
1552        let uuid = peek.uuid.into_bytes();
1553        ComputeEvent::Peek(PeekEvent {
1554            id,
1555            time: peek.timestamp,
1556            uuid,
1557            peek_type,
1558            installed,
1559        })
1560    }
1561
1562    fn index(peek: Peek, mut trace_bundle: TraceBundle) -> Self {
1563        let empty_frontier = Antichain::new();
1564        let timestamp_frontier = Antichain::from_elem(peek.timestamp);
1565        trace_bundle
1566            .oks_mut()
1567            .set_logical_compaction(timestamp_frontier.borrow());
1568        trace_bundle
1569            .errs_mut()
1570            .set_logical_compaction(timestamp_frontier.borrow());
1571        trace_bundle
1572            .oks_mut()
1573            .set_physical_compaction(empty_frontier.borrow());
1574        trace_bundle
1575            .errs_mut()
1576            .set_physical_compaction(empty_frontier.borrow());
1577
1578        PendingPeek::Index(IndexPeek {
1579            peek,
1580            trace_bundle,
1581            span: tracing::Span::current(),
1582        })
1583    }
1584
1585    fn persist(
1586        peek: Peek,
1587        persist_clients: Arc<PersistClientCache>,
1588        metadata: CollectionMetadata,
1589        max_result_size: usize,
1590        timely_worker: &TimelyWorker,
1591        row_iteration_config: PeekRowIterationConfig,
1592    ) -> Self {
1593        let active_worker = {
1594            // Choose the worker that does the actual peek arbitrarily but consistently.
1595            let chosen_index = usize::cast_from(peek.uuid.hashed()) % timely_worker.peers();
1596            chosen_index == timely_worker.index()
1597        };
1598        let activator = timely_worker.sync_activator_for([].into());
1599        let peek_uuid = peek.uuid;
1600
1601        let (result_tx, result_rx) = oneshot::channel();
1602        let timestamp = peek.timestamp;
1603        let mfp_plan = peek.map_filter_project.clone();
1604        let max_results_needed = peek
1605            .finishing
1606            .limit
1607            .map(|l| usize::cast_from(u64::from(l)))
1608            .unwrap_or(usize::MAX)
1609            + peek.finishing.offset;
1610        let order_by = peek.finishing.order_by.clone();
1611
1612        // Persist peeks can include at most one literal constraint.
1613        let literal_constraint = peek
1614            .literal_constraints
1615            .clone()
1616            .map(|rows| rows.into_element());
1617
1618        let task_handle = mz_ore::task::spawn(|| "persist::peek", async move {
1619            let start = Instant::now();
1620            let result = if active_worker {
1621                PersistPeek::do_peek(
1622                    &persist_clients,
1623                    metadata,
1624                    timestamp,
1625                    literal_constraint,
1626                    mfp_plan,
1627                    max_result_size,
1628                    max_results_needed,
1629                    row_iteration_config,
1630                )
1631                .await
1632            } else {
1633                Ok(vec![])
1634            };
1635            let result = match result {
1636                Ok(rows) => PeekResponse::Rows(vec![RowCollection::new(rows, &order_by)]),
1637                Err(error) => PeekResponse::Error(error),
1638            };
1639            match result_tx.send((result, start.elapsed())) {
1640                Ok(()) => {}
1641                Err((_result, elapsed)) => {
1642                    debug!(duration =? elapsed, "dropping result for cancelled peek {peek_uuid}")
1643                }
1644            }
1645            match activator.activate() {
1646                Ok(()) => {}
1647                Err(_) => {
1648                    debug!("unable to wake timely after completed peek {peek_uuid}");
1649                }
1650            }
1651        });
1652        PendingPeek::Persist(PersistPeek {
1653            peek,
1654            _abort_handle: task_handle.abort_on_drop(),
1655            result: result_rx,
1656            span: tracing::Span::current(),
1657        })
1658    }
1659
1660    fn span(&self) -> &tracing::Span {
1661        match self {
1662            PendingPeek::Index(p) => &p.span,
1663            PendingPeek::Persist(p) => &p.span,
1664            PendingPeek::Offloaded(p) => &p.span,
1665        }
1666    }
1667
1668    pub(crate) fn peek(&self) -> &Peek {
1669        match self {
1670            PendingPeek::Index(p) => &p.peek,
1671            PendingPeek::Persist(p) => &p.peek,
1672            PendingPeek::Offloaded(p) => &p.peek,
1673        }
1674    }
1675}
1676
1677/// An in-progress Persist peek.
1678///
1679/// Note that `PendingPeek` intentionally does not implement or derive `Clone`,
1680/// as each `PendingPeek` is meant to be dropped after it's responded to.
1681pub struct PersistPeek {
1682    pub(crate) peek: Peek,
1683    /// A background task that's responsible for producing the peek results.
1684    /// If we're no longer interested in the results, we abort the task.
1685    _abort_handle: AbortOnDropHandle<()>,
1686    /// The result of the background task, eventually.
1687    result: oneshot::Receiver<(PeekResponse, Duration)>,
1688    /// The `tracing::Span` tracking this peek's operation
1689    span: tracing::Span,
1690}
1691
1692impl PersistPeek {
1693    async fn do_peek(
1694        persist_clients: &PersistClientCache,
1695        metadata: CollectionMetadata,
1696        as_of: Timestamp,
1697        literal_constraint: Option<Row>,
1698        mfp_plan: SafeMfpPlan,
1699        max_result_size: usize,
1700        mut limit_remaining: usize,
1701        row_iteration_config: PeekRowIterationConfig,
1702    ) -> Result<Vec<(Row, NonZeroUsize)>, PeekError> {
1703        let client = persist_clients
1704            .open(metadata.persist_location)
1705            .await
1706            .map_err(|e| PeekError::unstructured(e.to_string()))?;
1707
1708        let mut reader: ReadHandle<SourceData, (), Timestamp, StorageDiff> = client
1709            .open_leased_reader(
1710                metadata.data_shard,
1711                Arc::new(metadata.relation_desc.clone()),
1712                Arc::new(UnitSchema),
1713                Diagnostics::from_purpose("persist::peek"),
1714                USE_CRITICAL_SINCE_SNAPSHOT.get(client.dyncfgs()),
1715            )
1716            .await
1717            .map_err(|e| PeekError::unstructured(e.to_string()))?;
1718
1719        // If we are using txn-wal for this collection, then the upper might
1720        // be advanced lazily and we have to go through txn-wal for reads.
1721        //
1722        // TODO: If/when we have a process-wide TxnsRead worker for clusterd,
1723        // use in here (instead of opening a new TxnsCache) to save a persist
1724        // reader registration and some txns shard read traffic.
1725        let mut txns_read = if let Some(txns_id) = metadata.txns_shard {
1726            Some(TxnsCache::open(&client, txns_id, Some(metadata.data_shard)).await)
1727        } else {
1728            None
1729        };
1730
1731        let metrics = client.metrics();
1732
1733        let mut cursor = StatsCursor::new(
1734            &mut reader,
1735            txns_read.as_mut(),
1736            metrics,
1737            &mfp_plan,
1738            &metadata.relation_desc,
1739            Antichain::from_elem(as_of),
1740        )
1741        .await
1742        .map_err(|since| {
1743            PeekError::unstructured(format!(
1744                "attempted to peek at {as_of}, but the since has advanced to {since:?}"
1745            ))
1746        })?;
1747
1748        // Re-used state for processing and building rows.
1749        let mut result = vec![];
1750        let mut datum_vec = DatumVec::new();
1751        let mut row_builder = Row::default();
1752        let arena = RowArena::new();
1753        let mut total_size = 0usize;
1754        let mut row_iteration_tracker = PeekRowIterationTracker::new(None, 0);
1755
1756        let literal_len = match &literal_constraint {
1757            None => 0,
1758            Some(row) => row.iter().count(),
1759        };
1760
1761        'collect: while limit_remaining > 0 {
1762            let Some(batch) = cursor.next().await else {
1763                break;
1764            };
1765            for (data, _, d) in batch {
1766                // Count before literal and MFP filtering because the Persist row
1767                // has already been read and must still be examined.
1768                row_iteration_tracker.set_limit(row_iteration_config.current_limit());
1769                row_iteration_tracker.track_next()?;
1770
1771                let row = data.map_err(PeekError::from)?;
1772
1773                if let Some(literal) = &literal_constraint {
1774                    match row.iter().take(literal_len).cmp(literal.iter()) {
1775                        Ordering::Less => continue,
1776                        Ordering::Equal => {}
1777                        Ordering::Greater => break 'collect,
1778                    }
1779                }
1780
1781                let count: usize = d.try_into().map_err(|_| {
1782                    error!(
1783                        shard = %metadata.data_shard, diff = d, ?row,
1784                        "persist peek encountered negative multiplicities",
1785                    );
1786                    PeekError::unstructured(format!(
1787                        "Invalid data in source, \
1788                         saw retractions ({}) for row that does not exist: {:?}",
1789                        -d, row,
1790                    ))
1791                })?;
1792                let Some(count) = NonZeroUsize::new(count) else {
1793                    continue;
1794                };
1795                let mut datum_local = datum_vec.borrow_with(&row);
1796                let eval_result = mfp_plan
1797                    .evaluate_into(&mut datum_local, &arena, &mut row_builder)
1798                    .map(|row| row.cloned())
1799                    .map_err(PeekError::from)?;
1800                if let Some(row) = eval_result {
1801                    total_size = total_size.saturating_add(entry_byte_len(&row));
1802                    if total_size > max_result_size {
1803                        return Err(PeekError::ResultExceedsMaxSize { max_result_size });
1804                    }
1805                    result.push((row, count));
1806                    limit_remaining = limit_remaining.saturating_sub(count.get());
1807                    if limit_remaining == 0 {
1808                        break;
1809                    }
1810                }
1811            }
1812        }
1813
1814        Ok(result)
1815    }
1816}
1817
1818/// An in-progress index-backed peek, and data to eventually fulfill it.
1819pub struct IndexPeek {
1820    peek: Peek,
1821    /// The data from which the trace derives.
1822    trace_bundle: TraceBundle,
1823    /// The `tracing::Span` tracking this peek's operation
1824    span: tracing::Span,
1825}
1826
1827impl IndexPeek {
1828    /// Attempts to fulfill the peek and reports success.
1829    ///
1830    /// To produce output at `peek.timestamp`, we must be certain that
1831    /// it is no longer changing. A trace guarantees that all future
1832    /// changes will be greater than or equal to an element of `upper`.
1833    ///
1834    /// If an element of `upper` is less or equal to `peek.timestamp`,
1835    /// then there can be further updates that would change the output.
1836    /// If no element of `upper` is less or equal to `peek.timestamp`,
1837    /// then for any time `t` less or equal to `peek.timestamp` it is
1838    /// not the case that `upper` is less or equal to that timestamp,
1839    /// and so the result cannot further evolve.
1840    ///
1841    /// `fuel` bounds how far the walk may go on this worker, in cursor positions, and is charged
1842    /// for the positions it visits. A walk that exhausts it with work left is offloaded rather than
1843    /// continued here, and a peek whose frontiers do not admit the read yet spends none of it.
1844    fn seek_fulfillment(
1845        &mut self,
1846        upper: &mut Antichain<Timestamp>,
1847        max_result_size: u64,
1848        stash: StashBounds,
1849        row_iteration_limit: Option<usize>,
1850        fuel: &mut usize,
1851        metrics: &IndexPeekMetrics<'_>,
1852    ) -> PeekStatus {
1853        let method_start = Instant::now();
1854
1855        self.trace_bundle.oks_mut().read_upper(upper);
1856        if upper.less_equal(&self.peek.timestamp) {
1857            return PeekStatus::NotReady;
1858        }
1859        self.trace_bundle.errs_mut().read_upper(upper);
1860        if upper.less_equal(&self.peek.timestamp) {
1861            return PeekStatus::NotReady;
1862        }
1863
1864        let read_frontier = self.trace_bundle.compaction_frontier();
1865        if !read_frontier.less_equal(&self.peek.timestamp) {
1866            let error = format!(
1867                "Arrangement compaction frontier ({:?}) is beyond the time of the attempted read ({})",
1868                read_frontier.elements(),
1869                self.peek.timestamp,
1870            );
1871            return PeekStatus::Ready(PeekResponse::Error(PeekError::unstructured(error)));
1872        }
1873
1874        metrics
1875            .frontier_check_seconds
1876            .observe(method_start.elapsed().as_secs_f64());
1877
1878        let result =
1879            self.collect_finished_data(max_result_size, stash, row_iteration_limit, fuel, metrics);
1880
1881        metrics
1882            .seek_fulfillment_seconds
1883            .observe(method_start.elapsed().as_secs_f64());
1884
1885        result
1886    }
1887
1888    /// Answers the peek by scanning the traces that fulfil it, for as long as `fuel` allows.
1889    ///
1890    /// One call opens one scan and either answers from it or hands it on, so nothing survives the
1891    /// call. A scan that runs out of fuel with work left leaves with the [`PeekStatus::Offload`]
1892    /// that reports it, so the positions it walked are not walked again.
1893    fn collect_finished_data(
1894        &mut self,
1895        max_result_size: u64,
1896        stash: StashBounds,
1897        row_iteration_limit: Option<usize>,
1898        fuel: &mut usize,
1899        metrics: &IndexPeekMetrics<'_>,
1900    ) -> PeekStatus {
1901        let peek = &self.peek;
1902        let (oks, errs) = self.trace_bundle.oks_errs_mut();
1903        let mut scan = PeekScan::new(peek, errs, oks, max_result_size, stash);
1904
1905        let outcome = scan.step(row_iteration_limit, fuel);
1906
1907        let phases = scan.phases();
1908        match outcome {
1909            // Both answers end the walk on this worker, so this driver accounts for it either
1910            // way.
1911            ScanOutcome::Finished(result) => {
1912                metrics.walk.walked_inline();
1913                metrics.walk.observe_error_phase(&phases);
1914                PeekStatus::Ready(match result {
1915                    Ok(rows) => {
1916                        metrics.walk.observe_ok_phase(&phases);
1917                        let start = Instant::now();
1918                        let response = rows_response(rows, &self.peek.finishing.order_by);
1919                        metrics.walk.observe_row_collection(start.elapsed());
1920                        response
1921                    }
1922                    // The ok phase goes unreported, because an error can come from either walk
1923                    // and its numbers describe a finished ok walk only when rows came out of it.
1924                    Err(error) => PeekResponse::Error(error),
1925                })
1926            }
1927            // The one outcome that leaves the walk unfinished, and so the one this driver
1928            // reports nothing for.
1929            //
1930            // A scan suspends out of fuel or holding a full batch, and this driver can carry on
1931            // with neither: it walks under a budget the slice has spent, and it writes no rows, so
1932            // a batch handed to it here would have to be dropped. Every position the scan walked
1933            // travels with it, and so does their cost, which is what makes offload cost one
1934            // hand-off rather than a second walk.
1935            ScanOutcome::Suspended => PeekStatus::Offload(scan),
1936        }
1937    }
1938}
1939
1940/// For keeping track of the state of pending or ready peeks, and managing
1941/// control flow.
1942enum PeekStatus {
1943    /// The frontiers of objects are not yet advanced enough, peek is still
1944    /// pending.
1945    NotReady,
1946    /// The walk stopped with work left, so it is finished away from the worker. Carries the scan,
1947    /// which resumes from the cursor positions it stopped on.
1948    ///
1949    /// A walk stops either because it spent the fuel this activation granted it or because its
1950    /// accumulated rows grew into a batch bound for the peek stash. Both leave here, because the
1951    /// driver that finishes a walk is also the one that writes to the stash.
1952    Offload(IndexPeekScan),
1953    /// The peek result is ready.
1954    Ready(PeekResponse),
1955}
1956
1957/// The frontiers we have reported to the controller for a collection.
1958#[derive(Debug)]
1959struct ReportedFrontiers {
1960    /// The reported write frontier.
1961    write_frontier: ReportedFrontier,
1962    /// The reported input frontier.
1963    input_frontier: ReportedFrontier,
1964    /// The reported output frontier.
1965    output_frontier: ReportedFrontier,
1966}
1967
1968impl ReportedFrontiers {
1969    /// Creates a new `ReportedFrontiers` instance.
1970    fn new() -> Self {
1971        Self {
1972            write_frontier: ReportedFrontier::new(),
1973            input_frontier: ReportedFrontier::new(),
1974            output_frontier: ReportedFrontier::new(),
1975        }
1976    }
1977}
1978
1979/// A frontier we have reported to the controller, or the least frontier we are allowed to report.
1980#[derive(Clone, Debug)]
1981pub enum ReportedFrontier {
1982    /// A frontier has been previously reported.
1983    Reported(Antichain<Timestamp>),
1984    /// No frontier has been reported yet.
1985    NotReported {
1986        /// A lower bound for frontiers that may be reported in the future.
1987        lower: Antichain<Timestamp>,
1988    },
1989}
1990
1991impl ReportedFrontier {
1992    /// Create a new `ReportedFrontier` enforcing the minimum lower bound.
1993    pub fn new() -> Self {
1994        let lower = Antichain::from_elem(timely::progress::Timestamp::minimum());
1995        Self::NotReported { lower }
1996    }
1997
1998    /// Whether the reported frontier is the empty frontier.
1999    pub fn is_empty(&self) -> bool {
2000        match self {
2001            Self::Reported(frontier) => frontier.is_empty(),
2002            Self::NotReported { .. } => false,
2003        }
2004    }
2005
2006    /// Whether this `ReportedFrontier` allows reporting the given frontier.
2007    ///
2008    /// A `ReportedFrontier` allows reporting of another frontier if:
2009    ///  * The other frontier is greater than the reported frontier.
2010    ///  * The other frontier is greater than or equal to the lower bound.
2011    fn allows_reporting(&self, other: &Antichain<Timestamp>) -> bool {
2012        match self {
2013            Self::Reported(frontier) => PartialOrder::less_than(frontier, other),
2014            Self::NotReported { lower } => PartialOrder::less_equal(lower, other),
2015        }
2016    }
2017}
2018
2019/// State maintained for a compute collection.
2020pub struct CollectionState {
2021    /// Tracks the frontiers that have been reported to the controller.
2022    reported_frontiers: ReportedFrontiers,
2023    /// The index of the dataflow computing this collection.
2024    ///
2025    /// Used for dropping the dataflow when the collection is dropped.
2026    /// The Dataflow index is wrapped in an `Rc`s and can be shared between collections, to reflect
2027    /// the possibility that a single dataflow can export multiple collections.
2028    dataflow_index: Rc<usize>,
2029    /// Whether this collection is a subscribe or copy-to.
2030    ///
2031    /// The compute protocol does not allow `Frontiers` responses for subscribe and copy-to
2032    /// collections, so we need to be able to recognize them. This is something we would like to
2033    /// change in the future (database-issues#4701).
2034    pub is_subscribe_or_copy: bool,
2035    /// The collection's initial as-of frontier.
2036    ///
2037    /// Used to determine hydration status.
2038    as_of: Antichain<Timestamp>,
2039
2040    /// A token that should be dropped when this collection is dropped to clean up associated
2041    /// sink state.
2042    ///
2043    /// Only `Some` if the collection is a sink.
2044    pub sink_token: Option<SinkToken>,
2045    /// Frontier of sink writes.
2046    ///
2047    /// Only `Some` if the collection is a sink and *not* a subscribe.
2048    pub sink_write_frontier: Option<Rc<RefCell<Antichain<Timestamp>>>>,
2049    /// Frontier probes for every input to the collection.
2050    pub input_probes: BTreeMap<GlobalId, probe::Handle<Timestamp>>,
2051    /// A probe reporting the frontier of times through which all collection outputs have been
2052    /// computed (but not necessarily written).
2053    ///
2054    /// `None` for collections with compute frontiers equal to their write frontiers.
2055    pub compute_probe: Option<probe::Handle<Timestamp>>,
2056    /// Logging state maintained for this collection.
2057    logging: Option<CollectionLogging>,
2058    /// Metrics tracked for this collection.
2059    metrics: CollectionMetrics,
2060    /// Send-side to transition a dataflow from read-only mode to read-write mode.
2061    ///
2062    /// All dataflows start in read-only mode. Only after receiving a
2063    /// `AllowWrites` command from the controller will they transition to
2064    /// read-write mode.
2065    ///
2066    /// A dataflow in read-only mode must not affect any external state.
2067    ///
2068    /// NOTE: In the future, we might want a more complicated flag, for example
2069    /// something that tells us after which timestamp we are allowed to write.
2070    /// In this first version we are keeping things as simple as possible!
2071    read_only_tx: watch::Sender<bool>,
2072    /// Receive-side to observe whether a dataflow is in read-only mode.
2073    pub read_only_rx: watch::Receiver<bool>,
2074}
2075
2076impl CollectionState {
2077    fn new(
2078        dataflow_index: Rc<usize>,
2079        is_subscribe_or_copy: bool,
2080        as_of: Antichain<Timestamp>,
2081        metrics: CollectionMetrics,
2082    ) -> Self {
2083        // We always initialize as read_only=true. Only when we're explicitly
2084        // allowed to we switch to read-write.
2085        let (read_only_tx, read_only_rx) = watch::channel(true);
2086
2087        Self {
2088            reported_frontiers: ReportedFrontiers::new(),
2089            dataflow_index,
2090            is_subscribe_or_copy,
2091            as_of,
2092            sink_token: None,
2093            sink_write_frontier: None,
2094            input_probes: Default::default(),
2095            compute_probe: None,
2096            logging: None,
2097            metrics,
2098            read_only_tx,
2099            read_only_rx,
2100        }
2101    }
2102
2103    /// Return the frontiers that have been reported to the controller.
2104    fn reported_frontiers(&self) -> &ReportedFrontiers {
2105        &self.reported_frontiers
2106    }
2107
2108    /// Reset all reported frontiers to the given value.
2109    pub fn reset_reported_frontiers(&mut self, frontier: ReportedFrontier) {
2110        self.reported_frontiers.write_frontier = frontier.clone();
2111        self.reported_frontiers.input_frontier = frontier.clone();
2112        self.reported_frontiers.output_frontier = frontier;
2113    }
2114
2115    /// Set the write frontier that has been reported to the controller.
2116    fn set_reported_write_frontier(&mut self, frontier: ReportedFrontier) {
2117        if let Some(logging) = &mut self.logging {
2118            let time = match &frontier {
2119                ReportedFrontier::Reported(frontier) => frontier.get(0).copied(),
2120                ReportedFrontier::NotReported { .. } => Some(Timestamp::MIN),
2121            };
2122            logging.set_frontier(time);
2123        }
2124
2125        self.reported_frontiers.write_frontier = frontier;
2126    }
2127
2128    /// Set the input frontier that has been reported to the controller.
2129    fn set_reported_input_frontier(&mut self, frontier: ReportedFrontier) {
2130        // Use this opportunity to update our input frontier logging.
2131        if let Some(logging) = &mut self.logging {
2132            for (id, probe) in &self.input_probes {
2133                let new_time = probe.with_frontier(|frontier| frontier.as_option().copied());
2134                logging.set_import_frontier(*id, new_time);
2135            }
2136        }
2137
2138        self.reported_frontiers.input_frontier = frontier;
2139    }
2140
2141    /// Set the output frontier that has been reported to the controller.
2142    fn set_reported_output_frontier(&mut self, frontier: ReportedFrontier) {
2143        let already_hydrated = self.hydrated();
2144
2145        self.reported_frontiers.output_frontier = frontier;
2146
2147        if !already_hydrated && self.hydrated() {
2148            if let Some(logging) = &mut self.logging {
2149                logging.set_hydrated();
2150            }
2151            self.metrics.record_collection_hydrated();
2152        }
2153    }
2154
2155    /// Return whether this collection is hydrated.
2156    fn hydrated(&self) -> bool {
2157        match &self.reported_frontiers.output_frontier {
2158            ReportedFrontier::Reported(frontier) => PartialOrder::less_than(&self.as_of, frontier),
2159            ReportedFrontier::NotReported { .. } => false,
2160        }
2161    }
2162
2163    /// Allow writes for this collection.
2164    fn allow_writes(&self) {
2165        info!(
2166            dataflow_index = *self.dataflow_index,
2167            export = ?self.logging.as_ref().map(|l| l.export_id()),
2168            "allowing writes for dataflow",
2169        );
2170        let _ = self.read_only_tx.send(false);
2171    }
2172}
2173
2174#[cfg(test)]
2175mod tests;
2176
2177/// Tests of the inline index-peek driver, and the fixtures [`peek_scan`]'s tests share with it.
2178#[cfg(test)]
2179pub(crate) mod index_peek_tests;
2180
2181/// Tests of the sweep that drives the pending index peeks.
2182#[cfg(test)]
2183mod peek_sweep_tests;