feldera-types 0.385.0

Public API types for Feldera
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
use bytemuck::NoUninit;
use chrono::{DateTime, SecondsFormat, Utc};
use serde::{Deserialize, Serialize};
use serde_json::Value as JsonValue;
use std::collections::BTreeMap;
use utoipa::ToSchema;
use uuid::Uuid;

use crate::{
    checkpoint::CheckpointActivity,
    coordination::Step,
    memory_pressure::MemoryPressure,
    suspend::{PermanentSuspendError, SuspendError},
    transaction::{CommitProgressSummary, ConcurrentBootstrapPhase, TransactionId},
};

/// Pipeline state.
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
#[serde(rename_all = "PascalCase")]
pub enum PipelineState {
    /// All input endpoints are paused (or are in the process of being paused).
    #[default]
    Paused,
    /// Controller is running.
    Running,
    /// Controller is being terminated.
    Terminated,
}

// Metrics for an input endpoint.
///
/// Serializes to match the subset of fields needed for error tracking.
#[derive(Default, Serialize, Deserialize, Debug, Clone)]
pub struct InputEndpointErrorMetrics {
    pub endpoint_name: String,
    #[serde(default)]
    pub num_transport_errors: u64,
    #[serde(default)]
    pub num_parse_errors: u64,
}

/// Metrics for an output endpoint.
///
/// Serializes to match the subset of fields needed for error tracking.
#[derive(Default, Serialize, Deserialize, Debug, Clone)]
pub struct OutputEndpointErrorMetrics {
    pub endpoint_name: String,
    #[serde(default)]
    pub num_encode_errors: u64,
    #[serde(default)]
    pub num_transport_errors: u64,
}

/// Endpoint statistics containing metrics.
///
/// Wraps metrics in a structure that matches the full stats API shape.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct EndpointErrorStats<T> {
    #[serde(default)]
    pub metrics: T,
}

/// Schema definition for endpoint config that only includes the stream field.
#[derive(Debug, Deserialize, Serialize, ToSchema)]
pub struct ShortEndpointConfig {
    /// The name of the stream.
    pub stream: String,
}

/// Pipeline error statistics response from the runtime.
///
/// Lightweight response containing only error counts from all endpoints.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct PipelineStatsErrorsResponse {
    #[serde(default)]
    pub inputs: Vec<EndpointErrorStats<InputEndpointErrorMetrics>>,
    #[serde(default)]
    pub outputs: Vec<EndpointErrorStats<OutputEndpointErrorMetrics>>,
}

// OpenAPI schema definitions for controller statistics
// These match the serialized JSON structure from the connectors crate

/// Transaction status summarized as a single value.
#[derive(
    Debug, Default, Copy, PartialEq, Eq, Clone, NoUninit, Serialize, Deserialize, ToSchema,
)]
#[repr(u8)]
pub enum TransactionStatus {
    #[default]
    NoTransaction,
    TransactionInProgress,
    CommitInProgress,
}

/// Transaction phase.
#[derive(Clone, Copy, PartialEq, Eq, Debug, Deserialize, Serialize, ToSchema)]
#[serde(rename_all = "PascalCase")]
#[schema(as = TransactionPhase)]
pub enum ExternalTransactionPhase {
    /// Transaction is in progress.
    Started,
    /// Transaction has been committed.
    Committed,
}

/// Connector transaction phase with debugging label.
#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize, ToSchema)]
#[schema(as = ConnectorTransactionPhase)]
pub struct ExternalConnectorTransactionPhase {
    /// Current phase of the transaction.
    #[schema(value_type = TransactionPhase)]
    pub phase: ExternalTransactionPhase,
    /// Optional label for debugging.
    pub label: Option<String>,
}

/// Information about entities that initiated the current transaction.
#[derive(Clone, Default, Debug, Deserialize, Serialize, ToSchema)]
#[schema(as = TransactionInitiators)]
pub struct ExternalTransactionInitiators {
    /// ID assigned to the transaction (None if no transaction is in progress).
    #[schema(value_type = Option<i64>)]
    pub transaction_id: Option<TransactionId>,
    /// Transaction phase initiated by the API.
    #[schema(value_type = Option<TransactionPhase>)]
    pub initiated_by_api: Option<ExternalTransactionPhase>,
    /// Transaction phases initiated by connectors, indexed by endpoint name.
    #[schema(value_type = BTreeMap<String, ConnectorTransactionPhase>)]
    pub initiated_by_connectors: BTreeMap<String, ExternalConnectorTransactionPhase>,
}

/// A watermark that has been fully processed by the pipeline.
#[derive(Clone, Debug, Deserialize, Serialize, ToSchema)]
pub struct CompletedWatermark {
    /// Metadata that describes the position in the input stream (e.g., Kafka partition/offset pairs).
    #[schema(value_type = Object)]
    pub metadata: JsonValue,
    /// Timestamp when the data was ingested from the wire.
    #[serde(serialize_with = "serialize_timestamp_micros")]
    pub ingested_at: DateTime<Utc>,
    /// Timestamp when the data was processed by the circuit.
    #[serde(serialize_with = "serialize_timestamp_micros")]
    pub processed_at: DateTime<Utc>,
    /// Timestamp when all outputs produced from this input have been pushed to all output endpoints.
    #[serde(serialize_with = "serialize_timestamp_micros")]
    pub completed_at: DateTime<Utc>,
}

#[derive(Debug, Default, Deserialize, Serialize, ToSchema, Clone)]
pub enum ConnectorHealthStatus {
    #[default]
    Healthy,
    Unhealthy,
}

#[derive(Debug, Default, Deserialize, Serialize, ToSchema, Clone)]
pub struct ConnectorHealth {
    pub status: ConnectorHealthStatus,
    pub description: Option<String>,
}

impl ConnectorHealth {
    pub fn healthy() -> Self {
        Self {
            status: ConnectorHealthStatus::Healthy,
            description: None,
        }
    }
    pub fn unhealthy(description: &str) -> Self {
        Self {
            status: ConnectorHealthStatus::Unhealthy,
            description: Some(description.to_string()),
        }
    }
}

