duroxide 0.1.27

Durable code execution framework for Rust
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
//! Observability infrastructure for metrics and structured logging.
//!
//! This module provides metrics via the `metrics` facade crate and structured logging
//! via `tracing`/`tracing-subscriber`. Users choose their own metrics backend by
//! installing a global recorder before starting the runtime.
//!
//! # Metrics Backend Options
//!
//! ```rust,ignore
//! // Option 1: Prometheus (direct scraping)
//! metrics_exporter_prometheus::PrometheusBuilder::new()
//!     .with_http_listener(([0, 0, 0, 0], 9090))
//!     .install()?;
//!
//! // Option 2: OpenTelemetry (via metrics-exporter-opentelemetry)
//! // metrics_exporter_opentelemetry::Recorder::builder("my-service").install_global()?;
//!
//! // Option 3: None - metrics become zero-cost no-ops
//! ```

// Observability uses Mutex locks - poison indicates a panic and should propagate
#![allow(clippy::expect_used)]
#![allow(clippy::unwrap_used)]

use metrics::{counter, gauge, histogram};
use std::sync::{
    Arc,
    atomic::{AtomicI64, AtomicU64, Ordering},
};
use std::time::Duration;
use tracing_subscriber::{EnvFilter, layer::SubscriberExt, util::SubscriberInitExt};

/// Log format options for structured logging
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub enum LogFormat {
    /// Structured JSON output for log aggregators
    Json,
    /// Human-readable format for development (with all fields)
    Pretty,
    /// Compact format: timestamp level module \[instance_id\] message
    #[default]
    Compact,
}

/// Observability configuration for metrics and logging.
///
/// Controls structured logging format and level. Metrics are always available
/// via the `metrics` facade - users install their preferred exporter.
///
/// # Example
///
/// ```rust,no_run
/// # use duroxide::runtime::{ObservabilityConfig, LogFormat};
/// // Simplest: Compact logs to stdout
/// let config = ObservabilityConfig {
///     log_format: LogFormat::Compact,
///     log_level: "info".to_string(),
///     ..Default::default()
/// };
///
/// // Production: JSON logs (metrics via user-installed exporter)
/// let config = ObservabilityConfig {
///     log_format: LogFormat::Json,
///     service_name: "my-app".to_string(),
///     ..Default::default()
/// };
/// ```
///
/// # Correlation Fields
///
/// All logs automatically include:
/// - `instance_id` - Orchestration instance identifier
/// - `execution_id` - Execution number (for ContinueAsNew)
/// - `orchestration_name` - Name of the orchestration
/// - `orchestration_version` - Semantic version
/// - `activity_name` - Activity name (in activity context)
/// - `worker_id` - Dispatcher worker ID
///
/// # See Also
///
/// - [Observability Guide](../../docs/observability-guide.md) - Full documentation
#[derive(Debug, Clone)]
pub struct ObservabilityConfig {
    // Structured logging configuration
    /// Log output format
    pub log_format: LogFormat,
    /// Log level filter (e.g., "info", "debug")
    pub log_level: String,

    // Common configuration
    /// Service name for identification in logs/metrics
    pub service_name: String,
    /// Optional service version
    pub service_version: Option<String>,

    // Gauge polling configuration
    /// Interval for polling the provider to refresh gauge metrics
    /// (queue depths, active orchestrations). Defaults to 60 seconds.
    pub gauge_poll_interval: Duration,
}

impl Default for ObservabilityConfig {
    fn default() -> Self {
        Self {
            log_format: LogFormat::Pretty,
            log_level: "info".to_string(),
            service_name: "duroxide".to_string(),
            service_version: None,
            gauge_poll_interval: Duration::from_secs(60),
        }
    }
}

fn default_filter_expression(level: &str) -> String {
    format!("warn,duroxide::orchestration={level},duroxide::activity={level}")
}

/// Snapshot of key observability metrics counters for tests and diagnostics.
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct MetricsSnapshot {
    pub orch_starts: u64,
    pub orch_completions: u64,
    pub orch_failures: u64,
    pub orch_application_errors: u64,
    pub orch_infrastructure_errors: u64,
    pub orch_configuration_errors: u64,
    pub orch_poison: u64,
    pub activity_success: u64,
    pub activity_app_errors: u64,
    pub activity_infra_errors: u64,
    pub activity_config_errors: u64,
    pub activity_poison: u64,
    pub orch_dispatcher_items_fetched: u64,
    pub worker_dispatcher_items_fetched: u64,
    pub orch_continue_as_new: u64,
    pub suborchestration_calls: u64,
    pub provider_errors: u64,
}

