runifold-model 0.2.0

Provider-neutral model protocol and streaming primitives for Runifold
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
use std::{
    sync::{Arc, Mutex},
    time::Duration,
};

use runifold_core::Instant;
use serde::{Deserialize, Serialize};
use thiserror::Error;

use crate::{ModelError, ModelErrorKind, ModelRef};

/// Clock used by model-routing resilience policy.
///
/// Applications may inject a deterministic implementation for tests.
pub trait RouterClock: Send + Sync {
    /// Returns the current monotonic time.
    fn now(&self) -> Instant;
}

/// Monotonic system clock.
#[derive(Clone, Copy, Debug, Default)]
pub struct SystemRouterClock;

impl RouterClock for SystemRouterClock {
    fn now(&self) -> Instant {
        Instant::now()
    }
}

/// Invalid circuit-breaker configuration.
#[derive(Clone, Copy, Debug, Error, Eq, PartialEq)]
#[non_exhaustive]
pub enum CircuitBreakerConfigError {
    /// A circuit could never open.
    #[error("circuit-breaker failure threshold must be greater than zero")]
    ZeroFailureThreshold,
    /// An open circuit would immediately expire.
    #[error("circuit-breaker cooldown must be greater than zero")]
    ZeroCooldown,
}

/// Per-route circuit-breaker policy.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct CircuitBreakerConfig {
    failure_threshold: u32,
    cooldown: Duration,
    counted_kinds: Vec<ModelErrorKind>,
}

impl Default for CircuitBreakerConfig {
    fn default() -> Self {
        Self {
            failure_threshold: 5,
            cooldown: Duration::from_secs(30),
            counted_kinds: vec![
                ModelErrorKind::Transport,
                ModelErrorKind::Provider,
                ModelErrorKind::Protocol,
                ModelErrorKind::StreamState,
            ],
        }
    }
}

impl CircuitBreakerConfig {
    /// Creates a breaker that counts transport, provider, protocol, and stream
    /// state failures.
    ///
    /// # Errors
    ///
    /// Returns [`CircuitBreakerConfigError`] when the threshold or cooldown is
    /// zero.
    pub fn new(
        failure_threshold: u32,
        cooldown: Duration,
    ) -> Result<Self, CircuitBreakerConfigError> {
        if failure_threshold == 0 {
            return Err(CircuitBreakerConfigError::ZeroFailureThreshold);
        }
        if cooldown.is_zero() {
            return Err(CircuitBreakerConfigError::ZeroCooldown);
        }
        Ok(Self {
            failure_threshold,
            cooldown,
            counted_kinds: vec![
                ModelErrorKind::Transport,
                ModelErrorKind::Provider,
                ModelErrorKind::Protocol,
                ModelErrorKind::StreamState,
            ],
        })
    }

    /// Replaces the failure kinds counted by this breaker.
    #[must_use]
    pub fn counted_kinds(mut self, kinds: impl IntoIterator<Item = ModelErrorKind>) -> Self {
        self.counted_kinds.clear();
        for kind in kinds {
            if !self.counted_kinds.contains(&kind) {
                self.counted_kinds.push(kind);
            }
        }
        self
    }

    /// Returns the consecutive counted-failure threshold.
    pub const fn failure_threshold(&self) -> u32 {
        self.failure_threshold
    }

    /// Returns how long an opened route remains unavailable before probing.
    pub const fn cooldown(&self) -> Duration {
        self.cooldown
    }

    /// Returns error kinds that contribute to opening the circuit.
    pub fn failure_kinds(&self) -> &[ModelErrorKind] {
        &self.counted_kinds
    }

    pub(crate) fn counts(&self, error: &ModelError) -> bool {
        error.kind != ModelErrorKind::Cancelled && self.counted_kinds.contains(&error.kind)
    }
}

#[cfg(test)]
mod config_tests {
    use std::time::Duration;

    use super::CircuitBreakerConfig;
    use crate::ModelErrorKind;

    #[test]
    fn default_breaker_is_bounded_and_counts_runtime_failures() {
        let config = CircuitBreakerConfig::default();

        assert_eq!(config.failure_threshold(), 5);
        assert_eq!(config.cooldown(), Duration::from_secs(30));
        assert!(config.failure_kinds().contains(&ModelErrorKind::Transport));
        assert!(config.failure_kinds().contains(&ModelErrorKind::Protocol));
    }
}

/// Public route-health state.
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum CircuitState {
    /// Requests may use the route.
    Closed,
    /// Requests skip the route during its cooldown.
    Open,
    /// Exactly one recovery probe is currently using the route.
    HalfOpen,
}

/// Point-in-time health for one physical model route.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ModelRouteHealth {
    /// Stable route name.
    pub route: String,
    /// Physical model target.
    pub target: ModelRef,
    /// Current circuit state.
    pub state: CircuitState,
    /// Consecutive counted failures in the current generation.
    pub consecutive_failures: u32,
    /// Remaining cooldown for an open route.
    pub retry_after: Option<Duration>,
}