#[derive(Debug, Default, Deserialize, Serialize, ToSchema, Clone, PartialEq, Eq)]
pub struct ConnectorError {
    /// Timestamp when the error occurred, serialized as RFC3339 with microseconds.
    #[serde(serialize_with = "serialize_timestamp_micros")]
    pub timestamp: DateTime<Utc>,

    /// Sequence number of the error.
    ///
    /// The client can use this field to detect gaps in the error list reported
    /// by the pipeline. When the connector reports a large number of errors, the
    /// pipeline will only preserve and report the most recent errors of each kind.
    pub index: u64,

    /// Optional tag for the error.
    ///
    /// The tag is used to group errors by their type.
    pub tag: Option<String>,

    /// Error message.
    pub message: String,
}

/// Performance metrics for an input endpoint.
#[derive(Debug, Default, Deserialize, Serialize, ToSchema)]
#[schema(as = InputEndpointMetrics)]
pub struct ExternalInputEndpointMetrics {
    /// Total bytes pushed to the endpoint since it was created.
    pub total_bytes: u64,
    /// Total records pushed to the endpoint since it was created.
    pub total_records: u64,
    /// Number of records currently buffered by the endpoint (not yet consumed by the circuit).
    pub buffered_records: u64,
    /// Number of bytes currently buffered by the endpoint (not yet consumed by the circuit).
    pub buffered_bytes: u64,
    /// Number of records in the most recent non-empty batch that the endpoint
    /// gave to the circuit.
    ///
    /// For a connector that runs on more than one host, this is the sum of
    /// each host's latest non-empty batch.  These batches can come from
    /// different steps, for example when a host has been idle.
    #[serde(default)]
    pub latest_batch_records: u64,
    /// Number of bytes in the most recent non-empty batch that the endpoint
    /// gave to the circuit.
    ///
    /// For a connector that runs on more than one host, this is the sum of
    /// each host's latest non-empty batch.  These batches can come from
    /// different steps, for example when a host has been idle.
    #[serde(default)]
    pub latest_batch_bytes: u64,
    /// Number of transport errors.
    pub num_transport_errors: u64,
    /// Number of parse errors.
    pub num_parse_errors: u64,
    /// True if end-of-input has been signaled.
    pub end_of_input: bool,
    /// 99th percentile processing latency (from ingesting a batch to finishing processing it) in microseconds.
    ///
    /// The time from ingesting a batch of records off the wire
    /// to the circuit finishing processing them,
    /// covering parsing, queuing, and the circuit step.
    ///
    /// Does not account for completion latency.
    ///
    /// Taken over the endpoint's sliding histogram, which holds the 10,000 most
    /// recent samples spanning at most 10 minutes, whichever bound is reached
    /// first. One sample is recorded per completed batch. An endpoint that stops
    /// ingesting keeps reporting its last known latency instead of dropping to
    /// `None`.
    ///
    /// `None` until the endpoint records its first sample.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub processing_latency_p99_micros: Option<u64>,
}

impl ExternalInputEndpointMetrics {
    /// Adds `other`, which another host reports for its part of the same
    /// distributed connector, to these metrics.
    pub fn merge(&mut self, other: &Self) {
        // Naming every field makes a new field a compile error until it is
        // merged here.
        let &Self {
            total_bytes,
            total_records,
            buffered_records,
            buffered_bytes,
            latest_batch_records,
            latest_batch_bytes,
            num_transport_errors,
            num_parse_errors,
            end_of_input,
            processing_latency_p99_micros,
        } = other;
        self.total_bytes += total_bytes;
        self.total_records += total_records;
        self.buffered_records += buffered_records;
        self.buffered_bytes += buffered_bytes;
        // Each host gives its own batch to the step, so add them.
        self.latest_batch_records += latest_batch_records;
        self.latest_batch_bytes += latest_batch_bytes;
        self.num_transport_errors += num_transport_errors;
        self.num_parse_errors += num_parse_errors;
        self.end_of_input &= end_of_input;
        // The worst host's latency bounds the connector's latency.
        self.processing_latency_p99_micros = self
            .processing_latency_p99_micros
            .max(processing_latency_p99_micros);
    }
}

/// Input endpoint status information.
#[derive(Debug, Serialize, Deserialize, ToSchema)]
#[schema(as = InputEndpointStatus)]
pub struct ExternalInputEndpointStatus {
    /// Endpoint name.
    pub endpoint_name: String,
    /// Endpoint configuration.
    pub config: ShortEndpointConfig,
    /// Performance metrics.
    #[schema(value_type = InputEndpointMetrics)]
    pub metrics: ExternalInputEndpointMetrics,
    /// The first fatal error that occurred at the endpoint.
    pub fatal_error: Option<String>,
    /// Recent parse errors on this endpoint.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub parse_errors: Option<Vec<ConnectorError>>,
    /// Recent transport errors on this endpoint.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub transport_errors: Option<Vec<ConnectorError>>,
    /// Health status of the connector.
    #[serde(default)]
    pub health: Option<ConnectorHealth>,
    /// Endpoint has been paused by the user.  A distributed connector in a
    /// multihost pipeline is paused only if it is paused on every host.
    pub paused: bool,
    /// Endpoint is currently a barrier to checkpointing and suspend.
    pub barrier: bool,
    /// The latest completed watermark.
    #[schema(value_type = Option<CompletedWatermark>)]
    pub completed_frontier: Option<CompletedWatermark>,
}

/// How to combine the metadata of the completed frontiers that the hosts of a
/// distributed input connector report (see
/// [`ExternalInputEndpointStatus::merge`]).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum FrontierMerge {
    /// The metadata is a position in one sequence that every host shares,
    /// such as a table version.  The combined frontier keeps the metadata of
    /// the host whose frontier it is.
    Shared,

    /// Each host's metadata describes only its own partitions, as an object
    /// with arrays `partitions` and `offsets` of the same length.  The
    /// combined metadata has every host's partitions, in order.
    Partitioned,

    /// The metadata has no known structure.  The combined frontier has no
    /// metadata if more than one host that is not at end of input reports a
    /// frontier.
    #[default]
    Opaque,
}

