Skip to main content

feldera_types/
adapter_stats.rs

1use bytemuck::NoUninit;
2use chrono::{DateTime, SecondsFormat, Utc};
3use serde::{Deserialize, Serialize};
4use serde_json::Value as JsonValue;
5use std::collections::BTreeMap;
6use utoipa::ToSchema;
7use uuid::Uuid;
8
9use crate::{
10    checkpoint::CheckpointActivity,
11    coordination::Step,
12    memory_pressure::MemoryPressure,
13    suspend::{PermanentSuspendError, SuspendError},
14    transaction::{CommitProgressSummary, ConcurrentBootstrapPhase, TransactionId},
15};
16
17/// Pipeline state.
18#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
19#[serde(rename_all = "PascalCase")]
20pub enum PipelineState {
21    /// All input endpoints are paused (or are in the process of being paused).
22    #[default]
23    Paused,
24    /// Controller is running.
25    Running,
26    /// Controller is being terminated.
27    Terminated,
28}
29
30// Metrics for an input endpoint.
31///
32/// Serializes to match the subset of fields needed for error tracking.
33#[derive(Default, Serialize, Deserialize, Debug, Clone)]
34pub struct InputEndpointErrorMetrics {
35    pub endpoint_name: String,
36    #[serde(default)]
37    pub num_transport_errors: u64,
38    #[serde(default)]
39    pub num_parse_errors: u64,
40}
41
42/// Metrics for an output endpoint.
43///
44/// Serializes to match the subset of fields needed for error tracking.
45#[derive(Default, Serialize, Deserialize, Debug, Clone)]
46pub struct OutputEndpointErrorMetrics {
47    pub endpoint_name: String,
48    #[serde(default)]
49    pub num_encode_errors: u64,
50    #[serde(default)]
51    pub num_transport_errors: u64,
52}
53
54/// Endpoint statistics containing metrics.
55///
56/// Wraps metrics in a structure that matches the full stats API shape.
57#[derive(Serialize, Deserialize, Debug, Clone)]
58pub struct EndpointErrorStats<T> {
59    #[serde(default)]
60    pub metrics: T,
61}
62
63/// Schema definition for endpoint config that only includes the stream field.
64#[derive(Debug, Deserialize, Serialize, ToSchema)]
65pub struct ShortEndpointConfig {
66    /// The name of the stream.
67    pub stream: String,
68}
69
70/// Pipeline error statistics response from the runtime.
71///
72/// Lightweight response containing only error counts from all endpoints.
73#[derive(Serialize, Deserialize, Debug, Clone)]
74pub struct PipelineStatsErrorsResponse {
75    #[serde(default)]
76    pub inputs: Vec<EndpointErrorStats<InputEndpointErrorMetrics>>,
77    #[serde(default)]
78    pub outputs: Vec<EndpointErrorStats<OutputEndpointErrorMetrics>>,
79}
80
81// OpenAPI schema definitions for controller statistics
82// These match the serialized JSON structure from the connectors crate
83
84/// Transaction status summarized as a single value.
85#[derive(
86    Debug, Default, Copy, PartialEq, Eq, Clone, NoUninit, Serialize, Deserialize, ToSchema,
87)]
88#[repr(u8)]
89pub enum TransactionStatus {
90    #[default]
91    NoTransaction,
92    TransactionInProgress,
93    CommitInProgress,
94}
95
96/// Transaction phase.
97#[derive(Clone, Copy, PartialEq, Eq, Debug, Deserialize, Serialize, ToSchema)]
98#[serde(rename_all = "PascalCase")]
99#[schema(as = TransactionPhase)]
100pub enum ExternalTransactionPhase {
101    /// Transaction is in progress.
102    Started,
103    /// Transaction has been committed.
104    Committed,
105}
106
107/// Connector transaction phase with debugging label.
108#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize, ToSchema)]
109#[schema(as = ConnectorTransactionPhase)]
110pub struct ExternalConnectorTransactionPhase {
111    /// Current phase of the transaction.
112    #[schema(value_type = TransactionPhase)]
113    pub phase: ExternalTransactionPhase,
114    /// Optional label for debugging.
115    pub label: Option<String>,
116}
117
118/// Information about entities that initiated the current transaction.
119#[derive(Clone, Default, Debug, Deserialize, Serialize, ToSchema)]
120#[schema(as = TransactionInitiators)]
121pub struct ExternalTransactionInitiators {
122    /// ID assigned to the transaction (None if no transaction is in progress).
123    #[schema(value_type = Option<i64>)]
124    pub transaction_id: Option<TransactionId>,
125    /// Transaction phase initiated by the API.
126    #[schema(value_type = Option<TransactionPhase>)]
127    pub initiated_by_api: Option<ExternalTransactionPhase>,
128    /// Transaction phases initiated by connectors, indexed by endpoint name.
129    #[schema(value_type = BTreeMap<String, ConnectorTransactionPhase>)]
130    pub initiated_by_connectors: BTreeMap<String, ExternalConnectorTransactionPhase>,
131}
132
133/// A watermark that has been fully processed by the pipeline.
134#[derive(Clone, Debug, Deserialize, Serialize, ToSchema)]
135pub struct CompletedWatermark {
136    /// Metadata that describes the position in the input stream (e.g., Kafka partition/offset pairs).
137    #[schema(value_type = Object)]
138    pub metadata: JsonValue,
139    /// Timestamp when the data was ingested from the wire.
140    #[serde(serialize_with = "serialize_timestamp_micros")]
141    pub ingested_at: DateTime<Utc>,
142    /// Timestamp when the data was processed by the circuit.
143    #[serde(serialize_with = "serialize_timestamp_micros")]
144    pub processed_at: DateTime<Utc>,
145    /// Timestamp when all outputs produced from this input have been pushed to all output endpoints.
146    #[serde(serialize_with = "serialize_timestamp_micros")]
147    pub completed_at: DateTime<Utc>,
148}
149
150#[derive(Debug, Default, Deserialize, Serialize, ToSchema, Clone)]
151pub enum ConnectorHealthStatus {
152    #[default]
153    Healthy,
154    Unhealthy,
155}
156
157#[derive(Debug, Default, Deserialize, Serialize, ToSchema, Clone)]
158pub struct ConnectorHealth {
159    pub status: ConnectorHealthStatus,
160    pub description: Option<String>,
161}
162
163impl ConnectorHealth {
164    pub fn healthy() -> Self {
165        Self {
166            status: ConnectorHealthStatus::Healthy,
167            description: None,
168        }
169    }
170    pub fn unhealthy(description: &str) -> Self {
171        Self {
172            status: ConnectorHealthStatus::Unhealthy,
173            description: Some(description.to_string()),
174        }
175    }
176}
177
178#[derive(Debug, Default, Deserialize, Serialize, ToSchema, Clone, PartialEq, Eq)]
179pub struct ConnectorError {
180    /// Timestamp when the error occurred, serialized as RFC3339 with microseconds.
181    #[serde(serialize_with = "serialize_timestamp_micros")]
182    pub timestamp: DateTime<Utc>,
183
184    /// Sequence number of the error.
185    ///
186    /// The client can use this field to detect gaps in the error list reported
187    /// by the pipeline. When the connector reports a large number of errors, the
188    /// pipeline will only preserve and report the most recent errors of each kind.
189    pub index: u64,
190
191    /// Optional tag for the error.
192    ///
193    /// The tag is used to group errors by their type.
194    pub tag: Option<String>,
195
196    /// Error message.
197    pub message: String,
198}
199
200/// Performance metrics for an input endpoint.
201#[derive(Debug, Default, Deserialize, Serialize, ToSchema)]
202#[schema(as = InputEndpointMetrics)]
203pub struct ExternalInputEndpointMetrics {
204    /// Total bytes pushed to the endpoint since it was created.
205    pub total_bytes: u64,
206    /// Total records pushed to the endpoint since it was created.
207    pub total_records: u64,
208    /// Number of records currently buffered by the endpoint (not yet consumed by the circuit).
209    pub buffered_records: u64,
210    /// Number of bytes currently buffered by the endpoint (not yet consumed by the circuit).
211    pub buffered_bytes: u64,
212    /// Number of records in the most recent non-empty batch that the endpoint
213    /// gave to the circuit.
214    ///
215    /// For a connector that runs on more than one host, this is the sum of
216    /// each host's latest non-empty batch.  These batches can come from
217    /// different steps, for example when a host has been idle.
218    #[serde(default)]
219    pub latest_batch_records: u64,
220    /// Number of bytes in the most recent non-empty batch that the endpoint
221    /// gave to the circuit.
222    ///
223    /// For a connector that runs on more than one host, this is the sum of
224    /// each host's latest non-empty batch.  These batches can come from
225    /// different steps, for example when a host has been idle.
226    #[serde(default)]
227    pub latest_batch_bytes: u64,
228    /// Number of transport errors.
229    pub num_transport_errors: u64,
230    /// Number of parse errors.
231    pub num_parse_errors: u64,
232    /// True if end-of-input has been signaled.
233    pub end_of_input: bool,
234    /// 99th percentile processing latency (from ingesting a batch to finishing processing it) in microseconds.
235    ///
236    /// The time from ingesting a batch of records off the wire
237    /// to the circuit finishing processing them,
238    /// covering parsing, queuing, and the circuit step.
239    ///
240    /// Does not account for completion latency.
241    ///
242    /// Taken over the endpoint's sliding histogram, which holds the 10,000 most
243    /// recent samples spanning at most 10 minutes, whichever bound is reached
244    /// first. One sample is recorded per completed batch. An endpoint that stops
245    /// ingesting keeps reporting its last known latency instead of dropping to
246    /// `None`.
247    ///
248    /// `None` until the endpoint records its first sample.
249    #[serde(default, skip_serializing_if = "Option::is_none")]
250    pub processing_latency_p99_micros: Option<u64>,
251}
252
253impl ExternalInputEndpointMetrics {
254    /// Adds `other`, which another host reports for its part of the same
255    /// distributed connector, to these metrics.
256    pub fn merge(&mut self, other: &Self) {
257        // Naming every field makes a new field a compile error until it is
258        // merged here.
259        let &Self {
260            total_bytes,
261            total_records,
262            buffered_records,
263            buffered_bytes,
264            latest_batch_records,
265            latest_batch_bytes,
266            num_transport_errors,
267            num_parse_errors,
268            end_of_input,
269            processing_latency_p99_micros,
270        } = other;
271        self.total_bytes += total_bytes;
272        self.total_records += total_records;
273        self.buffered_records += buffered_records;
274        self.buffered_bytes += buffered_bytes;
275        // Each host gives its own batch to the step, so add them.
276        self.latest_batch_records += latest_batch_records;
277        self.latest_batch_bytes += latest_batch_bytes;
278        self.num_transport_errors += num_transport_errors;
279        self.num_parse_errors += num_parse_errors;
280        self.end_of_input &= end_of_input;
281        // The worst host's latency bounds the connector's latency.
282        self.processing_latency_p99_micros = self
283            .processing_latency_p99_micros
284            .max(processing_latency_p99_micros);
285    }
286}
287
288/// Input endpoint status information.
289#[derive(Debug, Serialize, Deserialize, ToSchema)]
290#[schema(as = InputEndpointStatus)]
291pub struct ExternalInputEndpointStatus {
292    /// Endpoint name.
293    pub endpoint_name: String,
294    /// Endpoint configuration.
295    pub config: ShortEndpointConfig,
296    /// Performance metrics.
297    #[schema(value_type = InputEndpointMetrics)]
298    pub metrics: ExternalInputEndpointMetrics,
299    /// The first fatal error that occurred at the endpoint.
300    pub fatal_error: Option<String>,
301    /// Recent parse errors on this endpoint.
302    #[serde(default, skip_serializing_if = "Option::is_none")]
303    pub parse_errors: Option<Vec<ConnectorError>>,
304    /// Recent transport errors on this endpoint.
305    #[serde(default, skip_serializing_if = "Option::is_none")]
306    pub transport_errors: Option<Vec<ConnectorError>>,
307    /// Health status of the connector.
308    #[serde(default)]
309    pub health: Option<ConnectorHealth>,
310    /// Endpoint has been paused by the user.  A distributed connector in a
311    /// multihost pipeline is paused only if it is paused on every host.
312    pub paused: bool,
313    /// Endpoint is currently a barrier to checkpointing and suspend.
314    pub barrier: bool,
315    /// The latest completed watermark.
316    #[schema(value_type = Option<CompletedWatermark>)]
317    pub completed_frontier: Option<CompletedWatermark>,
318}
319
320/// How to combine the metadata of the completed frontiers that the hosts of a
321/// distributed input connector report (see
322/// [`ExternalInputEndpointStatus::merge`]).
323#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
324pub enum FrontierMerge {
325    /// The metadata is a position in one sequence that every host shares,
326    /// such as a table version.  The combined frontier keeps the metadata of
327    /// the host whose frontier it is.
328    Shared,
329
330    /// Each host's metadata describes only its own partitions, as an object
331    /// with arrays `partitions` and `offsets` of the same length.  The
332    /// combined metadata has every host's partitions, in order.
333    Partitioned,
334
335    /// The metadata has no known structure.  The combined frontier has no
336    /// metadata if more than one host that is not at end of input reports a
337    /// frontier.
338    #[default]
339    Opaque,
340}
341
342impl ExternalInputEndpointStatus {
343    /// Combines this status with `other`, which another host reports for its
344    /// part of the same distributed connector, into the status of the
345    /// connector as a whole.
346    ///
347    /// The combined connector is healthy, at end of input, paused, or free of
348    /// a fatal error only if every part is.  It is a barrier if any part is.
349    ///
350    /// Its completed frontier is the oldest one among the hosts that are not
351    /// at end of input, because input after that point is not complete on
352    /// that host.  A host that is not at end of input and has completed no
353    /// input yet gives no frontier.  Hosts at end of input do not hold back
354    /// the frontier; if every host is at end of input, the frontier is the
355    /// newest one.
356    ///
357    /// `frontier_merge` says how to combine the frontiers' metadata.
358    pub fn merge(&mut self, other: Self, frontier_merge: FrontierMerge) {
359        // Naming every field makes a new field a compile error until it is
360        // merged here.
361        let Self {
362            // Every host reports the same name and configuration.
363            endpoint_name: _,
364            config: _,
365            metrics,
366            fatal_error,
367            parse_errors,
368            transport_errors,
369            health,
370            paused,
371            barrier,
372            completed_frontier,
373        } = other;
374        let (a_eoi, b_eoi) = (self.metrics.end_of_input, metrics.end_of_input);
375        self.metrics.merge(&metrics);
376        if self.fatal_error.is_none() {
377            self.fatal_error = fatal_error;
378        }
379        merge_errors(&mut self.parse_errors, parse_errors);
380        merge_errors(&mut self.transport_errors, transport_errors);
381        self.health = merge_health(self.health.take(), health);
382        self.paused &= paused;
383        self.barrier |= barrier;
384        let (a, b) = (self.completed_frontier.take(), completed_frontier);
385        let several = !a_eoi && !b_eoi && a.is_some() && b.is_some();
386        // Joining with no partitions puts one host's metadata in the joined
387        // form.
388        let no_partitions = serde_json::json!({"partitions": [], "offsets": []});
389        let metadata = |f: &Option<CompletedWatermark>| {
390            f.as_ref().map_or(&no_partitions, |f| &f.metadata).clone()
391        };
392        let joined = join_partitions(&metadata(&a), &metadata(&b));
393        let oldest = |a: CompletedWatermark, b: CompletedWatermark| {
394            if b.ingested_at < a.ingested_at { b } else { a }
395        };
396        let newest = |a: CompletedWatermark, b: CompletedWatermark| {
397            if b.ingested_at > a.ingested_at { b } else { a }
398        };
399        self.completed_frontier = match (a_eoi, b_eoi) {
400            (false, false) => a.zip(b).map(|(a, b)| oldest(a, b)),
401            (false, true) => a,
402            (true, false) => b,
403            (true, true) => match (a, b) {
404                (Some(a), Some(b)) => Some(newest(a, b)),
405                (a, b) => a.or(b),
406            },
407        };
408        if let Some(frontier) = &mut self.completed_frontier {
409            match frontier_merge {
410                FrontierMerge::Shared => (),
411                FrontierMerge::Partitioned => frontier.metadata = joined,
412                FrontierMerge::Opaque => {
413                    if several {
414                        frontier.metadata = JsonValue::Null;
415                    }
416                }
417            }
418        }
419    }
420}
421
422/// Joins two [`FrontierMerge::Partitioned`] metadata values.  Returns null if
423/// either one is not an object with arrays `partitions` and `offsets` of the
424/// same length, or if they have a partition in common.
425fn join_partitions(a: &JsonValue, b: &JsonValue) -> JsonValue {
426    fn pairs(metadata: &JsonValue) -> Option<Vec<(i64, &JsonValue)>> {
427        let partitions = metadata.get("partitions")?.as_array()?;
428        let offsets = metadata.get("offsets")?.as_array()?;
429        if partitions.len() != offsets.len() {
430            return None;
431        }
432        partitions
433            .iter()
434            .zip(offsets)
435            .map(|(partition, offsets)| Some((partition.as_i64()?, offsets)))
436            .collect()
437    }
438    let (Some(a), Some(b)) = (pairs(a), pairs(b)) else {
439        return JsonValue::Null;
440    };
441    let mut joined = BTreeMap::new();
442    for (partition, offsets) in a.into_iter().chain(b) {
443        if joined.insert(partition, offsets.clone()).is_some() {
444            return JsonValue::Null;
445        }
446    }
447    let (partitions, offsets): (Vec<_>, Vec<_>) = joined.into_iter().unzip();
448    serde_json::json!({"partitions": partitions, "offsets": offsets})
449}
450
451/// Combines the health of two hosts' parts of a connector: unhealthy if either is.
452fn merge_health(a: Option<ConnectorHealth>, b: Option<ConnectorHealth>) -> Option<ConnectorHealth> {
453    match (a, b) {
454        (Some(a), Some(b)) => Some(if matches!(a.status, ConnectorHealthStatus::Unhealthy) {
455            a
456        } else {
457            b
458        }),
459        (a, b) => a.or(b),
460    }
461}
462
463/// Appends `b` to `a` and sorts the result by time, because each host numbers
464/// its own errors.
465fn merge_errors(a: &mut Option<Vec<ConnectorError>>, b: Option<Vec<ConnectorError>>) {
466    if let Some(b) = b {
467        let errors = a.get_or_insert_with(Vec::new);
468        errors.extend(b);
469        errors.sort_by_key(|error| error.timestamp);
470    }
471}
472
473/// Performance metrics for an output endpoint.
474#[derive(Debug, Default, Deserialize, Serialize, ToSchema, PartialEq, Eq, PartialOrd, Ord)]
475#[schema(as = OutputEndpointMetrics)]
476pub struct ExternalOutputEndpointMetrics {
477    /// Records sent on the underlying transport.
478    pub transmitted_records: u64,
479    /// Bytes sent on the underlying transport.
480    pub transmitted_bytes: u64,
481    /// Number of queued records.
482    pub queued_records: u64,
483    /// Number of queued batches.
484    pub queued_batches: u64,
485    /// Number of records pushed to the output buffer.
486    pub buffered_records: u64,
487    /// Number of batches in the buffer.
488    pub buffered_batches: u64,
489    /// Number of encoding errors.
490    pub num_encode_errors: u64,
491    /// Number of transport errors.
492    pub num_transport_errors: u64,
493    /// The number of input records processed by the circuit.
494    ///
495    /// This metric tracks the end-to-end progress of the pipeline: the output
496    /// of this endpoint is equal to the output of the circuit after
497    /// processing `total_processed_input_records` records.
498    ///
499    /// The counter never runs ahead of the endpoint's output. It advances to a
500    /// value `N` only once the endpoint has processed every batch derived from
501    /// the first `N` records received by the pipeline, which means transmitting
502    /// the batch, or discarding it while silent bootstrapping suppresses the
503    /// endpoint's output.
504    ///
505    /// In a multihost pipeline, `N` counts the input records that all of the
506    /// hosts received, not only the endpoint's own host.  (Each host counts
507    /// only its own input, and the coordinator adds up the hosts' counts as of
508    /// `total_processed_steps`.)  If a host runs an older version that does
509    /// not report its count to the coordinator, `N` counts only the input
510    /// records that the endpoint's own host received.
511    pub total_processed_input_records: u64,
512    /// The number of steps whose input records have been processed by the
513    /// endpoint.
514    ///
515    /// In a multihost pipeline, all of the hosts run the same steps together,
516    /// so a step number refers to the same step on every host.
517    ///
518    /// # Interpretation
519    ///
520    /// This is a count, not a step number.  If `total_processed_steps` is 0, no
521    /// steps have been processed to completion.  If `total_processed_steps >
522    /// 0`, then the last step whose input records have been processed to
523    /// completion is `total_processed_steps - 1`. A record that was ingested in
524    /// step `n` is fully processed when `total_processed_steps > n`.
525    #[schema(value_type = u64)]
526    pub total_processed_steps: Step,
527    /// Extra memory in use beyond that used for queuing records.
528    pub memory: u64,
529    /// Number of records written so far while the connector is processing a
530    /// batch of updates.  Resets to 0 after the batch is committed.
531    ///
532    /// `None` when the connector does not support batch-progress reporting.
533    #[serde(default, skip_serializing_if = "Option::is_none")]
534    pub batch_records_written: Option<u64>,
535}
536
537/// Output endpoint status information.
538#[derive(Debug, Deserialize, Serialize, ToSchema)]
539#[schema(as = OutputEndpointStatus)]
540pub struct ExternalOutputEndpointStatus {
541    /// Endpoint name.
542    pub endpoint_name: String,
543    /// Endpoint configuration.
544    pub config: ShortEndpointConfig,
545    /// Performance metrics.
546    #[schema(value_type = OutputEndpointMetrics)]
547    pub metrics: ExternalOutputEndpointMetrics,
548    /// The first fatal error that occurred at the endpoint.
549    pub fatal_error: Option<String>,
550    /// Recent encoding errors on this endpoint.
551    #[serde(default, skip_serializing_if = "Option::is_none")]
552    pub encode_errors: Option<Vec<ConnectorError>>,
553    /// Recent transport errors on this endpoint.
554    #[serde(default, skip_serializing_if = "Option::is_none")]
555    pub transport_errors: Option<Vec<ConnectorError>>,
556    /// Health status of the connector.
557    #[serde(default)]
558    pub health: Option<ConnectorHealth>,
559    /// Endpoint has been paused by the user.
560    ///
561    /// A paused output endpoint discards the output it receives instead of
562    /// sending it to its sink.
563    #[serde(default)]
564    pub paused: bool,
565}
566
567impl ExternalOutputEndpointMetrics {
568    /// Adds `other`, which another host reports for its part of the same
569    /// distributed connector, to these metrics.
570    ///
571    /// Counts add up.  The connector has processed only as much input as its
572    /// slowest part.
573    pub fn merge(&mut self, other: &Self) {
574        // Naming every field makes a new field a compile error until it is
575        // merged here.
576        let &Self {
577            transmitted_records,
578            transmitted_bytes,
579            queued_records,
580            queued_batches,
581            buffered_records,
582            buffered_batches,
583            num_encode_errors,
584            num_transport_errors,
585            total_processed_input_records,
586            total_processed_steps,
587            memory,
588            batch_records_written,
589        } = other;
590        self.transmitted_records += transmitted_records;
591        self.transmitted_bytes += transmitted_bytes;
592        self.queued_records += queued_records;
593        self.queued_batches += queued_batches;
594        self.buffered_records += buffered_records;
595        self.buffered_batches += buffered_batches;
596        self.num_encode_errors += num_encode_errors;
597        self.num_transport_errors += num_transport_errors;
598        self.total_processed_input_records = self
599            .total_processed_input_records
600            .min(total_processed_input_records);
601        self.total_processed_steps = self.total_processed_steps.min(total_processed_steps);
602        self.memory += memory;
603        self.batch_records_written = match (self.batch_records_written, batch_records_written) {
604            (Some(a), Some(b)) => Some(a + b),
605            (a, b) => a.or(b),
606        };
607    }
608}
609
610impl ExternalOutputEndpointStatus {
611    /// Combines this status with `other`, which another host reports for its
612    /// part of the same distributed connector, into the status of the
613    /// connector as a whole.
614    ///
615    /// The combined connector is healthy, paused, or free of a fatal error
616    /// only if every part is.
617    pub fn merge(&mut self, other: Self) {
618        // Naming every field makes a new field a compile error until it is
619        // merged here.
620        let Self {
621            // Every host reports the same name and configuration.
622            endpoint_name: _,
623            config: _,
624            metrics,
625            fatal_error,
626            encode_errors,
627            transport_errors,
628            health,
629            paused,
630        } = other;
631        self.metrics.merge(&metrics);
632        if self.fatal_error.is_none() {
633            self.fatal_error = fatal_error;
634        }
635        merge_errors(&mut self.encode_errors, encode_errors);
636        merge_errors(&mut self.transport_errors, transport_errors);
637        self.health = merge_health(self.health.take(), health);
638        self.paused &= paused;
639    }
640}
641
642/// Global controller metrics.
643#[derive(Debug, Default, Serialize, Deserialize, ToSchema)]
644#[schema(as = GlobalControllerMetrics)]
645pub struct ExternalGlobalControllerMetrics {
646    /// State of the pipeline: running, paused, or terminating.
647    pub state: PipelineState,
648    /// The pipeline has been resumed from a checkpoint and is currently bootstrapping new and modified views.
649    pub bootstrap_in_progress: bool,
650    /// Status of the current transaction.
651    pub transaction_status: TransactionStatus,
652    /// ID of the current transaction or 0 if no transaction is in progress.
653    #[schema(value_type = i64)]
654    pub transaction_id: TransactionId,
655    /// Elapsed time in milliseconds, according to `transaction_status`:
656    ///
657    /// - [TransactionStatus::TransactionInProgress]: Time that this transaction
658    ///   has been in progress.
659    ///
660    /// - [TransactionStatus::CommitInProgress]: Time that this transaction has
661    ///   been committing.
662    pub transaction_msecs: Option<u64>,
663    /// Number of records in this transaction, according to
664    /// `transaction_status`:
665    ///
666    /// - [TransactionStatus::TransactionInProgress]: Number of records added so
667    ///   far.  More records might be added.
668    ///
669    /// - [TransactionStatus::CommitInProgress]: Final number of records.
670    pub transaction_records: Option<u64>,
671    /// Progress of the current transaction commit, if one is in progress.
672    pub commit_progress: Option<CommitProgressSummary>,
673    /// Entities that initiated the current transaction.
674    #[schema(value_type = TransactionInitiators)]
675    pub transaction_initiators: ExternalTransactionInitiators,
676    /// Phase of a concurrent bootstrap, or `Inactive` if none is in progress.
677    pub concurrent_bootstrap_phase: ConcurrentBootstrapPhase,
678    /// Progress of the concurrent bootstrap's transaction commit, if a commit is
679    /// in progress: the backfill transaction during `ConcurrentBootstrapping` and
680    /// the synchronization transaction during `Synchronizing`.
681    pub concurrent_bootstrap_progress: Option<CommitProgressSummary>,
682    /// Resident set size of the pipeline process, in bytes.
683    pub rss_bytes: u64,
684    /// Memory pressure.
685    pub memory_pressure: MemoryPressure,
686    /// Memory pressure epoch.
687    pub memory_pressure_epoch: u64,
688    /// CPU time used by the pipeline across all threads, in milliseconds.
689    pub cpu_msecs: u64,
690    /// Time since the pipeline process started, including time that the
691    /// pipeline was running or paused.
692    ///
693    /// This is the elapsed time since `start_time`.
694    pub uptime_msecs: u64,
695    /// Time at which the pipeline process started, in seconds since the epoch.
696    #[serde(with = "chrono::serde::ts_seconds")]
697    #[schema(value_type = u64)]
698    pub start_time: DateTime<Utc>,
699    /// Uniquely identifies the pipeline process that started at start_time.
700    pub incarnation_uuid: Uuid,
701    /// Time at which the pipeline process from which we resumed started, in seconds since the epoch.
702    #[serde(with = "chrono::serde::ts_seconds")]
703    #[schema(value_type = u64)]
704    pub initial_start_time: DateTime<Utc>,
705    /// Current storage usage in bytes.
706    pub storage_bytes: u64,
707    /// Storage usage integrated over time, in megabytes * seconds.
708    pub storage_mb_secs: u64,
709    /// Capacity of the pipeline's storage disk, in bytes; absent when unknown.
710    #[serde(default, skip_serializing_if = "Option::is_none")]
711    pub disk_total_bytes: Option<u64>,
712    /// Bytes the pipeline can still write to its storage disk; absent when unknown.
713    #[serde(default, skip_serializing_if = "Option::is_none")]
714    pub disk_available_bytes: Option<u64>,
715    /// Time elapsed while the pipeline is executing a step, multiplied by the number of threads, in milliseconds.
716    pub runtime_elapsed_msecs: u64,
717    /// Total number of records currently buffered by all endpoints.
718    pub buffered_input_records: u64,
719    /// Total number of bytes currently buffered by all endpoints.
720    pub buffered_input_bytes: u64,
721    /// Total number of records received from all endpoints.
722    pub total_input_records: u64,
723    /// Total number of bytes received from all endpoints.
724    pub total_input_bytes: u64,
725    /// Total number of input records processed by the DBSP engine.
726    pub total_processed_records: u64,
727    /// Total bytes of input records processed by the DBSP engine.
728    pub total_processed_bytes: u64,
729    /// Total number of input records processed to completion.
730    ///
731    /// In a multihost pipeline, this counts the input records that all of the
732    /// hosts received.  If a host runs an older version that does not report
733    /// its count to the coordinator, this is instead the sum of the counts
734    /// that each host reports for its own input, which can include input whose
735    /// output an output connector on a different host has not yet processed.
736    pub total_completed_records: u64,
737    /// If the pipeline is stalled because one or more output connectors' output
738    /// buffers are full, this is the number of milliseconds that the current
739    /// stall has lasted.
740    ///
741    /// If this is nonzero, then the output connectors causing the stall can be
742    /// identified by noticing `ExternalOutputEndpointMetrics::queued_records`
743    /// is greater than or equal to `ConnectorConfig::max_queued_records`.
744    ///
745    /// In the ordinary case, the pipeline is not stalled, and this value is 0.
746    pub output_stall_msecs: u64,
747    /// Number of steps that have been initiated.
748    ///
749    /// # Interpretation
750    ///
751    /// This is a count, not a step number.  If `total_initiated_steps` is 0, no
752    /// steps have been initiated.  If `total_initiated_steps > 0`, then step
753    /// `total_initiated_steps - 1` has been started and all steps previous to
754    /// that have been completely processed by the circuit.
755    #[schema(value_type = u64)]
756    pub total_initiated_steps: Step,
757    /// Number of steps whose input records have been processed to completion.
758    ///
759    /// A record is processed to completion if it has been processed by the DBSP engine and
760    /// all outputs derived from it have been processed by all output connectors.
761    ///
762    /// # Interpretation
763    ///
764    /// This is a count, not a step number.  If `total_completed_steps` is 0, no
765    /// steps have been processed to completion.  If `total_completed_steps >
766    /// 0`, then the last step whose input records have been processed to
767    /// completion is `total_completed_steps - 1`. A record that was ingested
768    /// when `total_initiated_steps` was `n` is fully processed when
769    /// `total_completed_steps >= n`.
770    #[schema(value_type = u64)]
771    pub total_completed_steps: Step,
772    /// True if the pipeline has processed all input data to completion.
773    pub pipeline_complete: bool,
774    /// Version of the platform that compiled the pipeline, such as
775    /// `0.349.0+enterprise`.
776    ///
777    /// This is the platform's own version, which the compiler records in the
778    /// binary.
779    pub platform_version: String,
780    /// Runtime the pipeline was compiled against.
781    ///
782    /// Equal to `platform_version` when the program uses the platform's own
783    /// runtime; otherwise the selected runtime, a git SHA, a `vX.Y.Z` tag,
784    /// or `gen2`.
785    pub runtime_version: String,
786}
787
788/// Complete pipeline statistics returned by the `/stats` endpoint.
789///
790/// This schema definition matches the serialized JSON structure from
791/// `adapters::controller::ControllerStatus`. The actual implementation with
792/// atomics and mutexes lives in the adapters crate, which uses ExternalControllerStatus to
793/// register this OpenAPI schema, making it available to pipeline-manager
794/// without requiring a direct dependency on the adapters crate.
795#[derive(Debug, Deserialize, Serialize, ToSchema, Default)]
796#[schema(as = ControllerStatus)]
797pub struct ExternalControllerStatus {
798    /// Global controller metrics.
799    #[schema(value_type = GlobalControllerMetrics)]
800    pub global_metrics: ExternalGlobalControllerMetrics,
801    /// Reason why the pipeline cannot be suspended or checkpointed (if any).
802    pub suspend_error: Option<SuspendError>,
803    /// Current checkpoint activity (idle, delayed, or in-progress).
804    /// `None` when the pipeline binary predates checkpoint activity tracking.
805    pub checkpoint_activity: Option<CheckpointActivity>,
806    /// If the pipeline fundamentally cannot checkpoint (e.g. storage is not
807    /// configured, or an input endpoint does not support suspend), the reasons
808    /// are listed here.  Unlike a checkpoint failure, this means *no*
809    /// checkpoint can succeed until the pipeline configuration changes.
810    pub permanent_checkpoint_errors: Option<Vec<PermanentSuspendError>>,
811    /// Input endpoint configs and metrics.
812    #[schema(value_type = Vec<InputEndpointStatus>)]
813    pub inputs: Vec<ExternalInputEndpointStatus>,
814    /// Output endpoint configs and metrics.
815    #[schema(value_type = Vec<OutputEndpointStatus>)]
816    pub outputs: Vec<ExternalOutputEndpointStatus>,
817    /// Resource usage of each host in a multihost pipeline, by ordinal.
818    #[serde(default, skip_serializing_if = "Vec::is_empty")]
819    pub host_metrics: Vec<HostMetrics>,
820}
821
822/// Resource usage of one host in a multihost pipeline.
823#[derive(Debug, Default, Deserialize, Serialize, ToSchema)]
824pub struct HostMetrics {
825    /// Capacity of the host's storage disk, in bytes; absent when unknown.
826    #[serde(default, skip_serializing_if = "Option::is_none")]
827    pub disk_total_bytes: Option<u64>,
828    /// Bytes the host can still write to its storage disk; absent when unknown.
829    #[serde(default, skip_serializing_if = "Option::is_none")]
830    pub disk_available_bytes: Option<u64>,
831}
832
833impl From<&ExternalGlobalControllerMetrics> for HostMetrics {
834    fn from(metrics: &ExternalGlobalControllerMetrics) -> Self {
835        Self {
836            disk_total_bytes: metrics.disk_total_bytes,
837            disk_available_bytes: metrics.disk_available_bytes,
838        }
839    }
840}
841
842fn serialize_timestamp_micros<S>(
843    timestamp: &DateTime<Utc>,
844    serializer: S,
845) -> Result<S::Ok, S::Error>
846where
847    S: serde::Serializer,
848{
849    serializer.serialize_str(&timestamp.to_rfc3339_opts(SecondsFormat::Micros, true))
850}
851
852#[cfg(test)]
853mod tests {
854    use super::ConnectorError;
855    use chrono::{DateTime, Utc};
856
857    #[test]
858    fn connector_error_timestamp_serializes_with_microsecond_precision() {
859        let error = ConnectorError {
860            timestamp: DateTime::parse_from_rfc3339("2026-03-08T05:26:42.442438448Z")
861                .unwrap()
862                .with_timezone(&Utc),
863            index: 1,
864            tag: None,
865            message: "boom".to_string(),
866        };
867
868        let json = serde_json::to_string(&error).unwrap();
869        assert!(json.contains(r#""timestamp":"2026-03-08T05:26:42.442438Z""#));
870    }
871
872    #[test]
873    fn output_metrics_batch_records_written_serializes() {
874        use super::ExternalOutputEndpointMetrics;
875
876        let metrics = ExternalOutputEndpointMetrics {
877            batch_records_written: Some(42),
878            ..Default::default()
879        };
880        let json = serde_json::to_string(&metrics).unwrap();
881        assert!(json.contains(r#""batch_records_written":42"#));
882
883        let deserialized: ExternalOutputEndpointMetrics = serde_json::from_str(&json).unwrap();
884        assert_eq!(deserialized.batch_records_written, Some(42));
885    }
886
887    #[test]
888    fn output_metrics_batch_records_written_defaults_to_none() {
889        use super::ExternalOutputEndpointMetrics;
890
891        // Old JSON without batch_records_written defaults to None.
892        let json = r#"{"transmitted_records":0,"transmitted_bytes":0,"queued_records":0,"queued_batches":0,"buffered_records":0,"buffered_batches":0,"num_encode_errors":0,"num_transport_errors":0,"total_processed_input_records":0,"total_processed_steps":0,"memory":0}"#;
893        let metrics: ExternalOutputEndpointMetrics = serde_json::from_str(json).unwrap();
894        assert_eq!(metrics.batch_records_written, None);
895    }
896
897    mod merge {
898        use chrono::{DateTime, TimeZone, Utc};
899
900        use crate::adapter_stats::{
901            CompletedWatermark, ConnectorError, ConnectorHealth, ConnectorHealthStatus,
902            ExternalInputEndpointMetrics, ExternalInputEndpointStatus,
903            ExternalOutputEndpointMetrics, ExternalOutputEndpointStatus, FrontierMerge,
904            ShortEndpointConfig,
905        };
906        use serde_json::{Value, json};
907
908        fn time(secs: i64) -> DateTime<Utc> {
909            Utc.timestamp_opt(secs, 0).unwrap()
910        }
911
912        fn error(secs: i64, message: &str) -> ConnectorError {
913            ConnectorError {
914                timestamp: time(secs),
915                index: 0,
916                tag: None,
917                message: message.into(),
918            }
919        }
920
921        fn frontier(ingested_secs: i64) -> CompletedWatermark {
922            CompletedWatermark {
923                metadata: serde_json::json!(ingested_secs),
924                ingested_at: time(ingested_secs),
925                processed_at: time(ingested_secs + 1),
926                completed_at: time(ingested_secs + 2),
927            }
928        }
929
930        fn status() -> ExternalInputEndpointStatus {
931            ExternalInputEndpointStatus {
932                endpoint_name: "t.kafka".into(),
933                config: ShortEndpointConfig { stream: "t".into() },
934                metrics: ExternalInputEndpointMetrics {
935                    total_bytes: 10,
936                    total_records: 1,
937                    buffered_records: 2,
938                    buffered_bytes: 20,
939                    latest_batch_records: 5,
940                    latest_batch_bytes: 50,
941                    num_transport_errors: 3,
942                    num_parse_errors: 4,
943                    end_of_input: true,
944                    processing_latency_p99_micros: Some(100),
945                },
946                fatal_error: None,
947                parse_errors: None,
948                transport_errors: None,
949                health: Some(ConnectorHealth::healthy()),
950                paused: false,
951                barrier: false,
952                completed_frontier: None,
953            }
954        }
955
956        #[test]
957        fn counters_add_up() {
958            let mut a = status();
959            let mut b = status();
960            b.metrics.processing_latency_p99_micros = Some(500);
961            b.metrics.end_of_input = false;
962            a.merge(b, FrontierMerge::Opaque);
963            let m = &a.metrics;
964            assert_eq!(
965                (
966                    m.total_bytes,
967                    m.total_records,
968                    m.buffered_records,
969                    m.buffered_bytes
970                ),
971                (20, 2, 4, 40)
972            );
973            assert_eq!((m.latest_batch_records, m.latest_batch_bytes), (10, 100));
974            assert_eq!((m.num_transport_errors, m.num_parse_errors), (6, 8));
975            assert!(!m.end_of_input);
976            assert_eq!(m.processing_latency_p99_micros, Some(500));
977        }
978
979        #[test]
980        fn worst_host_decides() {
981            let mut a = status();
982            let mut b = status();
983            b.fatal_error = Some("broken".into());
984            b.health = Some(ConnectorHealth::unhealthy("sick"));
985            b.barrier = true;
986            a.merge(b, FrontierMerge::Opaque);
987            assert_eq!(a.fatal_error.as_deref(), Some("broken"));
988            assert!(matches!(
989                a.health.unwrap().status,
990                ConnectorHealthStatus::Unhealthy
991            ));
992            assert!(a.barrier);
993
994            // The first fatal error stays.
995            let mut a = status();
996            a.fatal_error = Some("first".into());
997            let mut b = status();
998            b.fatal_error = Some("second".into());
999            a.merge(b, FrontierMerge::Opaque);
1000            assert_eq!(a.fatal_error.as_deref(), Some("first"));
1001        }
1002
1003        /// Merges hosts given as (end of input, frontier ingestion time,
1004        /// metadata) with `kind`, and returns the merged frontier's ingestion
1005        /// time and metadata.
1006        fn merge_metadata(
1007            hosts: Vec<(bool, Option<(i64, Value)>)>,
1008            kind: FrontierMerge,
1009        ) -> Option<(DateTime<Utc>, Value)> {
1010            let mut statuses = hosts.into_iter().map(|(eoi, f)| {
1011                let mut s = status();
1012                s.metrics.end_of_input = eoi;
1013                s.completed_frontier = f.map(|(secs, metadata)| CompletedWatermark {
1014                    metadata,
1015                    ..frontier(secs)
1016                });
1017                s
1018            });
1019            let mut x = statuses.next().unwrap();
1020            statuses.for_each(|y| x.merge(y, kind));
1021            x.completed_frontier.map(|f| (f.ingested_at, f.metadata))
1022        }
1023
1024        /// Shared metadata stays with its host's frontier, however many
1025        /// hosts report one.
1026        #[test]
1027        fn shared_frontier_merge() {
1028            let merged = |hosts| merge_metadata(hosts, FrontierMerge::Shared);
1029            let version = |v: i64| json!({"version": v});
1030            assert_eq!(
1031                merged(vec![
1032                    (false, Some((10, version(3)))),
1033                    (false, Some((5, version(2))))
1034                ]),
1035                Some((time(5), version(2)))
1036            );
1037            assert_eq!(
1038                merged(vec![
1039                    (true, Some((5, version(2)))),
1040                    (false, Some((10, version(7))))
1041                ]),
1042                Some((time(10), version(7)))
1043            );
1044            assert_eq!(
1045                merged(vec![
1046                    (true, Some((5, version(2)))),
1047                    (true, Some((10, version(2))))
1048                ]),
1049                Some((time(10), version(2)))
1050            );
1051        }
1052
1053        /// Partitioned metadata joins every host's partitions, including
1054        /// those of hosts at end of input.
1055        #[test]
1056        fn partitioned_frontier_merge() {
1057            let merged = |hosts| merge_metadata(hosts, FrontierMerge::Partitioned);
1058            // A host's metadata, which also has fields that the join drops.
1059            let host = |partitions: &[i64], offsets: &[i64]| json!({"partitions": partitions, "offsets": offsets, "shard": {"host": 0}});
1060            let joined = |partitions: &[i64], offsets: &[i64]| json!({"partitions": partitions, "offsets": offsets});
1061
1062            // Busy hosts, in any order.
1063            assert_eq!(
1064                merged(vec![
1065                    (false, Some((10, host(&[1, 4], &[11, 14])))),
1066                    (false, Some((5, host(&[2], &[12])))),
1067                    (false, Some((7, host(&[0, 3], &[10, 13])))),
1068                ]),
1069                Some((time(5), joined(&[0, 1, 2, 3, 4], &[10, 11, 12, 13, 14])))
1070            );
1071
1072            // Hosts at end of input add their partitions but not their time.
1073            assert_eq!(
1074                merged(vec![
1075                    (true, Some((5, host(&[1], &[11])))),
1076                    (false, Some((10, host(&[0], &[10])))),
1077                ]),
1078                Some((time(10), joined(&[0, 1], &[10, 11])))
1079            );
1080            assert_eq!(
1081                merged(vec![
1082                    (true, Some((10, host(&[1], &[11])))),
1083                    (true, Some((5, host(&[0], &[10])))),
1084                ]),
1085                Some((time(10), joined(&[0, 1], &[10, 11])))
1086            );
1087
1088            // A host with no partitions and no frontier adds nothing, and one
1089            // host's metadata takes the joined form.
1090            assert_eq!(
1091                merged(vec![(true, None), (false, Some((10, host(&[0], &[10]))))]),
1092                Some((time(10), joined(&[0], &[10])))
1093            );
1094
1095            // A busy host with no frontier still holds back the frontier.
1096            assert_eq!(
1097                merged(vec![(false, None), (true, Some((10, host(&[0], &[10]))))]),
1098                None
1099            );
1100
1101            // Metadata without partitions, as from an older host, or with a
1102            // partition that two hosts report, joins to null.
1103            for other in [json!({"offsets": [11]}), host(&[0], &[11]), Value::Null] {
1104                assert_eq!(
1105                    merged(vec![
1106                        (false, Some((10, host(&[0], &[10])))),
1107                        (false, Some((5, other.clone()))),
1108                    ]),
1109                    Some((time(5), Value::Null)),
1110                    "{other}"
1111                );
1112            }
1113        }
1114
1115        fn output_status(steps: u64, records: u64) -> ExternalOutputEndpointStatus {
1116            ExternalOutputEndpointStatus {
1117                endpoint_name: "v.delta".into(),
1118                config: ShortEndpointConfig { stream: "v".into() },
1119                metrics: ExternalOutputEndpointMetrics {
1120                    transmitted_records: 1,
1121                    transmitted_bytes: 2,
1122                    queued_records: 3,
1123                    queued_batches: 4,
1124                    buffered_records: 5,
1125                    buffered_batches: 6,
1126                    num_encode_errors: 7,
1127                    num_transport_errors: 8,
1128                    total_processed_input_records: records,
1129                    total_processed_steps: steps,
1130                    memory: 9,
1131                    batch_records_written: None,
1132                },
1133                fatal_error: None,
1134                encode_errors: None,
1135                transport_errors: None,
1136                health: Some(ConnectorHealth::healthy()),
1137                paused: true,
1138            }
1139        }
1140
1141        /// The parts of a distributed output connector add up their counts,
1142        /// and the slowest part decides the progress, the health, and the
1143        /// pause.
1144        #[test]
1145        fn output_merge() {
1146            let mut a = output_status(5, 50);
1147            let mut b = output_status(3, 30);
1148            b.metrics.batch_records_written = Some(10);
1149            b.health = Some(ConnectorHealth::unhealthy("sick"));
1150            b.paused = false;
1151            b.fatal_error = Some("broken".into());
1152            b.transport_errors = Some(vec![error(2, "b2")]);
1153            a.merge(b);
1154            assert_eq!(
1155                a.metrics,
1156                ExternalOutputEndpointMetrics {
1157                    transmitted_records: 2,
1158                    transmitted_bytes: 4,
1159                    queued_records: 6,
1160                    queued_batches: 8,
1161                    buffered_records: 10,
1162                    buffered_batches: 12,
1163                    num_encode_errors: 14,
1164                    num_transport_errors: 16,
1165                    total_processed_input_records: 30,
1166                    total_processed_steps: 3,
1167                    memory: 18,
1168                    batch_records_written: Some(10),
1169                }
1170            );
1171            assert!(matches!(
1172                a.health.unwrap().status,
1173                ConnectorHealthStatus::Unhealthy
1174            ));
1175            assert!(!a.paused);
1176            assert_eq!(a.fatal_error.as_deref(), Some("broken"));
1177            assert_eq!(a.transport_errors.unwrap().len(), 1);
1178        }
1179
1180        /// A connector is paused only if every host is, in any order.
1181        #[test]
1182        fn pause_merge() {
1183            let merged = |hosts: &[bool]| {
1184                let mut statuses = hosts.iter().map(|&paused| {
1185                    let mut s = status();
1186                    s.paused = paused;
1187                    s
1188                });
1189                let mut x = statuses.next().unwrap();
1190                statuses.for_each(|y| x.merge(y, FrontierMerge::Opaque));
1191                x.paused
1192            };
1193            assert!(merged(&[true, true, true]));
1194            assert!(!merged(&[false, false, false]));
1195            for hosts in [
1196                [true, false, false],
1197                [false, true, false],
1198                [false, false, true],
1199                [true, true, false],
1200                [false, true, true],
1201                [true, false, true],
1202            ] {
1203                assert!(!merged(&hosts), "{hosts:?}");
1204            }
1205        }
1206
1207        #[test]
1208        fn errors_are_combined_in_time_order() {
1209            let mut a = status();
1210            a.parse_errors = Some(vec![error(1, "a1"), error(5, "a5")]);
1211            let mut b = status();
1212            b.parse_errors = Some(vec![error(3, "b3")]);
1213            b.transport_errors = Some(vec![error(2, "b2")]);
1214            a.merge(b, FrontierMerge::Opaque);
1215            let messages = |errors: &Option<Vec<ConnectorError>>| {
1216                errors
1217                    .iter()
1218                    .flatten()
1219                    .map(|e| e.message.clone())
1220                    .collect::<Vec<_>>()
1221            };
1222            assert_eq!(messages(&a.parse_errors), ["a1", "b3", "a5"]);
1223            assert_eq!(messages(&a.transport_errors), ["b2"]);
1224        }
1225
1226        #[test]
1227        fn opaque_frontier_merge() {
1228            // Merges hosts given as (end of input, frontier) and returns the
1229            // merged frontier's ingestion time and whether it kept metadata.
1230            let merged = |hosts: &[(bool, Option<i64>)]| {
1231                let mut statuses = hosts.iter().map(|&(eoi, f)| {
1232                    let mut s = status();
1233                    s.metrics.end_of_input = eoi;
1234                    s.completed_frontier = f.map(frontier);
1235                    s
1236                });
1237                let mut x = statuses.next().unwrap();
1238                statuses.for_each(|y| x.merge(y, FrontierMerge::Opaque));
1239                x.completed_frontier
1240                    .map(|f| (f.ingested_at, !f.metadata.is_null()))
1241            };
1242            let (busy, done) = (false, true);
1243
1244            // The oldest frontier among hosts that are still reading.
1245            assert_eq!(
1246                merged(&[(busy, Some(10)), (busy, Some(5))]),
1247                Some((time(5), false))
1248            );
1249            assert_eq!(
1250                merged(&[(busy, Some(5)), (busy, Some(10))]),
1251                Some((time(5), false))
1252            );
1253
1254            // A host still reading with no frontier holds back the frontier,
1255            // in any position.
1256            assert_eq!(merged(&[(busy, None), (busy, Some(10))]), None);
1257            assert_eq!(merged(&[(busy, Some(10)), (busy, None)]), None);
1258            assert_eq!(
1259                merged(&[(busy, Some(10)), (busy, None), (busy, Some(5))]),
1260                None
1261            );
1262            assert_eq!(
1263                merged(&[(busy, None), (done, Some(5)), (busy, Some(10))]),
1264                None
1265            );
1266
1267            // Hosts at end of input do not hold back the frontier, and the
1268            // one host still reading keeps its metadata, as a Delta Lake
1269            // connector's home host does while it follows the table.
1270            assert_eq!(
1271                merged(&[(busy, Some(10)), (done, Some(5))]),
1272                Some((time(10), true))
1273            );
1274            assert_eq!(
1275                merged(&[(done, Some(5)), (busy, Some(10))]),
1276                Some((time(10), true))
1277            );
1278            assert_eq!(
1279                merged(&[(done, None), (busy, Some(10))]),
1280                Some((time(10), true))
1281            );
1282            assert_eq!(
1283                merged(&[(busy, Some(10)), (done, None)]),
1284                Some((time(10), true))
1285            );
1286            assert_eq!(
1287                merged(&[(done, Some(5)), (busy, Some(10)), (done, Some(20))]),
1288                Some((time(10), true))
1289            );
1290            assert_eq!(
1291                merged(&[(done, Some(5)), (busy, Some(10)), (busy, Some(20))]),
1292                Some((time(10), false))
1293            );
1294
1295            // If every host is at end of input, the newest frontier.
1296            assert_eq!(
1297                merged(&[(done, Some(10)), (done, Some(5))]),
1298                Some((time(10), true))
1299            );
1300            assert_eq!(
1301                merged(&[(done, None), (done, Some(5))]),
1302                Some((time(5), true))
1303            );
1304            assert_eq!(merged(&[(done, None), (done, None)]), None);
1305        }
1306    }
1307}