/// Metrics provider using the `metrics` facade crate.
///
/// Emits metrics via `counter!`, `gauge!`, `histogram!` macros.
/// If no global recorder is installed, these are zero-cost no-ops.
/// Atomic counters are maintained for test snapshot assertions.
pub struct MetricsProvider {
    // Atomic counters for test snapshot assertions (mirrors facade metrics)
    orch_starts_atomic: AtomicU64,
    orch_completions_atomic: AtomicU64,
    orch_failures_atomic: AtomicU64,
    orch_application_errors_atomic: AtomicU64,
    orch_infrastructure_errors_atomic: AtomicU64,
    orch_configuration_errors_atomic: AtomicU64,
    orch_poison_atomic: AtomicU64,
    activity_success_atomic: AtomicU64,
    activity_app_errors_atomic: AtomicU64,
    activity_infra_errors_atomic: AtomicU64,
    activity_config_errors_atomic: AtomicU64,
    activity_poison_atomic: AtomicU64,

    // Dispatcher counters
    orch_dispatcher_items_fetched_atomic: AtomicU64,
    worker_dispatcher_items_fetched_atomic: AtomicU64,

    // Other counters
    orch_continue_as_new_atomic: AtomicU64,
    suborchestration_calls_atomic: AtomicU64,
    provider_errors_atomic: AtomicU64,

    // Queue depth tracking (updated by background task or direct calls)
    orch_queue_depth_atomic: Arc<AtomicU64>,
    worker_queue_depth_atomic: Arc<AtomicU64>,

    // Active orchestrations tracking (for gauge metrics)
    active_orchestrations_atomic: Arc<AtomicI64>,
}

impl MetricsProvider {
    /// Create a new metrics provider.
    ///
    /// # Errors
    ///
    /// Currently infallible, but returns Result for API compatibility.
    pub fn new(_config: &ObservabilityConfig) -> Result<Self, String> {
        Ok(Self {
            orch_starts_atomic: AtomicU64::new(0),
            orch_completions_atomic: AtomicU64::new(0),
            orch_failures_atomic: AtomicU64::new(0),
            orch_application_errors_atomic: AtomicU64::new(0),
            orch_infrastructure_errors_atomic: AtomicU64::new(0),
            orch_configuration_errors_atomic: AtomicU64::new(0),
            orch_poison_atomic: AtomicU64::new(0),
            activity_success_atomic: AtomicU64::new(0),
            activity_app_errors_atomic: AtomicU64::new(0),
            activity_infra_errors_atomic: AtomicU64::new(0),
            activity_config_errors_atomic: AtomicU64::new(0),
            activity_poison_atomic: AtomicU64::new(0),
            orch_dispatcher_items_fetched_atomic: AtomicU64::new(0),
            worker_dispatcher_items_fetched_atomic: AtomicU64::new(0),
            orch_continue_as_new_atomic: AtomicU64::new(0),
            suborchestration_calls_atomic: AtomicU64::new(0),
            provider_errors_atomic: AtomicU64::new(0),
            orch_queue_depth_atomic: Arc::new(AtomicU64::new(0)),
            worker_queue_depth_atomic: Arc::new(AtomicU64::new(0)),
            active_orchestrations_atomic: Arc::new(AtomicI64::new(0)),
        })
    }

    /// Shutdown the metrics provider gracefully.
    ///
    /// With the facade approach, there's nothing to shutdown - the global recorder
    /// (if any) is managed by the application.
    ///
    /// # Errors
    ///
    /// Currently infallible, but returns Result for API compatibility.
    pub async fn shutdown(self) -> Result<(), String> {
        Ok(())
    }

    // ========================================================================
    // Orchestration lifecycle methods
    // ========================================================================

    #[inline]
    pub fn record_orchestration_start(&self, orchestration_name: &str, version: &str, initiated_by: &str) {
        counter!(
            "duroxide_orchestration_starts_total",
            "orchestration_name" => orchestration_name.to_string(),
            "version" => version.to_string(),
            "initiated_by" => initiated_by.to_string(),
        )
        .increment(1);

        self.orch_starts_atomic.fetch_add(1, Ordering::Relaxed);
    }