#[derive(Debug)]
pub(crate) struct BreakerState {
    generation: u64,
    phase: BreakerPhase,
}

#[derive(Debug)]
enum BreakerPhase {
    Closed { failures: u32 },
    Open { until: Option<Instant> },
    HalfOpen,
}

impl Default for BreakerState {
    fn default() -> Self {
        Self {
            generation: 0,
            phase: BreakerPhase::Closed { failures: 0 },
        }
    }
}

pub(crate) type SharedBreakerState = Arc<Mutex<BreakerState>>;

pub(crate) enum RoutePermit {
    Disabled,
    Acquired(BreakerPermit),
    Rejected,
}

pub(crate) struct BreakerPermit {
    state: SharedBreakerState,
    config: CircuitBreakerConfig,
    clock: Arc<dyn RouterClock>,
    generation: u64,
    probe: bool,
    resolved: bool,
}

impl BreakerPermit {
    pub(crate) const fn is_probe(&self) -> bool {
        self.probe
    }

    pub(crate) fn success(mut self) {
        let mut state = lock(&self.state);
        if state.generation == self.generation {
            state.generation = state.generation.wrapping_add(1);
            state.phase = BreakerPhase::Closed { failures: 0 };
        }
        self.resolved = true;
    }

    pub(crate) fn failure(mut self, error: &ModelError) {
        if self.config.counts(error) {
            record_counted_failure(
                &self.state,
                &self.config,
                self.clock.now(),
                self.generation,
                self.probe,
            );
        } else if self.probe {
            reopen(
                &self.state,
                self.clock.now(),
                self.config.cooldown,
                self.generation,
            );
        }
        self.resolved = true;
    }
}

impl Drop for BreakerPermit {
    fn drop(&mut self) {
        if self.probe && !self.resolved {
            reopen(
                &self.state,
                self.clock.now(),
                self.config.cooldown,
                self.generation,
            );
        }
    }
}

pub(crate) fn acquire(
    state: &SharedBreakerState,
    config: Option<&CircuitBreakerConfig>,
    clock: &Arc<dyn RouterClock>,
) -> RoutePermit {
    let Some(config) = config else {
        return RoutePermit::Disabled;
    };
    let now = clock.now();
    let mut state_guard = lock(state);
    let generation = state_guard.generation;
    let probe = match state_guard.phase {
        BreakerPhase::Closed { .. } => false,
        BreakerPhase::Open { until: Some(until) } if now >= until => {
            state_guard.phase = BreakerPhase::HalfOpen;
            true
        }
        BreakerPhase::Open { .. } | BreakerPhase::HalfOpen => return RoutePermit::Rejected,
    };
    drop(state_guard);
    RoutePermit::Acquired(BreakerPermit {
        state: state.clone(),
        config: config.clone(),
        clock: clock.clone(),
        generation,
        probe,
        resolved: false,
    })
}

pub(crate) fn snapshot(
    state: &SharedBreakerState,
    route: String,
    target: ModelRef,
    config: Option<&CircuitBreakerConfig>,
    now: Instant,
) -> ModelRouteHealth {
    let state = lock(state);
    let (health, failures, retry_after) = match state.phase {
        BreakerPhase::Closed { failures } => (CircuitState::Closed, failures, None),
        BreakerPhase::Open { until } => (
            CircuitState::Open,
            0,
            until.map(|until| until.saturating_duration_since(now)),
        ),
        BreakerPhase::HalfOpen => (CircuitState::HalfOpen, 0, None),
    };
    if config.is_none() {
        return ModelRouteHealth {
            route,
            target,
            state: CircuitState::Closed,
            consecutive_failures: 0,
            retry_after: None,
        };
    }
    ModelRouteHealth {
        route,
        target,
        state: health,
        consecutive_failures: failures,
        retry_after,
    }
}

fn record_counted_failure(
    state: &SharedBreakerState,
    config: &CircuitBreakerConfig,
    now: Instant,
    generation: u64,
    probe: bool,
) {
    let mut state = lock(state);
    if state.generation != generation {
        return;
    }
    if probe {
        state.generation = state.generation.wrapping_add(1);
        state.phase = BreakerPhase::Open {
            until: now.checked_add(config.cooldown),
        };
        return;
    }
    let BreakerPhase::Closed { failures } = &mut state.phase else {
        return;
    };
    *failures = failures.saturating_add(1);
    if *failures >= config.failure_threshold {
        state.generation = state.generation.wrapping_add(1);
        state.phase = BreakerPhase::Open {
            until: now.checked_add(config.cooldown),
        };
    }
}

fn reopen(state: &SharedBreakerState, now: Instant, cooldown: Duration, generation: u64) {
    let mut state = lock(state);
    if state.generation == generation {
        state.generation = state.generation.wrapping_add(1);
        state.phase = BreakerPhase::Open {
            until: now.checked_add(cooldown),
        };
    }
}

