asupersync 0.3.0

Spec-first, cancel-correct, capability-secure async runtime 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
//! Comprehensive observability and logging infrastructure.
//!
//! This module provides structured observability primitives for the Asupersync
//! runtime and RaptorQ distributed layer. Unlike the low-level `trace` module
//! (which is optimized for deterministic replay), this module provides:
//!
//! - **Structured logging** with severity levels and rich context
//! - **Metrics** for runtime statistics (counters, gauges, histograms)
//! - **Diagnostic context** for hierarchical operation tracking
//! - **Event batching** for efficient reporting
//! - **Configuration** for runtime observability settings
//!
//! # Design Principles
//!
//! 1. **No stdout/stderr in core**: All output goes through structured types
//! 2. **Determinism-compatible**: Metrics use explicit time, not wall clock
//! 3. **Zero-allocation hot path**: Critical paths avoid heap allocation
//! 4. **Composable**: Works with both lab runtime and production
//!
//! # Example
//!
//! ```ignore
//! use asupersync::observability::{LogEntry, LogLevel, Metrics, ObservabilityConfig};
//!
//! let config = ObservabilityConfig::default()
//!     .with_log_level(LogLevel::Info)
//!     .with_sample_rate(0.1);
//!
//! let mut metrics = Metrics::new();
//! metrics.counter("symbols_encoded").increment(1);
//! metrics.gauge("pending_symbols").set(42);
//!
//! let entry = LogEntry::info("Symbol encoded successfully")
//!     .with_field("object_id", "Obj-12345678")
//!     .with_field("symbol_count", "10");
//! ```

pub mod analyzer_plugin;
pub mod cancellation_analyzer;
pub mod cancellation_debt_monitor;
pub mod cancellation_tracer;
pub mod cancellation_visualizer;
pub mod collector;
pub mod context;
pub mod debt_runtime_integration;
pub mod diagnostics;
pub mod entry;
#[cfg(feature = "metrics")]
pub mod histogram_conformance;
pub mod level;
pub mod metrics;
pub mod obligation_tracker;
#[cfg(feature = "metrics")]
pub mod otel;
pub mod otel_structured_concurrency;
pub mod performance_budget_monitor;
pub mod resource_accounting;
pub mod runtime_integration;
pub mod spectral_health;
pub mod structured_cancellation_analyzer;
pub mod task_inspector;