    #[inline]
    pub fn record_orchestration_completion(
        &self,
        orchestration_name: &str,
        version: &str,
        status: &str,
        duration_seconds: f64,
        turn_count: u64,
        history_events: u64,
    ) {
        let turn_bucket = match turn_count {
            1..=5 => "1-5",
            6..=10 => "6-10",
            11..=50 => "11-50",
            _ => "50+",
        };

        counter!(
            "duroxide_orchestration_completions_total",
            "orchestration_name" => orchestration_name.to_string(),
            "version" => version.to_string(),
            "status" => status.to_string(),
            "final_turn_count" => turn_bucket.to_string(),
        )
        .increment(1);

        histogram!(
            "duroxide_orchestration_duration_seconds",
            "orchestration_name" => orchestration_name.to_string(),
            "version" => version.to_string(),
            "status" => status.to_string(),
        )
        .record(duration_seconds);

        histogram!(
            "duroxide_orchestration_turns",
            "orchestration_name" => orchestration_name.to_string(),
        )
        .record(turn_count as f64);

        histogram!(
            "duroxide_orchestration_history_size",
            "orchestration_name" => orchestration_name.to_string(),
        )
        .record(history_events as f64);

        self.orch_completions_atomic.fetch_add(1, Ordering::Relaxed);
    }

    #[inline]
    pub fn record_orchestration_failure(
        &self,
        orchestration_name: &str,
        version: &str,
        error_type: &str,
        error_category: &str,
    ) {
        counter!(
            "duroxide_orchestration_failures_total",
            "orchestration_name" => orchestration_name.to_string(),
            "version" => version.to_string(),
            "error_type" => error_type.to_string(),
            "error_category" => error_category.to_string(),
        )
        .increment(1);

        self.orch_failures_atomic.fetch_add(1, Ordering::Relaxed);

        match error_type {
            "app_error" => {
                self.orch_application_errors_atomic.fetch_add(1, Ordering::Relaxed);
            }
            "infrastructure_error" => {
                self.orch_infrastructure_errors_atomic.fetch_add(1, Ordering::Relaxed);
                counter!(
                    "duroxide_orchestration_infrastructure_errors_total",
                    "orchestration_name" => orchestration_name.to_string(),
                    "error_category" => error_category.to_string(),
                )
                .increment(1);
            }
            "config_error" => {
                self.orch_configuration_errors_atomic.fetch_add(1, Ordering::Relaxed);
                counter!(
                    "duroxide_orchestration_configuration_errors_total",
                    "orchestration_name" => orchestration_name.to_string(),
                    "error_category" => error_category.to_string(),
                )
                .increment(1);
            }
            _ => {}
        }
    }

    #[inline]
    pub fn record_orchestration_application_error(&self) {
        counter!("duroxide_orchestration_failures_total", "error_type" => "app_error").increment(1);
        self.orch_failures_atomic.fetch_add(1, Ordering::Relaxed);
        self.orch_application_errors_atomic.fetch_add(1, Ordering::Relaxed);
    }

    #[inline]
    pub fn record_orchestration_infrastructure_error(&self) {
        counter!("duroxide_orchestration_failures_total", "error_type" => "infrastructure_error").increment(1);
        counter!("duroxide_orchestration_infrastructure_errors_total").increment(1);
        self.orch_failures_atomic.fetch_add(1, Ordering::Relaxed);
        self.orch_infrastructure_errors_atomic.fetch_add(1, Ordering::Relaxed);
    }

    #[inline]
    pub fn record_orchestration_configuration_error(&self) {
        counter!("duroxide_orchestration_failures_total", "error_type" => "config_error").increment(1);
        counter!("duroxide_orchestration_configuration_errors_total").increment(1);
        self.orch_failures_atomic.fetch_add(1, Ordering::Relaxed);
        self.orch_configuration_errors_atomic.fetch_add(1, Ordering::Relaxed);
    }

    #[inline]
    pub fn record_continue_as_new(&self, orchestration_name: &str, execution_id: u64) {
        counter!(
            "duroxide_orchestration_continue_as_new_total",
            "orchestration_name" => orchestration_name.to_string(),
            "execution_id" => execution_id.to_string(),
        )
        .increment(1);

        self.orch_continue_as_new_atomic.fetch_add(1, Ordering::Relaxed);
    }

