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, this count reflects only the input records
480    /// processed on the same host as the output endpoint, which is not usually
481    /// meaningful.
482    pub total_processed_input_records: u64,
483    /// The number of steps whose input records have been processed by the
484    /// endpoint.
485    ///
486    /// This is meaningful in a multihost pipeline because steps are
487    /// synchronized across all of the hosts.
488    ///
489    /// # Interpretation
490    ///
491    /// This is a count, not a step number.  If `total_processed_steps` is 0, no
492    /// steps have been processed to completion.  If `total_processed_steps >
493    /// 0`, then the last step whose input records have been processed to
494    /// completion is `total_processed_steps - 1`. A record that was ingested in
495    /// step `n` is fully processed when `total_processed_steps > n`.
496    #[schema(value_type = u64)]
497    pub total_processed_steps: Step,
498    /// Extra memory in use beyond that used for queuing records.
499    pub memory: u64,
500    /// Number of records written so far while the connector is processing a
501    /// batch of updates.  Resets to 0 after the batch is committed.
502    ///
503    /// `None` when the connector does not support batch-progress reporting.
504    #[serde(default, skip_serializing_if = "Option::is_none")]
505    pub batch_records_written: Option<u64>,
506}
507
508/// Output endpoint status information.
509#[derive(Debug, Deserialize, Serialize, ToSchema)]
510#[schema(as = OutputEndpointStatus)]
511pub struct ExternalOutputEndpointStatus {
512    /// Endpoint name.
513    pub endpoint_name: String,
514    /// Endpoint configuration.
515    pub config: ShortEndpointConfig,
516    /// Performance metrics.
517    #[schema(value_type = OutputEndpointMetrics)]
518    pub metrics: ExternalOutputEndpointMetrics,
519    /// The first fatal error that occurred at the endpoint.
520    pub fatal_error: Option<String>,
521    /// Recent encoding errors on this endpoint.
522    #[serde(default, skip_serializing_if = "Option::is_none")]
523    pub encode_errors: Option<Vec<ConnectorError>>,
524    /// Recent transport errors on this endpoint.
525    #[serde(default, skip_serializing_if = "Option::is_none")]
526    pub transport_errors: Option<Vec<ConnectorError>>,
527    /// Health status of the connector.
528    #[serde(default)]
529    pub health: Option<ConnectorHealth>,
530    /// Endpoint has been paused by the user.
531    ///
532    /// A paused output endpoint discards the output it receives instead of
533    /// sending it to its sink.
534    #[serde(default)]
535    pub paused: bool,
536}
537
538/// Global controller metrics.
539#[derive(Debug, Default, Serialize, Deserialize, ToSchema)]
540#[schema(as = GlobalControllerMetrics)]
541pub struct ExternalGlobalControllerMetrics {
542    /// State of the pipeline: running, paused, or terminating.
543    pub state: PipelineState,
544    /// The pipeline has been resumed from a checkpoint and is currently bootstrapping new and modified views.
545    pub bootstrap_in_progress: bool,
546    /// Status of the current transaction.
547    pub transaction_status: TransactionStatus,
548    /// ID of the current transaction or 0 if no transaction is in progress.
549    #[schema(value_type = i64)]
550    pub transaction_id: TransactionId,
551    /// Elapsed time in milliseconds, according to `transaction_status`:
552    ///
553    /// - [TransactionStatus::TransactionInProgress]: Time that this transaction
554    ///   has been in progress.
555    ///
556    /// - [TransactionStatus::CommitInProgress]: Time that this transaction has
557    ///   been committing.
558    pub transaction_msecs: Option<u64>,
559    /// Number of records in this transaction, according to
560    /// `transaction_status`:
561    ///
562    /// - [TransactionStatus::TransactionInProgress]: Number of records added so
563    ///   far.  More records might be added.
564    ///
565    /// - [TransactionStatus::CommitInProgress]: Final number of records.
566    pub transaction_records: Option<u64>,
567    /// Progress of the current transaction commit, if one is in progress.
568    pub commit_progress: Option<CommitProgressSummary>,
569    /// Entities that initiated the current transaction.
570    #[schema(value_type = TransactionInitiators)]
571    pub transaction_initiators: ExternalTransactionInitiators,
572    /// Phase of a concurrent bootstrap, or `Inactive` if none is in progress.
573    pub concurrent_bootstrap_phase: ConcurrentBootstrapPhase,
574    /// Progress of the concurrent bootstrap's transaction commit, if a commit is
575    /// in progress: the backfill transaction during `ConcurrentBootstrapping` and
576    /// the synchronization transaction during `Synchronizing`.
577    pub concurrent_bootstrap_progress: Option<CommitProgressSummary>,
578    /// Resident set size of the pipeline process, in bytes.
579    pub rss_bytes: u64,
580    /// Memory pressure.
581    pub memory_pressure: MemoryPressure,
582    /// Memory pressure epoch.
583    pub memory_pressure_epoch: u64,
584    /// CPU time used by the pipeline across all threads, in milliseconds.
585    pub cpu_msecs: u64,
586    /// Time since the pipeline process started, including time that the
587    /// pipeline was running or paused.
588    ///
589    /// This is the elapsed time since `start_time`.
590    pub uptime_msecs: u64,
591    /// Time at which the pipeline process started, in seconds since the epoch.
592    #[serde(with = "chrono::serde::ts_seconds")]
593    #[schema(value_type = u64)]
594    pub start_time: DateTime<Utc>,
595    /// Uniquely identifies the pipeline process that started at start_time.
596    pub incarnation_uuid: Uuid,
597    /// Time at which the pipeline process from which we resumed started, in seconds since the epoch.
598    #[serde(with = "chrono::serde::ts_seconds")]
599    #[schema(value_type = u64)]
600    pub initial_start_time: DateTime<Utc>,
601    /// Current storage usage in bytes.
602    pub storage_bytes: u64,
603    /// Storage usage integrated over time, in megabytes * seconds.
604    pub storage_mb_secs: u64,
605    /// Capacity of the pipeline's storage disk, in bytes; absent when unknown.
606    #[serde(default, skip_serializing_if = "Option::is_none")]
607    pub disk_total_bytes: Option<u64>,
608    /// Bytes the pipeline can still write to its storage disk; absent when unknown.
609    #[serde(default, skip_serializing_if = "Option::is_none")]
610    pub disk_available_bytes: Option<u64>,
611    /// Time elapsed while the pipeline is executing a step, multiplied by the number of threads, in milliseconds.
612    pub runtime_elapsed_msecs: u64,
613    /// Total number of records currently buffered by all endpoints.
614    pub buffered_input_records: u64,
615    /// Total number of bytes currently buffered by all endpoints.
616    pub buffered_input_bytes: u64,
617    /// Total number of records received from all endpoints.
618    pub total_input_records: u64,
619    /// Total number of bytes received from all endpoints.
620    pub total_input_bytes: u64,
621    /// Total number of input records processed by the DBSP engine.
622    pub total_processed_records: u64,
623    /// Total bytes of input records processed by the DBSP engine.
624    pub total_processed_bytes: u64,
625    /// Total number of input records processed to completion.
626    pub total_completed_records: u64,
627    /// If the pipeline is stalled because one or more output connectors' output
628    /// buffers are full, this is the number of milliseconds that the current
629    /// stall has lasted.
630    ///
631    /// If this is nonzero, then the output connectors causing the stall can be
632    /// identified by noticing `ExternalOutputEndpointMetrics::queued_records`
633    /// is greater than or equal to `ConnectorConfig::max_queued_records`.
634    ///
635    /// In the ordinary case, the pipeline is not stalled, and this value is 0.
636    pub output_stall_msecs: u64,
637    /// Number of steps that have been initiated.
638    ///
639    /// # Interpretation
640    ///
641    /// This is a count, not a step number.  If `total_initiated_steps` is 0, no
642    /// steps have been initiated.  If `total_initiated_steps > 0`, then step
643    /// `total_initiated_steps - 1` has been started and all steps previous to
644    /// that have been completely processed by the circuit.
645    #[schema(value_type = u64)]
646    pub total_initiated_steps: Step,
647    /// Number of steps whose input records have been processed to completion.
648    ///
649    /// A record is processed to completion if it has been processed by the DBSP engine and
650    /// all outputs derived from it have been processed by all output connectors.
651    ///
652    /// # Interpretation
653    ///
654    /// This is a count, not a step number.  If `total_completed_steps` is 0, no
655    /// steps have been processed to completion.  If `total_completed_steps >
656    /// 0`, then the last step whose input records have been processed to
657    /// completion is `total_completed_steps - 1`. A record that was ingested
658    /// when `total_initiated_steps` was `n` is fully processed when
659    /// `total_completed_steps >= n`.
660    #[schema(value_type = u64)]
661    pub total_completed_steps: Step,
662    /// True if the pipeline has processed all input data to completion.
663    pub pipeline_complete: bool,
664    /// Version of the platform that compiled the pipeline, such as
665    /// `0.349.0+enterprise`.
666    ///
667    /// This is the platform's own version, which the compiler records in the
668    /// binary.
669    pub platform_version: String,
670    /// Runtime the pipeline was compiled against.
671    ///
672    /// Equal to `platform_version` when the program uses the platform's own
673    /// runtime; otherwise the selected runtime, a git SHA, a `vX.Y.Z` tag,
674    /// or `gen2`.
675    pub runtime_version: String,
676}
677
678/// Complete pipeline statistics returned by the `/stats` endpoint.
679///
680/// This schema definition matches the serialized JSON structure from
681/// `adapters::controller::ControllerStatus`. The actual implementation with
682/// atomics and mutexes lives in the adapters crate, which uses ExternalControllerStatus to
683/// register this OpenAPI schema, making it available to pipeline-manager
684/// without requiring a direct dependency on the adapters crate.
685#[derive(Debug, Deserialize, Serialize, ToSchema, Default)]
686#[schema(as = ControllerStatus)]
687pub struct ExternalControllerStatus {
688    /// Global controller metrics.
689    #[schema(value_type = GlobalControllerMetrics)]
690    pub global_metrics: ExternalGlobalControllerMetrics,
691    /// Reason why the pipeline cannot be suspended or checkpointed (if any).
692    pub suspend_error: Option<SuspendError>,
693    /// Current checkpoint activity (idle, delayed, or in-progress).
694    /// `None` when the pipeline binary predates checkpoint activity tracking.
695    pub checkpoint_activity: Option<CheckpointActivity>,
696    /// If the pipeline fundamentally cannot checkpoint (e.g. storage is not
697    /// configured, or an input endpoint does not support suspend), the reasons
698    /// are listed here.  Unlike a checkpoint failure, this means *no*
699    /// checkpoint can succeed until the pipeline configuration changes.
700    pub permanent_checkpoint_errors: Option<Vec<PermanentSuspendError>>,
701    /// Input endpoint configs and metrics.
702    #[schema(value_type = Vec<InputEndpointStatus>)]
703    pub inputs: Vec<ExternalInputEndpointStatus>,
704    /// Output endpoint configs and metrics.
705    #[schema(value_type = Vec<OutputEndpointStatus>)]
706    pub outputs: Vec<ExternalOutputEndpointStatus>,
707    /// Resource usage of each host in a multihost pipeline, by ordinal.
708    #[serde(default, skip_serializing_if = "Vec::is_empty")]
709    pub host_metrics: Vec<HostMetrics>,
710}
711
712/// Resource usage of one host in a multihost pipeline.
713#[derive(Debug, Default, Deserialize, Serialize, ToSchema)]
714pub struct HostMetrics {
715    /// Capacity of the host's storage disk, in bytes; absent when unknown.
716    #[serde(default, skip_serializing_if = "Option::is_none")]
717    pub disk_total_bytes: Option<u64>,
718    /// Bytes the host can still write to its storage disk; absent when unknown.
719    #[serde(default, skip_serializing_if = "Option::is_none")]
720    pub disk_available_bytes: Option<u64>,
721}
722
723impl From<&ExternalGlobalControllerMetrics> for HostMetrics {
724    fn from(metrics: &ExternalGlobalControllerMetrics) -> Self {
725        Self {
726            disk_total_bytes: metrics.disk_total_bytes,
727            disk_available_bytes: metrics.disk_available_bytes,
728        }
729    }
730}
731
732fn serialize_timestamp_micros<S>(
733    timestamp: &DateTime<Utc>,
734    serializer: S,
735) -> Result<S::Ok, S::Error>
736where
737    S: serde::Serializer,
738{
739    serializer.serialize_str(&timestamp.to_rfc3339_opts(SecondsFormat::Micros, true))
740}
741
742#[cfg(test)]
743mod tests {
744    use super::ConnectorError;
745    use chrono::{DateTime, Utc};
746
747    #[test]
748    fn connector_error_timestamp_serializes_with_microsecond_precision() {
749        let error = ConnectorError {
750            timestamp: DateTime::parse_from_rfc3339("2026-03-08T05:26:42.442438448Z")
751                .unwrap()
752                .with_timezone(&Utc),
753            index: 1,
754            tag: None,
755            message: "boom".to_string(),
756        };
757
758        let json = serde_json::to_string(&error).unwrap();
759        assert!(json.contains(r#""timestamp":"2026-03-08T05:26:42.442438Z""#));
760    }
761
762    #[test]
763    fn output_metrics_batch_records_written_serializes() {
764        use super::ExternalOutputEndpointMetrics;
765
766        let metrics = ExternalOutputEndpointMetrics {
767            batch_records_written: Some(42),
768            ..Default::default()
769        };
770        let json = serde_json::to_string(&metrics).unwrap();
771        assert!(json.contains(r#""batch_records_written":42"#));
772
773        let deserialized: ExternalOutputEndpointMetrics = serde_json::from_str(&json).unwrap();
774        assert_eq!(deserialized.batch_records_written, Some(42));
775    }
776
777    #[test]
778    fn output_metrics_batch_records_written_defaults_to_none() {
779        use super::ExternalOutputEndpointMetrics;
780
781        // Old JSON without batch_records_written defaults to None.
782        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}"#;
783        let metrics: ExternalOutputEndpointMetrics = serde_json::from_str(json).unwrap();
784        assert_eq!(metrics.batch_records_written, None);
785    }
786
787    mod merge {
788        use chrono::{DateTime, TimeZone, Utc};
789
790        use crate::adapter_stats::{
791            CompletedWatermark, ConnectorError, ConnectorHealth, ConnectorHealthStatus,
792            ExternalInputEndpointMetrics, ExternalInputEndpointStatus, FrontierMerge,
793            ShortEndpointConfig,
794        };
795        use serde_json::{Value, json};
796
797        fn time(secs: i64) -> DateTime<Utc> {
798            Utc.timestamp_opt(secs, 0).unwrap()
799        }
800
801        fn error(secs: i64, message: &str) -> ConnectorError {
802            ConnectorError {
803                timestamp: time(secs),
804                index: 0,
805                tag: None,
806                message: message.into(),
807            }
808        }
809
810        fn frontier(ingested_secs: i64) -> CompletedWatermark {
811            CompletedWatermark {
812                metadata: serde_json::json!(ingested_secs),
813                ingested_at: time(ingested_secs),
814                processed_at: time(ingested_secs + 1),
815                completed_at: time(ingested_secs + 2),
816            }
817        }
818
819        fn status() -> ExternalInputEndpointStatus {
820            ExternalInputEndpointStatus {
821                endpoint_name: "t.kafka".into(),
822                config: ShortEndpointConfig { stream: "t".into() },
823                metrics: ExternalInputEndpointMetrics {
824                    total_bytes: 10,
825                    total_records: 1,
826                    buffered_records: 2,
827                    buffered_bytes: 20,
828                    num_transport_errors: 3,
829                    num_parse_errors: 4,
830                    end_of_input: true,
831                    processing_latency_p99_micros: Some(100),
832                },
833                fatal_error: None,
834                parse_errors: None,
835                transport_errors: None,
836                health: Some(ConnectorHealth::healthy()),
837                paused: false,
838                barrier: false,
839                completed_frontier: None,
840            }
841        }
842
843        #[test]
844        fn counters_add_up() {
845            let mut a = status();
846            let mut b = status();
847            b.metrics.processing_latency_p99_micros = Some(500);
848            b.metrics.end_of_input = false;
849            a.merge(b, FrontierMerge::Opaque);
850            let m = &a.metrics;
851            assert_eq!(
852                (
853                    m.total_bytes,
854                    m.total_records,
855                    m.buffered_records,
856                    m.buffered_bytes
857                ),
858                (20, 2, 4, 40)
859            );
860            assert_eq!((m.num_transport_errors, m.num_parse_errors), (6, 8));
861            assert!(!m.end_of_input);
862            assert_eq!(m.processing_latency_p99_micros, Some(500));
863        }
864
865        #[test]
866        fn worst_host_decides() {
867            let mut a = status();
868            let mut b = status();
869            b.fatal_error = Some("broken".into());
870            b.health = Some(ConnectorHealth::unhealthy("sick"));
871            b.barrier = true;
872            a.merge(b, FrontierMerge::Opaque);
873            assert_eq!(a.fatal_error.as_deref(), Some("broken"));
874            assert!(matches!(
875                a.health.unwrap().status,
876                ConnectorHealthStatus::Unhealthy
877            ));
878            assert!(a.barrier);
879
880            // The first fatal error stays.
881            let mut a = status();
882            a.fatal_error = Some("first".into());
883            let mut b = status();
884            b.fatal_error = Some("second".into());
885            a.merge(b, FrontierMerge::Opaque);
886            assert_eq!(a.fatal_error.as_deref(), Some("first"));
887        }
888
889        /// Merges hosts given as (end of input, frontier ingestion time,
890        /// metadata) with `kind`, and returns the merged frontier's ingestion
891        /// time and metadata.
892        fn merge_metadata(
893            hosts: Vec<(bool, Option<(i64, Value)>)>,
894            kind: FrontierMerge,
895        ) -> Option<(DateTime<Utc>, Value)> {
896            let mut statuses = hosts.into_iter().map(|(eoi, f)| {
897                let mut s = status();
898                s.metrics.end_of_input = eoi;
899                s.completed_frontier = f.map(|(secs, metadata)| CompletedWatermark {
900                    metadata,
901                    ..frontier(secs)
902                });
903                s
904            });
905            let mut x = statuses.next().unwrap();
906            statuses.for_each(|y| x.merge(y, kind));
907            x.completed_frontier.map(|f| (f.ingested_at, f.metadata))
908        }
909
910        /// Shared metadata stays with its host's frontier, however many
911        /// hosts report one.
912        #[test]
913        fn shared_frontier_merge() {
914            let merged = |hosts| merge_metadata(hosts, FrontierMerge::Shared);
915            let version = |v: i64| json!({"version": v});
916            assert_eq!(
917                merged(vec![
918                    (false, Some((10, version(3)))),
919                    (false, Some((5, version(2))))
920                ]),
921                Some((time(5), version(2)))
922            );
923            assert_eq!(
924                merged(vec![
925                    (true, Some((5, version(2)))),
926                    (false, Some((10, version(7))))
927                ]),
928                Some((time(10), version(7)))
929            );
930            assert_eq!(
931                merged(vec![
932                    (true, Some((5, version(2)))),
933                    (true, Some((10, version(2))))
934                ]),
935                Some((time(10), version(2)))
936            );
937        }
938
939        /// Partitioned metadata joins every host's partitions, including
940        /// those of hosts at end of input.
941        #[test]
942        fn partitioned_frontier_merge() {
943            let merged = |hosts| merge_metadata(hosts, FrontierMerge::Partitioned);
944            // A host's metadata, which also has fields that the join drops.
945            let host = |partitions: &[i64], offsets: &[i64]| json!({"partitions": partitions, "offsets": offsets, "shard": {"host": 0}});
946            let joined = |partitions: &[i64], offsets: &[i64]| json!({"partitions": partitions, "offsets": offsets});
947
948            // Busy hosts, in any order.
949            assert_eq!(
950                merged(vec![
951                    (false, Some((10, host(&[1, 4], &[11, 14])))),
952                    (false, Some((5, host(&[2], &[12])))),
953                    (false, Some((7, host(&[0, 3], &[10, 13])))),
954                ]),
955                Some((time(5), joined(&[0, 1, 2, 3, 4], &[10, 11, 12, 13, 14])))
956            );
957
958            // Hosts at end of input add their partitions but not their time.
959            assert_eq!(
960                merged(vec![
961                    (true, Some((5, host(&[1], &[11])))),
962                    (false, Some((10, host(&[0], &[10])))),
963                ]),
964                Some((time(10), joined(&[0, 1], &[10, 11])))
965            );
966            assert_eq!(
967                merged(vec![
968                    (true, Some((10, host(&[1], &[11])))),
969                    (true, Some((5, host(&[0], &[10])))),
970                ]),
971                Some((time(10), joined(&[0, 1], &[10, 11])))
972            );
973
974            // A host with no partitions and no frontier adds nothing, and one
975            // host's metadata takes the joined form.
976            assert_eq!(
977                merged(vec![(true, None), (false, Some((10, host(&[0], &[10]))))]),
978                Some((time(10), joined(&[0], &[10])))
979            );
980
981            // A busy host with no frontier still holds back the frontier.
982            assert_eq!(
983                merged(vec![(false, None), (true, Some((10, host(&[0], &[10]))))]),
984                None
985            );
986
987            // Metadata without partitions, as from an older host, or with a
988            // partition that two hosts report, joins to null.
989            for other in [json!({"offsets": [11]}), host(&[0], &[11]), Value::Null] {
990                assert_eq!(
991                    merged(vec![
992                        (false, Some((10, host(&[0], &[10])))),
993                        (false, Some((5, other.clone()))),
994                    ]),
995                    Some((time(5), Value::Null)),
996                    "{other}"
997                );
998            }
999        }
1000
1001        /// A connector is paused only if every host is, in any order.
1002        #[test]
1003        fn pause_merge() {
1004            let merged = |hosts: &[bool]| {
1005                let mut statuses = hosts.iter().map(|&paused| {
1006                    let mut s = status();
1007                    s.paused = paused;
1008                    s
1009                });
1010                let mut x = statuses.next().unwrap();
1011                statuses.for_each(|y| x.merge(y, FrontierMerge::Opaque));
1012                x.paused
1013            };
1014            assert!(merged(&[true, true, true]));
1015            assert!(!merged(&[false, false, false]));
1016            for hosts in [
1017                [true, false, false],
1018                [false, true, false],
1019                [false, false, true],
1020                [true, true, false],
1021                [false, true, true],
1022                [true, false, true],
1023            ] {
1024                assert!(!merged(&hosts), "{hosts:?}");
1025            }
1026        }
1027
1028        #[test]
1029        fn errors_are_combined_in_time_order() {
1030            let mut a = status();
1031            a.parse_errors = Some(vec![error(1, "a1"), error(5, "a5")]);
1032            let mut b = status();
1033            b.parse_errors = Some(vec![error(3, "b3")]);
1034            b.transport_errors = Some(vec![error(2, "b2")]);
1035            a.merge(b, FrontierMerge::Opaque);
1036            let messages = |errors: &Option<Vec<ConnectorError>>| {
1037                errors
1038                    .iter()
1039                    .flatten()
1040                    .map(|e| e.message.clone())
1041                    .collect::<Vec<_>>()
1042            };
1043            assert_eq!(messages(&a.parse_errors), ["a1", "b3", "a5"]);
1044            assert_eq!(messages(&a.transport_errors), ["b2"]);
1045        }
1046
1047        #[test]
1048        fn opaque_frontier_merge() {
1049            // Merges hosts given as (end of input, frontier) and returns the
1050            // merged frontier's ingestion time and whether it kept metadata.
1051            let merged = |hosts: &[(bool, Option<i64>)]| {
1052                let mut statuses = hosts.iter().map(|&(eoi, f)| {
1053                    let mut s = status();
1054                    s.metrics.end_of_input = eoi;
1055                    s.completed_frontier = f.map(frontier);
1056                    s
1057                });
1058                let mut x = statuses.next().unwrap();
1059                statuses.for_each(|y| x.merge(y, FrontierMerge::Opaque));
1060                x.completed_frontier
1061                    .map(|f| (f.ingested_at, !f.metadata.is_null()))
1062            };
1063            let (busy, done) = (false, true);
1064
1065            // The oldest frontier among hosts that are still reading.
1066            assert_eq!(
1067                merged(&[(busy, Some(10)), (busy, Some(5))]),
1068                Some((time(5), false))
1069            );
1070            assert_eq!(
1071                merged(&[(busy, Some(5)), (busy, Some(10))]),
1072                Some((time(5), false))
1073            );
1074
1075            // A host still reading with no frontier holds back the frontier,
1076            // in any position.
1077            assert_eq!(merged(&[(busy, None), (busy, Some(10))]), None);
1078            assert_eq!(merged(&[(busy, Some(10)), (busy, None)]), None);
1079            assert_eq!(
1080                merged(&[(busy, Some(10)), (busy, None), (busy, Some(5))]),
1081                None
1082            );
1083            assert_eq!(
1084                merged(&[(busy, None), (done, Some(5)), (busy, Some(10))]),
1085                None
1086            );
1087
1088            // Hosts at end of input do not hold back the frontier, and the
1089            // one host still reading keeps its metadata, as a Delta Lake
1090            // connector's home host does while it follows the table.
1091            assert_eq!(
1092                merged(&[(busy, Some(10)), (done, Some(5))]),
1093                Some((time(10), true))
1094            );
1095            assert_eq!(
1096                merged(&[(done, Some(5)), (busy, Some(10))]),
1097                Some((time(10), true))
1098            );
1099            assert_eq!(
1100                merged(&[(done, None), (busy, Some(10))]),
1101                Some((time(10), true))
1102            );
1103            assert_eq!(
1104                merged(&[(busy, Some(10)), (done, None)]),
1105                Some((time(10), true))
1106            );
1107            assert_eq!(
1108                merged(&[(done, Some(5)), (busy, Some(10)), (done, Some(20))]),
1109                Some((time(10), true))
1110            );
1111            assert_eq!(
1112                merged(&[(done, Some(5)), (busy, Some(10)), (busy, Some(20))]),
1113                Some((time(10), false))
1114            );
1115
1116            // If every host is at end of input, the newest frontier.
1117            assert_eq!(
1118                merged(&[(done, Some(10)), (done, Some(5))]),
1119                Some((time(10), true))
1120            );
1121            assert_eq!(
1122                merged(&[(done, None), (done, Some(5))]),
1123                Some((time(5), true))
1124            );
1125            assert_eq!(merged(&[(done, None), (done, None)]), None);
1126        }
1127    }
1128}