Skip to main content

feldera_types/
adapter_stats.rs

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