    // ========================================================================
    // Activity execution methods
    // ========================================================================

    #[inline]
    pub fn record_activity_execution(
        &self,
        activity_name: &str,
        outcome: &str,
        duration_seconds: f64,
        retry_attempt: u32,
        tag: Option<&str>,
    ) {
        let retry_label = match retry_attempt {
            0 => "0",
            1 => "1",
            2 => "2",
            _ => "3+",
        };

        let tag_label = tag.unwrap_or("default");

        counter!(
            "duroxide_activity_executions_total",
            "activity_name" => activity_name.to_string(),
            "outcome" => outcome.to_string(),
            "retry_attempt" => retry_label.to_string(),
            "tag" => tag_label.to_string(),
        )
        .increment(1);

        histogram!(
            "duroxide_activity_duration_seconds",
            "activity_name" => activity_name.to_string(),
            "outcome" => outcome.to_string(),
            "tag" => tag_label.to_string(),
        )
        .record(duration_seconds);

        match outcome {
            "success" => {
                self.activity_success_atomic.fetch_add(1, Ordering::Relaxed);
            }
            "app_error" => {
                self.activity_app_errors_atomic.fetch_add(1, Ordering::Relaxed);
            }
            "infra_error" => {
                self.activity_infra_errors_atomic.fetch_add(1, Ordering::Relaxed);
                counter!(
                    "duroxide_activity_infrastructure_errors_total",
                    "activity_name" => activity_name.to_string(),
                )
                .increment(1);
            }
            "config_error" => {
                self.activity_config_errors_atomic.fetch_add(1, Ordering::Relaxed);
                counter!(
                    "duroxide_activity_configuration_errors_total",
                    "activity_name" => activity_name.to_string(),
                )
                .increment(1);
            }
            _ => {}
        }
    }

    #[inline]
    pub fn record_activity_success(&self) {
        counter!("duroxide_activity_executions_total", "outcome" => "success").increment(1);
        self.activity_success_atomic.fetch_add(1, Ordering::Relaxed);
    }

    #[inline]
    pub fn record_activity_app_error(&self) {
        counter!("duroxide_activity_executions_total", "outcome" => "app_error").increment(1);
        self.activity_app_errors_atomic.fetch_add(1, Ordering::Relaxed);
    }

    #[inline]
    pub fn record_activity_infra_error(&self) {
        counter!("duroxide_activity_executions_total", "outcome" => "infra_error").increment(1);
        counter!("duroxide_activity_infrastructure_errors_total").increment(1);
        self.activity_infra_errors_atomic.fetch_add(1, Ordering::Relaxed);
    }

    #[inline]
    pub fn record_activity_config_error(&self) {
        counter!("duroxide_activity_executions_total", "outcome" => "config_error").increment(1);
        counter!("duroxide_activity_configuration_errors_total").increment(1);
        self.activity_config_errors_atomic.fetch_add(1, Ordering::Relaxed);
    }

    #[inline]
    pub fn record_orchestration_poison(&self) {
        self.orch_poison_atomic.fetch_add(1, Ordering::Relaxed);
        counter!("duroxide_orchestration_poison_total").increment(1);
    }

    #[inline]
    pub fn record_activity_poison(&self) {
        self.activity_poison_atomic.fetch_add(1, Ordering::Relaxed);
        counter!("duroxide_activity_poison_total").increment(1);
    }

    // ========================================================================
    // Sub-orchestration methods
    // ========================================================================

    #[inline]
    pub fn record_suborchestration_call(&self, parent_orchestration: &str, child_orchestration: &str, outcome: &str) {
        counter!(
            "duroxide_suborchestration_calls_total",
            "parent_orchestration" => parent_orchestration.to_string(),
            "child_orchestration" => child_orchestration.to_string(),
            "outcome" => outcome.to_string(),
        )
        .increment(1);

        self.suborchestration_calls_atomic.fetch_add(1, Ordering::Relaxed);
    }