impl ExternalInputEndpointStatus {
    /// Combines this status with `other`, which another host reports for its
    /// part of the same distributed connector, into the status of the
    /// connector as a whole.
    ///
    /// The combined connector is healthy, at end of input, paused, or free of
    /// a fatal error only if every part is.  It is a barrier if any part is.
    ///
    /// Its completed frontier is the oldest one among the hosts that are not
    /// at end of input, because input after that point is not complete on
    /// that host.  A host that is not at end of input and has completed no
    /// input yet gives no frontier.  Hosts at end of input do not hold back
    /// the frontier; if every host is at end of input, the frontier is the
    /// newest one.
    ///
    /// `frontier_merge` says how to combine the frontiers' metadata.
    pub fn merge(&mut self, other: Self, frontier_merge: FrontierMerge) {
        // Naming every field makes a new field a compile error until it is
        // merged here.
        let Self {
            // Every host reports the same name and configuration.
            endpoint_name: _,
            config: _,
            metrics,
            fatal_error,
            parse_errors,
            transport_errors,
            health,
            paused,
            barrier,
            completed_frontier,
        } = other;
        let (a_eoi, b_eoi) = (self.metrics.end_of_input, metrics.end_of_input);
        self.metrics.merge(&metrics);
        if self.fatal_error.is_none() {
            self.fatal_error = fatal_error;
        }
        merge_errors(&mut self.parse_errors, parse_errors);
        merge_errors(&mut self.transport_errors, transport_errors);
        self.health = merge_health(self.health.take(), health);
        self.paused &= paused;
        self.barrier |= barrier;
        let (a, b) = (self.completed_frontier.take(), completed_frontier);
        let several = !a_eoi && !b_eoi && a.is_some() && b.is_some();
        // Joining with no partitions puts one host's metadata in the joined
        // form.
        let no_partitions = serde_json::json!({"partitions": [], "offsets": []});
        let metadata = |f: &Option<CompletedWatermark>| {
            f.as_ref().map_or(&no_partitions, |f| &f.metadata).clone()
        };
        let joined = join_partitions(&metadata(&a), &metadata(&b));
        let oldest = |a: CompletedWatermark, b: CompletedWatermark| {
            if b.ingested_at < a.ingested_at { b } else { a }
        };
        let newest = |a: CompletedWatermark, b: CompletedWatermark| {
            if b.ingested_at > a.ingested_at { b } else { a }
        };
        self.completed_frontier = match (a_eoi, b_eoi) {
            (false, false) => a.zip(b).map(|(a, b)| oldest(a, b)),
            (false, true) => a,
            (true, false) => b,
            (true, true) => match (a, b) {
                (Some(a), Some(b)) => Some(newest(a, b)),
                (a, b) => a.or(b),
            },
        };
        if let Some(frontier) = &mut self.completed_frontier {
            match frontier_merge {
                FrontierMerge::Shared => (),
                FrontierMerge::Partitioned => frontier.metadata = joined,
                FrontierMerge::Opaque => {
                    if several {
                        frontier.metadata = JsonValue::Null;
                    }
                }
            }
        }
    }
}

/// Joins two [`FrontierMerge::Partitioned`] metadata values.  Returns null if
/// either one is not an object with arrays `partitions` and `offsets` of the
/// same length, or if they have a partition in common.
fn join_partitions(a: &JsonValue, b: &JsonValue) -> JsonValue {
    fn pairs(metadata: &JsonValue) -> Option<Vec<(i64, &JsonValue)>> {
        let partitions = metadata.get("partitions")?.as_array()?;
        let offsets = metadata.get("offsets")?.as_array()?;
        if partitions.len() != offsets.len() {
            return None;
        }
        partitions
            .iter()
            .zip(offsets)
            .map(|(partition, offsets)| Some((partition.as_i64()?, offsets)))
            .collect()
    }
    let (Some(a), Some(b)) = (pairs(a), pairs(b)) else {
        return JsonValue::Null;
    };
    let mut joined = BTreeMap::new();
    for (partition, offsets) in a.into_iter().chain(b) {
        if joined.insert(partition, offsets.clone()).is_some() {
            return JsonValue::Null;
        }
    }
    let (partitions, offsets): (Vec<_>, Vec<_>) = joined.into_iter().unzip();
    serde_json::json!({"partitions": partitions, "offsets": offsets})
}

/// Combines the health of two hosts' parts of a connector: unhealthy if either is.
fn merge_health(a: Option<ConnectorHealth>, b: Option<ConnectorHealth>) -> Option<ConnectorHealth> {
    match (a, b) {
        (Some(a), Some(b)) => Some(if matches!(a.status, ConnectorHealthStatus::Unhealthy) {
            a
        } else {
            b
        }),
        (a, b) => a.or(b),
    }
}

/// Appends `b` to `a` and sorts the result by time, because each host numbers
/// its own errors.
fn merge_errors(a: &mut Option<Vec<ConnectorError>>, b: Option<Vec<ConnectorError>>) {
    if let Some(b) = b {
        let errors = a.get_or_insert_with(Vec::new);
        errors.extend(b);
        errors.sort_by_key(|error| error.timestamp);
    }
}

