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#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
19#[serde(rename_all = "PascalCase")]
20pub enum PipelineState {
21 #[default]
23 Paused,
24 Running,
26 Terminated,
28}
29
30#[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#[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#[derive(Serialize, Deserialize, Debug, Clone)]
58pub struct EndpointErrorStats<T> {
59 #[serde(default)]
60 pub metrics: T,
61}
62
63#[derive(Debug, Deserialize, Serialize, ToSchema)]
65pub struct ShortEndpointConfig {
66 pub stream: String,
68}
69
70#[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#[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#[derive(Clone, Copy, PartialEq, Eq, Debug, Deserialize, Serialize, ToSchema)]
98#[serde(rename_all = "PascalCase")]
99#[schema(as = TransactionPhase)]
100pub enum ExternalTransactionPhase {
101 Started,
103 Committed,
105}
106
107#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize, ToSchema)]
109#[schema(as = ConnectorTransactionPhase)]
110pub struct ExternalConnectorTransactionPhase {
111 #[schema(value_type = TransactionPhase)]
113 pub phase: ExternalTransactionPhase,
114 pub label: Option<String>,
116}
117
118#[derive(Clone, Default, Debug, Deserialize, Serialize, ToSchema)]
120#[schema(as = TransactionInitiators)]
121pub struct ExternalTransactionInitiators {
122 #[schema(value_type = Option<i64>)]
124 pub transaction_id: Option<TransactionId>,
125 #[schema(value_type = Option<TransactionPhase>)]
127 pub initiated_by_api: Option<ExternalTransactionPhase>,
128 #[schema(value_type = BTreeMap<String, ConnectorTransactionPhase>)]
130 pub initiated_by_connectors: BTreeMap<String, ExternalConnectorTransactionPhase>,
131}
132
133#[derive(Clone, Debug, Deserialize, Serialize, ToSchema)]
135pub struct CompletedWatermark {
136 #[schema(value_type = Object)]
138 pub metadata: JsonValue,
139 #[serde(serialize_with = "serialize_timestamp_micros")]
141 pub ingested_at: DateTime<Utc>,
142 #[serde(serialize_with = "serialize_timestamp_micros")]
144 pub processed_at: DateTime<Utc>,
145 #[serde(serialize_with = "serialize_timestamp_micros")]
147 pub completed_at: DateTime<Utc>,
148}
149
150#[derive(Clone, Debug, Deserialize, Serialize, ToSchema)]
155pub struct CircuitInputWatermark {
156 #[schema(value_type = Object)]
158 pub metadata: JsonValue,
159 #[serde(serialize_with = "serialize_timestamp_micros")]
161 pub ingested_at: DateTime<Utc>,
162 #[serde(serialize_with = "serialize_timestamp_micros")]
164 pub processed_at: DateTime<Utc>,
165}
166
167#[derive(Debug, Default, Deserialize, Serialize, ToSchema, Clone)]
168pub enum ConnectorHealthStatus {
169 #[default]
170 Healthy,
171 Unhealthy,
172}
173
174#[derive(Debug, Default, Deserialize, Serialize, ToSchema, Clone)]
175pub struct ConnectorHealth {
176 pub status: ConnectorHealthStatus,
177 pub description: Option<String>,
178}
179
180impl ConnectorHealth {
181 pub fn healthy() -> Self {
182 Self {
183 status: ConnectorHealthStatus::Healthy,
184 description: None,
185 }
186 }
187 pub fn unhealthy(description: &str) -> Self {
188 Self {
189 status: ConnectorHealthStatus::Unhealthy,
190 description: Some(description.to_string()),
191 }
192 }
193}
194
195#[derive(Debug, Default, Deserialize, Serialize, ToSchema, Clone, PartialEq, Eq)]
196pub struct ConnectorError {
197 #[serde(serialize_with = "serialize_timestamp_micros")]
199 pub timestamp: DateTime<Utc>,
200
201 pub index: u64,
207
208 pub tag: Option<String>,
212
213 pub message: String,
215}
216
217#[derive(Debug, Default, Deserialize, Serialize, ToSchema)]
219#[schema(as = InputEndpointMetrics)]
220pub struct ExternalInputEndpointMetrics {
221 pub total_bytes: u64,
223 pub total_records: u64,
225 pub buffered_records: u64,
227 pub buffered_bytes: u64,
229 #[serde(default)]
236 pub latest_batch_records: u64,
237 #[serde(default)]
244 pub latest_batch_bytes: u64,
245 pub num_transport_errors: u64,
247 pub num_parse_errors: u64,
249 pub end_of_input: bool,
251 #[serde(default, skip_serializing_if = "Option::is_none")]
267 pub processing_latency_p99_micros: Option<u64>,
268}
269
270impl ExternalInputEndpointMetrics {
271 pub fn merge(&mut self, other: &Self) {
274 let &Self {
277 total_bytes,
278 total_records,
279 buffered_records,
280 buffered_bytes,
281 latest_batch_records,
282 latest_batch_bytes,
283 num_transport_errors,
284 num_parse_errors,
285 end_of_input,
286 processing_latency_p99_micros,
287 } = other;
288 self.total_bytes += total_bytes;
289 self.total_records += total_records;
290 self.buffered_records += buffered_records;
291 self.buffered_bytes += buffered_bytes;
292 self.latest_batch_records += latest_batch_records;
294 self.latest_batch_bytes += latest_batch_bytes;
295 self.num_transport_errors += num_transport_errors;
296 self.num_parse_errors += num_parse_errors;
297 self.end_of_input &= end_of_input;
298 self.processing_latency_p99_micros = self
300 .processing_latency_p99_micros
301 .max(processing_latency_p99_micros);
302 }
303}
304
305#[derive(Debug, Serialize, Deserialize, ToSchema)]
307#[schema(as = InputEndpointStatus)]
308pub struct ExternalInputEndpointStatus {
309 pub endpoint_name: String,
311 pub config: ShortEndpointConfig,
313 #[schema(value_type = InputEndpointMetrics)]
315 pub metrics: ExternalInputEndpointMetrics,
316 pub fatal_error: Option<String>,
318 #[serde(default, skip_serializing_if = "Option::is_none")]
320 pub parse_errors: Option<Vec<ConnectorError>>,
321 #[serde(default, skip_serializing_if = "Option::is_none")]
323 pub transport_errors: Option<Vec<ConnectorError>>,
324 #[serde(default)]
326 pub health: Option<ConnectorHealth>,
327 pub paused: bool,
330 pub barrier: bool,
332 #[schema(value_type = Option<CompletedWatermark>)]
334 pub completed_frontier: Option<CompletedWatermark>,
335 #[schema(value_type = Option<CircuitInputWatermark>)]
340 pub circuit_input_frontier: Option<CircuitInputWatermark>,
341}
342
343#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
347pub enum FrontierMerge {
348 Shared,
352
353 Partitioned,
357
358 #[default]
362 Opaque,
363}
364
365impl ExternalInputEndpointStatus {
366 pub fn merge(&mut self, other: Self, frontier_merge: FrontierMerge) {
382 let Self {
385 endpoint_name: _,
387 config: _,
388 metrics,
389 fatal_error,
390 parse_errors,
391 transport_errors,
392 health,
393 paused,
394 barrier,
395 completed_frontier,
396 circuit_input_frontier,
397 } = other;
398 let (a_eoi, b_eoi) = (self.metrics.end_of_input, metrics.end_of_input);
399 self.metrics.merge(&metrics);
400 if self.fatal_error.is_none() {
401 self.fatal_error = fatal_error;
402 }
403 merge_errors(&mut self.parse_errors, parse_errors);
404 merge_errors(&mut self.transport_errors, transport_errors);
405 self.health = merge_health(self.health.take(), health);
406 self.paused &= paused;
407 self.barrier |= barrier;
408 self.completed_frontier = merge_frontiers(
409 (self.completed_frontier.take(), a_eoi),
410 (completed_frontier, b_eoi),
411 frontier_merge,
412 );
413 self.circuit_input_frontier = merge_frontiers(
414 (self.circuit_input_frontier.take(), a_eoi),
415 (circuit_input_frontier, b_eoi),
416 frontier_merge,
417 );
418 }
419}
420
421trait Frontier {
423 fn ingested_at(&self) -> DateTime<Utc>;
425
426 fn metadata(&self) -> &JsonValue;
428
429 fn metadata_mut(&mut self) -> &mut JsonValue;
431}
432
433impl Frontier for CompletedWatermark {
434 fn ingested_at(&self) -> DateTime<Utc> {
435 self.ingested_at
436 }
437
438 fn metadata(&self) -> &JsonValue {
439 &self.metadata
440 }
441
442 fn metadata_mut(&mut self) -> &mut JsonValue {
443 &mut self.metadata
444 }
445}
446
447impl Frontier for CircuitInputWatermark {
448 fn ingested_at(&self) -> DateTime<Utc> {
449 self.ingested_at
450 }
451
452 fn metadata(&self) -> &JsonValue {
453 &self.metadata
454 }
455
456 fn metadata_mut(&mut self) -> &mut JsonValue {
457 &mut self.metadata
458 }
459}
460
461fn merge_frontiers<F: Frontier>(
476 (a, a_eoi): (Option<F>, bool),
477 (b, b_eoi): (Option<F>, bool),
478 frontier_merge: FrontierMerge,
479) -> Option<F> {
480 let several = !a_eoi && !b_eoi && a.is_some() && b.is_some();
481 let no_partitions = serde_json::json!({"partitions": [], "offsets": []});
484 let metadata = |f: &Option<F>| f.as_ref().map_or(&no_partitions, F::metadata).clone();
485 let joined = join_partitions(&metadata(&a), &metadata(&b));
486 let oldest = |a: F, b: F| {
487 if b.ingested_at() < a.ingested_at() {
488 b
489 } else {
490 a
491 }
492 };
493 let newest = |a: F, b: F| {
494 if b.ingested_at() > a.ingested_at() {
495 b
496 } else {
497 a
498 }
499 };
500 let mut frontier = match (a_eoi, b_eoi) {
501 (false, false) => a.zip(b).map(|(a, b)| oldest(a, b)),
502 (false, true) => a,
503 (true, false) => b,
504 (true, true) => match (a, b) {
505 (Some(a), Some(b)) => Some(newest(a, b)),
506 (a, b) => a.or(b),
507 },
508 };
509 if let Some(frontier) = &mut frontier {
510 match frontier_merge {
511 FrontierMerge::Shared => (),
512 FrontierMerge::Partitioned => *frontier.metadata_mut() = joined,
513 FrontierMerge::Opaque => {
514 if several {
515 *frontier.metadata_mut() = JsonValue::Null;
516 }
517 }
518 }
519 }
520 frontier
521}
522
523fn join_partitions(a: &JsonValue, b: &JsonValue) -> JsonValue {
527 fn pairs(metadata: &JsonValue) -> Option<Vec<(i64, &JsonValue)>> {
528 let partitions = metadata.get("partitions")?.as_array()?;
529 let offsets = metadata.get("offsets")?.as_array()?;
530 if partitions.len() != offsets.len() {
531 return None;
532 }
533 partitions
534 .iter()
535 .zip(offsets)
536 .map(|(partition, offsets)| Some((partition.as_i64()?, offsets)))
537 .collect()
538 }
539 let (Some(a), Some(b)) = (pairs(a), pairs(b)) else {
540 return JsonValue::Null;
541 };
542 let mut joined = BTreeMap::new();
543 for (partition, offsets) in a.into_iter().chain(b) {
544 if joined.insert(partition, offsets.clone()).is_some() {
545 return JsonValue::Null;
546 }
547 }
548 let (partitions, offsets): (Vec<_>, Vec<_>) = joined.into_iter().unzip();
549 serde_json::json!({"partitions": partitions, "offsets": offsets})
550}
551
552fn merge_health(a: Option<ConnectorHealth>, b: Option<ConnectorHealth>) -> Option<ConnectorHealth> {
554 match (a, b) {
555 (Some(a), Some(b)) => Some(if matches!(a.status, ConnectorHealthStatus::Unhealthy) {
556 a
557 } else {
558 b
559 }),
560 (a, b) => a.or(b),
561 }
562}
563
564fn merge_errors(a: &mut Option<Vec<ConnectorError>>, b: Option<Vec<ConnectorError>>) {
567 if let Some(b) = b {
568 let errors = a.get_or_insert_with(Vec::new);
569 errors.extend(b);
570 errors.sort_by_key(|error| error.timestamp);
571 }
572}
573
574#[derive(Debug, Default, Deserialize, Serialize, ToSchema, PartialEq, Eq, PartialOrd, Ord)]
576#[schema(as = OutputEndpointMetrics)]
577pub struct ExternalOutputEndpointMetrics {
578 pub transmitted_records: u64,
580 pub transmitted_bytes: u64,
582 pub queued_records: u64,
584 pub queued_batches: u64,
586 pub buffered_records: u64,
588 pub buffered_batches: u64,
590 pub num_encode_errors: u64,
592 pub num_transport_errors: u64,
594 pub total_processed_input_records: u64,
613 #[schema(value_type = u64)]
627 pub total_processed_steps: Step,
628 pub memory: u64,
630 #[serde(default, skip_serializing_if = "Option::is_none")]
635 pub batch_records_written: Option<u64>,
636}
637
638#[derive(Debug, Deserialize, Serialize, ToSchema)]
640#[schema(as = OutputEndpointStatus)]
641pub struct ExternalOutputEndpointStatus {
642 pub endpoint_name: String,
644 pub config: ShortEndpointConfig,
646 #[schema(value_type = OutputEndpointMetrics)]
648 pub metrics: ExternalOutputEndpointMetrics,
649 pub fatal_error: Option<String>,
651 #[serde(default, skip_serializing_if = "Option::is_none")]
653 pub encode_errors: Option<Vec<ConnectorError>>,
654 #[serde(default, skip_serializing_if = "Option::is_none")]
656 pub transport_errors: Option<Vec<ConnectorError>>,
657 #[serde(default)]
659 pub health: Option<ConnectorHealth>,
660 #[serde(default)]
665 pub paused: bool,
666}
667
668impl ExternalOutputEndpointMetrics {
669 pub fn merge(&mut self, other: &Self) {
675 let &Self {
678 transmitted_records,
679 transmitted_bytes,
680 queued_records,
681 queued_batches,
682 buffered_records,
683 buffered_batches,
684 num_encode_errors,
685 num_transport_errors,
686 total_processed_input_records,
687 total_processed_steps,
688 memory,
689 batch_records_written,
690 } = other;
691 self.transmitted_records += transmitted_records;
692 self.transmitted_bytes += transmitted_bytes;
693 self.queued_records += queued_records;
694 self.queued_batches += queued_batches;
695 self.buffered_records += buffered_records;
696 self.buffered_batches += buffered_batches;
697 self.num_encode_errors += num_encode_errors;
698 self.num_transport_errors += num_transport_errors;
699 self.total_processed_input_records = self
700 .total_processed_input_records
701 .min(total_processed_input_records);
702 self.total_processed_steps = self.total_processed_steps.min(total_processed_steps);
703 self.memory += memory;
704 self.batch_records_written = match (self.batch_records_written, batch_records_written) {
705 (Some(a), Some(b)) => Some(a + b),
706 (a, b) => a.or(b),
707 };
708 }
709}
710
711impl ExternalOutputEndpointStatus {
712 pub fn merge(&mut self, other: Self) {
719 let Self {
722 endpoint_name: _,
724 config: _,
725 metrics,
726 fatal_error,
727 encode_errors,
728 transport_errors,
729 health,
730 paused,
731 } = other;
732 self.metrics.merge(&metrics);
733 if self.fatal_error.is_none() {
734 self.fatal_error = fatal_error;
735 }
736 merge_errors(&mut self.encode_errors, encode_errors);
737 merge_errors(&mut self.transport_errors, transport_errors);
738 self.health = merge_health(self.health.take(), health);
739 self.paused &= paused;
740 }
741}
742
743#[derive(Debug, Default, Serialize, Deserialize, ToSchema)]
745#[schema(as = GlobalControllerMetrics)]
746pub struct ExternalGlobalControllerMetrics {
747 pub state: PipelineState,
749 pub bootstrap_in_progress: bool,
751 pub transaction_status: TransactionStatus,
753 #[schema(value_type = i64)]
755 pub transaction_id: TransactionId,
756 pub transaction_msecs: Option<u64>,
764 pub transaction_records: Option<u64>,
772 pub commit_progress: Option<CommitProgressSummary>,
774 #[schema(value_type = TransactionInitiators)]
776 pub transaction_initiators: ExternalTransactionInitiators,
777 pub concurrent_bootstrap_phase: ConcurrentBootstrapPhase,
779 pub concurrent_bootstrap_progress: Option<CommitProgressSummary>,
783 pub rss_bytes: u64,
785 pub memory_pressure: MemoryPressure,
787 pub memory_pressure_epoch: u64,
789 pub cpu_msecs: u64,
791 pub uptime_msecs: u64,
796 #[serde(with = "chrono::serde::ts_seconds")]
798 #[schema(value_type = u64)]
799 pub start_time: DateTime<Utc>,
800 pub incarnation_uuid: Uuid,
802 #[serde(with = "chrono::serde::ts_seconds")]
804 #[schema(value_type = u64)]
805 pub initial_start_time: DateTime<Utc>,
806 pub storage_bytes: u64,
808 pub storage_mb_secs: u64,
810 #[serde(default, skip_serializing_if = "Option::is_none")]
812 pub disk_total_bytes: Option<u64>,
813 #[serde(default, skip_serializing_if = "Option::is_none")]
815 pub disk_available_bytes: Option<u64>,
816 pub runtime_elapsed_msecs: u64,
818 pub buffered_input_records: u64,
820 pub buffered_input_bytes: u64,
822 pub total_input_records: u64,
824 pub total_input_bytes: u64,
826 pub total_processed_records: u64,
828 pub total_processed_bytes: u64,
830 pub total_completed_records: u64,
838 pub output_stall_msecs: u64,
848 #[schema(value_type = u64)]
857 pub total_initiated_steps: Step,
858 #[schema(value_type = u64)]
872 pub total_completed_steps: Step,
873 pub pipeline_complete: bool,
875 pub platform_version: String,
881 pub runtime_version: String,
887}
888
889#[derive(Debug, Deserialize, Serialize, ToSchema, Default)]
897#[schema(as = ControllerStatus)]
898pub struct ExternalControllerStatus {
899 #[schema(value_type = GlobalControllerMetrics)]
901 pub global_metrics: ExternalGlobalControllerMetrics,
902 pub suspend_error: Option<SuspendError>,
904 pub checkpoint_activity: Option<CheckpointActivity>,
907 pub permanent_checkpoint_errors: Option<Vec<PermanentSuspendError>>,
912 #[schema(value_type = Vec<InputEndpointStatus>)]
914 pub inputs: Vec<ExternalInputEndpointStatus>,
915 #[schema(value_type = Vec<OutputEndpointStatus>)]
917 pub outputs: Vec<ExternalOutputEndpointStatus>,
918 #[serde(default, skip_serializing_if = "Vec::is_empty")]
920 pub host_metrics: Vec<HostMetrics>,
921}
922
923#[derive(Debug, Default, Deserialize, Serialize, ToSchema)]
925pub struct HostMetrics {
926 #[serde(default, skip_serializing_if = "Option::is_none")]
928 pub disk_total_bytes: Option<u64>,
929 #[serde(default, skip_serializing_if = "Option::is_none")]
931 pub disk_available_bytes: Option<u64>,
932}
933
934impl From<&ExternalGlobalControllerMetrics> for HostMetrics {
935 fn from(metrics: &ExternalGlobalControllerMetrics) -> Self {
936 Self {
937 disk_total_bytes: metrics.disk_total_bytes,
938 disk_available_bytes: metrics.disk_available_bytes,
939 }
940 }
941}
942
943fn serialize_timestamp_micros<S>(
944 timestamp: &DateTime<Utc>,
945 serializer: S,
946) -> Result<S::Ok, S::Error>
947where
948 S: serde::Serializer,
949{
950 serializer.serialize_str(×tamp.to_rfc3339_opts(SecondsFormat::Micros, true))
951}
952
953#[cfg(test)]
954mod tests {
955 use super::ConnectorError;
956 use chrono::{DateTime, Utc};
957
958 #[test]
959 fn connector_error_timestamp_serializes_with_microsecond_precision() {
960 let error = ConnectorError {
961 timestamp: DateTime::parse_from_rfc3339("2026-03-08T05:26:42.442438448Z")
962 .unwrap()
963 .with_timezone(&Utc),
964 index: 1,
965 tag: None,
966 message: "boom".to_string(),
967 };
968
969 let json = serde_json::to_string(&error).unwrap();
970 assert!(json.contains(r#""timestamp":"2026-03-08T05:26:42.442438Z""#));
971 }
972
973 #[test]
974 fn output_metrics_batch_records_written_serializes() {
975 use super::ExternalOutputEndpointMetrics;
976
977 let metrics = ExternalOutputEndpointMetrics {
978 batch_records_written: Some(42),
979 ..Default::default()
980 };
981 let json = serde_json::to_string(&metrics).unwrap();
982 assert!(json.contains(r#""batch_records_written":42"#));
983
984 let deserialized: ExternalOutputEndpointMetrics = serde_json::from_str(&json).unwrap();
985 assert_eq!(deserialized.batch_records_written, Some(42));
986 }
987
988 #[test]
989 fn output_metrics_batch_records_written_defaults_to_none() {
990 use super::ExternalOutputEndpointMetrics;
991
992 let json = r#"{"transmitted_records":0,"transmitted_bytes":0,"queued_records":0,"queued_batches":0,"buffered_records":0,"buffered_batches":0,"num_encode_errors":0,"num_transport_errors":0,"total_processed_input_records":0,"total_processed_steps":0,"memory":0}"#;
994 let metrics: ExternalOutputEndpointMetrics = serde_json::from_str(json).unwrap();
995 assert_eq!(metrics.batch_records_written, None);
996 }
997
998 mod merge {
999 use chrono::{DateTime, TimeZone, Utc};
1000
1001 use crate::adapter_stats::{
1002 CircuitInputWatermark, CompletedWatermark, ConnectorError, ConnectorHealth,
1003 ConnectorHealthStatus, ExternalInputEndpointMetrics, ExternalInputEndpointStatus,
1004 ExternalOutputEndpointMetrics, ExternalOutputEndpointStatus, FrontierMerge,
1005 ShortEndpointConfig,
1006 };
1007 use serde_json::{Value, json};
1008
1009 fn time(secs: i64) -> DateTime<Utc> {
1010 Utc.timestamp_opt(secs, 0).unwrap()
1011 }
1012
1013 fn error(secs: i64, message: &str) -> ConnectorError {
1014 ConnectorError {
1015 timestamp: time(secs),
1016 index: 0,
1017 tag: None,
1018 message: message.into(),
1019 }
1020 }
1021
1022 fn frontier(ingested_secs: i64) -> CompletedWatermark {
1023 CompletedWatermark {
1024 metadata: serde_json::json!(ingested_secs),
1025 ingested_at: time(ingested_secs),
1026 processed_at: time(ingested_secs + 1),
1027 completed_at: time(ingested_secs + 2),
1028 }
1029 }
1030
1031 fn circuit_input_frontier(ingested_secs: i64) -> CircuitInputWatermark {
1032 CircuitInputWatermark {
1033 metadata: serde_json::json!(ingested_secs),
1034 ingested_at: time(ingested_secs),
1035 processed_at: time(ingested_secs + 1),
1036 }
1037 }
1038
1039 fn status() -> ExternalInputEndpointStatus {
1040 ExternalInputEndpointStatus {
1041 endpoint_name: "t.kafka".into(),
1042 config: ShortEndpointConfig { stream: "t".into() },
1043 metrics: ExternalInputEndpointMetrics {
1044 total_bytes: 10,
1045 total_records: 1,
1046 buffered_records: 2,
1047 buffered_bytes: 20,
1048 latest_batch_records: 5,
1049 latest_batch_bytes: 50,
1050 num_transport_errors: 3,
1051 num_parse_errors: 4,
1052 end_of_input: true,
1053 processing_latency_p99_micros: Some(100),
1054 },
1055 fatal_error: None,
1056 parse_errors: None,
1057 transport_errors: None,
1058 health: Some(ConnectorHealth::healthy()),
1059 paused: false,
1060 barrier: false,
1061 completed_frontier: None,
1062 circuit_input_frontier: None,
1063 }
1064 }
1065
1066 #[test]
1067 fn counters_add_up() {
1068 let mut a = status();
1069 let mut b = status();
1070 b.metrics.processing_latency_p99_micros = Some(500);
1071 b.metrics.end_of_input = false;
1072 a.merge(b, FrontierMerge::Opaque);
1073 let m = &a.metrics;
1074 assert_eq!(
1075 (
1076 m.total_bytes,
1077 m.total_records,
1078 m.buffered_records,
1079 m.buffered_bytes
1080 ),
1081 (20, 2, 4, 40)
1082 );
1083 assert_eq!((m.latest_batch_records, m.latest_batch_bytes), (10, 100));
1084 assert_eq!((m.num_transport_errors, m.num_parse_errors), (6, 8));
1085 assert!(!m.end_of_input);
1086 assert_eq!(m.processing_latency_p99_micros, Some(500));
1087 }
1088
1089 #[test]
1090 fn worst_host_decides() {
1091 let mut a = status();
1092 let mut b = status();
1093 b.fatal_error = Some("broken".into());
1094 b.health = Some(ConnectorHealth::unhealthy("sick"));
1095 b.barrier = true;
1096 a.merge(b, FrontierMerge::Opaque);
1097 assert_eq!(a.fatal_error.as_deref(), Some("broken"));
1098 assert!(matches!(
1099 a.health.unwrap().status,
1100 ConnectorHealthStatus::Unhealthy
1101 ));
1102 assert!(a.barrier);
1103
1104 let mut a = status();
1106 a.fatal_error = Some("first".into());
1107 let mut b = status();
1108 b.fatal_error = Some("second".into());
1109 a.merge(b, FrontierMerge::Opaque);
1110 assert_eq!(a.fatal_error.as_deref(), Some("first"));
1111 }
1112
1113 fn merge_metadata(
1118 hosts: Vec<(bool, Option<(i64, Value)>)>,
1119 kind: FrontierMerge,
1120 ) -> Option<(DateTime<Utc>, Value)> {
1121 let mut statuses = hosts.into_iter().map(|(eoi, f)| {
1122 let mut s = status();
1123 s.metrics.end_of_input = eoi;
1124 s.completed_frontier = f.clone().map(|(secs, metadata)| CompletedWatermark {
1125 metadata,
1126 ..frontier(secs)
1127 });
1128 s.circuit_input_frontier = f.map(|(secs, metadata)| CircuitInputWatermark {
1129 metadata,
1130 ..circuit_input_frontier(secs)
1131 });
1132 s
1133 });
1134 let mut x = statuses.next().unwrap();
1135 statuses.for_each(|y| x.merge(y, kind));
1136 let completed = x.completed_frontier.map(|f| (f.ingested_at, f.metadata));
1137 let circuit_input = x
1138 .circuit_input_frontier
1139 .map(|f| (f.ingested_at, f.metadata));
1140 assert_eq!(completed, circuit_input);
1141 completed
1142 }
1143
1144 #[test]
1147 fn shared_frontier_merge() {
1148 let merged = |hosts| merge_metadata(hosts, FrontierMerge::Shared);
1149 let version = |v: i64| json!({"version": v});
1150 assert_eq!(
1151 merged(vec![
1152 (false, Some((10, version(3)))),
1153 (false, Some((5, version(2))))
1154 ]),
1155 Some((time(5), version(2)))
1156 );
1157 assert_eq!(
1158 merged(vec![
1159 (true, Some((5, version(2)))),
1160 (false, Some((10, version(7))))
1161 ]),
1162 Some((time(10), version(7)))
1163 );
1164 assert_eq!(
1165 merged(vec![
1166 (true, Some((5, version(2)))),
1167 (true, Some((10, version(2))))
1168 ]),
1169 Some((time(10), version(2)))
1170 );
1171 }
1172
1173 #[test]
1176 fn partitioned_frontier_merge() {
1177 let merged = |hosts| merge_metadata(hosts, FrontierMerge::Partitioned);
1178 let host = |partitions: &[i64], offsets: &[i64]| json!({"partitions": partitions, "offsets": offsets, "shard": {"host": 0}});
1180 let joined = |partitions: &[i64], offsets: &[i64]| json!({"partitions": partitions, "offsets": offsets});
1181
1182 assert_eq!(
1184 merged(vec![
1185 (false, Some((10, host(&[1, 4], &[11, 14])))),
1186 (false, Some((5, host(&[2], &[12])))),
1187 (false, Some((7, host(&[0, 3], &[10, 13])))),
1188 ]),
1189 Some((time(5), joined(&[0, 1, 2, 3, 4], &[10, 11, 12, 13, 14])))
1190 );
1191
1192 assert_eq!(
1194 merged(vec![
1195 (true, Some((5, host(&[1], &[11])))),
1196 (false, Some((10, host(&[0], &[10])))),
1197 ]),
1198 Some((time(10), joined(&[0, 1], &[10, 11])))
1199 );
1200 assert_eq!(
1201 merged(vec![
1202 (true, Some((10, host(&[1], &[11])))),
1203 (true, Some((5, host(&[0], &[10])))),
1204 ]),
1205 Some((time(10), joined(&[0, 1], &[10, 11])))
1206 );
1207
1208 assert_eq!(
1211 merged(vec![(true, None), (false, Some((10, host(&[0], &[10]))))]),
1212 Some((time(10), joined(&[0], &[10])))
1213 );
1214
1215 assert_eq!(
1217 merged(vec![(false, None), (true, Some((10, host(&[0], &[10]))))]),
1218 None
1219 );
1220
1221 for other in [json!({"offsets": [11]}), host(&[0], &[11]), Value::Null] {
1224 assert_eq!(
1225 merged(vec![
1226 (false, Some((10, host(&[0], &[10])))),
1227 (false, Some((5, other.clone()))),
1228 ]),
1229 Some((time(5), Value::Null)),
1230 "{other}"
1231 );
1232 }
1233 }
1234
1235 fn output_status(steps: u64, records: u64) -> ExternalOutputEndpointStatus {
1236 ExternalOutputEndpointStatus {
1237 endpoint_name: "v.delta".into(),
1238 config: ShortEndpointConfig { stream: "v".into() },
1239 metrics: ExternalOutputEndpointMetrics {
1240 transmitted_records: 1,
1241 transmitted_bytes: 2,
1242 queued_records: 3,
1243 queued_batches: 4,
1244 buffered_records: 5,
1245 buffered_batches: 6,
1246 num_encode_errors: 7,
1247 num_transport_errors: 8,
1248 total_processed_input_records: records,
1249 total_processed_steps: steps,
1250 memory: 9,
1251 batch_records_written: None,
1252 },
1253 fatal_error: None,
1254 encode_errors: None,
1255 transport_errors: None,
1256 health: Some(ConnectorHealth::healthy()),
1257 paused: true,
1258 }
1259 }
1260
1261 #[test]
1265 fn output_merge() {
1266 let mut a = output_status(5, 50);
1267 let mut b = output_status(3, 30);
1268 b.metrics.batch_records_written = Some(10);
1269 b.health = Some(ConnectorHealth::unhealthy("sick"));
1270 b.paused = false;
1271 b.fatal_error = Some("broken".into());
1272 b.transport_errors = Some(vec![error(2, "b2")]);
1273 a.merge(b);
1274 assert_eq!(
1275 a.metrics,
1276 ExternalOutputEndpointMetrics {
1277 transmitted_records: 2,
1278 transmitted_bytes: 4,
1279 queued_records: 6,
1280 queued_batches: 8,
1281 buffered_records: 10,
1282 buffered_batches: 12,
1283 num_encode_errors: 14,
1284 num_transport_errors: 16,
1285 total_processed_input_records: 30,
1286 total_processed_steps: 3,
1287 memory: 18,
1288 batch_records_written: Some(10),
1289 }
1290 );
1291 assert!(matches!(
1292 a.health.unwrap().status,
1293 ConnectorHealthStatus::Unhealthy
1294 ));
1295 assert!(!a.paused);
1296 assert_eq!(a.fatal_error.as_deref(), Some("broken"));
1297 assert_eq!(a.transport_errors.unwrap().len(), 1);
1298 }
1299
1300 #[test]
1302 fn pause_merge() {
1303 let merged = |hosts: &[bool]| {
1304 let mut statuses = hosts.iter().map(|&paused| {
1305 let mut s = status();
1306 s.paused = paused;
1307 s
1308 });
1309 let mut x = statuses.next().unwrap();
1310 statuses.for_each(|y| x.merge(y, FrontierMerge::Opaque));
1311 x.paused
1312 };
1313 assert!(merged(&[true, true, true]));
1314 assert!(!merged(&[false, false, false]));
1315 for hosts in [
1316 [true, false, false],
1317 [false, true, false],
1318 [false, false, true],
1319 [true, true, false],
1320 [false, true, true],
1321 [true, false, true],
1322 ] {
1323 assert!(!merged(&hosts), "{hosts:?}");
1324 }
1325 }
1326
1327 #[test]
1328 fn errors_are_combined_in_time_order() {
1329 let mut a = status();
1330 a.parse_errors = Some(vec![error(1, "a1"), error(5, "a5")]);
1331 let mut b = status();
1332 b.parse_errors = Some(vec![error(3, "b3")]);
1333 b.transport_errors = Some(vec![error(2, "b2")]);
1334 a.merge(b, FrontierMerge::Opaque);
1335 let messages = |errors: &Option<Vec<ConnectorError>>| {
1336 errors
1337 .iter()
1338 .flatten()
1339 .map(|e| e.message.clone())
1340 .collect::<Vec<_>>()
1341 };
1342 assert_eq!(messages(&a.parse_errors), ["a1", "b3", "a5"]);
1343 assert_eq!(messages(&a.transport_errors), ["b2"]);
1344 }
1345
1346 #[test]
1347 fn opaque_frontier_merge() {
1348 let merged = |hosts: &[(bool, Option<i64>)]| {
1353 let mut statuses = hosts.iter().map(|&(eoi, f)| {
1354 let mut s = status();
1355 s.metrics.end_of_input = eoi;
1356 s.completed_frontier = f.map(frontier);
1357 s.circuit_input_frontier = f.map(circuit_input_frontier);
1358 s
1359 });
1360 let mut x = statuses.next().unwrap();
1361 statuses.for_each(|y| x.merge(y, FrontierMerge::Opaque));
1362 let completed = x
1363 .completed_frontier
1364 .map(|f| (f.ingested_at, !f.metadata.is_null()));
1365 let circuit_input = x
1366 .circuit_input_frontier
1367 .map(|f| (f.ingested_at, !f.metadata.is_null()));
1368 assert_eq!(completed, circuit_input);
1369 completed
1370 };
1371 let (busy, done) = (false, true);
1372
1373 assert_eq!(
1375 merged(&[(busy, Some(10)), (busy, Some(5))]),
1376 Some((time(5), false))
1377 );
1378 assert_eq!(
1379 merged(&[(busy, Some(5)), (busy, Some(10))]),
1380 Some((time(5), false))
1381 );
1382
1383 assert_eq!(merged(&[(busy, None), (busy, Some(10))]), None);
1386 assert_eq!(merged(&[(busy, Some(10)), (busy, None)]), None);
1387 assert_eq!(
1388 merged(&[(busy, Some(10)), (busy, None), (busy, Some(5))]),
1389 None
1390 );
1391 assert_eq!(
1392 merged(&[(busy, None), (done, Some(5)), (busy, Some(10))]),
1393 None
1394 );
1395
1396 assert_eq!(
1400 merged(&[(busy, Some(10)), (done, Some(5))]),
1401 Some((time(10), true))
1402 );
1403 assert_eq!(
1404 merged(&[(done, Some(5)), (busy, Some(10))]),
1405 Some((time(10), true))
1406 );
1407 assert_eq!(
1408 merged(&[(done, None), (busy, Some(10))]),
1409 Some((time(10), true))
1410 );
1411 assert_eq!(
1412 merged(&[(busy, Some(10)), (done, None)]),
1413 Some((time(10), true))
1414 );
1415 assert_eq!(
1416 merged(&[(done, Some(5)), (busy, Some(10)), (done, Some(20))]),
1417 Some((time(10), true))
1418 );
1419 assert_eq!(
1420 merged(&[(done, Some(5)), (busy, Some(10)), (busy, Some(20))]),
1421 Some((time(10), false))
1422 );
1423
1424 assert_eq!(
1426 merged(&[(done, Some(10)), (done, Some(5))]),
1427 Some((time(10), true))
1428 );
1429 assert_eq!(
1430 merged(&[(done, None), (done, Some(5))]),
1431 Some((time(5), true))
1432 );
1433 assert_eq!(merged(&[(done, None), (done, None)]), None);
1434 }
1435 }
1436}