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 transport errors.
213    pub num_transport_errors: u64,
214    /// Number of parse errors.
215    pub num_parse_errors: u64,
216    /// True if end-of-input has been signaled.
217    pub end_of_input: bool,
218    /// 99th percentile processing latency (from ingesting a batch to finishing processing it) in microseconds.
219    ///
220    /// The time from ingesting a batch of records off the wire
221    /// to the circuit finishing processing them,
222    /// covering parsing, queuing, and the circuit step.
223    ///
224    /// Does not account for completion latency.
225    ///
226    /// Taken over the endpoint's sliding histogram, which holds the 10,000 most
227    /// recent samples spanning at most 10 minutes, whichever bound is reached
228    /// first. One sample is recorded per completed batch. An endpoint that stops
229    /// ingesting keeps reporting its last known latency instead of dropping to
230    /// `None`.
231    ///
232    /// `None` until the endpoint records its first sample.
233    #[serde(default, skip_serializing_if = "Option::is_none")]
234    pub processing_latency_p99_micros: Option<u64>,
235}
236
237impl ExternalInputEndpointMetrics {
238    /// Adds `other`, which another host reports for its part of the same
239    /// distributed connector, to these metrics.
240    pub fn merge(&mut self, other: &Self) {
241        // Naming every field makes a new field a compile error until it is
242        // merged here.
243        let &Self {
244            total_bytes,
245            total_records,
246            buffered_records,
247            buffered_bytes,
248            num_transport_errors,
249            num_parse_errors,
250            end_of_input,
251            processing_latency_p99_micros,
252        } = other;
253        self.total_bytes += total_bytes;
254        self.total_records += total_records;
255        self.buffered_records += buffered_records;
256        self.buffered_bytes += buffered_bytes;
257        self.num_transport_errors += num_transport_errors;
258        self.num_parse_errors += num_parse_errors;
259        self.end_of_input &= end_of_input;
260        // The worst host's latency bounds the connector's latency.
261        self.processing_latency_p99_micros = self
262            .processing_latency_p99_micros
263            .max(processing_latency_p99_micros);
264    }
265}
266
267/// Input endpoint status information.
268#[derive(Debug, Serialize, Deserialize, ToSchema)]
269#[schema(as = InputEndpointStatus)]
270pub struct ExternalInputEndpointStatus {
271    /// Endpoint name.
272    pub endpoint_name: String,
273    /// Endpoint configuration.
274    pub config: ShortEndpointConfig,
275    /// Performance metrics.
276    #[schema(value_type = InputEndpointMetrics)]
277    pub metrics: ExternalInputEndpointMetrics,
278    /// The first fatal error that occurred at the endpoint.
279    pub fatal_error: Option<String>,
280    /// Recent parse errors on this endpoint.
281    #[serde(default, skip_serializing_if = "Option::is_none")]
282    pub parse_errors: Option<Vec<ConnectorError>>,
283    /// Recent transport errors on this endpoint.
284    #[serde(default, skip_serializing_if = "Option::is_none")]
285    pub transport_errors: Option<Vec<ConnectorError>>,
286    /// Health status of the connector.
287    #[serde(default)]
288    pub health: Option<ConnectorHealth>,
289    /// Endpoint has been paused by the user.  A distributed connector in a
290    /// multihost pipeline is paused only if it is paused on every host.
291    pub paused: bool,
292    /// Endpoint is currently a barrier to checkpointing and suspend.
293    pub barrier: bool,
294    /// The latest completed watermark.
295    #[schema(value_type = Option<CompletedWatermark>)]
296    pub completed_frontier: Option<CompletedWatermark>,
297}
298
299/// How to combine the metadata of the completed frontiers that the hosts of a
300/// distributed input connector report (see
301/// [`ExternalInputEndpointStatus::merge`]).
302#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
303pub enum FrontierMerge {
304    /// The metadata is a position in one sequence that every host shares,
305    /// such as a table version.  The combined frontier keeps the metadata of
306    /// the host whose frontier it is.
307    Shared,
308
309    /// Each host's metadata describes only its own partitions, as an object
310    /// with arrays `partitions` and `offsets` of the same length.  The
311    /// combined metadata has every host's partitions, in order.
312    Partitioned,
313
314    /// The metadata has no known structure.  The combined frontier has no
315    /// metadata if more than one host that is not at end of input reports a
316    /// frontier.
317    #[default]
318    Opaque,
319}
320
321impl ExternalInputEndpointStatus {
322    /// Combines this status with `other`, which another host reports for its
323    /// part of the same distributed connector, into the status of the
324    /// connector as a whole.
325    ///
326    /// The combined connector is healthy, at end of input, paused, or free of
327    /// a fatal error only if every part is.  It is a barrier if any part is.
328    ///
329    /// Its completed frontier is the oldest one among the hosts that are not
330    /// at end of input, because input after that point is not complete on
331    /// that host.  A host that is not at end of input and has completed no
332    /// input yet gives no frontier.  Hosts at end of input do not hold back
333    /// the frontier; if every host is at end of input, the frontier is the
334    /// newest one.
335    ///
336    /// `frontier_merge` says how to combine the frontiers' metadata.
337    pub fn merge(&mut self, other: Self, frontier_merge: FrontierMerge) {
338        // Naming every field makes a new field a compile error until it is
339        // merged here.
340        let Self {
341            // Every host reports the same name and configuration.
342            endpoint_name: _,
343            config: _,
344            metrics,
345            fatal_error,
346            parse_errors,
347            transport_errors,
348            health,
349            paused,
350            barrier,
351            completed_frontier,
352        } = other;
353        let (a_eoi, b_eoi) = (self.metrics.end_of_input, metrics.end_of_input);
354        self.metrics.merge(&metrics);
355        if self.fatal_error.is_none() {
356            self.fatal_error = fatal_error;
357        }
358        merge_errors(&mut self.parse_errors, parse_errors);
359        merge_errors(&mut self.transport_errors, transport_errors);
360        self.health = match (self.health.take(), health) {
361            (Some(a), Some(b)) => Some(if matches!(a.status, ConnectorHealthStatus::Unhealthy) {
362                a
363            } else {
364                b
365            }),
366            (a, b) => a.or(b),
367        };
368        self.paused &= paused;
369        self.barrier |= barrier;
370        let (a, b) = (self.completed_frontier.take(), completed_frontier);
371        let several = !a_eoi && !b_eoi && a.is_some() && b.is_some();
372        // Joining with no partitions puts one host's metadata in the joined
373        // form.
374        let no_partitions = serde_json::json!({"partitions": [], "offsets": []});
375        let metadata = |f: &Option<CompletedWatermark>| {
376            f.as_ref().map_or(&no_partitions, |f| &f.metadata).clone()
377        };
378        let joined = join_partitions(&metadata(&a), &metadata(&b));
379        let oldest = |a: CompletedWatermark, b: CompletedWatermark| {
380            if b.ingested_at < a.ingested_at { b } else { a }
381        };
382        let newest = |a: CompletedWatermark, b: CompletedWatermark| {
383            if b.ingested_at > a.ingested_at { b } else { a }
384        };
385        self.completed_frontier = match (a_eoi, b_eoi) {
386            (false, false) => a.zip(b).map(|(a, b)| oldest(a, b)),
387            (false, true) => a,
388            (true, false) => b,
389            (true, true) => match (a, b) {
390                (Some(a), Some(b)) => Some(newest(a, b)),
391                (a, b) => a.or(b),
392            },
393        };
394        if let Some(frontier) = &mut self.completed_frontier {
395            match frontier_merge {
396                FrontierMerge::Shared => (),
397                FrontierMerge::Partitioned => frontier.metadata = joined,
398                FrontierMerge::Opaque => {
399                    if several {
400                        frontier.metadata = JsonValue::Null;
401                    }
402                }
403            }
404        }
405    }
406}
407
408/// Joins two [`FrontierMerge::Partitioned`] metadata values.  Returns null if
409/// either one is not an object with arrays `partitions` and `offsets` of the
410/// same length, or if they have a partition in common.
411fn join_partitions(a: &JsonValue, b: &JsonValue) -> JsonValue {
412    fn pairs(metadata: &JsonValue) -> Option<Vec<(i64, &JsonValue)>> {
413        let partitions = metadata.get("partitions")?.as_array()?;
414        let offsets = metadata.get("offsets")?.as_array()?;
415        if partitions.len() != offsets.len() {
416            return None;
417        }
418        partitions
419            .iter()
420            .zip(offsets)
421            .map(|(partition, offsets)| Some((partition.as_i64()?, offsets)))
422            .collect()
423    }
424    let (Some(a), Some(b)) = (pairs(a), pairs(b)) else {
425        return JsonValue::Null;
426    };
427    let mut joined = BTreeMap::new();
428    for (partition, offsets) in a.into_iter().chain(b) {
429        if joined.insert(partition, offsets.clone()).is_some() {
430            return JsonValue::Null;
431        }
432    }
433    let (partitions, offsets): (Vec<_>, Vec<_>) = joined.into_iter().unzip();
434    serde_json::json!({"partitions": partitions, "offsets": offsets})
435}
436
437/// Appends `b` to `a` and sorts the result by time, because each host numbers
438/// its own errors.
439fn merge_errors(a: &mut Option<Vec<ConnectorError>>, b: Option<Vec<ConnectorError>>) {
440    if let Some(b) = b {
441        let errors = a.get_or_insert_with(Vec::new);
442        errors.extend(b);
443        errors.sort_by_key(|error| error.timestamp);
444    }
445}
446
447/// Performance metrics for an output endpoint.
448#[derive(Debug, Default, Deserialize, Serialize, ToSchema, PartialEq, Eq, PartialOrd, Ord)]
449#[schema(as = OutputEndpointMetrics)]
450pub struct ExternalOutputEndpointMetrics {
451    /// Records sent on the underlying transport.
452    pub transmitted_records: u64,
453    /// Bytes sent on the underlying transport.
454    pub transmitted_bytes: u64,
455    /// Number of queued records.
456    pub queued_records: u64,
457    /// Number of queued batches.
458    pub queued_batches: u64,
459    /// Number of records pushed to the output buffer.
460    pub buffered_records: u64,
461    /// Number of batches in the buffer.
462    pub buffered_batches: u64,
463    /// Number of encoding errors.
464    pub num_encode_errors: u64,
465    /// Number of transport errors.
466    pub num_transport_errors: u64,
467    /// The number of input records processed by the circuit.
468    ///
469    /// This metric tracks the end-to-end progress of the pipeline: the output
470    /// of this endpoint is equal to the output of the circuit after
471    /// processing `total_processed_input_records` records.
472    ///
473    /// The counter never runs ahead of the endpoint's output. It advances to a
474    /// value `N` only once the endpoint has processed every batch derived from
475    /// the first `N` records received by the pipeline, which means transmitting
476    /// the batch, or discarding it while silent bootstrapping suppresses the
477    /// endpoint's output.
478    ///
479    /// In a multihost pipeline, `N` counts the input records that all of the
480    /// hosts received, not only the endpoint's own host.  (Each host counts
481    /// only its own input, and the coordinator adds up the hosts' counts as of
482    /// `total_processed_steps`.)  If a host runs an older version that does
483    /// not report its count to the coordinator, `N` counts only the input
484    /// records that the endpoint's own host received.
485    pub total_processed_input_records: u64,
486    /// The number of steps whose input records have been processed by the
487    /// endpoint.
488    ///
489    /// In a multihost pipeline, all of the hosts run the same steps together,
490    /// so a step number refers to the same step on every host.
491    ///
492    /// # Interpretation
493    ///
494    /// This is a count, not a step number.  If `total_processed_steps` is 0, no
495    /// steps have been processed to completion.  If `total_processed_steps >
496    /// 0`, then the last step whose input records have been processed to
497    /// completion is `total_processed_steps - 1`. A record that was ingested in
498    /// step `n` is fully processed when `total_processed_steps > n`.
499    #[schema(value_type = u64)]
500    pub total_processed_steps: Step,
501    /// Extra memory in use beyond that used for queuing records.
502    pub memory: u64,
503    /// Number of records written so far while the connector is processing a
504    /// batch of updates.  Resets to 0 after the batch is committed.
505    ///
506    /// `None` when the connector does not support batch-progress reporting.
507    #[serde(default, skip_serializing_if = "Option::is_none")]
508    pub batch_records_written: Option<u64>,
509}
510
511/// Output endpoint status information.
512#[derive(Debug, Deserialize, Serialize, ToSchema)]
513#[schema(as = OutputEndpointStatus)]
514pub struct ExternalOutputEndpointStatus {
515    /// Endpoint name.
516    pub endpoint_name: String,
517    /// Endpoint configuration.
518    pub config: ShortEndpointConfig,
519    /// Performance metrics.
520    #[schema(value_type = OutputEndpointMetrics)]
521    pub metrics: ExternalOutputEndpointMetrics,
522    /// The first fatal error that occurred at the endpoint.
523    pub fatal_error: Option<String>,
524    /// Recent encoding errors on this endpoint.
525    #[serde(default, skip_serializing_if = "Option::is_none")]
526    pub encode_errors: Option<Vec<ConnectorError>>,
527    /// Recent transport errors on this endpoint.
528    #[serde(default, skip_serializing_if = "Option::is_none")]
529    pub transport_errors: Option<Vec<ConnectorError>>,
530    /// Health status of the connector.
531    #[serde(default)]
532    pub health: Option<ConnectorHealth>,
533    /// Endpoint has been paused by the user.
534    ///
535    /// A paused output endpoint discards the output it receives instead of
536    /// sending it to its sink.
537    #[serde(default)]
538    pub paused: bool,
539}
540
541/// Global controller metrics.
542#[derive(Debug, Default, Serialize, Deserialize, ToSchema)]
543#[schema(as = GlobalControllerMetrics)]
544pub struct ExternalGlobalControllerMetrics {
545    /// State of the pipeline: running, paused, or terminating.
546    pub state: PipelineState,
547    /// The pipeline has been resumed from a checkpoint and is currently bootstrapping new and modified views.
548    pub bootstrap_in_progress: bool,
549    /// Status of the current transaction.
550    pub transaction_status: TransactionStatus,
551    /// ID of the current transaction or 0 if no transaction is in progress.
552    #[schema(value_type = i64)]
553    pub transaction_id: TransactionId,
554    /// Elapsed time in milliseconds, according to `transaction_status`:
555    ///
556    /// - [TransactionStatus::TransactionInProgress]: Time that this transaction
557    ///   has been in progress.
558    ///
559    /// - [TransactionStatus::CommitInProgress]: Time that this transaction has
560    ///   been committing.
561    pub transaction_msecs: Option<u64>,
562    /// Number of records in this transaction, according to
563    /// `transaction_status`:
564    ///
565    /// - [TransactionStatus::TransactionInProgress]: Number of records added so
566    ///   far.  More records might be added.
567    ///
568    /// - [TransactionStatus::CommitInProgress]: Final number of records.
569    pub transaction_records: Option<u64>,
570    /// Progress of the current transaction commit, if one is in progress.
571    pub commit_progress: Option<CommitProgressSummary>,
572    /// Entities that initiated the current transaction.
573    #[schema(value_type = TransactionInitiators)]
574    pub transaction_initiators: ExternalTransactionInitiators,
575    /// Phase of a concurrent bootstrap, or `Inactive` if none is in progress.
576    pub concurrent_bootstrap_phase: ConcurrentBootstrapPhase,
577    /// Progress of the concurrent bootstrap's transaction commit, if a commit is
578    /// in progress: the backfill transaction during `ConcurrentBootstrapping` and
579    /// the synchronization transaction during `Synchronizing`.
580    pub concurrent_bootstrap_progress: Option<CommitProgressSummary>,
581    /// Resident set size of the pipeline process, in bytes.
582    pub rss_bytes: u64,
583    /// Memory pressure.
584    pub memory_pressure: MemoryPressure,
585    /// Memory pressure epoch.
586    pub memory_pressure_epoch: u64,
587    /// CPU time used by the pipeline across all threads, in milliseconds.
588    pub cpu_msecs: u64,
589    /// Time since the pipeline process started, including time that the
590    /// pipeline was running or paused.
591    ///
592    /// This is the elapsed time since `start_time`.
593    pub uptime_msecs: u64,
594    /// Time at which the pipeline process started, in seconds since the epoch.
595    #[serde(with = "chrono::serde::ts_seconds")]
596    #[schema(value_type = u64)]
597    pub start_time: DateTime<Utc>,
598    /// Uniquely identifies the pipeline process that started at start_time.
599    pub incarnation_uuid: Uuid,
600    /// Time at which the pipeline process from which we resumed started, in seconds since the epoch.
601    #[serde(with = "chrono::serde::ts_seconds")]
602    #[schema(value_type = u64)]
603    pub initial_start_time: DateTime<Utc>,
604    /// Current storage usage in bytes.
605    pub storage_bytes: u64,
606    /// Storage usage integrated over time, in megabytes * seconds.
607    pub storage_mb_secs: u64,
608    /// Capacity of the pipeline's storage disk, in bytes; absent when unknown.
609    #[serde(default, skip_serializing_if = "Option::is_none")]
610    pub disk_total_bytes: Option<u64>,
611    /// Bytes the pipeline can still write to its storage disk; absent when unknown.
612    #[serde(default, skip_serializing_if = "Option::is_none")]
613    pub disk_available_bytes: Option<u64>,
614    /// Time elapsed while the pipeline is executing a step, multiplied by the number of threads, in milliseconds.
615    pub runtime_elapsed_msecs: u64,
616    /// Total number of records currently buffered by all endpoints.
617    pub buffered_input_records: u64,
618    /// Total number of bytes currently buffered by all endpoints.
619    pub buffered_input_bytes: u64,
620    /// Total number of records received from all endpoints.
621    pub total_input_records: u64,
622    /// Total number of bytes received from all endpoints.
623    pub total_input_bytes: u64,
624    /// Total number of input records processed by the DBSP engine.
625    pub total_processed_records: u64,
626    /// Total bytes of input records processed by the DBSP engine.
627    pub total_processed_bytes: u64,
628    /// Total number of input records processed to completion.
629    ///
630    /// In a multihost pipeline, this counts the input records that all of the
631    /// hosts received.  If a host runs an older version that does not report
632    /// its count to the coordinator, this is instead the sum of the counts
633    /// that each host reports for its own input, which can include input whose
634    /// output an output connector on a different host has not yet processed.
635    pub total_completed_records: u64,
636    /// If the pipeline is stalled because one or more output connectors' output
637    /// buffers are full, this is the number of milliseconds that the current
638    /// stall has lasted.
639    ///
640    /// If this is nonzero, then the output connectors causing the stall can be
641    /// identified by noticing `ExternalOutputEndpointMetrics::queued_records`
642    /// is greater than or equal to `ConnectorConfig::max_queued_records`.
643    ///
644    /// In the ordinary case, the pipeline is not stalled, and this value is 0.
645    pub output_stall_msecs: u64,
646    /// Number of steps that have been initiated.
647    ///
648    /// # Interpretation
649    ///
650    /// This is a count, not a step number.  If `total_initiated_steps` is 0, no
651    /// steps have been initiated.  If `total_initiated_steps > 0`, then step
652    /// `total_initiated_steps - 1` has been started and all steps previous to
653    /// that have been completely processed by the circuit.
654    #[schema(value_type = u64)]
655    pub total_initiated_steps: Step,
656    /// Number of steps whose input records have been processed to completion.
657    ///
658    /// A record is processed to completion if it has been processed by the DBSP engine and
659    /// all outputs derived from it have been processed by all output connectors.
660    ///
661    /// # Interpretation
662    ///
663    /// This is a count, not a step number.  If `total_completed_steps` is 0, no
664    /// steps have been processed to completion.  If `total_completed_steps >
665    /// 0`, then the last step whose input records have been processed to
666    /// completion is `total_completed_steps - 1`. A record that was ingested
667    /// when `total_initiated_steps` was `n` is fully processed when
668    /// `total_completed_steps >= n`.
669    #[schema(value_type = u64)]
670    pub total_completed_steps: Step,
671    /// True if the pipeline has processed all input data to completion.
672    pub pipeline_complete: bool,
673    /// Version of the platform that compiled the pipeline, such as
674    /// `0.349.0+enterprise`.
675    ///
676    /// This is the platform's own version, which the compiler records in the
677    /// binary.
678    pub platform_version: String,
679    /// Runtime the pipeline was compiled against.
680    ///
681    /// Equal to `platform_version` when the program uses the platform's own
682    /// runtime; otherwise the selected runtime, a git SHA, a `vX.Y.Z` tag,
683    /// or `gen2`.
684    pub runtime_version: String,
685}
686
687/// Complete pipeline statistics returned by the `/stats` endpoint.
688///
689/// This schema definition matches the serialized JSON structure from
690/// `adapters::controller::ControllerStatus`. The actual implementation with
691/// atomics and mutexes lives in the adapters crate, which uses ExternalControllerStatus to
692/// register this OpenAPI schema, making it available to pipeline-manager
693/// without requiring a direct dependency on the adapters crate.
694#[derive(Debug, Deserialize, Serialize, ToSchema, Default)]
695#[schema(as = ControllerStatus)]
696pub struct ExternalControllerStatus {
697    /// Global controller metrics.
698    #[schema(value_type = GlobalControllerMetrics)]
699    pub global_metrics: ExternalGlobalControllerMetrics,
700    /// Reason why the pipeline cannot be suspended or checkpointed (if any).
701    pub suspend_error: Option<SuspendError>,
702    /// Current checkpoint activity (idle, delayed, or in-progress).
703    /// `None` when the pipeline binary predates checkpoint activity tracking.
704    pub checkpoint_activity: Option<CheckpointActivity>,
705    /// If the pipeline fundamentally cannot checkpoint (e.g. storage is not
706    /// configured, or an input endpoint does not support suspend), the reasons
707    /// are listed here.  Unlike a checkpoint failure, this means *no*
708    /// checkpoint can succeed until the pipeline configuration changes.
709    pub permanent_checkpoint_errors: Option<Vec<PermanentSuspendError>>,
710    /// Input endpoint configs and metrics.
711    #[schema(value_type = Vec<InputEndpointStatus>)]
712    pub inputs: Vec<ExternalInputEndpointStatus>,
713    /// Output endpoint configs and metrics.
714    #[schema(value_type = Vec<OutputEndpointStatus>)]
715    pub outputs: Vec<ExternalOutputEndpointStatus>,
716    /// Resource usage of each host in a multihost pipeline, by ordinal.
717    #[serde(default, skip_serializing_if = "Vec::is_empty")]
718    pub host_metrics: Vec<HostMetrics>,
719}
720
721/// Resource usage of one host in a multihost pipeline.
722#[derive(Debug, Default, Deserialize, Serialize, ToSchema)]
723pub struct HostMetrics {
724    /// Capacity of the host's storage disk, in bytes; absent when unknown.
725    #[serde(default, skip_serializing_if = "Option::is_none")]
726    pub disk_total_bytes: Option<u64>,
727    /// Bytes the host can still write to its storage disk; absent when unknown.
728    #[serde(default, skip_serializing_if = "Option::is_none")]
729    pub disk_available_bytes: Option<u64>,
730}
731
732impl From<&ExternalGlobalControllerMetrics> for HostMetrics {
733    fn from(metrics: &ExternalGlobalControllerMetrics) -> Self {
734        Self {
735            disk_total_bytes: metrics.disk_total_bytes,
736            disk_available_bytes: metrics.disk_available_bytes,
737        }
738    }
739}
740
741fn serialize_timestamp_micros<S>(
742    timestamp: &DateTime<Utc>,
743    serializer: S,
744) -> Result<S::Ok, S::Error>
745where
746    S: serde::Serializer,
747{
748    serializer.serialize_str(&timestamp.to_rfc3339_opts(SecondsFormat::Micros, true))
749}
750
751#[cfg(test)]
752mod tests {
753    use super::ConnectorError;
754    use chrono::{DateTime, Utc};
755
756    #[test]
757    fn connector_error_timestamp_serializes_with_microsecond_precision() {
758        let error = ConnectorError {
759            timestamp: DateTime::parse_from_rfc3339("2026-03-08T05:26:42.442438448Z")
760                .unwrap()
761                .with_timezone(&Utc),
762            index: 1,
763            tag: None,
764            message: "boom".to_string(),
765        };
766
767        let json = serde_json::to_string(&error).unwrap();
768        assert!(json.contains(r#""timestamp":"2026-03-08T05:26:42.442438Z""#));
769    }
770
771    #[test]
772    fn output_metrics_batch_records_written_serializes() {
773        use super::ExternalOutputEndpointMetrics;
774
775        let metrics = ExternalOutputEndpointMetrics {
776            batch_records_written: Some(42),
777            ..Default::default()
778        };
779        let json = serde_json::to_string(&metrics).unwrap();
780        assert!(json.contains(r#""batch_records_written":42"#));
781
782        let deserialized: ExternalOutputEndpointMetrics = serde_json::from_str(&json).unwrap();
783        assert_eq!(deserialized.batch_records_written, Some(42));
784    }
785
786    #[test]
787    fn output_metrics_batch_records_written_defaults_to_none() {
788        use super::ExternalOutputEndpointMetrics;
789
790        // Old JSON without batch_records_written defaults to None.
791        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}"#;
792        let metrics: ExternalOutputEndpointMetrics = serde_json::from_str(json).unwrap();
793        assert_eq!(metrics.batch_records_written, None);
794    }
795
796    mod merge {
797        use chrono::{DateTime, TimeZone, Utc};
798
799        use crate::adapter_stats::{
800            CompletedWatermark, ConnectorError, ConnectorHealth, ConnectorHealthStatus,
801            ExternalInputEndpointMetrics, ExternalInputEndpointStatus, FrontierMerge,
802            ShortEndpointConfig,
803        };
804        use serde_json::{Value, json};
805
806        fn time(secs: i64) -> DateTime<Utc> {
807            Utc.timestamp_opt(secs, 0).unwrap()
808        }
809
810        fn error(secs: i64, message: &str) -> ConnectorError {
811            ConnectorError {
812                timestamp: time(secs),
813                index: 0,
814                tag: None,
815                message: message.into(),
816            }
817        }
818
819        fn frontier(ingested_secs: i64) -> CompletedWatermark {
820            CompletedWatermark {
821                metadata: serde_json::json!(ingested_secs),
822                ingested_at: time(ingested_secs),
823                processed_at: time(ingested_secs + 1),
824                completed_at: time(ingested_secs + 2),
825            }
826        }
827
828        fn status() -> ExternalInputEndpointStatus {
829            ExternalInputEndpointStatus {
830                endpoint_name: "t.kafka".into(),
831                config: ShortEndpointConfig { stream: "t".into() },
832                metrics: ExternalInputEndpointMetrics {
833                    total_bytes: 10,
834                    total_records: 1,
835                    buffered_records: 2,
836                    buffered_bytes: 20,
837                    num_transport_errors: 3,
838                    num_parse_errors: 4,
839                    end_of_input: true,
840                    processing_latency_p99_micros: Some(100),
841                },
842                fatal_error: None,
843                parse_errors: None,
844                transport_errors: None,
845                health: Some(ConnectorHealth::healthy()),
846                paused: false,
847                barrier: false,
848                completed_frontier: None,
849            }
850        }
851
852        #[test]
853        fn counters_add_up() {
854            let mut a = status();
855            let mut b = status();
856            b.metrics.processing_latency_p99_micros = Some(500);
857            b.metrics.end_of_input = false;
858            a.merge(b, FrontierMerge::Opaque);
859            let m = &a.metrics;
860            assert_eq!(
861                (
862                    m.total_bytes,
863                    m.total_records,
864                    m.buffered_records,
865                    m.buffered_bytes
866                ),
867                (20, 2, 4, 40)
868            );
869            assert_eq!((m.num_transport_errors, m.num_parse_errors), (6, 8));
870            assert!(!m.end_of_input);
871            assert_eq!(m.processing_latency_p99_micros, Some(500));
872        }
873
874        #[test]
875        fn worst_host_decides() {
876            let mut a = status();
877            let mut b = status();
878            b.fatal_error = Some("broken".into());
879            b.health = Some(ConnectorHealth::unhealthy("sick"));
880            b.barrier = true;
881            a.merge(b, FrontierMerge::Opaque);
882            assert_eq!(a.fatal_error.as_deref(), Some("broken"));
883            assert!(matches!(
884                a.health.unwrap().status,
885                ConnectorHealthStatus::Unhealthy
886            ));
887            assert!(a.barrier);
888
889            // The first fatal error stays.
890            let mut a = status();
891            a.fatal_error = Some("first".into());
892            let mut b = status();
893            b.fatal_error = Some("second".into());
894            a.merge(b, FrontierMerge::Opaque);
895            assert_eq!(a.fatal_error.as_deref(), Some("first"));
896        }
897
898        /// Merges hosts given as (end of input, frontier ingestion time,
899        /// metadata) with `kind`, and returns the merged frontier's ingestion
900        /// time and metadata.
901        fn merge_metadata(
902            hosts: Vec<(bool, Option<(i64, Value)>)>,
903            kind: FrontierMerge,
904        ) -> Option<(DateTime<Utc>, Value)> {
905            let mut statuses = hosts.into_iter().map(|(eoi, f)| {
906                let mut s = status();
907                s.metrics.end_of_input = eoi;
908                s.completed_frontier = f.map(|(secs, metadata)| CompletedWatermark {
909                    metadata,
910                    ..frontier(secs)
911                });
912                s
913            });
914            let mut x = statuses.next().unwrap();
915            statuses.for_each(|y| x.merge(y, kind));
916            x.completed_frontier.map(|f| (f.ingested_at, f.metadata))
917        }
918
919        /// Shared metadata stays with its host's frontier, however many
920        /// hosts report one.
921        #[test]
922        fn shared_frontier_merge() {
923            let merged = |hosts| merge_metadata(hosts, FrontierMerge::Shared);
924            let version = |v: i64| json!({"version": v});
925            assert_eq!(
926                merged(vec![
927                    (false, Some((10, version(3)))),
928                    (false, Some((5, version(2))))
929                ]),
930                Some((time(5), version(2)))
931            );
932            assert_eq!(
933                merged(vec![
934                    (true, Some((5, version(2)))),
935                    (false, Some((10, version(7))))
936                ]),
937                Some((time(10), version(7)))
938            );
939            assert_eq!(
940                merged(vec![
941                    (true, Some((5, version(2)))),
942                    (true, Some((10, version(2))))
943                ]),
944                Some((time(10), version(2)))
945            );
946        }
947
948        /// Partitioned metadata joins every host's partitions, including
949        /// those of hosts at end of input.
950        #[test]
951        fn partitioned_frontier_merge() {
952            let merged = |hosts| merge_metadata(hosts, FrontierMerge::Partitioned);
953            // A host's metadata, which also has fields that the join drops.
954            let host = |partitions: &[i64], offsets: &[i64]| json!({"partitions": partitions, "offsets": offsets, "shard": {"host": 0}});
955            let joined = |partitions: &[i64], offsets: &[i64]| json!({"partitions": partitions, "offsets": offsets});
956
957            // Busy hosts, in any order.
958            assert_eq!(
959                merged(vec![
960                    (false, Some((10, host(&[1, 4], &[11, 14])))),
961                    (false, Some((5, host(&[2], &[12])))),
962                    (false, Some((7, host(&[0, 3], &[10, 13])))),
963                ]),
964                Some((time(5), joined(&[0, 1, 2, 3, 4], &[10, 11, 12, 13, 14])))
965            );
966
967            // Hosts at end of input add their partitions but not their time.
968            assert_eq!(
969                merged(vec![
970                    (true, Some((5, host(&[1], &[11])))),
971                    (false, Some((10, host(&[0], &[10])))),
972                ]),
973                Some((time(10), joined(&[0, 1], &[10, 11])))
974            );
975            assert_eq!(
976                merged(vec![
977                    (true, Some((10, host(&[1], &[11])))),
978                    (true, Some((5, host(&[0], &[10])))),
979                ]),
980                Some((time(10), joined(&[0, 1], &[10, 11])))
981            );
982
983            // A host with no partitions and no frontier adds nothing, and one
984            // host's metadata takes the joined form.
985            assert_eq!(
986                merged(vec![(true, None), (false, Some((10, host(&[0], &[10]))))]),
987                Some((time(10), joined(&[0], &[10])))
988            );
989
990            // A busy host with no frontier still holds back the frontier.
991            assert_eq!(
992                merged(vec![(false, None), (true, Some((10, host(&[0], &[10]))))]),
993                None
994            );
995
996            // Metadata without partitions, as from an older host, or with a
997            // partition that two hosts report, joins to null.
998            for other in [json!({"offsets": [11]}), host(&[0], &[11]), Value::Null] {
999                assert_eq!(
1000                    merged(vec![
1001                        (false, Some((10, host(&[0], &[10])))),
1002                        (false, Some((5, other.clone()))),
1003                    ]),
1004                    Some((time(5), Value::Null)),
1005                    "{other}"
1006                );
1007            }
1008        }
1009
1010        /// A connector is paused only if every host is, in any order.
1011        #[test]
1012        fn pause_merge() {
1013            let merged = |hosts: &[bool]| {
1014                let mut statuses = hosts.iter().map(|&paused| {
1015                    let mut s = status();
1016                    s.paused = paused;
1017                    s
1018                });
1019                let mut x = statuses.next().unwrap();
1020                statuses.for_each(|y| x.merge(y, FrontierMerge::Opaque));
1021                x.paused
1022            };
1023            assert!(merged(&[true, true, true]));
1024            assert!(!merged(&[false, false, false]));
1025            for hosts in [
1026                [true, false, false],
1027                [false, true, false],
1028                [false, false, true],
1029                [true, true, false],
1030                [false, true, true],
1031                [true, false, true],
1032            ] {
1033                assert!(!merged(&hosts), "{hosts:?}");
1034            }
1035        }
1036
1037        #[test]
1038        fn errors_are_combined_in_time_order() {
1039            let mut a = status();
1040            a.parse_errors = Some(vec![error(1, "a1"), error(5, "a5")]);
1041            let mut b = status();
1042            b.parse_errors = Some(vec![error(3, "b3")]);
1043            b.transport_errors = Some(vec![error(2, "b2")]);
1044            a.merge(b, FrontierMerge::Opaque);
1045            let messages = |errors: &Option<Vec<ConnectorError>>| {
1046                errors
1047                    .iter()
1048                    .flatten()
1049                    .map(|e| e.message.clone())
1050                    .collect::<Vec<_>>()
1051            };
1052            assert_eq!(messages(&a.parse_errors), ["a1", "b3", "a5"]);
1053            assert_eq!(messages(&a.transport_errors), ["b2"]);
1054        }
1055
1056        #[test]
1057        fn opaque_frontier_merge() {
1058            // Merges hosts given as (end of input, frontier) and returns the
1059            // merged frontier's ingestion time and whether it kept metadata.
1060            let merged = |hosts: &[(bool, Option<i64>)]| {
1061                let mut statuses = hosts.iter().map(|&(eoi, f)| {
1062                    let mut s = status();
1063                    s.metrics.end_of_input = eoi;
1064                    s.completed_frontier = f.map(frontier);
1065                    s
1066                });
1067                let mut x = statuses.next().unwrap();
1068                statuses.for_each(|y| x.merge(y, FrontierMerge::Opaque));
1069                x.completed_frontier
1070                    .map(|f| (f.ingested_at, !f.metadata.is_null()))
1071            };
1072            let (busy, done) = (false, true);
1073
1074            // The oldest frontier among hosts that are still reading.
1075            assert_eq!(
1076                merged(&[(busy, Some(10)), (busy, Some(5))]),
1077                Some((time(5), false))
1078            );
1079            assert_eq!(
1080                merged(&[(busy, Some(5)), (busy, Some(10))]),
1081                Some((time(5), false))
1082            );
1083
1084            // A host still reading with no frontier holds back the frontier,
1085            // in any position.
1086            assert_eq!(merged(&[(busy, None), (busy, Some(10))]), None);
1087            assert_eq!(merged(&[(busy, Some(10)), (busy, None)]), None);
1088            assert_eq!(
1089                merged(&[(busy, Some(10)), (busy, None), (busy, Some(5))]),
1090                None
1091            );
1092            assert_eq!(
1093                merged(&[(busy, None), (done, Some(5)), (busy, Some(10))]),
1094                None
1095            );
1096
1097            // Hosts at end of input do not hold back the frontier, and the
1098            // one host still reading keeps its metadata, as a Delta Lake
1099            // connector's home host does while it follows the table.
1100            assert_eq!(
1101                merged(&[(busy, Some(10)), (done, Some(5))]),
1102                Some((time(10), true))
1103            );
1104            assert_eq!(
1105                merged(&[(done, Some(5)), (busy, Some(10))]),
1106                Some((time(10), true))
1107            );
1108            assert_eq!(
1109                merged(&[(done, None), (busy, Some(10))]),
1110                Some((time(10), true))
1111            );
1112            assert_eq!(
1113                merged(&[(busy, Some(10)), (done, None)]),
1114                Some((time(10), true))
1115            );
1116            assert_eq!(
1117                merged(&[(done, Some(5)), (busy, Some(10)), (done, Some(20))]),
1118                Some((time(10), true))
1119            );
1120            assert_eq!(
1121                merged(&[(done, Some(5)), (busy, Some(10)), (busy, Some(20))]),
1122                Some((time(10), false))
1123            );
1124
1125            // If every host is at end of input, the newest frontier.
1126            assert_eq!(
1127                merged(&[(done, Some(10)), (done, Some(5))]),
1128                Some((time(10), true))
1129            );
1130            assert_eq!(
1131                merged(&[(done, None), (done, Some(5))]),
1132                Some((time(5), true))
1133            );
1134            assert_eq!(merged(&[(done, None), (done, None)]), None);
1135        }
1136    }
1137}