/// Performance metrics for an output endpoint.
#[derive(Debug, Default, Deserialize, Serialize, ToSchema, PartialEq, Eq, PartialOrd, Ord)]
#[schema(as = OutputEndpointMetrics)]
pub struct ExternalOutputEndpointMetrics {
    /// Records sent on the underlying transport.
    pub transmitted_records: u64,
    /// Bytes sent on the underlying transport.
    pub transmitted_bytes: u64,
    /// Number of queued records.
    pub queued_records: u64,
    /// Number of queued batches.
    pub queued_batches: u64,
    /// Number of records pushed to the output buffer.
    pub buffered_records: u64,
    /// Number of batches in the buffer.
    pub buffered_batches: u64,
    /// Number of encoding errors.
    pub num_encode_errors: u64,
    /// Number of transport errors.
    pub num_transport_errors: u64,
    /// The number of input records processed by the circuit.
    ///
    /// This metric tracks the end-to-end progress of the pipeline: the output
    /// of this endpoint is equal to the output of the circuit after
    /// processing `total_processed_input_records` records.
    ///
    /// The counter never runs ahead of the endpoint's output. It advances to a
    /// value `N` only once the endpoint has processed every batch derived from
    /// the first `N` records received by the pipeline, which means transmitting
    /// the batch, or discarding it while silent bootstrapping suppresses the
    /// endpoint's output.
    ///
    /// In a multihost pipeline, `N` counts the input records that all of the
    /// hosts received, not only the endpoint's own host.  (Each host counts
    /// only its own input, and the coordinator adds up the hosts' counts as of
    /// `total_processed_steps`.)  If a host runs an older version that does
    /// not report its count to the coordinator, `N` counts only the input
    /// records that the endpoint's own host received.
    pub total_processed_input_records: u64,
    /// The number of steps whose input records have been processed by the
    /// endpoint.
    ///
    /// In a multihost pipeline, all of the hosts run the same steps together,
    /// so a step number refers to the same step on every host.
    ///
    /// # Interpretation
    ///
    /// This is a count, not a step number.  If `total_processed_steps` is 0, no
    /// steps have been processed to completion.  If `total_processed_steps >
    /// 0`, then the last step whose input records have been processed to
    /// completion is `total_processed_steps - 1`. A record that was ingested in
    /// step `n` is fully processed when `total_processed_steps > n`.
    #[schema(value_type = u64)]
    pub total_processed_steps: Step,
    /// Extra memory in use beyond that used for queuing records.
    pub memory: u64,
    /// Number of records written so far while the connector is processing a
    /// batch of updates.  Resets to 0 after the batch is committed.
    ///
    /// `None` when the connector does not support batch-progress reporting.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub batch_records_written: Option<u64>,
}

/// Output endpoint status information.
#[derive(Debug, Deserialize, Serialize, ToSchema)]
#[schema(as = OutputEndpointStatus)]
pub struct ExternalOutputEndpointStatus {
    /// Endpoint name.
    pub endpoint_name: String,
    /// Endpoint configuration.
    pub config: ShortEndpointConfig,
    /// Performance metrics.
    #[schema(value_type = OutputEndpointMetrics)]
    pub metrics: ExternalOutputEndpointMetrics,
    /// The first fatal error that occurred at the endpoint.
    pub fatal_error: Option<String>,
    /// Recent encoding errors on this endpoint.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub encode_errors: Option<Vec<ConnectorError>>,
    /// Recent transport errors on this endpoint.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub transport_errors: Option<Vec<ConnectorError>>,
    /// Health status of the connector.
    #[serde(default)]
    pub health: Option<ConnectorHealth>,
    /// Endpoint has been paused by the user.
    ///
    /// A paused output endpoint discards the output it receives instead of
    /// sending it to its sink.
    #[serde(default)]
    pub paused: bool,
}

impl ExternalOutputEndpointMetrics {
    /// Adds `other`, which another host reports for its part of the same
    /// distributed connector, to these metrics.
    ///
    /// Counts add up.  The connector has processed only as much input as its
    /// slowest part.
    pub fn merge(&mut self, other: &Self) {
        // Naming every field makes a new field a compile error until it is
        // merged here.
        let &Self {
            transmitted_records,
            transmitted_bytes,
            queued_records,
            queued_batches,
            buffered_records,
            buffered_batches,
            num_encode_errors,
            num_transport_errors,
            total_processed_input_records,
            total_processed_steps,
            memory,
            batch_records_written,
        } = other;
        self.transmitted_records += transmitted_records;
        self.transmitted_bytes += transmitted_bytes;
        self.queued_records += queued_records;
        self.queued_batches += queued_batches;
        self.buffered_records += buffered_records;
        self.buffered_batches += buffered_batches;
        self.num_encode_errors += num_encode_errors;
        self.num_transport_errors += num_transport_errors;
        self.total_processed_input_records = self
            .total_processed_input_records
            .min(total_processed_input_records);
        self.total_processed_steps = self.total_processed_steps.min(total_processed_steps);
        self.memory += memory;
        self.batch_records_written = match (self.batch_records_written, batch_records_written) {
            (Some(a), Some(b)) => Some(a + b),
            (a, b) => a.or(b),
        };
    }
}

impl ExternalOutputEndpointStatus {
    /// Combines this status with `other`, which another host reports for its
    /// part of the same distributed connector, into the status of the
    /// connector as a whole.
    ///
    /// The combined connector is healthy, paused, or free of a fatal error
    /// only if every part is.
    pub fn merge(&mut self, other: Self) {
        // Naming every field makes a new field a compile error until it is
        // merged here.
        let Self {
            // Every host reports the same name and configuration.
            endpoint_name: _,
            config: _,
            metrics,
            fatal_error,
            encode_errors,
            transport_errors,
            health,
            paused,
        } = other;
        self.metrics.merge(&metrics);
        if self.fatal_error.is_none() {
            self.fatal_error = fatal_error;
        }
        merge_errors(&mut self.encode_errors, encode_errors);
        merge_errors(&mut self.transport_errors, transport_errors);
        self.health = merge_health(self.health.take(), health);
        self.paused &= paused;
    }
}