pub use analyzer_plugin::{
    ANALYZER_PLUGIN_CONTRACT_VERSION, AggregatedAnalyzerFinding, AnalyzerCapability,
    AnalyzerFinding, AnalyzerOutput, AnalyzerPlugin, AnalyzerPluginDescriptor,
    AnalyzerPluginPackReport, AnalyzerPluginRegistry, AnalyzerPluginRunError, AnalyzerRequest,
    AnalyzerSandboxPolicy, AnalyzerSchemaVersion, AnalyzerSeverity, PluginExecutionRecord,
    PluginExecutionState, PluginLifecycleEvent, PluginLifecyclePhase, PluginRegistrationError,
    SchemaDecision, SchemaNegotiation, negotiate_schema_version, run_analyzer_plugin_pack_smoke,
};
pub use cancellation_analyzer::{
    AnalyzerConfig as CancellationAnalyzerConfig, BottleneckAnalysis, CancellationAnalyzer,
    CleanupEfficiency, CleanupTimingAnalysis, DistributionStats, EntityPerformance,
    ImplementationComplexity, OptimizationRecommendation, PerformanceAnalysis,
    PerformanceRegression, RecommendationPriority, ThroughputMetrics, TrendAnalysis,
    TrendDirection,
};
pub use cancellation_debt_monitor::{
    CancellationDebtConfig, CancellationDebtMonitor, DebtAlert, DebtAlertLevel, DebtSnapshot,
    PendingWork, WorkType,
};
pub use cancellation_tracer::{
    CancellationAnalysis, CancellationTrace, CancellationTraceStep, CancellationTracer,
    CancellationTracerConfig, CancellationTracerStats, CancellationTracerStatsSnapshot, EntityType,
    PropagationAnomaly, TraceId, analyze_cancellation_patterns,
};
pub use cancellation_visualizer::{
    AnomalyInfo, AnomalySeverity, BottleneckInfo, CancellationDashboard, CancellationTreeNode,
    CancellationVisualizer, ThroughputStats, TimingFormat, VisualizerConfig,
};
pub use collector::LogCollector;
pub use context::{DiagnosticContext, Span, SpanId};
pub use debt_runtime_integration::{DebtHealthReport, DebtRuntimeIntegration};
pub use diagnostics::{
    BlockReason, CancelReasonInfo, CancellationExplanation, CancellationStep, DeadlockCycle,
    DeadlockSeverity, Diagnostics, DirectionalDeadlockReport, ObligationLeak, Reason,
    RegionOpenExplanation, TAIL_LATENCY_TAXONOMY_CONTRACT_VERSION, TailLatencyLogFieldSpec,
    TailLatencySignalSpec, TailLatencyTaxonomyContract, TailLatencyTermSpec,
    TaskBlockedExplanation, tail_latency_taxonomy_contract,
};
pub use entry::LogEntry;
pub use level::LogLevel;
pub use metrics::{
    Counter, Gauge, Histogram, MetricValue, Metrics, MetricsProvider, NoOpMetrics, OutcomeKind,
};
pub use obligation_tracker::{
    ObligationInfo, ObligationStateInfo, ObligationSummary, ObligationTracker,
    ObligationTrackerConfig, TypeSummary,
};
#[cfg(feature = "metrics")]
pub use otel::{
    CardinalityOverflow, ExportError, InMemoryExporter, MetricsConfig, MetricsExporter,
    MetricsSnapshot, MultiExporter, NullExporter, OtelMetrics, SamplingConfig, StdoutExporter,
};
pub use otel_structured_concurrency::{
    EntityId, OtelStructuredConcurrencyConfig, SpanStorage, SpanType,
};
pub use performance_budget_monitor::{
    BudgetAlert, BudgetDirection, BudgetEvaluation, BudgetSample, BudgetSeverity,
    PerformanceBudget, PerformanceBudgetMonitor, PerformanceBudgetSnapshot,
};
pub use resource_accounting::{
    AdmissionKindStats, ObligationKindStats, ResourceAccounting, ResourceAccountingSnapshot,
};
pub use structured_cancellation_analyzer::{
    AlertSeverity, AlertType, CancellationAlert, LabRuntimeIntegration, RealTimeStats,
    StructuredCancellationAnalyzer, StructuredCancellationConfig,
};
pub use task_inspector::{
    TASK_CONSOLE_WIRE_SCHEMA_V1, TaskConsoleWireSnapshot, TaskDetails, TaskDetailsWire,
    TaskInspector, TaskInspectorConfig, TaskRegionCountWire, TaskStateInfo, TaskSummary,
    TaskSummaryWire,
};

#[allow(clippy::cast_precision_loss)]
fn sample_unit_interval(key: u64) -> f64 {
    const TWO_POW_53_F64: f64 = 9_007_199_254_740_992.0;
    let bits = splitmix64(key) >> 11;
    bits as f64 / TWO_POW_53_F64
}

fn splitmix64(mut state: u64) -> u64 {
    state = state.wrapping_add(0x9e37_79b9_7f4a_7c15);
    let mut z = state;
    z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
    z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
    z ^ (z >> 31)
}

/// Configuration for observability and logging.
///
/// This struct controls logging levels, tracing behavior, and sampling rates
/// for the runtime. It integrates with both the high-level observability
/// infrastructure and the low-level trace module.
///
/// # Example
///
/// ```
/// use asupersync::observability::{LogLevel, ObservabilityConfig};
///
/// // Development config: verbose logging
/// let dev_config = ObservabilityConfig::default()
///     .with_log_level(LogLevel::Debug)
///     .with_trace_all_symbols(true);
///
/// // Production config: minimal overhead
/// let prod_config = ObservabilityConfig::default()
///     .with_log_level(LogLevel::Warn)
///     .with_sample_rate(0.01)
///     .with_trace_all_symbols(false);
/// ```
#[derive(Debug, Clone)]
pub struct ObservabilityConfig {
    /// Minimum log level to record.
    log_level: LogLevel,
    /// Whether to trace all symbols (expensive, useful for debugging).
    trace_all_symbols: bool,
    /// Sampling rate for traces (0.0 = none, 1.0 = all).
    sample_rate: f64,
    /// Maximum number of spans to retain in the diagnostic context.
    max_spans: usize,
    /// Maximum number of log entries to retain in the collector.
    max_log_entries: usize,
    /// Whether to include timestamps in log entries.
    include_timestamps: bool,
    /// Whether to enable metrics collection.
    metrics_enabled: bool,
}