    #[inline]
    pub fn record_suborchestration_duration(
        &self,
        parent_orchestration: &str,
        child_orchestration: &str,
        duration_seconds: f64,
        outcome: &str,
    ) {
        histogram!(
            "duroxide_suborchestration_duration_seconds",
            "parent_orchestration" => parent_orchestration.to_string(),
            "child_orchestration" => child_orchestration.to_string(),
            "outcome" => outcome.to_string(),
        )
        .record(duration_seconds);
    }

    // ========================================================================
    // Provider operation methods
    // ========================================================================

    #[inline]
    pub fn record_provider_operation(&self, operation: &str, duration_seconds: f64, status: &str) {
        histogram!(
            "duroxide_provider_operation_duration_seconds",
            "operation" => operation.to_string(),
            "status" => status.to_string(),
        )
        .record(duration_seconds);
    }

    #[inline]
    pub fn record_provider_error(&self, operation: &str, error_type: &str) {
        counter!(
            "duroxide_provider_errors_total",
            "operation" => operation.to_string(),
            "error_type" => error_type.to_string(),
        )
        .increment(1);

        self.provider_errors_atomic.fetch_add(1, Ordering::Relaxed);
    }

    // ========================================================================
    // Dispatcher metrics
    // ========================================================================

    #[inline]
    pub fn record_orch_dispatcher_items_fetched(&self, count: u64) {
        counter!("duroxide_orchestration_dispatcher_items_fetched").increment(count);
        self.orch_dispatcher_items_fetched_atomic
            .fetch_add(count, Ordering::Relaxed);
    }

    #[inline]
    pub fn record_orch_dispatcher_processing_duration(&self, duration_ms: u64) {
        histogram!("duroxide_orchestration_dispatcher_processing_duration_ms").record(duration_ms as f64);
    }

    #[inline]
    pub fn record_worker_dispatcher_items_fetched(&self, count: u64) {
        counter!("duroxide_worker_dispatcher_items_fetched").increment(count);
        self.worker_dispatcher_items_fetched_atomic
            .fetch_add(count, Ordering::Relaxed);
    }

    #[inline]
    pub fn record_worker_dispatcher_execution_duration(&self, duration_ms: u64) {
        histogram!("duroxide_worker_dispatcher_execution_duration_ms").record(duration_ms as f64);
    }

    // ========================================================================
    // Queue depth management (stateful gauges)
    // ========================================================================

    #[inline]
    pub fn update_queue_depths(&self, orch_depth: u64, worker_depth: u64) {
        self.orch_queue_depth_atomic.store(orch_depth, Ordering::Relaxed);
        self.worker_queue_depth_atomic.store(worker_depth, Ordering::Relaxed);

        // Update gauges
        gauge!("duroxide_orchestrator_queue_depth").set(orch_depth as f64);
        gauge!("duroxide_worker_queue_depth").set(worker_depth as f64);
    }

    #[inline]
    pub fn get_queue_depths(&self) -> (u64, u64) {
        (
            self.orch_queue_depth_atomic.load(Ordering::Relaxed),
            self.worker_queue_depth_atomic.load(Ordering::Relaxed),
        )
    }

    // ========================================================================
    // Active orchestrations tracking (stateful gauge)
    // ========================================================================

    #[inline]
    pub fn increment_active_orchestrations(&self) {
        let count = self.active_orchestrations_atomic.fetch_add(1, Ordering::Relaxed) + 1;
        gauge!("duroxide_active_orchestrations").set(count as f64);
    }

    #[inline]
    pub fn decrement_active_orchestrations(&self) {
        let count = self.active_orchestrations_atomic.fetch_sub(1, Ordering::Relaxed) - 1;
        gauge!("duroxide_active_orchestrations").set(count as f64);
    }

    #[inline]
    pub fn set_active_orchestrations(&self, count: i64) {
        self.active_orchestrations_atomic.store(count, Ordering::Relaxed);
        gauge!("duroxide_active_orchestrations").set(count as f64);
    }

    #[inline]
    pub fn get_active_orchestrations(&self) -> i64 {
        self.active_orchestrations_atomic.load(Ordering::Relaxed)
    }

    // ========================================================================
    // Snapshot for testing
    // ========================================================================

