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