impl ObservabilityConfig {
    /// Creates a new observability configuration with default values.
    #[must_use]
    pub fn new() -> Self {
        Self {
            log_level: LogLevel::Info,
            trace_all_symbols: false,
            sample_rate: 1.0,
            max_spans: 1000,
            max_log_entries: 10000,
            include_timestamps: true,
            metrics_enabled: true,
        }
    }

    /// Sets the minimum log level.
    #[must_use]
    pub fn with_log_level(mut self, level: LogLevel) -> Self {
        self.log_level = level;
        self
    }

    /// Sets whether to trace all symbols.
    #[must_use]
    pub fn with_trace_all_symbols(mut self, trace: bool) -> Self {
        self.trace_all_symbols = trace;
        self
    }

    /// Sets the sampling rate for traces.
    ///
    /// # Panics
    ///
    /// Panics if the rate is not in the range [0.0, 1.0].
    #[must_use]
    pub fn with_sample_rate(mut self, rate: f64) -> Self {
        assert!(
            (0.0..=1.0).contains(&rate),
            "sample_rate must be between 0.0 and 1.0"
        );
        self.sample_rate = rate;
        self
    }

    /// Sets the maximum number of spans to retain.
    #[must_use]
    pub fn with_max_spans(mut self, max: usize) -> Self {
        self.max_spans = max;
        self
    }

    /// Sets the maximum number of log entries to retain.
    #[must_use]
    pub fn with_max_log_entries(mut self, max: usize) -> Self {
        self.max_log_entries = max;
        self
    }

    /// Sets whether to include timestamps in log entries.
    #[must_use]
    pub fn with_include_timestamps(mut self, include: bool) -> Self {
        self.include_timestamps = include;
        self
    }

    /// Sets whether to enable metrics collection.
    #[must_use]
    pub fn with_metrics_enabled(mut self, enabled: bool) -> Self {
        self.metrics_enabled = enabled;
        self
    }

    /// Returns the minimum log level.
    #[must_use]
    pub const fn log_level(&self) -> LogLevel {
        self.log_level
    }

    /// Returns whether to trace all symbols.
    #[must_use]
    pub const fn trace_all_symbols(&self) -> bool {
        self.trace_all_symbols
    }

    /// Returns the sampling rate for traces.
    #[must_use]
    pub const fn sample_rate(&self) -> f64 {
        self.sample_rate
    }

    /// Returns the maximum number of spans to retain.
    #[must_use]
    pub const fn max_spans(&self) -> usize {
        self.max_spans
    }

    /// Returns the maximum number of log entries to retain.
    #[must_use]
    pub const fn max_log_entries(&self) -> usize {
        self.max_log_entries
    }

    /// Returns whether timestamps are included in log entries.
    #[must_use]
    pub const fn include_timestamps(&self) -> bool {
        self.include_timestamps
    }

    /// Returns whether metrics collection is enabled.
    #[must_use]
    pub const fn metrics_enabled(&self) -> bool {
        self.metrics_enabled
    }

    /// Creates a log collector configured according to this config.
    #[must_use]
    pub fn create_collector(&self) -> LogCollector {
        LogCollector::new(self.max_log_entries).with_min_level(self.log_level)
    }

    /// Creates a diagnostic context configured according to this config.
    #[must_use]
    pub fn create_diagnostic_context(&self) -> DiagnosticContext {
        DiagnosticContext::new().with_max_completed(self.max_spans)
    }

    /// Creates a metrics registry if metrics are enabled.
    #[must_use]
    pub fn create_metrics(&self) -> Option<Metrics> {
        if self.metrics_enabled {
            Some(Metrics::new())
        } else {
            None
        }
    }

    /// Checks if a trace should be sampled based on the sample rate.
    ///
    /// Uses deterministic sampling based on a hash of the provided key.
    #[must_use]
    pub fn should_sample(&self, key: u64) -> bool {
        if self.sample_rate >= 1.0 {
            return true;
        }
        if self.sample_rate <= 0.0 {
            return false;
        }

        sample_unit_interval(key) < self.sample_rate
    }

    /// Returns a development-oriented configuration.
    ///
    /// Verbose logging, full tracing, all metrics enabled.
    #[must_use]
    pub fn development() -> Self {
        Self::new()
            .with_log_level(LogLevel::Debug)
            .with_trace_all_symbols(true)
            .with_sample_rate(1.0)
    }