    pub fn snapshot(&self) -> MetricsSnapshot {
        MetricsSnapshot {
            orch_starts: self.orch_starts_atomic.load(Ordering::Relaxed),
            orch_completions: self.orch_completions_atomic.load(Ordering::Relaxed),
            orch_failures: self.orch_failures_atomic.load(Ordering::Relaxed),
            orch_application_errors: self.orch_application_errors_atomic.load(Ordering::Relaxed),
            orch_infrastructure_errors: self.orch_infrastructure_errors_atomic.load(Ordering::Relaxed),
            orch_configuration_errors: self.orch_configuration_errors_atomic.load(Ordering::Relaxed),
            orch_poison: self.orch_poison_atomic.load(Ordering::Relaxed),
            activity_success: self.activity_success_atomic.load(Ordering::Relaxed),
            activity_app_errors: self.activity_app_errors_atomic.load(Ordering::Relaxed),
            activity_infra_errors: self.activity_infra_errors_atomic.load(Ordering::Relaxed),
            activity_config_errors: self.activity_config_errors_atomic.load(Ordering::Relaxed),
            activity_poison: self.activity_poison_atomic.load(Ordering::Relaxed),
            orch_dispatcher_items_fetched: self.orch_dispatcher_items_fetched_atomic.load(Ordering::Relaxed),
            worker_dispatcher_items_fetched: self.worker_dispatcher_items_fetched_atomic.load(Ordering::Relaxed),
            orch_continue_as_new: self.orch_continue_as_new_atomic.load(Ordering::Relaxed),
            suborchestration_calls: self.suborchestration_calls_atomic.load(Ordering::Relaxed),
            provider_errors: self.provider_errors_atomic.load(Ordering::Relaxed),
        }
    }
}

/// Initialize logging subsystem
///
/// # Errors
///
/// Returns an error if logging initialization fails.
pub fn init_logging(config: &ObservabilityConfig) -> Result<(), String> {
    let env_filter = EnvFilter::try_from_default_env()
        .unwrap_or_else(|_| EnvFilter::new(default_filter_expression(&config.log_level)));

    match config.log_format {
        LogFormat::Json => {
            tracing_subscriber::registry()
                .with(env_filter)
                .with(tracing_subscriber::fmt::layer().json())
                .try_init()
                .map_err(|e| format!("Failed to initialize JSON logging: {e}"))?;
        }
        LogFormat::Pretty => {
            tracing_subscriber::registry()
                .with(env_filter)
                .with(tracing_subscriber::fmt::layer())
                .try_init()
                .map_err(|e| format!("Failed to initialize pretty logging: {e}"))?;
        }
        LogFormat::Compact => {
            tracing_subscriber::registry()
                .with(env_filter)
                .with(tracing_subscriber::fmt::layer().compact())
                .try_init()
                .map_err(|e| format!("Failed to initialize compact logging: {e}"))?;
        }
    }

    Ok(())
}

/// Observability handle that manages metrics and logging lifecycle
pub struct ObservabilityHandle {
    metrics_provider: Arc<MetricsProvider>,
}

impl ObservabilityHandle {
    /// Initialize observability with the given configuration
    ///
    /// Metrics are always available via the `metrics` facade. If no global recorder
    /// is installed by the application, metric calls are zero-cost no-ops.
    ///
    /// # Errors
    ///
    /// Returns an error if metrics initialization fails.
    pub fn init(config: &ObservabilityConfig) -> Result<Self, String> {
        // Initialize logging first, but tolerate failures (e.g., global subscriber already set)
        if let Err(_err) = init_logging(config) {
            // Silently ignore — this happens when multiple runtimes share a process
        }

        // Always create metrics provider (facade is zero-cost if no recorder installed)
        let metrics_provider = Arc::new(MetricsProvider::new(config)?);

        Ok(Self { metrics_provider })
    }

    /// Get the metrics provider
    #[inline]
    pub fn metrics_provider(&self) -> &Arc<MetricsProvider> {
        &self.metrics_provider
    }

    /// Shutdown observability gracefully
    ///
    /// # Errors
    ///
    /// Returns an error if shutdown fails.
    pub async fn shutdown(self) -> Result<(), String> {
        // Take ownership out of Arc if we're the last reference
        if let Ok(provider) = Arc::try_unwrap(self.metrics_provider) {
            provider.shutdown().await?;
        }
        Ok(())
    }

    /// Get a snapshot of metrics for testing
    pub fn metrics_snapshot(&self) -> MetricsSnapshot {
        self.metrics_provider.snapshot()
    }
}