Skip to main content

mz_adapter/coord/
message_handler.rs

1// Copyright Materialize, Inc. and contributors. All rights reserved.
2//
3// Use of this software is governed by the Business Source License
4// included in the LICENSE file.
5//
6// As of the Change Date specified in that file, in accordance with
7// the Business Source License, use of this software will be governed
8// by the Apache License, Version 2.0.
9
10//! Logic for processing [`Coordinator`] messages. The [`Coordinator`] receives
11//! messages from various sources (ex: controller, clients, background tasks, etc).
12
13use std::collections::{BTreeMap, BTreeSet, btree_map};
14use std::sync::Arc;
15use std::time::{Duration, Instant};
16
17use futures::FutureExt;
18use maplit::btreemap;
19use mz_audit_log::VersionedStorageUsage;
20use mz_catalog::memory::objects::ClusterReplicaProcessStatus;
21use mz_controller::ControllerResponse;
22use mz_controller::clusters::{ClusterEvent, ClusterStatus};
23use mz_ore::cast::CastFrom;
24use mz_ore::instrument;
25use mz_ore::now::EpochMillis;
26use mz_ore::option::OptionExt;
27use mz_ore::tracing::OpenTelemetryContext;
28use mz_ore::{soft_assert_or_log, soft_panic_or_log, task};
29use mz_persist_client::usage::ShardsUsageReferenced;
30use mz_repr::{Datum, Diff, Row, Timestamp};
31use mz_sql::ast::Statement;
32use mz_sql::pure::PurifiedStatement;
33use mz_storage_client::controller::IntrospectionType;
34use mz_storage_types::StorageDiff;
35use mz_storage_types::sources::Timeline;
36use opentelemetry::trace::TraceContextExt;
37use rand::{RngExt, SeedableRng, rngs};
38use serde_json::json;
39use tracing::{Instrument, Level, event, info_span, warn};
40use tracing_opentelemetry::OpenTelemetrySpanExt;
41
42use crate::active_compute_sink::{ActiveComputeSink, ActiveComputeSinkRetireReason};
43use crate::catalog::BuiltinTableUpdate;
44use crate::command::Command;
45use crate::coord::{
46    ArrangementSizeRecord, ClusterReplicaStatuses, Coordinator, Message, PurifiedStatementReady,
47    WatchSetResponse,
48};
49use crate::telemetry::{EventDetails, SegmentClientExt};
50use crate::{AdapterError, AdapterNotice};
51
52/// How long an introspection subscribe must have been delivering data before
53/// the arrangement sizes snapshot trusts its replica's rows.
54///
55/// See `Coordinator::fresh_introspection_replicas` for why a margin is needed.
56/// 10s comfortably covers the collection manager's ~1s write batching plus the
57/// oracle read timestamp trailing the wall clock.
58const ARRANGEMENT_SIZES_FRESHNESS_MARGIN: Duration = Duration::from_secs(10);
59
60impl Coordinator {
61    /// BOXED FUTURE: As of Nov 2023 the returned Future from this function was 74KB. This would
62    /// get stored on the stack which is bad for runtime performance, and blow up our stack usage.
63    /// Because of that we purposefully move Futures of inner function calls onto the heap
64    /// (i.e. Box it).
65    #[instrument]
66    pub(crate) async fn handle_message(&mut self, msg: Message) -> () {
67        match msg {
68            Message::Command(otel_ctx, cmd) => {
69                // TODO: We need a Span that is not none for the otel_ctx to attach the parent
70                // relationship to. If we swap the otel_ctx in `Command::Message` for a Span, we
71                // can downgrade this to a debug_span.
72                let span = tracing::info_span!("message_command").or_current();
73                span.in_scope(|| otel_ctx.attach_as_parent());
74                self.message_command(cmd).instrument(span).await
75            }
76            Message::ControllerReady { controller: _ } => {
77                let Coordinator {
78                    controller,
79                    catalog,
80                    ..
81                } = self;
82                let storage_metadata = catalog.state().storage_metadata();
83                if let Some(m) = controller
84                    .process(storage_metadata)
85                    .expect("`process` never returns an error")
86                {
87                    self.message_controller(m).boxed_local().await
88                }
89            }
90            Message::SourceStatementReady {
91                pending,
92                response,
93                otel_ctx,
94            } => {
95                otel_ctx.attach_as_parent();
96                self.sequence_source_statement_ready(pending, Some(response))
97                    .boxed_local()
98                    .await;
99            }
100            Message::DdlCommandsReady { pending, otel_ctx } => {
101                otel_ctx.attach_as_parent();
102                self.sequence_ddl_commit(pending).boxed_local().await;
103            }
104            Message::PurifiedStatementReady(ready) => {
105                self.message_purified_statement_ready(ready)
106                    .boxed_local()
107                    .await
108            }
109            Message::GroupCommitInitiate(span, permit) => {
110                // Add an OpenTelemetry link to our current span.
111                tracing::Span::current().add_link(span.context().span().span_context().clone());
112                span.in_scope(|| self.stage_group_commit(permit));
113            }
114            Message::GroupCommitApplied {
115                responses,
116                statement_logging_ids,
117                internal_results,
118                write_ts,
119            } => {
120                // Record statement timestamps before retiring, since retiring ends the statement
121                // execution and drops its logging record.
122                for id in statement_logging_ids {
123                    self.set_statement_execution_timestamp(id, write_ts);
124                }
125                for response in responses {
126                    let (mut ctx, result) = response.finalize();
127                    ctx.session_mut().apply_write(write_ts);
128                    ctx.retire(result);
129                }
130                // The committer applied `write_ts` to the oracle, so the read ts is at least
131                // that and we can downgrade the local read holds without an oracle round trip.
132                self.downgrade_local_read_holds(write_ts);
133                self.retire_local_reads_linearized_by(write_ts);
134                self.advance_custom_timelines().boxed_local().await;
135                for result in internal_results {
136                    result.send(crate::coord::appends::WriteResult::Success {
137                        timestamp: write_ts,
138                    });
139                }
140            }
141            Message::AdvanceTimelines => {
142                // Only sent by the periodic tick in read-only mode, where group commits (which
143                // otherwise drive the local timeline) don't run. Fetch the oracle's read ts here,
144                // it is the freshest timestamp the read holds may downgrade to.
145                let read_ts = self.get_local_read_ts().await;
146                self.downgrade_local_read_holds(read_ts);
147                self.advance_custom_timelines().boxed_local().await;
148            }
149            Message::ClusterEvent(event) => self.message_cluster_event(event).boxed_local().await,
150            Message::LinearizeReads => {
151                self.message_linearize_reads().boxed_local().await;
152            }
153            Message::StagedBatches {
154                conn_id,
155                table_id,
156                batches,
157            } => {
158                self.commit_staged_batches(conn_id, table_id, batches);
159            }
160            Message::StorageUsageSchedule => {
161                self.schedule_storage_usage_collection().boxed_local().await;
162            }
163            Message::StorageUsageFetch => {
164                self.storage_usage_fetch().boxed_local().await;
165            }
166            Message::StorageUsageUpdate(sizes) => {
167                self.storage_usage_update(sizes).boxed_local().await;
168            }
169            Message::StorageUsagePrune(expired) => {
170                self.storage_usage_prune(expired).boxed_local().await;
171            }
172            Message::ArrangementSizesSchedule => {
173                self.schedule_arrangement_sizes_collection();
174            }
175            Message::ArrangementSizesSnapshot => {
176                self.arrangement_sizes_snapshot();
177            }
178            Message::ArrangementSizesWrite {
179                records,
180                collection_ts,
181            } => {
182                self.arrangement_sizes_write(records, collection_ts);
183            }
184            Message::ArrangementSizesPrune(expired) => {
185                self.arrangement_sizes_prune(expired);
186            }
187            Message::HydrationHistorySchedule => {
188                self.schedule_hydration_history_collection();
189            }
190            Message::HydrationHistoryRun => {
191                self.run_hydration_history_collection();
192            }
193            Message::CaughtUpCheck(request) => {
194                self.handle_caught_up_check_request(request);
195            }
196            Message::RetireExecute {
197                otel_ctx,
198                data,
199                reason,
200            } => {
201                otel_ctx.attach_as_parent();
202                self.retire_execution(reason, data);
203            }
204            Message::ExecuteSingleStatementTransaction {
205                ctx,
206                otel_ctx,
207                stmt,
208                params,
209            } => {
210                otel_ctx.attach_as_parent();
211                self.sequence_execute_single_statement_transaction(ctx, stmt, params)
212                    .boxed_local()
213                    .await;
214            }
215            Message::CreateIndexStageReady { ctx, span, stage } => {
216                self.sequence_staged(ctx, span, stage).boxed_local().await;
217            }
218            Message::CreateMetricSinkStageReady { ctx, span, stage } => {
219                self.sequence_staged(ctx, span, stage).boxed_local().await;
220            }
221            Message::CreateViewStageReady { ctx, span, stage } => {
222                self.sequence_staged(ctx, span, stage).boxed_local().await;
223            }
224            Message::CreateMaterializedViewStageReady { ctx, span, stage } => {
225                self.sequence_staged(ctx, span, stage).boxed_local().await;
226            }
227            Message::IntrospectionSubscribeStageReady { span, stage } => {
228                self.sequence_staged((), span, stage).boxed_local().await;
229            }
230            Message::MetricSinkStageReady { span, stage } => {
231                self.sequence_staged((), span, stage).boxed_local().await;
232            }
233            Message::SecretStageReady { ctx, span, stage } => {
234                self.sequence_staged(ctx, span, stage).boxed_local().await;
235            }
236            Message::ClusterStageReady { ctx, span, stage } => {
237                self.sequence_staged(ctx, span, stage).boxed_local().await;
238            }
239            Message::DrainStatementLog => {
240                self.drain_statement_log();
241            }
242            Message::PrivateLinkVpcEndpointEvents(events) => {
243                if !self.controller.read_only() {
244                    self.controller.storage.append_introspection_updates(
245                        IntrospectionType::PrivatelinkConnectionStatusHistory,
246                        events
247                            .into_iter()
248                            .map(|e| (mz_repr::Row::from(e), Diff::ONE))
249                            .collect(),
250                    );
251                }
252            }
253            Message::ClusterControllerRequest(request) => {
254                self.handle_cluster_controller_request(request)
255                    .boxed_local()
256                    .await;
257            }
258            Message::DeferredStatementReady => {
259                self.handle_deferred_statement().boxed_local().await;
260            }
261        }
262    }
263
264    #[mz_ore::instrument(level = "debug")]
265    pub async fn storage_usage_fetch(&self) {
266        // In read-only mode (e.g. a standby coordinator during a zero-downtime
267        // deployment) we cannot durably write the per-batch allocator bump or
268        // append to `mz_storage_usage_by_shard`, and we also don't want to do
269        // the slow shard scan on a process that isn't going to record the
270        // results. Skip the whole cycle and reschedule so we resume
271        // automatically once the coordinator transitions out of read-only.
272        if self.controller.read_only() {
273            tracing::info!("skipping storage usage collection in read-only mode");
274            if let Err(e) = self.internal_cmd_tx.send(Message::StorageUsageSchedule) {
275                warn!("internal_cmd_rx dropped before we could send: {:?}", e);
276            }
277            return;
278        }
279
280        let internal_cmd_tx = self.internal_cmd_tx.clone();
281        let client = self.storage_usage_client.clone();
282
283        // Record the currently live shards.
284        let live_shards: BTreeSet<_> = self
285            .controller
286            .storage
287            .active_collection_metadatas()
288            .into_iter()
289            .map(|(_id, m)| m.data_shard)
290            .collect();
291
292        let collection_metric = self.metrics.storage_usage_collection_time_seconds.clone();
293
294        // Spawn an asynchronous task to compute the storage usage, which
295        // requires a slow scan of the underlying storage engine.
296        task::spawn(|| "storage_usage_fetch", async move {
297            let collection_metric_timer = collection_metric.start_timer();
298            let shard_sizes = client.shards_usage_referenced(live_shards).await;
299            collection_metric_timer.observe_duration();
300
301            // It is not an error for shard sizes to become ready after
302            // `internal_cmd_rx` is dropped.
303            if let Err(e) = internal_cmd_tx.send(Message::StorageUsageUpdate(shard_sizes)) {
304                warn!("internal_cmd_rx dropped before we could send: {:?}", e);
305            }
306        });
307    }
308
309    #[mz_ore::instrument(level = "debug")]
310    async fn storage_usage_update(&mut self, shards_usage: ShardsUsageReferenced) {
311        // Similar to audit events, use the oracle ts so this is guaranteed to
312        // increase. This is intentionally the timestamp of when collection
313        // finished, not when it started, so that we don't write data with a
314        // timestamp in the past.
315        //
316        // `storage_usage_fetch` skips this path in read-only mode, so we can
317        // unconditionally bump the oracle write ts here.
318        let write_ts = self.get_catalog_write_ts().await;
319        let collection_timestamp: EpochMillis = write_ts.into();
320
321        // All rows in this collection cycle share `batch_id` so consumers can
322        // identify rows that were collected together. We use one durable
323        // allocator bump per cycle (rather than per shard) so the id is
324        // monotonic across coordinator restarts while still keeping the
325        // coord-blocking cost proportional to one round-trip, not N.
326        let batch_id = match self.catalog().allocate_storage_usage_id(write_ts).await {
327            Ok(id) => id,
328            Err(err) => {
329                tracing::warn!("failed to allocate storage usage batch id: {:?}", err);
330                return;
331            }
332        };
333
334        let updates: Vec<_> = shards_usage
335            .by_shard
336            .into_iter()
337            .map(|(shard_id, shard_usage)| {
338                let event = VersionedStorageUsage::new(
339                    batch_id,
340                    Some(shard_id.to_string()),
341                    shard_usage.size_bytes(),
342                    collection_timestamp,
343                );
344                self.catalog().pack_storage_usage_update(event, Diff::ONE)
345            })
346            .collect();
347
348        let table_updates = self.builtin_table_update().execute(updates);
349
350        let internal_cmd_tx = self.internal_cmd_tx.clone();
351        let task_span = info_span!(parent: None, "coord::storage_usage_update::table_updates");
352        OpenTelemetryContext::obtain().attach_as_parent_to(&task_span);
353        task::spawn(|| "storage_usage_update_table_updates", async move {
354            table_updates.instrument(task_span).await;
355            // It is not an error for this task to be running after `internal_cmd_rx` is dropped.
356            if let Err(e) = internal_cmd_tx.send(Message::StorageUsageSchedule) {
357                warn!("internal_cmd_rx dropped before we could send: {e:?}");
358            }
359        });
360    }
361
362    #[mz_ore::instrument(level = "debug")]
363    async fn storage_usage_prune(&mut self, expired: Vec<BuiltinTableUpdate>) {
364        let fut = self.builtin_table_update().execute(expired);
365        task::spawn(|| "storage_usage_pruning_apply", async move {
366            fut.await;
367        });
368    }
369
370    pub async fn schedule_storage_usage_collection(&self) {
371        // Instead of using an `tokio::timer::Interval`, we calculate the time until the next
372        // usage collection and wait for that amount of time. This is so we can keep the intervals
373        // consistent even across restarts. If collection takes too long, it is possible that
374        // we miss an interval.
375
376        // 1) Deterministically pick some offset within the collection interval to prevent
377        // thundering herds across environments.
378        const SEED_LEN: usize = 32;
379        let mut seed = [0; SEED_LEN];
380        for (i, byte) in self
381            .catalog()
382            .state()
383            .config()
384            .environment_id
385            .organization_id()
386            .as_bytes()
387            .into_iter()
388            .take(SEED_LEN)
389            .enumerate()
390        {
391            seed[i] = *byte;
392        }
393        let storage_usage_collection_interval_ms: EpochMillis =
394            EpochMillis::try_from(self.storage_usage_collection_interval.as_millis())
395                .expect("storage usage collection interval must fit into u64");
396        let offset =
397            rngs::SmallRng::from_seed(seed).random_range(0..storage_usage_collection_interval_ms);
398        let now_ts: EpochMillis = self.peek_local_write_ts().await.into();
399
400        // 2) Determine the amount of ms between now and the next collection time.
401        let previous_collection_ts =
402            (now_ts - (now_ts % storage_usage_collection_interval_ms)) + offset;
403        let next_collection_ts = if previous_collection_ts > now_ts {
404            previous_collection_ts
405        } else {
406            previous_collection_ts + storage_usage_collection_interval_ms
407        };
408        let next_collection_interval = Duration::from_millis(next_collection_ts - now_ts);
409
410        // 3) Sleep for that amount of time, then initiate another storage usage collection.
411        let internal_cmd_tx = self.internal_cmd_tx.clone();
412        task::spawn(|| "storage_usage_collection", async move {
413            tokio::time::sleep(next_collection_interval).await;
414            if internal_cmd_tx.send(Message::StorageUsageFetch).is_err() {
415                // If sending fails, the main thread has shutdown.
416            }
417        });
418    }
419
420    /// Schedules the next per-object arrangement sizes snapshot.
421    ///
422    /// Aligns each fire to an `organization_id`-seeded offset within the
423    /// interval so collections stay consistent across restarts and don't
424    /// synchronize across environments. Sleeps are capped at `MAX_SLEEP`,
425    /// so dyncfg changes (interval edits or the `0s` disable sentinel) take
426    /// effect within one cap rather than after the full interval.
427    pub fn schedule_arrangement_sizes_collection(&self) {
428        const MAX_SLEEP: Duration = Duration::from_secs(60);
429
430        let interval_duration =
431            mz_adapter_types::dyncfgs::ARRANGEMENT_SIZE_HISTORY_COLLECTION_INTERVAL
432                .get(self.catalog().system_config().dyncfgs());
433
434        // `0s` disables collection. Keep polling so re-enabling takes effect
435        // within `MAX_SLEEP` rather than requiring an envd restart.
436        if interval_duration.is_zero() {
437            let internal_cmd_tx = self.internal_cmd_tx.clone();
438            task::spawn(|| "arrangement_sizes_collection_disabled", async move {
439                tokio::time::sleep(MAX_SLEEP).await;
440                let _ = internal_cmd_tx.send(Message::ArrangementSizesSchedule);
441            });
442            return;
443        }
444
445        const SEED_LEN: usize = 32;
446        let mut seed = [0; SEED_LEN];
447        for (i, byte) in self
448            .catalog()
449            .state()
450            .config()
451            .environment_id
452            .organization_id()
453            .as_bytes()
454            .into_iter()
455            .take(SEED_LEN)
456            .enumerate()
457        {
458            seed[i] = *byte;
459        }
460        let interval_ms: EpochMillis = EpochMillis::try_from(interval_duration.as_millis())
461            .expect("arrangement_size_history_collection_interval must fit into u64");
462        // `rand::random_range` panics on an empty range.
463        let interval_ms = interval_ms.max(1);
464        let offset = rngs::SmallRng::from_seed(seed).random_range(0..interval_ms);
465
466        // The oracle peek is a network round trip with unbounded tail latency,
467        // so it must not run on the coordinator loop.
468        let oracle = self.get_local_timestamp_oracle();
469        let internal_cmd_tx = self.internal_cmd_tx.clone();
470        task::spawn(|| "arrangement_sizes_collection", async move {
471            let now_ts: EpochMillis = oracle.peek_write_ts().await.into();
472
473            let previous_collection_ts = (now_ts - (now_ts % interval_ms)) + offset;
474            let next_collection_ts = if previous_collection_ts > now_ts {
475                previous_collection_ts
476            } else {
477                previous_collection_ts + interval_ms
478            };
479            let sleep_for = Duration::from_millis(next_collection_ts - now_ts);
480
481            // Within one cap of the next fire we sleep the remainder and
482            // snapshot; further out we sleep the cap and re-enter so a dyncfg
483            // change is picked up before committing to a long sleep.
484            let (capped_sleep, fire_snapshot) = if sleep_for <= MAX_SLEEP {
485                (sleep_for, true)
486            } else {
487                (MAX_SLEEP, false)
488            };
489
490            tokio::time::sleep(capped_sleep).await;
491            let msg = if fire_snapshot {
492                Message::ArrangementSizesSnapshot
493            } else {
494                Message::ArrangementSizesSchedule
495            };
496            // Send is best-effort: if the coordinator is shutting down, drop.
497            let _ = internal_cmd_tx.send(msg);
498        });
499    }
500
501    /// Kicks off a snapshot of `mz_object_arrangement_sizes` for appending to
502    /// `mz_object_arrangement_size_history`.
503    ///
504    /// The oracle read, persist reads, and row preparation are too slow for
505    /// the coordinator main loop, so they run on a spawned task. The prepared
506    /// records come back as [`Message::ArrangementSizesWrite`] and are
507    /// appended by [`Coordinator::arrangement_sizes_write`], which also
508    /// reschedules the next collection. An empty or failed snapshot
509    /// reschedules directly.
510    ///
511    /// Rows from replicas without fresh introspection data are excluded, so
512    /// sizes predating an environmentd or replica restart are not recorded.
513    /// See [`Coordinator::fresh_introspection_replicas`].
514    #[mz_ore::instrument(level = "debug")]
515    fn arrangement_sizes_snapshot(&self) {
516        // Builtin collections are not writable in read-only mode. Skip the
517        // cycle but keep rescheduling, mirroring `storage_usage_fetch`, so
518        // collection stays alive regardless of how the coordinator leaves
519        // read-only mode. The transition is one-way, so
520        // `arrangement_sizes_write` needs no check of its own.
521        if self.controller.read_only() {
522            self.schedule_arrangement_sizes_collection();
523            return;
524        }
525
526        let fresh_size_replicas = self.fresh_introspection_replicas(
527            IntrospectionType::ComputeObjectArrangementSizes,
528            ARRANGEMENT_SIZES_FRESHNESS_MARGIN,
529        );
530        let fresh_hydration_replicas = self.fresh_introspection_replicas(
531            IntrospectionType::ComputeHydrationTimes,
532            ARRANGEMENT_SIZES_FRESHNESS_MARGIN,
533        );
534        if fresh_size_replicas.is_empty() {
535            // No replica has reported sizes in this process yet, so the live
536            // collection contains only stale rows (or none). Skip the cycle.
537            self.schedule_arrangement_sizes_collection();
538            return;
539        }
540
541        let live_item_id = self.catalog().resolve_builtin_storage_collection(
542            &mz_catalog::builtin::MZ_OBJECT_ARRANGEMENT_SIZES_UNIFIED,
543        );
544        let live_global_id = self.catalog.get_entry(&live_item_id).latest_global_id();
545        let hydration_item_id = self
546            .catalog()
547            .resolve_builtin_storage_collection(&mz_catalog::builtin::MZ_COMPUTE_HYDRATION_TIMES);
548        let hydration_global_id = self
549            .catalog
550            .get_entry(&hydration_item_id)
551            .latest_global_id();
552
553        let oracle = self.get_local_timestamp_oracle();
554        let storage_collections = Arc::clone(&self.controller.storage_collections);
555        let collection_metric = self
556            .metrics
557            .arrangement_sizes_collection_time_seconds
558            .clone();
559        let internal_cmd_tx = self.internal_cmd_tx.clone();
560
561        task::spawn(|| "arrangement_sizes_snapshot", async move {
562            let collection_metric_timer = collection_metric.start_timer();
563
564            // No read hold is taken, so the reads rely on both collections
565            // being retained-metrics objects, whose since lags the upper by
566            // `metrics_retention` rather than tracking it closely. If the
567            // since still overtakes `read_ts`, the snapshot fails, and the
568            // cycle is skipped and retried at the next interval.
569            let read_ts = oracle.read_ts().await;
570            let live_snapshot = match storage_collections.snapshot(live_global_id, read_ts).await {
571                Ok(s) => s,
572                Err(e) => {
573                    // Unreachable short of a read-policy bug or catalog
574                    // corruption, so be loud, but degrade to a skipped cycle
575                    // in production.
576                    soft_panic_or_log!("arrangement sizes snapshot failed: {e:?}");
577                    let _ = internal_cmd_tx.send(Message::ArrangementSizesSchedule);
578                    return;
579                }
580            };
581            let hydration_snapshot = match storage_collections
582                .snapshot(hydration_global_id, read_ts)
583                .await
584            {
585                Ok(s) => s,
586                Err(e) => {
587                    soft_panic_or_log!("arrangement sizes hydration snapshot failed: {e:?}");
588                    let _ = internal_cmd_tx.send(Message::ArrangementSizesSchedule);
589                    return;
590                }
591            };
592
593            let records = arrangement_sizes_records(
594                live_snapshot,
595                hydration_snapshot,
596                &fresh_size_replicas,
597                &fresh_hydration_replicas,
598            );
599            collection_metric_timer.observe_duration();
600
601            let msg = if records.is_empty() {
602                Message::ArrangementSizesSchedule
603            } else {
604                // `collection_ts` is the snapshot's read timestamp, the state
605                // the rows describe. Stamps strictly increase within a process,
606                // because the next snapshot is only scheduled after this append
607                // applies, and across restarts via the oracle. This assumes a
608                // single writer, which fencing ensures.
609                Message::ArrangementSizesWrite {
610                    records,
611                    collection_ts: read_ts.into(),
612                }
613            };
614            // It is not an error for this task to outlive `internal_cmd_rx`.
615            let _ = internal_cmd_tx.send(msg);
616        });
617    }
618
619    /// Appends prepared snapshot records to
620    /// `mz_object_arrangement_size_history`, stamped with the snapshot's
621    /// `collection_ts`. Reschedules the next collection once the append
622    /// completes.
623    #[mz_ore::instrument(level = "debug")]
624    fn arrangement_sizes_write(
625        &mut self,
626        records: Vec<ArrangementSizeRecord>,
627        collection_ts: EpochMillis,
628    ) {
629        // Freshness may have been invalidated while the snapshot task ran,
630        // e.g. by a cluster event reporting a replica offline. Revalidate so
631        // records prepared from a now-untrusted replica's data are dropped.
632        let fresh_size_replicas = self.fresh_introspection_replicas(
633            IntrospectionType::ComputeObjectArrangementSizes,
634            ARRANGEMENT_SIZES_FRESHNESS_MARGIN,
635        );
636        let records: Vec<_> = records
637            .into_iter()
638            .filter(|record| fresh_size_replicas.contains(&record.replica_id))
639            .collect();
640        if records.is_empty() {
641            self.schedule_arrangement_sizes_collection();
642            return;
643        }
644
645        let collection_datum = Datum::TimestampTz(
646            mz_ore::now::to_datetime(collection_ts)
647                .try_into()
648                .expect("collection_timestamp must fit into TimestampTz"),
649        );
650
651        let history_item_id = self
652            .catalog()
653            .resolve_builtin_table(&mz_catalog::builtin::MZ_OBJECT_ARRANGEMENT_SIZE_HISTORY);
654
655        let updates: Vec<_> = records
656            .into_iter()
657            .map(|record| {
658                let row = Row::pack_slice(&[
659                    Datum::String(&record.replica_id),
660                    Datum::String(&record.object_id),
661                    Datum::Int64(record.size),
662                    collection_datum,
663                    Datum::from(record.hydration_complete),
664                ]);
665                BuiltinTableUpdate::row(history_item_id, row, Diff::ONE)
666            })
667            .collect();
668
669        let row_count = updates.len();
670        self.metrics
671            .arrangement_sizes_rows_written
672            .inc_by(u64::cast_from(row_count));
673
674        // TODO(arrangement-sizes): when the writeable-catalog-server plumbing
675        // in https://github.com/MaterializeInc/materialize/pull/35436 lands,
676        // append directly on `mz_catalog_server` instead of going through
677        // the environmentd builtin-table-update path.
678        let fut = self.builtin_table_update().execute(updates);
679        let internal_cmd_tx = self.internal_cmd_tx.clone();
680        let task_span = info_span!(parent: None, "coord::arrangement_sizes_write::table_updates");
681        OpenTelemetryContext::obtain().attach_as_parent_to(&task_span);
682        task::spawn(|| "arrangement_sizes_write_table_updates", async move {
683            fut.instrument(task_span).await;
684            if let Err(e) = internal_cmd_tx.send(Message::ArrangementSizesSchedule) {
685                warn!("internal_cmd_rx dropped before we could send: {e:?}");
686            }
687        });
688
689        tracing::debug!(
690            "appended {row_count} rows to mz_object_arrangement_size_history at ts {collection_ts}"
691        );
692    }
693
694    #[mz_ore::instrument(level = "debug")]
695    fn arrangement_sizes_prune(&mut self, expired: Vec<BuiltinTableUpdate>) {
696        let fut = self.builtin_table_update().execute(expired);
697        task::spawn(|| "arrangement_sizes_pruning_apply", async move {
698            fut.await;
699        });
700    }
701
702    #[mz_ore::instrument(level = "debug")]
703    async fn message_command(&mut self, cmd: Command) {
704        self.handle_command(cmd).await;
705    }
706
707    #[mz_ore::instrument(level = "debug")]
708    async fn message_controller(&mut self, message: ControllerResponse) {
709        event!(Level::TRACE, message = format!("{:?}", message));
710        match message {
711            ControllerResponse::PeekNotification(uuid, _, _) => {
712                // The adapter issues every peek with a lifecycle, which
713                // receives the notification in place of the coordinator.
714                soft_panic_or_log!("unexpected notification for peek {uuid}");
715            }
716            ControllerResponse::SubscribeResponse(sink_id, response) => {
717                if let Some(ActiveComputeSink::Subscribe(active_subscribe)) =
718                    self.active_compute_sinks.get_mut(&sink_id)
719                {
720                    let finished = active_subscribe.process_response(response);
721                    // Read the backlog into a `Copy` local so the mutable borrow
722                    // of `active_subscribe` (and the accounting lock) ends before
723                    // we call `self.retire_compute_sinks`. The producer runs on
724                    // this loop, so it cannot block on a slow client. Instead we
725                    // bound the backlog here and retire the subscribe once it
726                    // exceeds the budget.
727                    //
728                    // The backlog excludes the message the client is currently
729                    // draining, so a client working through a single large batch
730                    // (e.g. the initial snapshot) is never retired for it.
731                    let buffered_bytes = active_subscribe
732                        .backlog_accounting
733                        .lock()
734                        .expect("subscribe backlog accounting poisoned")
735                        .backlog_size();
736                    let max_buffered_bytes = active_subscribe.max_buffered_bytes;
737
738                    let reason = if finished {
739                        Some(ActiveComputeSinkRetireReason::Finished)
740                    } else if buffered_bytes > max_buffered_bytes {
741                        Some(ActiveComputeSinkRetireReason::BufferExceeded {
742                            buffered_bytes,
743                            max_buffered_bytes,
744                        })
745                    } else {
746                        None
747                    };
748                    if let Some(reason) = reason {
749                        let retire_notify = self
750                            .retire_compute_sinks(btreemap! {
751                                sink_id => reason,
752                            })
753                            .await;
754                        // `retire_compute_sinks` waits before sending the terminal
755                        // SUBSCRIBE response. There is no separate statement response here.
756                        drop(retire_notify);
757                    }
758
759                    soft_assert_or_log!(
760                        !self.introspection_subscribes.contains_key(&sink_id),
761                        "`sink_id` {sink_id} unexpectedly found in both `active_subscribes` \
762                         and `introspection_subscribes`",
763                    );
764                } else if self.introspection_subscribes.contains_key(&sink_id) {
765                    self.handle_introspection_subscribe_batch(sink_id, response)
766                        .await;
767                } else {
768                    // Cancellation may cause us to receive responses for subscribes no longer
769                    // tracked, so we quietly ignore them.
770                }
771            }
772            ControllerResponse::CopyToResponse(sink_id, response) => {
773                match self.drop_compute_sink(sink_id).await {
774                    Some((ActiveComputeSink::CopyTo(active_copy_to), _write_notify)) => {
775                        active_copy_to.retire_with_response(response);
776                    }
777                    _ => {
778                        // Cancellation may cause us to receive responses for subscribes no longer
779                        // tracked, so we quietly ignore them.
780                    }
781                }
782            }
783            ControllerResponse::WatchSetFinished(ws_ids) => {
784                let now = self.now();
785                for ws_id in ws_ids {
786                    let Some((conn_id, rsp)) = self.installed_watch_sets.remove(&ws_id) else {
787                        continue;
788                    };
789                    self.connection_watch_sets
790                        .get_mut(&conn_id)
791                        .expect("corrupted coordinator state: unknown connection id")
792                        .remove(&ws_id);
793                    if self.connection_watch_sets[&conn_id].is_empty() {
794                        self.connection_watch_sets.remove(&conn_id);
795                    }
796
797                    match rsp {
798                        WatchSetResponse::StatementDependenciesReady(id, ev) => {
799                            self.record_statement_lifecycle_event(&id, &ev, now);
800                        }
801                        WatchSetResponse::AlterSinkReady(ctx) => {
802                            self.sequence_alter_sink_finish(ctx).await;
803                        }
804                        WatchSetResponse::AlterMaterializedViewReady(ctx) => {
805                            self.sequence_alter_materialized_view_apply_replacement_finish(ctx)
806                                .await;
807                        }
808                    }
809                }
810            }
811        }
812    }
813
814    #[mz_ore::instrument(level = "debug")]
815    async fn message_purified_statement_ready(
816        &mut self,
817        PurifiedStatementReady {
818            ctx,
819            result,
820            params,
821            mut plan_validity,
822            original_stmt,
823            otel_ctx,
824        }: PurifiedStatementReady,
825    ) {
826        otel_ctx.attach_as_parent();
827
828        // Ensure that all dependencies still exist after purification, as a
829        // `DROP CONNECTION` or other `DROP` may have sneaked in. If any have gone missing, we
830        // repurify the original statement. This will either produce a nice
831        // "unknown connector" error, or pick up a new connector that has
832        // replaced the dropped connector.
833        //
834        // n.b. an `ALTER CONNECTION` occurring during purification is OK
835        // because we always look up/populate a connection's state after
836        // committing to the catalog, so are guaranteed to see the connection's
837        // most recent version.
838        if plan_validity.check(self.catalog()).is_err() {
839            self.handle_execute_inner(original_stmt, params, ctx).await;
840            return;
841        }
842
843        let purified_statement = match result {
844            Ok(ok) => ok,
845            Err(e) => return ctx.retire(Err(e)),
846        };
847
848        let plan = match purified_statement {
849            PurifiedStatement::PurifiedCreateSource { .. }
850            | PurifiedStatement::PurifiedAlterSourceAddSubsources { .. }
851            | PurifiedStatement::PurifiedAlterSourceRefreshReferences { .. }
852            | PurifiedStatement::PurifiedCreateTableFromSource { .. } => {
853                let msg = "source preparation must execute as a catalog command";
854                soft_panic_or_log!("{msg}");
855                Err(AdapterError::Internal(msg.into()))
856            }
857            o @ (PurifiedStatement::PurifiedAlterSource { .. }
858            | PurifiedStatement::PurifiedCreateSink(..)) => {
859                // Unify these into a `Statement`.
860                let stmt = match o {
861                    PurifiedStatement::PurifiedAlterSource { alter_source_stmt } => {
862                        Statement::AlterSource(alter_source_stmt)
863                    }
864                    PurifiedStatement::PurifiedCreateSink(stmt) => Statement::CreateSink(stmt),
865                    PurifiedStatement::PurifiedCreateSource { .. }
866                    | PurifiedStatement::PurifiedCreateTableFromSource { .. }
867                    | PurifiedStatement::PurifiedAlterSourceAddSubsources { .. }
868                    | PurifiedStatement::PurifiedAlterSourceRefreshReferences { .. } => {
869                        unreachable!("not part of exterior match stmt")
870                    }
871                };
872
873                // Determine all dependencies, not just those in the statement
874                // itself.
875                let catalog = self.catalog().for_session(ctx.session());
876                let resolved_ids = mz_sql::names::visit_dependencies(&catalog, &stmt);
877                self.plan_statement(ctx.session(), stmt, &params, &resolved_ids)
878                    .map(|(plan, sql_impl_ids)| (plan, resolved_ids, sql_impl_ids))
879            }
880        };
881
882        match plan {
883            Ok((plan, resolved_ids, sql_impl_ids)) => {
884                self.sequence_plan(ctx, plan, resolved_ids, sql_impl_ids)
885                    .await
886            }
887            Err(e) => ctx.retire(Err(e)),
888        }
889    }
890
891    #[mz_ore::instrument(level = "debug")]
892    async fn message_cluster_event(&mut self, event: ClusterEvent) {
893        event!(Level::TRACE, event = format!("{:?}", event));
894
895        if let Some(segment_client) = &self.segment_client {
896            let env_id = &self.catalog().config().environment_id;
897            let mut properties = json!({
898                "cluster_id": event.cluster_id.to_string(),
899                "replica_id": event.replica_id.to_string(),
900                "process_id": event.process_id,
901                "status": event.status.as_kebab_case_str(),
902            });
903            match event.status {
904                ClusterStatus::Online => (),
905                ClusterStatus::Offline(reason) => {
906                    let properties = match &mut properties {
907                        serde_json::Value::Object(map) => map,
908                        _ => unreachable!(),
909                    };
910                    properties.insert(
911                        "reason".into(),
912                        json!(reason.display_or("unknown").to_string()),
913                    );
914                }
915            };
916            segment_client.environment_track(
917                env_id,
918                "Cluster Changed Status",
919                properties,
920                EventDetails {
921                    timestamp: Some(event.time),
922                    ..Default::default()
923                },
924            );
925        }
926
927        // It is possible that we receive a status update for a replica that has
928        // already been dropped from the catalog. Just ignore these events.
929        let Some(replica_statuses) = self
930            .cluster_replica_statuses
931            .try_get_cluster_replica_statuses(event.cluster_id, event.replica_id)
932        else {
933            return;
934        };
935
936        let old_process_status = &replica_statuses[&event.process_id];
937        let status_changed = event.status != old_process_status.status;
938        let restart_count_changed = event.restart_count != old_process_status.restart_count;
939
940        // We mirror the restart count in memory even when only it changes (and the
941        // status stays the same), so the 0dt caught-up check can detect replica
942        // restarts it would otherwise miss by only sampling the status. The status
943        // history and the status-changed notice are keyed on the status itself, so
944        // we only touch those when the status actually changes.
945        //
946        // NOTE: The 0dt stability gate detects flaps by watching a process's
947        // status-change `time` advance between checks. That only works because we
948        // freeze `time` on no-op events, i.e. we return early here instead of
949        // rewriting the record when neither the status nor the restart count
950        // changed.
951        if !status_changed && !restart_count_changed {
952            return;
953        }
954
955        if status_changed && !self.controller.read_only() {
956            let offline_reason = match event.status {
957                ClusterStatus::Online => None,
958                ClusterStatus::Offline(None) => None,
959                ClusterStatus::Offline(Some(reason)) => Some(reason.to_string()),
960            };
961            let row = Row::pack_slice(&[
962                Datum::String(&event.replica_id.to_string()),
963                Datum::UInt64(event.process_id),
964                Datum::String(event.status.as_kebab_case_str()),
965                Datum::from(offline_reason.as_deref()),
966                Datum::TimestampTz(event.time.try_into().expect("must fit")),
967            ]);
968            self.controller.storage.append_introspection_updates(
969                IntrospectionType::ReplicaStatusHistory,
970                vec![(row, Diff::ONE)],
971            );
972        }
973
974        // Capture the rolled-up replica status before the update so we can tell
975        // whether the user-visible status changed. Only needed for the notice.
976        let old_replica_status = status_changed
977            .then(|| ClusterReplicaStatuses::cluster_replica_status(replica_statuses));
978
979        let new_process_status = ClusterReplicaProcessStatus {
980            status: event.status,
981            restart_count: event.restart_count,
982            time: event.time,
983        };
984        self.cluster_replica_statuses.ensure_cluster_status(
985            event.cluster_id,
986            event.replica_id,
987            event.process_id,
988            new_process_status,
989        );
990
991        // The replica's introspection subscribes may keep serving data written
992        // for its previous incarnation until their failure responses are
993        // processed. Invalidate freshness eagerly so consumers like the
994        // arrangement sizes history don't record that data as current.
995        if !matches!(event.status, ClusterStatus::Online) || restart_count_changed {
996            self.invalidate_introspection_freshness(event.replica_id);
997        }
998
999        if let Some(old_replica_status) = old_replica_status {
1000            let cluster = self.catalog().get_cluster(event.cluster_id);
1001            let replica = cluster.replica(event.replica_id).expect("Replica exists");
1002            let new_replica_status = self
1003                .cluster_replica_statuses
1004                .get_cluster_replica_status(event.cluster_id, event.replica_id);
1005
1006            if old_replica_status != new_replica_status {
1007                let notifier = self.broadcast_notice_tx();
1008                let notice = AdapterNotice::ClusterReplicaStatusChanged {
1009                    cluster: cluster.name.clone(),
1010                    replica: replica.name.clone(),
1011                    status: new_replica_status,
1012                    time: event.time,
1013                };
1014                notifier(notice);
1015            }
1016        }
1017    }
1018
1019    /// Retires pending local-timeline reads at or below `applied_ts`.
1020    fn retire_local_reads_linearized_by(&mut self, applied_ts: Timestamp) {
1021        if self.pending_linearize_read_txns.is_empty() {
1022            return;
1023        }
1024        let now = Instant::now();
1025        let (ready_txns, pending_txns) = std::mem::take(&mut self.pending_linearize_read_txns)
1026            .into_iter()
1027            .partition::<BTreeMap<_, _>, _>(|(_conn_id, read_txn)| {
1028                read_txn.linearized_by(&Timeline::EpochMilliseconds, &applied_ts)
1029            });
1030        self.pending_linearize_read_txns = pending_txns;
1031        for ready_txn in ready_txns.into_values() {
1032            ready_txn.finish_with_metrics(&self.metrics, now);
1033        }
1034    }
1035
1036    #[mz_ore::instrument(level = "debug")]
1037    /// Linearizes sending the results of a read transaction by,
1038    ///   1. Holding back any results that were executed at some point in the future, until the
1039    ///   containing timeline has advanced to that point in the future.
1040    ///   2. Confirming that we are still the current leader before sending results to the client.
1041    async fn message_linearize_reads(&mut self) {
1042        let mut shortest_wait = Duration::MAX;
1043        let mut ready_txns = Vec::new();
1044
1045        // Cache for `TimestampOracle::read_ts` calls. These are somewhat
1046        // expensive so we cache the value. This is correct since all we're
1047        // risking is being too conservative. We will not accidentally "release"
1048        // a result too early.
1049        let mut cached_oracle_ts = BTreeMap::new();
1050
1051        for (conn_id, mut read_txn) in std::mem::take(&mut self.pending_linearize_read_txns) {
1052            if let Some((timeline, chosen_ts)) = read_txn.timestamp_to_linearize() {
1053                // See what the oracle timestamp is now and delay when needed.
1054                let current_oracle_ts = cached_oracle_ts.entry(timeline.clone());
1055                let current_oracle_ts = match current_oracle_ts {
1056                    btree_map::Entry::Vacant(entry) => {
1057                        let timestamp_oracle = self.get_timestamp_oracle(timeline);
1058                        let read_ts = timestamp_oracle.read_ts().await;
1059                        entry.insert(read_ts.clone());
1060                        read_ts
1061                    }
1062                    btree_map::Entry::Occupied(entry) => entry.get().clone(),
1063                };
1064
1065                if *chosen_ts <= current_oracle_ts {
1066                    ready_txns.push(read_txn);
1067                } else {
1068                    let wait =
1069                        Duration::from_millis(chosen_ts.saturating_sub(current_oracle_ts).into());
1070                    if wait < shortest_wait {
1071                        shortest_wait = wait;
1072                    }
1073                    read_txn.num_requeues += 1;
1074                    self.pending_linearize_read_txns.insert(conn_id, read_txn);
1075                }
1076            } else {
1077                ready_txns.push(read_txn);
1078            }
1079        }
1080
1081        if !ready_txns.is_empty() {
1082            // Sniff out one ctx, this is where tracing breaks down because we
1083            // process all outstanding txns as a batch here.
1084            let otel_ctx = ready_txns.first().expect("known to exist").otel_ctx.clone();
1085            let span = tracing::debug_span!("message_linearize_reads");
1086            otel_ctx.attach_as_parent_to(&span);
1087
1088            let now = Instant::now();
1089            for ready_txn in ready_txns {
1090                ready_txn.finish_with_metrics(&self.metrics, now);
1091            }
1092        }
1093
1094        if !self.pending_linearize_read_txns.is_empty() {
1095            // Cap wait time to 1s, then signal a re-check. `serve` awaits this
1096            // below group commit; see its linearize branch for why.
1097            let remaining_ms = std::cmp::min(shortest_wait, Duration::from_millis(1_000));
1098            let linearize_reads_notify = Arc::clone(&self.linearize_reads_notify);
1099            task::spawn(|| "deferred_read_txns", async move {
1100                tokio::time::sleep(remaining_ms).await;
1101                linearize_reads_notify.notify_one();
1102            });
1103        }
1104    }
1105}
1106
1107/// Builds history records from snapshots of `mz_object_arrangement_sizes` and
1108/// `mz_compute_hydration_times`.
1109///
1110/// Each `(replica_id, object_id)` pair is recorded with a
1111/// `hydration_complete` flag: `true` once the pair's initial hydration on that
1112/// replica is finished (`time_ns IS NOT NULL`), `false` while still building.
1113/// Consumers that want only stable sizes should filter
1114/// `WHERE hydration_complete`.
1115///
1116/// Rows from replicas outside `fresh_size_replicas` are dropped, and the
1117/// hydration flag is only trusted for replicas in `fresh_hydration_replicas`.
1118/// Rows for other replicas may predate an environmentd or replica restart.
1119///
1120/// Rows with a size of 0 (arrangements below the live collection's 5 MiB
1121/// quantization threshold) are not recorded.
1122fn arrangement_sizes_records(
1123    mut live_snapshot: Vec<(Row, StorageDiff)>,
1124    mut hydration_snapshot: Vec<(Row, StorageDiff)>,
1125    fresh_size_replicas: &BTreeSet<String>,
1126    fresh_hydration_replicas: &BTreeSet<String>,
1127) -> Vec<ArrangementSizeRecord> {
1128    differential_dataflow::consolidation::consolidate(&mut live_snapshot);
1129    differential_dataflow::consolidation::consolidate(&mut hydration_snapshot);
1130
1131    let mut datum_vec = mz_repr::DatumVec::new();
1132
1133    // Column positions in `mz_compute_hydration_times`.
1134    const HYDRATION_COL_REPLICA_ID: usize = 0;
1135    const HYDRATION_COL_OBJECT_ID: usize = 1;
1136    const HYDRATION_COL_TIME_NS: usize = 2;
1137    const HYDRATION_COL_COUNT: usize = 3;
1138
1139    let mut hydrated: BTreeSet<(String, String)> = BTreeSet::new();
1140    for (row, diff) in &hydration_snapshot {
1141        if *diff != 1 {
1142            continue;
1143        }
1144        let datums = datum_vec.borrow_with(row);
1145        if datums.len() < HYDRATION_COL_COUNT {
1146            continue;
1147        }
1148        if datums[HYDRATION_COL_TIME_NS].is_null() {
1149            continue;
1150        }
1151        let replica_id = datums[HYDRATION_COL_REPLICA_ID].unwrap_str();
1152        if !fresh_hydration_replicas.contains(replica_id) {
1153            continue;
1154        }
1155        hydrated.insert((
1156            replica_id.to_string(),
1157            datums[HYDRATION_COL_OBJECT_ID].unwrap_str().to_string(),
1158        ));
1159    }
1160
1161    // Column positions in `mz_object_arrangement_sizes`.
1162    const LIVE_COL_REPLICA_ID: usize = 0;
1163    const LIVE_COL_OBJECT_ID: usize = 1;
1164    const LIVE_COL_SIZE: usize = 2;
1165    const LIVE_COL_COUNT: usize = 3;
1166
1167    let mut skipped_malformed: u64 = 0;
1168    let mut skipped_null_size: u64 = 0;
1169    let mut skipped_zero_size: u64 = 0;
1170    let mut skipped_stale_replica: u64 = 0;
1171    let mut records = Vec::with_capacity(live_snapshot.len());
1172    for (row, diff) in &live_snapshot {
1173        if *diff != 1 {
1174            continue;
1175        }
1176        let datums = datum_vec.borrow_with(row);
1177        // Surface schema drift via a warn log below rather than silently
1178        // skipping entire snapshots.
1179        if datums.len() != LIVE_COL_COUNT {
1180            skipped_malformed += 1;
1181            continue;
1182        }
1183        let replica_id = datums[LIVE_COL_REPLICA_ID].unwrap_str();
1184        if !fresh_size_replicas.contains(replica_id) {
1185            skipped_stale_replica += 1;
1186            continue;
1187        }
1188        let object_id = datums[LIVE_COL_OBJECT_ID].unwrap_str();
1189        let size_datum = datums[LIVE_COL_SIZE];
1190        // The history table's `size` is non-null; fabricating zero would
1191        // be misleading, so drop.
1192        if size_datum.is_null() {
1193            skipped_null_size += 1;
1194            continue;
1195        }
1196        // A quantized size of 0 means "below 5 MiB". The live collection
1197        // keeps such rows so small objects stay visible, but recording them
1198        // every cycle would bloat the history with rows carrying no signal.
1199        if size_datum.unwrap_int64() == 0 {
1200            skipped_zero_size += 1;
1201            continue;
1202        }
1203        let hydration_complete =
1204            hydrated.contains(&(replica_id.to_string(), object_id.to_string()));
1205        records.push(ArrangementSizeRecord {
1206            replica_id: replica_id.to_string(),
1207            object_id: object_id.to_string(),
1208            size: size_datum.unwrap_int64(),
1209            hydration_complete,
1210        });
1211    }
1212    if skipped_malformed > 0 {
1213        warn!(
1214            "mz_object_arrangement_sizes schema drift: skipped {skipped_malformed} rows \
1215             with unexpected arity"
1216        );
1217    }
1218    if skipped_null_size > 0 {
1219        tracing::debug!("skipped {skipped_null_size} live rows with null size");
1220    }
1221    if skipped_zero_size > 0 {
1222        tracing::debug!("skipped {skipped_zero_size} live rows with zero size");
1223    }
1224    if skipped_stale_replica > 0 {
1225        tracing::debug!(
1226            "skipped {skipped_stale_replica} live rows from replicas without fresh \
1227             introspection data"
1228        );
1229    }
1230    records
1231}
1232
1233#[cfg(test)]
1234mod arrangement_sizes_records_tests {
1235    use std::collections::BTreeSet;
1236
1237    use mz_repr::{Datum, Row};
1238
1239    use super::arrangement_sizes_records;
1240
1241    fn live_row(replica_id: &str, object_id: &str, size: Option<i64>) -> Row {
1242        Row::pack_slice(&[
1243            Datum::String(replica_id),
1244            Datum::String(object_id),
1245            size.map_or(Datum::Null, Datum::Int64),
1246        ])
1247    }
1248
1249    fn hydration_row(replica_id: &str, object_id: &str, hydrated: bool) -> Row {
1250        Row::pack_slice(&[
1251            Datum::String(replica_id),
1252            Datum::String(object_id),
1253            if hydrated {
1254                Datum::UInt64(1)
1255            } else {
1256                Datum::Null
1257            },
1258        ])
1259    }
1260
1261    fn replicas(ids: &[&str]) -> BTreeSet<String> {
1262        ids.iter().map(|id| id.to_string()).collect()
1263    }
1264
1265    #[mz_ore::test]
1266    fn hydration_flag_per_pair() {
1267        let live = vec![
1268            (live_row("u1", "u100", Some(10)), 1),
1269            (live_row("u1", "u200", Some(20)), 1),
1270        ];
1271        let hydration = vec![
1272            (hydration_row("u1", "u100", true), 1),
1273            (hydration_row("u1", "u200", false), 1),
1274        ];
1275        let fresh = replicas(&["u1"]);
1276        let records = arrangement_sizes_records(live, hydration, &fresh, &fresh);
1277        assert_eq!(records.len(), 2);
1278        assert!(
1279            records
1280                .iter()
1281                .any(|r| r.object_id == "u100" && r.hydration_complete)
1282        );
1283        assert!(
1284            records
1285                .iter()
1286                .any(|r| r.object_id == "u200" && !r.hydration_complete)
1287        );
1288    }
1289
1290    #[mz_ore::test]
1291    fn skips_malformed_null_and_retracted() {
1292        let live = vec![
1293            // Wrong arity.
1294            (Row::pack_slice(&[Datum::String("u1")]), 1),
1295            // Null size.
1296            (live_row("u1", "u100", None), 1),
1297            // Retracted by consolidation.
1298            (live_row("u1", "u200", Some(20)), 1),
1299            (live_row("u1", "u200", Some(20)), -1),
1300            (live_row("u1", "u300", Some(30)), 1),
1301        ];
1302        let fresh = replicas(&["u1"]);
1303        let records = arrangement_sizes_records(live, Vec::new(), &fresh, &fresh);
1304        assert_eq!(records.len(), 1);
1305        assert_eq!(records[0].object_id, "u300");
1306        assert_eq!(records[0].size, 30);
1307        assert!(!records[0].hydration_complete);
1308    }
1309
1310    #[mz_ore::test]
1311    fn skips_zero_size_rows() {
1312        // Size 0 means "below the live collection's quantization threshold".
1313        // Such objects stay visible live but are not recorded in the history.
1314        let live = vec![
1315            (live_row("u1", "u100", Some(0)), 1),
1316            (live_row("u1", "u200", Some(10485760)), 1),
1317        ];
1318        let fresh = replicas(&["u1"]);
1319        let records = arrangement_sizes_records(live, Vec::new(), &fresh, &fresh);
1320        assert_eq!(records.len(), 1);
1321        assert_eq!(records[0].object_id, "u200");
1322    }
1323
1324    #[mz_ore::test]
1325    fn skips_rows_from_stale_replicas() {
1326        // u1 has fresh introspection data, u2's rows predate a restart.
1327        let live = vec![
1328            (live_row("u1", "u100", Some(10)), 1),
1329            (live_row("u2", "u100", Some(99)), 1),
1330        ];
1331        let hydration = vec![
1332            (hydration_row("u1", "u100", true), 1),
1333            (hydration_row("u2", "u100", true), 1),
1334        ];
1335        let fresh = replicas(&["u1"]);
1336        let records = arrangement_sizes_records(live, hydration, &fresh, &fresh);
1337        assert_eq!(records.len(), 1);
1338        assert_eq!(records[0].replica_id, "u1");
1339        assert!(records[0].hydration_complete);
1340    }
1341
1342    #[mz_ore::test]
1343    fn stale_hydration_data_is_not_trusted() {
1344        // u1's sizes subscribe is fresh but its hydration subscribe is not,
1345        // so its stale "hydrated" row must not mark the record complete.
1346        let live = vec![(live_row("u1", "u100", Some(10)), 1)];
1347        let hydration = vec![(hydration_row("u1", "u100", true), 1)];
1348        let records =
1349            arrangement_sizes_records(live, hydration, &replicas(&["u1"]), &replicas(&[]));
1350        assert_eq!(records.len(), 1);
1351        assert!(!records[0].hydration_complete);
1352    }
1353}