fn lock(state: &SharedBreakerState) -> std::sync::MutexGuard<'_, BreakerState> {
    state
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner)
}

#[cfg(test)]
mod tests {
    use std::{
        sync::{Arc, Mutex},
        time::{Duration, Instant},
    };

    use runifold_core::RetrySafety;

    use crate::{ModelError, ModelErrorKind, ModelRef};

    use super::{
        BreakerState, CircuitBreakerConfig, CircuitState, RoutePermit, RouterClock,
        SharedBreakerState, acquire, snapshot,
    };

    struct ManualClock {
        now: Mutex<Instant>,
    }

    impl ManualClock {
        fn new() -> Self {
            Self {
                now: Mutex::new(Instant::now()),
            }
        }

        fn advance(&self, duration: Duration) {
            let mut now = self
                .now
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            *now += duration;
        }
    }

    impl RouterClock for ManualClock {
        fn now(&self) -> Instant {
            *self
                .now
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
        }
    }

    fn state() -> SharedBreakerState {
        Arc::new(Mutex::new(BreakerState::default()))
    }

    fn config(threshold: u32) -> CircuitBreakerConfig {
        CircuitBreakerConfig::new(threshold, Duration::from_secs(10)).unwrap()
    }

    fn failure() -> ModelError {
        let mut error = ModelError::local(ModelErrorKind::Transport, "failure");
        error.retry_safety = RetrySafety::Safe;
        error
    }

    fn permit(
        state: &SharedBreakerState,
        config: &CircuitBreakerConfig,
        clock: &Arc<dyn RouterClock>,
    ) -> super::BreakerPermit {
        match acquire(state, Some(config), clock) {
            RoutePermit::Acquired(permit) => permit,
            RoutePermit::Disabled | RoutePermit::Rejected => panic!("expected route permit"),
        }
    }

    fn health(
        state: &SharedBreakerState,
        config: &CircuitBreakerConfig,
        clock: &Arc<dyn RouterClock>,
    ) -> super::ModelRouteHealth {
        snapshot(
            state,
            "route".into(),
            ModelRef::new("test", "model"),
            Some(config),
            clock.now(),
        )
    }

    #[test]
    fn threshold_opens_then_one_successful_probe_closes() {
        let state = state();
        let clock_impl = Arc::new(ManualClock::new());
        let clock: Arc<dyn RouterClock> = clock_impl.clone();
        let config = config(2);

        permit(&state, &config, &clock).failure(&failure());
        assert_eq!(health(&state, &config, &clock).consecutive_failures, 1);
        permit(&state, &config, &clock).failure(&failure());
        assert_eq!(health(&state, &config, &clock).state, CircuitState::Open);
        assert!(matches!(
            acquire(&state, Some(&config), &clock),
            RoutePermit::Rejected
        ));

        clock_impl.advance(config.cooldown());
        let probe = permit(&state, &config, &clock);
        assert_eq!(
            health(&state, &config, &clock).state,
            CircuitState::HalfOpen
        );
        assert!(matches!(
            acquire(&state, Some(&config), &clock),
            RoutePermit::Rejected
        ));
        probe.success();

        let health = health(&state, &config, &clock);
        assert_eq!(health.state, CircuitState::Closed);
        assert_eq!(health.consecutive_failures, 0);
    }

    #[test]
    fn stale_failure_cannot_overwrite_a_newer_success_generation() {
        let state = state();
        let clock_impl = Arc::new(ManualClock::new());
        let clock: Arc<dyn RouterClock> = clock_impl.clone();
        let config = config(1);
        let delayed_permit = permit(&state, &config, &clock);
        let opener = permit(&state, &config, &clock);

        opener.failure(&failure());
        clock_impl.advance(config.cooldown());
        permit(&state, &config, &clock).success();
        delayed_permit.failure(&failure());

        assert_eq!(health(&state, &config, &clock).state, CircuitState::Closed);
    }

    #[test]
    fn abandoned_half_open_probe_reopens_the_route() {
        let state = state();
        let clock_impl = Arc::new(ManualClock::new());
        let clock: Arc<dyn RouterClock> = clock_impl.clone();
        let config = config(1);

        permit(&state, &config, &clock).failure(&failure());
        clock_impl.advance(config.cooldown());
        let probe = permit(&state, &config, &clock);
        drop(probe);

        let health = health(&state, &config, &clock);
        assert_eq!(health.state, CircuitState::Open);
        assert_eq!(health.retry_after, Some(config.cooldown()));
    }

    #[test]
    fn non_counted_failure_does_not_damage_a_closed_route() {
        let state = state();
        let clock: Arc<dyn RouterClock> = Arc::new(ManualClock::new());
        let config = config(1);
        let error = ModelError::local(ModelErrorKind::InvalidRequest, "caller error");

        permit(&state, &config, &clock).failure(&error);

        let health = health(&state, &config, &clock);
        assert_eq!(health.state, CircuitState::Closed);
        assert_eq!(health.consecutive_failures, 0);
    }
}