obzenflow_core 0.2.4

Core domain layer for ObzenFlow - pure abstractions with minimal dependencies
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
// SPDX-License-Identifier: MIT OR Apache-2.0
// SPDX-FileCopyrightText: 2025-2026 ObzenFlow Contributors
// https://obzenflow.dev

//! Snapshot DTOs for metrics collection
//!
//! These DTOs define the observations published by execution and host samplers,
//! implementing the dual collection pattern for application and infrastructure metrics.

use crate::event::context::StageType;
use crate::event::observability::{
    EdgeLivenessState, HttpPullMetricsSnapshot, HttpSurfaceRouteMetricsSnapshot, MeasurementWindow,
    StageActivity,
};
use crate::event::payloads::system_payload::{
    ContractName, ContractResultStatusLabel, SystemFeedRole,
};
use crate::event::status::processing_status::ErrorKind;
use crate::event::types::EventType;
use crate::event::SinkOperationPhase;
use crate::id::{FlowId, StageId};
use crate::ingress::IngressKey;
use crate::metrics::composite::{
    CompositeContract, CompositeDurationHistogram, CompositeDurationInvalid, CompositeMemberHealth,
    CompositePortTraffic,
};
use crate::metrics::Percentile;
use crate::time::MetricsDuration;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// Snapshot of application-level metrics derived from the event stream
#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub struct AppMetricsSnapshot {
    #[serde(default)]
    pub throughput: super::ThroughputSnapshot,
    #[serde(default)]
    pub observation_export_interval: Option<std::time::Duration>,
    /// Timestamp when this snapshot was created
    pub timestamp: chrono::DateTime<chrono::Utc>,

    /// Event counts by stage
    pub event_counts: HashMap<StageId, u64>,

    /// Total events accumulated into internal state by stage (stateful/join stages).
    pub events_accumulated_total: HashMap<StageId, u64>,

    /// Total events emitted by stage (data/delivery; excludes observability-only events).
    pub events_emitted_total: HashMap<StageId, u64>,

    /// Join-only gauge (Live join): number of reference events processed since the last stream event.
    pub join_reference_since_last_stream: HashMap<StageId, u64>,

    /// Error counts by stage
    pub error_counts: HashMap<StageId, u64>,

    /// Error counts by stage and ErrorKind
    pub error_counts_by_kind: HashMap<StageId, HashMap<ErrorKind, u64>>,

    /// Failure counts projected exclusively from durable
    /// `SinkOperationFailed` facts.
    pub sink_operation_failures: Vec<SinkOperationFailureMetric>,

    /// Processing time histograms by stage (in seconds)
    pub processing_times: HashMap<StageId, HistogramSnapshot>,

    /// In-flight events by stage
    pub in_flight: HashMap<StageId, f64>,

    /// CPU usage ratio by stage (0.0-1.0)
    pub cpu_usage_ratio: HashMap<StageId, f64>,

    /// Memory usage in bytes by stage
    pub memory_bytes: HashMap<StageId, f64>,

    /// Anomalies total by stage
    pub anomalies_total: HashMap<StageId, u64>,

    /// Amendments total by stage
    pub amendments_total: HashMap<StageId, u64>,

    /// Saturation ratio by stage (0.0-1.0)
    pub saturation_ratio: HashMap<StageId, f64>,

    /// Failures total by stage (critical failures)
    pub failures_total: HashMap<StageId, u64>,

    /// Event loops total by stage
    pub event_loops_total: HashMap<StageId, u64>,

    /// Event loops with work by stage
    pub event_loops_with_work_total: HashMap<StageId, u64>,

    /// Flow-level latency histograms by flow name (in seconds)
    pub flow_latency_seconds: HashMap<StageId, HistogramSnapshot>,

    /// Dropped events by flow name
    pub dropped_events: HashMap<StageId, f64>,

    /// Circuit breaker state by stage (0=closed, 0.5=half_open, 1=open)
    pub circuit_breaker_state: HashMap<StageId, f64>,

    /// Circuit breaker rejection rate by stage (0.0-1.0)
    pub circuit_breaker_rejection_rate: HashMap<StageId, f64>,

    /// Circuit breaker consecutive failures by stage
    pub circuit_breaker_consecutive_failures: HashMap<StageId, f64>,

    /// Circuit breaker requests processed total by stage (monotonic counter)
    pub circuit_breaker_requests_total: HashMap<StageId, u64>,

    /// Circuit breaker requests rejected total by stage (monotonic counter)
    pub circuit_breaker_rejections_total: HashMap<StageId, u64>,

    /// Circuit breaker times entered Open by stage (monotonic counter).
    pub circuit_breaker_opened_total: HashMap<StageId, u64>,

    /// Circuit breaker allowed calls classified as non-failures by stage (monotonic counter).
    ///
    /// This is "success" from the breaker’s perspective (i.e., it did not count as an
    /// infra failure toward opening), not necessarily domain-level success.
    pub circuit_breaker_successes_total: HashMap<StageId, u64>,

    /// Circuit breaker allowed calls classified as failures by stage (monotonic counter).
    ///
    /// These are calls that counted toward breaker opening (e.g. Timeout/Remote failures).
    pub circuit_breaker_failures_total: HashMap<StageId, u64>,

    /// Circuit breaker slow physical calls by stage (monotonic counter).
    pub circuit_breaker_slow_total: HashMap<StageId, u64>,

    /// Circuit breaker time spent in each state by stage (monotonic counter, seconds).
    /// Maps (StageId, state) -> seconds_total, where state is one of: "closed", "half_open", "open".
    pub circuit_breaker_time_in_state_seconds_total: HashMap<(StageId, String), f64>,

    /// Circuit breaker state transitions by stage (monotonic counter).
    /// Maps (StageId, from_state, to_state) -> transitions_total.
    pub circuit_breaker_state_transitions_total: HashMap<(StageId, String, String), u64>,

    /// Rate limiter utilization by stage (0.0-1.0)
    pub rate_limiter_utilization: HashMap<StageId, f64>,

    /// Rate limiter events processed total by stage (monotonic counter)
    pub rate_limiter_events_total: HashMap<StageId, u64>,

    /// Rate limiter delayed events total by stage (monotonic counter)
    pub rate_limiter_delayed_total: HashMap<StageId, u64>,

    /// Rate limiter tokens consumed total by stage (monotonic counter).
    pub rate_limiter_tokens_consumed_total: HashMap<StageId, f64>,

    /// Rate limiter total time spent blocked waiting for tokens (seconds, monotonic counter).
    pub rate_limiter_delay_seconds_total: HashMap<StageId, f64>,

    /// Rate limiter current bucket tokens by stage (FLOWIP-059a-3 Issue 3).
    pub rate_limiter_bucket_tokens: HashMap<StageId, f64>,

    /// Rate limiter bucket capacity by stage (FLOWIP-059a-3 Issue 3).
    pub rate_limiter_bucket_capacity: HashMap<StageId, f64>,

    /// Backpressure window per edge (upstream, downstream) (FLOWIP-086k).
    pub backpressure_window: HashMap<(StageId, StageId), u64>,

    /// Backpressure in-flight per edge (upstream, downstream) (FLOWIP-086k).
    pub backpressure_in_flight: HashMap<(StageId, StageId), u64>,

    /// Backpressure credits per edge (upstream, downstream) (FLOWIP-086k).
    pub backpressure_credits: HashMap<(StageId, StageId), u64>,

    /// Backpressure blocked state by stage (0/1; blocked on any downstream edge) (FLOWIP-086k).
    pub backpressure_blocked: HashMap<StageId, f64>,

    /// Whether the global backpressure bypass is enabled (debug-only) (FLOWIP-086k).
    pub backpressure_bypass_enabled: bool,

    /// Minimum downstream reader sequence observed by stage (FLOWIP-086k).
    pub backpressure_min_reader_seq: HashMap<StageId, u64>,

    /// Writer sequence observed by stage (FLOWIP-086k).
    pub backpressure_writer_seq: HashMap<StageId, u64>,

    /// Total time spent blocked waiting for downstream credits by stage (seconds; monotonic) (FLOWIP-086k).
    pub backpressure_wait_seconds_total: HashMap<StageId, f64>,

    /// Edge liveness state per edge (upstream, downstream) (FLOWIP-063e).
    ///
    /// The latest semantic state from `SystemPayload::EdgeLiveness`.
    /// Reporting encodings belong to the consuming projection.
    pub edge_liveness_state: HashMap<(StageId, StageId), EdgeLivenessState>,

    /// Contract verification metrics per edge (upstream/downstream)
    pub contract_metrics: ContractMetricsSnapshot,

    /// Generic hosted-surface HTTP metrics derived from system events (FLOWIP-093a).
    ///
    /// Low-cardinality labels: (surface_name, method, path, status_class).
    pub http_surface_metrics: Vec<HttpSurfaceRouteMetricsSnapshot>,

    /// Hosted-ingress refusal totals projected from `IngressRefusal` facts
    /// (FLOWIP-115d), keyed by `(ingress_key, reason)`. This replaces the former
    /// in-memory ingestion reject counters, so the metric folds journal facts and
    /// is replay-faithful.
    pub ingestion_refusal_totals: HashMap<(IngressKey, String), u64>,

    /// HTTP pull telemetry metrics derived from wide events (FLOWIP-084e).
    ///
    /// Keyed by stage ID (labels attach via `stage_metadata`).
    pub http_pull_metrics: HashMap<StageId, HttpPullMetricsSnapshot>,

    /// AI chunking metrics derived from `ai_chunking.snapshot` wide events (FLOWIP-086z).
    ///
    /// Keyed by stage ID.
    pub ai_chunking_metrics: HashMap<StageId, AiChunkingMetricsSnapshot>,

    /// Flow-level metrics (if journey events are implemented)
    pub flow_metrics: Option<FlowMetricsSnapshot>,

    /// Stage metadata for display and categorization
    pub stage_metadata: HashMap<StageId, StageMetadata>,

    /// First event time for each stage (for rate calculation)
    pub stage_first_event_time: HashMap<StageId, chrono::DateTime<chrono::Utc>>,

    /// Last event time for each stage (for rate calculation)
    pub stage_last_event_time: HashMap<StageId, chrono::DateTime<chrono::Utc>>,

    /// Stage lifecycle states (FLOWIP-059b - essential events only)
    /// Maps (StageId, state_name) to the retained current state.
    pub stage_lifecycle_states: HashMap<(StageId, String), bool>,

    /// Pipeline state (FLOWIP-059b)
    pub pipeline_state: String,

    /// Per-stage vector clock watermark (FLOWIP-059c).
    /// This mirrors MetricsStore.stage_vector_clocks and is used by exporters
    /// to expose obzenflow_stage_vector_clock metrics.
    /// Each value identifies a selected own-writer carrier in the data journal.
    /// It does not certify complete historical coverage.
    pub stage_vector_clocks: HashMap<StageId, u64>,

    /// Exact logical throughput at connected named composite ports
    /// (FLOWIP-128a B3). Fan-out is counted once per authored output fact.
    pub composite_port_traffic: Vec<CompositePortTraffic>,

    /// Member error volume per composite. This is component health, not an
    /// inferred failed-activation count.
    pub composite_member_health: Vec<CompositeMemberHealth>,

    /// Exact paired boundary duration histograms, reconstructed from durable
    /// output facts and their propagated activation contexts.
    pub composite_boundary_durations: Vec<CompositeDurationHistogram>,

    /// Rejected duration evidence, such as an exit timestamp before its exact
    /// entry timestamp.
    pub composite_boundary_duration_invalid: Vec<CompositeDurationInvalid>,

    /// Composite boundary contract views (FLOWIP-128a B5). A pure re-key of the
    /// `contract_metrics` above to the composite boundary; the exporter renders
    /// these as `obzenflow_composite_contract_*{composite,peer,direction}`
    /// families.
    pub composite_contracts: Vec<CompositeContract>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SinkOperationFailureMetric {
    pub stage_id: StageId,
    pub phase: SinkOperationPhase,
    pub error_kind: ErrorKind,
    pub count: u64,
}