/// Global controller metrics.
#[derive(Debug, Default, Serialize, Deserialize, ToSchema)]
#[schema(as = GlobalControllerMetrics)]
pub struct ExternalGlobalControllerMetrics {
    /// State of the pipeline: running, paused, or terminating.
    pub state: PipelineState,
    /// The pipeline has been resumed from a checkpoint and is currently bootstrapping new and modified views.
    pub bootstrap_in_progress: bool,
    /// Status of the current transaction.
    pub transaction_status: TransactionStatus,
    /// ID of the current transaction or 0 if no transaction is in progress.
    #[schema(value_type = i64)]
    pub transaction_id: TransactionId,
    /// Elapsed time in milliseconds, according to `transaction_status`:
    ///
    /// - [TransactionStatus::TransactionInProgress]: Time that this transaction
    ///   has been in progress.
    ///
    /// - [TransactionStatus::CommitInProgress]: Time that this transaction has
    ///   been committing.
    pub transaction_msecs: Option<u64>,
    /// Number of records in this transaction, according to
    /// `transaction_status`:
    ///
    /// - [TransactionStatus::TransactionInProgress]: Number of records added so
    ///   far.  More records might be added.
    ///
    /// - [TransactionStatus::CommitInProgress]: Final number of records.
    pub transaction_records: Option<u64>,
    /// Progress of the current transaction commit, if one is in progress.
    pub commit_progress: Option<CommitProgressSummary>,
    /// Entities that initiated the current transaction.
    #[schema(value_type = TransactionInitiators)]
    pub transaction_initiators: ExternalTransactionInitiators,
    /// Phase of a concurrent bootstrap, or `Inactive` if none is in progress.
    pub concurrent_bootstrap_phase: ConcurrentBootstrapPhase,
    /// Progress of the concurrent bootstrap's transaction commit, if a commit is
    /// in progress: the backfill transaction during `ConcurrentBootstrapping` and
    /// the synchronization transaction during `Synchronizing`.
    pub concurrent_bootstrap_progress: Option<CommitProgressSummary>,
    /// Resident set size of the pipeline process, in bytes.
    pub rss_bytes: u64,
    /// Memory pressure.
    pub memory_pressure: MemoryPressure,
    /// Memory pressure epoch.
    pub memory_pressure_epoch: u64,
    /// CPU time used by the pipeline across all threads, in milliseconds.
    pub cpu_msecs: u64,
    /// Time since the pipeline process started, including time that the
    /// pipeline was running or paused.
    ///
    /// This is the elapsed time since `start_time`.
    pub uptime_msecs: u64,
    /// Time at which the pipeline process started, in seconds since the epoch.
    #[serde(with = "chrono::serde::ts_seconds")]
    #[schema(value_type = u64)]
    pub start_time: DateTime<Utc>,
    /// Uniquely identifies the pipeline process that started at start_time.
    pub incarnation_uuid: Uuid,
    /// Time at which the pipeline process from which we resumed started, in seconds since the epoch.
    #[serde(with = "chrono::serde::ts_seconds")]
    #[schema(value_type = u64)]
    pub initial_start_time: DateTime<Utc>,
    /// Current storage usage in bytes.
    pub storage_bytes: u64,
    /// Storage usage integrated over time, in megabytes * seconds.
    pub storage_mb_secs: u64,
    /// Capacity of the pipeline's storage disk, in bytes; absent when unknown.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub disk_total_bytes: Option<u64>,
    /// Bytes the pipeline can still write to its storage disk; absent when unknown.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub disk_available_bytes: Option<u64>,
    /// Time elapsed while the pipeline is executing a step, multiplied by the number of threads, in milliseconds.
    pub runtime_elapsed_msecs: u64,
    /// Total number of records currently buffered by all endpoints.
    pub buffered_input_records: u64,
    /// Total number of bytes currently buffered by all endpoints.
    pub buffered_input_bytes: u64,
    /// Total number of records received from all endpoints.
    pub total_input_records: u64,
    /// Total number of bytes received from all endpoints.
    pub total_input_bytes: u64,
    /// Total number of input records processed by the DBSP engine.
    pub total_processed_records: u64,
    /// Total bytes of input records processed by the DBSP engine.
    pub total_processed_bytes: u64,
    /// Total number of input records processed to completion.
    ///
    /// In a multihost pipeline, this counts the input records that all of the
    /// hosts received.  If a host runs an older version that does not report
    /// its count to the coordinator, this is instead the sum of the counts
    /// that each host reports for its own input, which can include input whose
    /// output an output connector on a different host has not yet processed.
    pub total_completed_records: u64,
    /// If the pipeline is stalled because one or more output connectors' output
    /// buffers are full, this is the number of milliseconds that the current
    /// stall has lasted.
    ///
    /// If this is nonzero, then the output connectors causing the stall can be
    /// identified by noticing `ExternalOutputEndpointMetrics::queued_records`
    /// is greater than or equal to `ConnectorConfig::max_queued_records`.
    ///
    /// In the ordinary case, the pipeline is not stalled, and this value is 0.
    pub output_stall_msecs: u64,
    /// Number of steps that have been initiated.
    ///
    /// # Interpretation
    ///
    /// This is a count, not a step number.  If `total_initiated_steps` is 0, no
    /// steps have been initiated.  If `total_initiated_steps > 0`, then step
    /// `total_initiated_steps - 1` has been started and all steps previous to
    /// that have been completely processed by the circuit.
    #[schema(value_type = u64)]
    pub total_initiated_steps: Step,
    /// Number of steps whose input records have been processed to completion.
    ///
    /// A record is processed to completion if it has been processed by the DBSP engine and
    /// all outputs derived from it have been processed by all output connectors.
    ///
    /// # Interpretation
    ///
    /// This is a count, not a step number.  If `total_completed_steps` is 0, no
    /// steps have been processed to completion.  If `total_completed_steps >
    /// 0`, then the last step whose input records have been processed to
    /// completion is `total_completed_steps - 1`. A record that was ingested
    /// when `total_initiated_steps` was `n` is fully processed when
    /// `total_completed_steps >= n`.
    #[schema(value_type = u64)]
    pub total_completed_steps: Step,
    /// True if the pipeline has processed all input data to completion.
    pub pipeline_complete: bool,
    /// Version of the platform that compiled the pipeline, such as
    /// `0.349.0+enterprise`.
    ///
    /// This is the platform's own version, which the compiler records in the
    /// binary.
    pub platform_version: String,
    /// Runtime the pipeline was compiled against.
    ///
    /// Equal to `platform_version` when the program uses the platform's own
    /// runtime; otherwise the selected runtime, a git SHA, a `vX.Y.Z` tag,
    /// or `gen2`.
    pub runtime_version: String,
}