    /// Returns a production-oriented configuration.
    ///
    /// Minimal logging, sampled tracing, metrics enabled.
    #[must_use]
    pub fn production() -> Self {
        Self::new()
            .with_log_level(LogLevel::Warn)
            .with_trace_all_symbols(false)
            .with_sample_rate(0.01)
    }

    /// Returns a testing-oriented configuration.
    ///
    /// Full logging and tracing for deterministic replay.
    #[must_use]
    pub fn testing() -> Self {
        Self::new()
            .with_log_level(LogLevel::Trace)
            .with_trace_all_symbols(true)
            .with_sample_rate(1.0)
            .with_max_spans(10_000)
            .with_max_log_entries(100_000)
    }
}

impl Default for ObservabilityConfig {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn config_default() {
        let config = ObservabilityConfig::default();
        assert_eq!(config.log_level(), LogLevel::Info);
        assert!(!config.trace_all_symbols());
        assert!((config.sample_rate() - 1.0).abs() < f64::EPSILON);
        assert!(config.metrics_enabled());
    }

    #[test]
    fn config_builder() {
        let config = ObservabilityConfig::new()
            .with_log_level(LogLevel::Debug)
            .with_trace_all_symbols(true)
            .with_sample_rate(0.5)
            .with_max_spans(500)
            .with_max_log_entries(5000)
            .with_include_timestamps(false)
            .with_metrics_enabled(false);

        assert_eq!(config.log_level(), LogLevel::Debug);
        assert!(config.trace_all_symbols());
        assert!((config.sample_rate() - 0.5).abs() < f64::EPSILON);
        assert_eq!(config.max_spans(), 500);
        assert_eq!(config.max_log_entries(), 5000);
        assert!(!config.include_timestamps());
        assert!(!config.metrics_enabled());
    }

    #[test]
    fn config_presets() {
        let dev = ObservabilityConfig::development();
        assert_eq!(dev.log_level(), LogLevel::Debug);
        assert!(dev.trace_all_symbols());

        let prod = ObservabilityConfig::production();
        assert_eq!(prod.log_level(), LogLevel::Warn);
        assert!(!prod.trace_all_symbols());
        assert!(prod.sample_rate() < 0.1);

        let test = ObservabilityConfig::testing();
        assert_eq!(test.log_level(), LogLevel::Trace);
        assert!(test.trace_all_symbols());
    }

    #[test]
    fn config_create_collector() {
        let config = ObservabilityConfig::new()
            .with_log_level(LogLevel::Warn)
            .with_max_log_entries(100);

        let collector = config.create_collector();
        assert_eq!(collector.min_level(), LogLevel::Warn);
        assert_eq!(collector.capacity(), 100);
    }

    #[test]
    fn config_create_metrics() {
        let enabled = ObservabilityConfig::new().with_metrics_enabled(true);
        assert!(enabled.create_metrics().is_some());

        let disabled = ObservabilityConfig::new().with_metrics_enabled(false);
        assert!(disabled.create_metrics().is_none());
    }

    #[test]
    fn config_sampling() {
        let full = ObservabilityConfig::new().with_sample_rate(1.0);
        assert!(full.should_sample(0));
        assert!(full.should_sample(u64::MAX));

        let none = ObservabilityConfig::new().with_sample_rate(0.0);
        assert!(!none.should_sample(0));
        assert!(!none.should_sample(u64::MAX));

        let half = ObservabilityConfig::new().with_sample_rate(0.5);
        // Deterministic: same key always gives same result
        let result1 = half.should_sample(12345);
        let result2 = half.should_sample(12345);
        assert_eq!(result1, result2);
    }

    #[test]
    fn config_sampling_hashes_low_sequential_keys() {
        let half = ObservabilityConfig::new().with_sample_rate(0.5);
        let sampled = (0..64).filter(|&key| half.should_sample(key)).count();

        assert!(
            sampled > 0,
            "hashed sampling should accept some low sequential keys"
        );
        assert!(
            sampled < 64,
            "hashed sampling should not deterministically accept every low sequential key"
        );
    }

    #[test]
    #[should_panic(expected = "sample_rate must be between 0.0 and 1.0")]
    fn config_invalid_sample_rate_high() {
        let _ = ObservabilityConfig::new().with_sample_rate(1.5);
    }

    #[test]
    #[should_panic(expected = "sample_rate must be between 0.0 and 1.0")]
    fn config_invalid_sample_rate_negative() {
        let _ = ObservabilityConfig::new().with_sample_rate(-0.1);
    }
}