/// Contract verification metrics per edge.
///
/// These are derived from contract verification events emitted by readers
/// (e.g. via UpstreamSubscription) and are exported to Prometheus.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct ContractMetricEdgeKey {
    pub upstream: StageId,
    pub downstream: StageId,
    pub contract: ContractName,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub selected_event_type: Option<EventType>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub feed_role: Option<SystemFeedRole>,
}

#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct ContractMetricResultKey {
    pub edge: ContractMetricEdgeKey,
    pub status: ContractResultStatusLabel,
}

#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct ContractViolationCauseLabel(String);

impl ContractViolationCauseLabel {
    pub fn new(value: impl Into<String>) -> Self {
        Self(value.into())
    }

    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl std::fmt::Display for ContractViolationCauseLabel {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

impl From<&str> for ContractViolationCauseLabel {
    fn from(value: &str) -> Self {
        Self::new(value)
    }
}

impl From<String> for ContractViolationCauseLabel {
    fn from(value: String) -> Self {
        Self::new(value)
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct ContractMetricViolationKey {
    pub edge: ContractMetricEdgeKey,
    pub cause: ContractViolationCauseLabel,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ContractMetricsSnapshot {
    /// Contract results by contract edge and status.
    pub results_total: HashMap<ContractMetricResultKey, u64>,

    /// Contract violations by contract edge and stable cause label.
    pub violations_total: HashMap<ContractMetricViolationKey, u64>,

    /// Latest reader sequence per contract edge.
    pub reader_seq: HashMap<ContractMetricEdgeKey, u64>,

    /// Latest advertised writer sequence per contract edge.
    pub advertised_writer_seq: HashMap<ContractMetricEdgeKey, u64>,
}

/// Snapshot of infrastructure-level metrics from direct observation
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct InfraMetricsSnapshot {
    /// Timestamp when this snapshot was created
    pub timestamp: chrono::DateTime<chrono::Utc>,

    /// Journal write metrics
    pub journal_metrics: JournalMetricsSnapshot,

    /// Stage-level infrastructure metrics
    pub stage_metrics: HashMap<StageId, StageInfraMetrics>,

    /// Continuous liveness metrics derived from the in-memory heartbeat snapshots store (FLOWIP-063e).
    pub liveness_metrics: LivenessMetricsSnapshot,
}

/// Snapshot of continuous heartbeat-derived liveness metrics (FLOWIP-063e).
///
/// These values are wall-clock based and are not derived from journal events.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct LivenessMetricsSnapshot {
    /// Stage handler blocked time (seconds). 0 when not processing.
    pub stage_handler_blocked_seconds: HashMap<StageId, f64>,

    /// Latest observed activity, independent of its reporting representation.
    pub stage_activity: HashMap<StageId, StageActivity>,

    /// Edge idle time (seconds) per edge (upstream, downstream).
    pub edge_idle_seconds: HashMap<(StageId, StageId), f64>,
}

/// Current AI chunk planning measurements per stage. Historical fact totals
/// are absent when no cumulative measurement supplies them.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct AiChunkingMetricsSnapshot {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub jobs_total: Option<u64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub input_items_total: Option<u64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub planned_items_total: Option<u64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub excluded_items_total: Option<u64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub chunks_emitted_total: Option<u64>,
    pub rerender_attempts_total: Option<u64>,
    pub max_depth_reached: Option<u32>,
    pub budget_overhead_tokens: Option<u64>,
}

/// Histogram data for a single metric
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HistogramSnapshot {
    /// Number of observations
    pub count: u64,

    /// Sum of all observations
    pub sum: f64,

    /// Minimum value observed
    pub min: f64,

    /// Maximum value observed
    pub max: f64,

    /// Percentiles (0.5, 0.9, 0.95, 0.99)
    pub percentiles: HashMap<Percentile, f64>,
}

/// Flow-level metrics
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FlowMetricsSnapshot {
    /// Total duration of the flow (wall clock time)
    pub flow_duration: MetricsDuration,

    /// Total number of events processed across all stages
    pub total_events_processed: u64,

    /// Events entering from sources only
    pub events_in: u64,

    /// Events exiting through sinks only
    pub events_out: u64,

    /// Total errors across all stages
    pub errors_total: u64,

    /// Total event loops across all stages
    pub event_loops_total: Option<u64>,

    /// Event loops with work across all stages
    pub event_loops_with_work_total: Option<u64>,
}

/// Stage metrics projection for lifecycle views.
///
/// Combines protected execution accounting with retained optional observations
/// for topology cards and lifecycle views. Terminal authors capture accounting
/// directly from the stage owner; this projection does not author durable facts.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StageMetricsSnapshot {
    pub processing_time_count: Option<u64>,
    pub timing_window: Option<MeasurementWindow>,
    /// Total events processed by this stage
    pub events_processed_total: u64,

    /// Total events accumulated into internal state by this stage (stateful/join stages).
    #[serde(default)]
    pub events_accumulated_total: u64,

    /// Total events emitted by this stage (data/delivery; excludes observability-only events).
    #[serde(default)]
    pub events_emitted_total: u64,

    /// Total errors observed at this stage
    pub errors_total: u64,

    /// Error breakdown by kind (authoritative, journal-backed)
    pub errors_by_kind:
        std::collections::HashMap<crate::event::status::processing_status::ErrorKind, u64>,

    /// Number of in-flight events at snapshot time
    pub in_flight: Option<u32>,

    /// Recent latency percentiles in milliseconds
    pub recent_p50_ms: Option<u64>,
    pub recent_p90_ms: Option<u64>,
    pub recent_p95_ms: Option<u64>,
    pub recent_p99_ms: Option<u64>,
    pub recent_p999_ms: Option<u64>,

    /// Actual sum of processing times (nanoseconds) - never reconstructed from percentiles
    /// FLOWIP-059a-3: This field tracks the real sum for accurate histogram _sum export.
    #[serde(default)]
    pub processing_time_sum_nanos: Option<u64>,

    /// Event loop utilization counters for this stage
    pub event_loops_total: Option<u64>,
    pub event_loops_with_work_total: Option<u64>,
}

/// Flow-level lifecycle metrics snapshot for UI events
///
/// This complements `FlowMetricsSnapshot` by providing a minimal view that
/// is cheap to serialize on every lifecycle event and sufficient to drive
/// the Flow Summary panel in the UI.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FlowLifecycleMetricsSnapshot {
    /// Events entering the flow from all sources
    pub events_in_total: u64,

    /// Events exiting the flow through all sinks
    pub events_out_total: u64,

    /// Total errors across all stages in the flow
    pub errors_total: u64,
}

/// Journal performance metrics
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct JournalMetricsSnapshot {
    /// Total write operations
    pub writes_total: u64,

    /// Write latency histogram (in microseconds)
    pub write_latency: HistogramSnapshot,

    /// Current throughput (events per second)
    pub throughput: f64,

    /// Total bytes written
    pub bytes_written: u64,
}

/// Stage-specific infrastructure metrics
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StageInfraMetrics {
    /// Events currently being processed
    pub in_flight: u64,
}

/// Stage metadata for display and categorization
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StageMetadata {
    /// Human-readable stage name (e.g., "event_source", "processor", "event_sink")
    pub name: String,

    /// Stage type for categorization
    pub stage_type: StageType,

    /// Optional stage mode hint for filtering/diagnostics (e.g., join reference mode).
    ///
    /// This is intentionally a free-form string so exporters can attach it as a label
    /// without introducing stage-type-specific dependencies into `obzenflow_core`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reference_mode: Option<String>,

    /// Flow name this stage belongs to
    pub flow_name: String,

    /// Optional flow execution ID for joinability across surfaces (FLOWIP-059a)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub flow_id: Option<FlowId>,
}

impl Default for AppMetricsSnapshot {
    fn default() -> Self {
        Self {
            throughput: Default::default(),
            observation_export_interval: None,
            timestamp: chrono::Utc::now(),
            event_counts: HashMap::new(),
            events_accumulated_total: HashMap::new(),
            events_emitted_total: HashMap::new(),
            join_reference_since_last_stream: HashMap::new(),
            error_counts: HashMap::new(),
            error_counts_by_kind: HashMap::new(),
            sink_operation_failures: Vec::new(),
            processing_times: HashMap::new(),
            in_flight: HashMap::new(),
            cpu_usage_ratio: HashMap::new(),
            memory_bytes: HashMap::new(),
            anomalies_total: HashMap::new(),
            amendments_total: HashMap::new(),
            saturation_ratio: HashMap::new(),
            failures_total: HashMap::new(),
            event_loops_total: HashMap::new(),
            event_loops_with_work_total: HashMap::new(),
            flow_latency_seconds: HashMap::new(),
            dropped_events: HashMap::new(),
            circuit_breaker_state: HashMap::new(),
            circuit_breaker_rejection_rate: HashMap::new(),
            circuit_breaker_consecutive_failures: HashMap::new(),
            circuit_breaker_requests_total: HashMap::new(),
            circuit_breaker_rejections_total: HashMap::new(),
            circuit_breaker_opened_total: HashMap::new(),
            circuit_breaker_successes_total: HashMap::new(),
            circuit_breaker_failures_total: HashMap::new(),
            circuit_breaker_slow_total: HashMap::new(),
            circuit_breaker_time_in_state_seconds_total: HashMap::new(),
            circuit_breaker_state_transitions_total: HashMap::new(),
            rate_limiter_utilization: HashMap::new(),
            rate_limiter_events_total: HashMap::new(),
            rate_limiter_delayed_total: HashMap::new(),
            rate_limiter_tokens_consumed_total: HashMap::new(),
            rate_limiter_delay_seconds_total: HashMap::new(),
            rate_limiter_bucket_tokens: HashMap::new(),
            rate_limiter_bucket_capacity: HashMap::new(),
            backpressure_window: HashMap::new(),
            backpressure_in_flight: HashMap::new(),
            backpressure_credits: HashMap::new(),
            backpressure_blocked: HashMap::new(),
            backpressure_bypass_enabled: false,
            backpressure_min_reader_seq: HashMap::new(),
            backpressure_writer_seq: HashMap::new(),
            backpressure_wait_seconds_total: HashMap::new(),
            edge_liveness_state: HashMap::new(),
            contract_metrics: ContractMetricsSnapshot::default(),
            http_surface_metrics: Vec::new(),
            ingestion_refusal_totals: HashMap::new(),
            http_pull_metrics: HashMap::new(),
            ai_chunking_metrics: HashMap::new(),
            flow_metrics: None,
            stage_metadata: HashMap::new(),
            stage_first_event_time: HashMap::new(),
            stage_last_event_time: HashMap::new(),
            stage_lifecycle_states: HashMap::new(),
            pipeline_state: String::new(),
            stage_vector_clocks: HashMap::new(),
            composite_port_traffic: Vec::new(),
            composite_member_health: Vec::new(),
            composite_boundary_durations: Vec::new(),
            composite_boundary_duration_invalid: Vec::new(),
            composite_contracts: Vec::new(),
        }
    }
}

impl Default for InfraMetricsSnapshot {
    fn default() -> Self {
        Self {
            timestamp: chrono::Utc::now(),
            journal_metrics: JournalMetricsSnapshot::default(),
            stage_metrics: HashMap::new(),
            liveness_metrics: LivenessMetricsSnapshot::default(),
        }
    }
}

impl Default for HistogramSnapshot {
    fn default() -> Self {
        Self {
            count: 0,
            sum: 0.0,
            min: f64::INFINITY,
            max: f64::NEG_INFINITY,
            percentiles: HashMap::new(),
        }
    }
}

impl Default for JournalMetricsSnapshot {
    fn default() -> Self {
        Self {
            writes_total: 0,
            write_latency: HistogramSnapshot::default(),
            throughput: 0.0,
            bytes_written: 0,
        }
    }
}