/// Complete pipeline statistics returned by the `/stats` endpoint.
///
/// This schema definition matches the serialized JSON structure from
/// `adapters::controller::ControllerStatus`. The actual implementation with
/// atomics and mutexes lives in the adapters crate, which uses ExternalControllerStatus to
/// register this OpenAPI schema, making it available to pipeline-manager
/// without requiring a direct dependency on the adapters crate.
#[derive(Debug, Deserialize, Serialize, ToSchema, Default)]
#[schema(as = ControllerStatus)]
pub struct ExternalControllerStatus {
    /// Global controller metrics.
    #[schema(value_type = GlobalControllerMetrics)]
    pub global_metrics: ExternalGlobalControllerMetrics,
    /// Reason why the pipeline cannot be suspended or checkpointed (if any).
    pub suspend_error: Option<SuspendError>,
    /// Current checkpoint activity (idle, delayed, or in-progress).
    /// `None` when the pipeline binary predates checkpoint activity tracking.
    pub checkpoint_activity: Option<CheckpointActivity>,
    /// If the pipeline fundamentally cannot checkpoint (e.g. storage is not
    /// configured, or an input endpoint does not support suspend), the reasons
    /// are listed here.  Unlike a checkpoint failure, this means *no*
    /// checkpoint can succeed until the pipeline configuration changes.
    pub permanent_checkpoint_errors: Option<Vec<PermanentSuspendError>>,
    /// Input endpoint configs and metrics.
    #[schema(value_type = Vec<InputEndpointStatus>)]
    pub inputs: Vec<ExternalInputEndpointStatus>,
    /// Output endpoint configs and metrics.
    #[schema(value_type = Vec<OutputEndpointStatus>)]
    pub outputs: Vec<ExternalOutputEndpointStatus>,
    /// Resource usage of each host in a multihost pipeline, by ordinal.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub host_metrics: Vec<HostMetrics>,
}

/// Resource usage of one host in a multihost pipeline.
#[derive(Debug, Default, Deserialize, Serialize, ToSchema)]
pub struct HostMetrics {
    /// Capacity of the host's storage disk, in bytes; absent when unknown.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub disk_total_bytes: Option<u64>,
    /// Bytes the host can still write to its storage disk; absent when unknown.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub disk_available_bytes: Option<u64>,
}

impl From<&ExternalGlobalControllerMetrics> for HostMetrics {
    fn from(metrics: &ExternalGlobalControllerMetrics) -> Self {
        Self {
            disk_total_bytes: metrics.disk_total_bytes,
            disk_available_bytes: metrics.disk_available_bytes,
        }
    }
}

fn serialize_timestamp_micros<S>(
    timestamp: &DateTime<Utc>,
    serializer: S,
) -> Result<S::Ok, S::Error>
where
    S: serde::Serializer,
{
    serializer.serialize_str(&timestamp.to_rfc3339_opts(SecondsFormat::Micros, true))
}

#[cfg(test)]
mod tests {
    use super::ConnectorError;
    use chrono::{DateTime, Utc};

    #[test]
    fn connector_error_timestamp_serializes_with_microsecond_precision() {
        let error = ConnectorError {
            timestamp: DateTime::parse_from_rfc3339("2026-03-08T05:26:42.442438448Z")
                .unwrap()
                .with_timezone(&Utc),
            index: 1,
            tag: None,
            message: "boom".to_string(),
        };

        let json = serde_json::to_string(&error).unwrap();
        assert!(json.contains(r#""timestamp":"2026-03-08T05:26:42.442438Z""#));
    }

    #[test]
    fn output_metrics_batch_records_written_serializes() {
        use super::ExternalOutputEndpointMetrics;

        let metrics = ExternalOutputEndpointMetrics {
            batch_records_written: Some(42),
            ..Default::default()
        };
        let json = serde_json::to_string(&metrics).unwrap();
        assert!(json.contains(r#""batch_records_written":42"#));

        let deserialized: ExternalOutputEndpointMetrics = serde_json::from_str(&json).unwrap();
        assert_eq!(deserialized.batch_records_written, Some(42));
    }

    #[test]
    fn output_metrics_batch_records_written_defaults_to_none() {
        use super::ExternalOutputEndpointMetrics;

        // Old JSON without batch_records_written defaults to None.
        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}"#;
        let metrics: ExternalOutputEndpointMetrics = serde_json::from_str(json).unwrap();
        assert_eq!(metrics.batch_records_written, None);
    }

    mod merge {
        use chrono::{DateTime, TimeZone, Utc};

        use crate::adapter_stats::{
            CompletedWatermark, ConnectorError, ConnectorHealth, ConnectorHealthStatus,
            ExternalInputEndpointMetrics, ExternalInputEndpointStatus,
            ExternalOutputEndpointMetrics, ExternalOutputEndpointStatus, FrontierMerge,
            ShortEndpointConfig,
        };
        use serde_json::{Value, json};

        fn time(secs: i64) -> DateTime<Utc> {
            Utc.timestamp_opt(secs, 0).unwrap()
        }

        fn error(secs: i64, message: &str) -> ConnectorError {
            ConnectorError {
                timestamp: time(secs),
                index: 0,
                tag: None,
                message: message.into(),
            }
        }

        fn frontier(ingested_secs: i64) -> CompletedWatermark {
            CompletedWatermark {
                metadata: serde_json::json!(ingested_secs),
                ingested_at: time(ingested_secs),
                processed_at: time(ingested_secs + 1),
                completed_at: time(ingested_secs + 2),
            }
        }

        fn status() -> ExternalInputEndpointStatus {
            ExternalInputEndpointStatus {
                endpoint_name: "t.kafka".into(),
                config: ShortEndpointConfig { stream: "t".into() },
                metrics: ExternalInputEndpointMetrics {
                    total_bytes: 10,
                    total_records: 1,
                    buffered_records: 2,
                    buffered_bytes: 20,
                    latest_batch_records: 5,
                    latest_batch_bytes: 50,
                    num_transport_errors: 3,
                    num_parse_errors: 4,
                    end_of_input: true,
                    processing_latency_p99_micros: Some(100),
                },
                fatal_error: None,
                parse_errors: None,
                transport_errors: None,
                health: Some(ConnectorHealth::healthy()),
                paused: false,
                barrier: false,
                completed_frontier: None,
            }
        }

        #[test]
        fn counters_add_up() {
            let mut a = status();
            let mut b = status();
            b.metrics.processing_latency_p99_micros = Some(500);
            b.metrics.end_of_input = false;
            a.merge(b, FrontierMerge::Opaque);
            let m = &a.metrics;
            assert_eq!(
                (
                    m.total_bytes,
                    m.total_records,
                    m.buffered_records,
                    m.buffered_bytes
                ),
                (20, 2, 4, 40)
            );
            assert_eq!((m.latest_batch_records, m.latest_batch_bytes), (10, 100));
            assert_eq!((m.num_transport_errors, m.num_parse_errors), (6, 8));
            assert!(!m.end_of_input);
            assert_eq!(m.processing_latency_p99_micros, Some(500));
        }

        #[test]
        fn worst_host_decides() {
            let mut a = status();
            let mut b = status();
            b.fatal_error = Some("broken".into());
            b.health = Some(ConnectorHealth::unhealthy("sick"));
            b.barrier = true;
            a.merge(b, FrontierMerge::Opaque);
            assert_eq!(a.fatal_error.as_deref(), Some("broken"));
            assert!(matches!(
                a.health.unwrap().status,
                ConnectorHealthStatus::Unhealthy
            ));
            assert!(a.barrier);

            // The first fatal error stays.
            let mut a = status();
            a.fatal_error = Some("first".into());
            let mut b = status();
            b.fatal_error = Some("second".into());
            a.merge(b, FrontierMerge::Opaque);
            assert_eq!(a.fatal_error.as_deref(), Some("first"));
        }

        /// Merges hosts given as (end of input, frontier ingestion time,
        /// metadata) with `kind`, and returns the merged frontier's ingestion
        /// time and metadata.
        fn merge_metadata(
            hosts: Vec<(bool, Option<(i64, Value)>)>,
            kind: FrontierMerge,
        ) -> Option<(DateTime<Utc>, Value)> {
            let mut statuses = hosts.into_iter().map(|(eoi, f)| {
                let mut s = status();
                s.metrics.end_of_input = eoi;
                s.completed_frontier = f.map(|(secs, metadata)| CompletedWatermark {
                    metadata,
                    ..frontier(secs)
                });
                s
            });
            let mut x = statuses.next().unwrap();
            statuses.for_each(|y| x.merge(y, kind));
            x.completed_frontier.map(|f| (f.ingested_at, f.metadata))
        }

        /// Shared metadata stays with its host's frontier, however many
        /// hosts report one.
        #[test]
        fn shared_frontier_merge() {
            let merged = |hosts| merge_metadata(hosts, FrontierMerge::Shared);
            let version = |v: i64| json!({"version": v});
            assert_eq!(
                merged(vec![
                    (false, Some((10, version(3)))),
                    (false, Some((5, version(2))))
                ]),
                Some((time(5), version(2)))
            );
            assert_eq!(
                merged(vec![
                    (true, Some((5, version(2)))),
                    (false, Some((10, version(7))))
                ]),
                Some((time(10), version(7)))
            );
            assert_eq!(
                merged(vec![
                    (true, Some((5, version(2)))),
                    (true, Some((10, version(2))))
                ]),
                Some((time(10), version(2)))
            );
        }

        /// Partitioned metadata joins every host's partitions, including
        /// those of hosts at end of input.
        #[test]
        fn partitioned_frontier_merge() {
            let merged = |hosts| merge_metadata(hosts, FrontierMerge::Partitioned);
            // A host's metadata, which also has fields that the join drops.
            let host = |partitions: &[i64], offsets: &[i64]| json!({"partitions": partitions, "offsets": offsets, "shard": {"host": 0}});
            let joined = |partitions: &[i64], offsets: &[i64]| json!({"partitions": partitions, "offsets": offsets});

            // Busy hosts, in any order.
            assert_eq!(
                merged(vec![
                    (false, Some((10, host(&[1, 4], &[11, 14])))),
                    (false, Some((5, host(&[2], &[12])))),
                    (false, Some((7, host(&[0, 3], &[10, 13])))),
                ]),
                Some((time(5), joined(&[0, 1, 2, 3, 4], &[10, 11, 12, 13, 14])))
            );

            // Hosts at end of input add their partitions but not their time.
            assert_eq!(
                merged(vec![
                    (true, Some((5, host(&[1], &[11])))),
                    (false, Some((10, host(&[0], &[10])))),
                ]),
                Some((time(10), joined(&[0, 1], &[10, 11])))
            );
            assert_eq!(
                merged(vec![
                    (true, Some((10, host(&[1], &[11])))),
                    (true, Some((5, host(&[0], &[10])))),
                ]),
                Some((time(10), joined(&[0, 1], &[10, 11])))
            );

            // A host with no partitions and no frontier adds nothing, and one
            // host's metadata takes the joined form.
            assert_eq!(
                merged(vec![(true, None), (false, Some((10, host(&[0], &[10]))))]),
                Some((time(10), joined(&[0], &[10])))
            );

            // A busy host with no frontier still holds back the frontier.
            assert_eq!(
                merged(vec![(false, None), (true, Some((10, host(&[0], &[10]))))]),
                None
            );

            // Metadata without partitions, as from an older host, or with a
            // partition that two hosts report, joins to null.
            for other in [json!({"offsets": [11]}), host(&[0], &[11]), Value::Null] {
                assert_eq!(
                    merged(vec![
                        (false, Some((10, host(&[0], &[10])))),
                        (false, Some((5, other.clone()))),
                    ]),
                    Some((time(5), Value::Null)),
                    "{other}"
                );
            }
        }

        fn output_status(steps: u64, records: u64) -> ExternalOutputEndpointStatus {
            ExternalOutputEndpointStatus {
                endpoint_name: "v.delta".into(),
                config: ShortEndpointConfig { stream: "v".into() },
                metrics: ExternalOutputEndpointMetrics {
                    transmitted_records: 1,
                    transmitted_bytes: 2,
                    queued_records: 3,
                    queued_batches: 4,
                    buffered_records: 5,
                    buffered_batches: 6,
                    num_encode_errors: 7,
                    num_transport_errors: 8,
                    total_processed_input_records: records,
                    total_processed_steps: steps,
                    memory: 9,
                    batch_records_written: None,
                },
                fatal_error: None,
                encode_errors: None,
                transport_errors: None,
                health: Some(ConnectorHealth::healthy()),
                paused: true,
            }
        }

        /// The parts of a distributed output connector add up their counts,
        /// and the slowest part decides the progress, the health, and the
        /// pause.
        #[test]
        fn output_merge() {
            let mut a = output_status(5, 50);
            let mut b = output_status(3, 30);
            b.metrics.batch_records_written = Some(10);
            b.health = Some(ConnectorHealth::unhealthy("sick"));
            b.paused = false;
            b.fatal_error = Some("broken".into());
            b.transport_errors = Some(vec![error(2, "b2")]);
            a.merge(b);
            assert_eq!(
                a.metrics,
                ExternalOutputEndpointMetrics {
                    transmitted_records: 2,
                    transmitted_bytes: 4,
                    queued_records: 6,
                    queued_batches: 8,
                    buffered_records: 10,
                    buffered_batches: 12,
                    num_encode_errors: 14,
                    num_transport_errors: 16,
                    total_processed_input_records: 30,
                    total_processed_steps: 3,
                    memory: 18,
                    batch_records_written: Some(10),
                }
            );
            assert!(matches!(
                a.health.unwrap().status,
                ConnectorHealthStatus::Unhealthy
            ));
            assert!(!a.paused);
            assert_eq!(a.fatal_error.as_deref(), Some("broken"));
            assert_eq!(a.transport_errors.unwrap().len(), 1);
        }

        /// A connector is paused only if every host is, in any order.
        #[test]
        fn pause_merge() {
            let merged = |hosts: &[bool]| {
                let mut statuses = hosts.iter().map(|&paused| {
                    let mut s = status();
                    s.paused = paused;
                    s
                });
                let mut x = statuses.next().unwrap();
                statuses.for_each(|y| x.merge(y, FrontierMerge::Opaque));
                x.paused
            };
            assert!(merged(&[true, true, true]));
            assert!(!merged(&[false, false, false]));
            for hosts in [
                [true, false, false],
                [false, true, false],
                [false, false, true],
                [true, true, false],
                [false, true, true],
                [true, false, true],
            ] {
                assert!(!merged(&hosts), "{hosts:?}");
            }
        }

        #[test]
        fn errors_are_combined_in_time_order() {
            let mut a = status();
            a.parse_errors = Some(vec![error(1, "a1"), error(5, "a5")]);
            let mut b = status();
            b.parse_errors = Some(vec![error(3, "b3")]);
            b.transport_errors = Some(vec![error(2, "b2")]);
            a.merge(b, FrontierMerge::Opaque);
            let messages = |errors: &Option<Vec<ConnectorError>>| {
                errors
                    .iter()
                    .flatten()
                    .map(|e| e.message.clone())
                    .collect::<Vec<_>>()
            };
            assert_eq!(messages(&a.parse_errors), ["a1", "b3", "a5"]);
            assert_eq!(messages(&a.transport_errors), ["b2"]);
        }

        #[test]
        fn opaque_frontier_merge() {
            // Merges hosts given as (end of input, frontier) and returns the
            // merged frontier's ingestion time and whether it kept metadata.
            let merged = |hosts: &[(bool, Option<i64>)]| {
                let mut statuses = hosts.iter().map(|&(eoi, f)| {
                    let mut s = status();
                    s.metrics.end_of_input = eoi;
                    s.completed_frontier = f.map(frontier);
                    s
                });
                let mut x = statuses.next().unwrap();
                statuses.for_each(|y| x.merge(y, FrontierMerge::Opaque));
                x.completed_frontier
                    .map(|f| (f.ingested_at, !f.metadata.is_null()))
            };
            let (busy, done) = (false, true);

            // The oldest frontier among hosts that are still reading.
            assert_eq!(
                merged(&[(busy, Some(10)), (busy, Some(5))]),
                Some((time(5), false))
            );
            assert_eq!(
                merged(&[(busy, Some(5)), (busy, Some(10))]),
                Some((time(5), false))
            );

            // A host still reading with no frontier holds back the frontier,
            // in any position.
            assert_eq!(merged(&[(busy, None), (busy, Some(10))]), None);
            assert_eq!(merged(&[(busy, Some(10)), (busy, None)]), None);
            assert_eq!(
                merged(&[(busy, Some(10)), (busy, None), (busy, Some(5))]),
                None
            );
            assert_eq!(
                merged(&[(busy, None), (done, Some(5)), (busy, Some(10))]),
                None
            );

            // Hosts at end of input do not hold back the frontier, and the
            // one host still reading keeps its metadata, as a Delta Lake
            // connector's home host does while it follows the table.
            assert_eq!(
                merged(&[(busy, Some(10)), (done, Some(5))]),
                Some((time(10), true))
            );
            assert_eq!(
                merged(&[(done, Some(5)), (busy, Some(10))]),
                Some((time(10), true))
            );
            assert_eq!(
                merged(&[(done, None), (busy, Some(10))]),
                Some((time(10), true))
            );
            assert_eq!(
                merged(&[(busy, Some(10)), (done, None)]),
                Some((time(10), true))
            );
            assert_eq!(
                merged(&[(done, Some(5)), (busy, Some(10)), (done, Some(20))]),
                Some((time(10), true))
            );
            assert_eq!(
                merged(&[(done, Some(5)), (busy, Some(10)), (busy, Some(20))]),
                Some((time(10), false))
            );

            // If every host is at end of input, the newest frontier.
            assert_eq!(
                merged(&[(done, Some(10)), (done, Some(5))]),
                Some((time(10), true))
            );
            assert_eq!(
                merged(&[(done, None), (done, Some(5))]),
                Some((time(5), true))
            );
            assert_eq!(merged(&[(done, None), (done, None)]), None);
        }
    }
}