awaken-runtime 0.6.0

Phase-based execution engine, plugin system, and agent loop for Awaken
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
//! [`PoolExecutor`] presents a model pool through the single-model
//! [`LlmExecutor`] contract.
//!
//! The pool pins each routed session to one member for prompt-cache affinity,
//! while a shared [`CircuitBreaker`] carries member health across sessions.
//! Switching stays conservative: quota and permanent member errors may fail
//! over within the same call, transient failures are left to provider retry,
//! and request-level errors never switch because they would fail on every
//! member.

use std::collections::HashMap;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};

use awaken_runtime_contract::contract::executor::{
    InferenceExecutionError, InferenceRequest, LlmExecutor,
};
use awaken_runtime_contract::registry_spec::HomeStrategy;

use super::circuit_breaker::CircuitBreaker;
use super::pool_router::PoolRouter;

const MAX_POOL_SESSION_STATES: usize = 4096;
const MAX_POOL_STREAM_ATTEMPTS: usize = 4096;

#[path = "pool_executor_llm.rs"]
mod pool_executor_llm;
#[path = "pool_observed_stream.rs"]
mod pool_observed_stream;

/// A resolved pool member paired with its concrete provider executor.
pub struct PoolMemberExecutor {
    /// Member `ModelSpec.id`; the circuit-breaker key and router member id.
    pub model_id: String,
    /// Member `ModelSpec.upstream_model`, written onto the request when this
    /// member serves it.
    pub upstream_model: String,
    /// The resolved provider executor (possibly already a `RetryingExecutor`).
    pub executor: Arc<dyn LlmExecutor>,
}

/// A model pool exposed as a single [`LlmExecutor`].
pub struct PoolExecutor {
    inner: Arc<PoolExecutorInner>,
}

struct PoolExecutorInner {
    pool_id: String,
    fallback_home_key: String,
    members: Vec<PoolMemberExecutor>,
    router: PoolRouter,
    breaker: Arc<CircuitBreaker>,
    sessions: parking_lot::RwLock<HashMap<String, PoolSessionState>>,
    stream_attempts: parking_lot::RwLock<HashMap<String, PoolStreamAttemptState>>,
    permanent_quarantine: parking_lot::RwLock<Vec<bool>>,
    home_sequence: AtomicU64,
    anonymous_session_sequence: AtomicU64,
    stream_attempt_sequence: AtomicUsize,
    session_sequence: AtomicUsize,
}

#[derive(Debug, Clone, Copy, Default)]
struct PoolSessionState {
    active: Option<usize>,
    switch_count: u32,
    /// Monotonic access stamp for LRU eviction, mirroring
    /// [`PoolStreamAttemptState::last_access`]. Bumped on every read/touch so
    /// `ensure_session_capacity` can evict the least-recently-used session.
    last_access: usize,
}

#[derive(Debug, Clone)]
struct PoolStreamAttemptState {
    active: Option<usize>,
    tried: Vec<bool>,
    failure_observed: bool,
    in_flight: bool,
    live_streams: usize,
    request_callbacks_ambiguous: bool,
    last_access: usize,
}

impl PoolStreamAttemptState {
    fn new(member_count: usize) -> Self {
        Self {
            active: None,
            tried: vec![false; member_count],
            failure_observed: false,
            in_flight: false,
            live_streams: 0,
            request_callbacks_ambiguous: false,
            last_access: 0,
        }
    }
}

impl PoolExecutor {
    /// Build a pool executor. `members` and `router.members()` must align by
    /// index (same order). `home_key` is the fallback key used when a request
    /// has no routing key; `breaker` is shared across sessions of the pool.
    pub fn new(
        pool_id: impl Into<String>,
        home_key: impl Into<String>,
        members: Vec<PoolMemberExecutor>,
        router: PoolRouter,
        breaker: Arc<CircuitBreaker>,
    ) -> Self {
        debug_assert_eq!(
            members.len(),
            router.members().len(),
            "member executors must align with router members"
        );
        let member_count = members.len();
        Self {
            inner: Arc::new(PoolExecutorInner {
                pool_id: pool_id.into(),
                fallback_home_key: home_key.into(),
                members,
                router,
                breaker,
                sessions: parking_lot::RwLock::new(HashMap::new()),
                stream_attempts: parking_lot::RwLock::new(HashMap::new()),
                permanent_quarantine: parking_lot::RwLock::new(vec![false; member_count]),
                home_sequence: AtomicU64::new(0),
                anonymous_session_sequence: AtomicU64::new(0),
                stream_attempt_sequence: AtomicUsize::new(0),
                session_sequence: AtomicUsize::new(0),
            }),
        }
    }
}

impl PoolExecutorInner {
    /// Health of each member by index, honoring `on_circuit_open`: when the
    /// policy ignores circuit state, every member reads as healthy so the
    /// breaker never drives a switch.
    fn health_mask(&self) -> Vec<bool> {
        let quarantined = self.permanent_quarantine.read().clone();
        if self.router.switch_policy().on_circuit_open {
            self.members
                .iter()
                .enumerate()
                .map(|(idx, m)| {
                    !quarantined.get(idx).copied().unwrap_or(false)
                        && self.breaker.is_available(&m.model_id)
                })
                .collect()
        } else {
            (0..self.members.len())
                .map(|idx| !quarantined.get(idx).copied().unwrap_or(false))
                .collect()
        }
    }

    fn switches_remain(&self, switch_count: u32) -> bool {
        match self.router.switch_policy().max_switches_per_session {
            Some(max) => switch_count < max,
            None => true,
        }
    }

    fn session_key(&self, request: &InferenceRequest) -> String {
        let routing_key = request.routing_key.as_ref();
        if let Some(key) = routing_key.and_then(|key| key.for_scope(self.router.sticky_scope())) {
            return key;
        }
        // A request with only a logical_inference_id (no thread/run/fallback)
        // still needs a *stable* key: external stream-failure callbacks
        // recompute it to relocate the originating attempt, which an anonymous
        // per-call key would defeat — dropping the failure.
        if let Some(logical_id) = routing_key.and_then(|key| key.logical_inference_id.as_deref()) {
            return format!("{}\0logical\0{logical_id}", self.fallback_home_key);
        }
        let sequence = self
            .anonymous_session_sequence
            .fetch_add(1, Ordering::Relaxed)
            .saturating_add(1);
        tracing::warn!(
            pool = %self.pool_id,
            sticky_scope = ?self.router.sticky_scope(),
            "model pool request missing routing key; using anonymous session"
        );
        format!("{}\0anonymous\0{sequence}", self.fallback_home_key)
    }

    fn ensure_session_capacity(sessions: &mut HashMap<String, PoolSessionState>, current: &str) {
        if sessions.len() < MAX_POOL_SESSION_STATES || sessions.contains_key(current) {
            return;
        }
        // Evict the least-recently-accessed session (never `current`), mirroring
        // `ensure_stream_attempt_capacity`. HashMap iteration order is arbitrary,
        // so picking by `last_access` keeps hot sessions resident instead of
        // dropping whichever key the map happened to surface first.
        let victim = sessions
            .iter()
            .filter(|(key, _)| key.as_str() != current)
            .min_by_key(|(_, state)| state.last_access)
            .map(|(key, _)| key.clone());
        if let Some(victim) = victim {
            sessions.remove(&victim);
        }
    }

    fn next_session_sequence(&self) -> usize {
        self.session_sequence
            .fetch_add(1, Ordering::Relaxed)
            .saturating_add(1)
    }

    fn ensure_stream_attempt_capacity(
        attempts: &mut HashMap<String, PoolStreamAttemptState>,
        current: &str,
    ) -> bool {
        if attempts.len() < MAX_POOL_STREAM_ATTEMPTS || attempts.contains_key(current) {
            return true;
        }
        let victim = attempts
            .iter()
            .filter(|(key, attempt)| key.as_str() != current && !attempt.in_flight)
            .min_by_key(|(_, attempt)| attempt.last_access)
            .map(|(key, _)| key.clone());
        if let Some(victim) = victim {
            attempts.remove(&victim);
            true
        } else {
            false
        }
    }

    fn next_stream_attempt_sequence(&self) -> usize {
        self.stream_attempt_sequence
            .fetch_add(1, Ordering::Relaxed)
            .saturating_add(1)
    }

    fn stream_attempt_key(&self, session_key: &str, request: &InferenceRequest) -> Option<String> {
        request
            .routing_key
            .as_ref()
            .and_then(|key| key.logical_inference_id.as_ref())
            .map(|id| format!("{session_key}\0{id}"))
    }

    fn stream_tried_mask(&self, attempt_key: Option<&str>) -> Vec<bool> {
        let Some(attempt_key) = attempt_key else {
            return vec![false; self.members.len()];
        };
        self.stream_attempts
            .write()
            .get_mut(attempt_key)
            .map(|attempt| {
                attempt.last_access = self.next_stream_attempt_sequence();
                attempt.tried.clone()
            })
            .unwrap_or_else(|| vec![false; self.members.len()])
    }

    fn merge_stream_tried_mask(&self, tried: &mut [bool], attempt_key: Option<&str>) {
        let cached = self.stream_tried_mask(attempt_key);
        for (attempted, cached_attempted) in tried.iter_mut().zip(cached) {
            *attempted |= cached_attempted;
        }
    }

    fn mark_stream_active(&self, attempt_key: Option<&str>, idx: usize) -> bool {
        let Some(attempt_key) = attempt_key else {
            return false;
        };
        let mut attempts = self.stream_attempts.write();
        if !Self::ensure_stream_attempt_capacity(&mut attempts, attempt_key) {
            tracing::debug!(
                pool = %self.pool_id,
                attempt_key,
                member = %self.members[idx].model_id,
                "model pool stream attempt cache full; recording stream terminal events by captured member only"
            );
            return false;
        }
        let attempt = attempts
            .entry(attempt_key.to_string())
            .or_insert_with(|| PoolStreamAttemptState::new(self.members.len()));
        attempt.last_access = self.next_stream_attempt_sequence();
        if idx < attempt.tried.len() {
            attempt.tried[idx] = true;
        }
        attempt.active = Some(idx);
        attempt.failure_observed = false;
        attempt.request_callbacks_ambiguous |= attempt.live_streams > 0;
        attempt.live_streams = attempt.live_streams.saturating_add(1);
        attempt.in_flight = true;
        true
    }

    fn mark_stream_open_failure(&self, attempt_key: Option<&str>, idx: usize) {
        let Some(attempt_key) = attempt_key else {
            return;
        };
        let mut attempts = self.stream_attempts.write();
        if !Self::ensure_stream_attempt_capacity(&mut attempts, attempt_key) {
            tracing::debug!(
                pool = %self.pool_id,
                attempt_key,
                member = %self.members[idx].model_id,
                "model pool stream attempt cache full; keeping stream-open failure in local tried mask only"
            );
            return;
        }
        let attempt = attempts
            .entry(attempt_key.to_string())
            .or_insert_with(|| PoolStreamAttemptState::new(self.members.len()));
        attempt.last_access = self.next_stream_attempt_sequence();
        if idx < attempt.tried.len() {
            attempt.tried[idx] = true;
        }
        attempt.active = Some(idx);
        attempt.failure_observed = true;
        attempt.in_flight = attempt.live_streams > 0;
    }

    fn home_sequence_for_new_session(&self) -> Option<u64> {
        matches!(self.router.home_strategy(), HomeStrategy::RoundRobin)
            .then(|| self.home_sequence.fetch_add(1, Ordering::Relaxed))
    }

    /// Resolve the active member for this session: home on first use, then a
    /// session-level failover if the active member's breaker has since opened.
    fn select_active(&self, session_key: &str) -> usize {
        let health = self.health_mask();
        let access = self.next_session_sequence();
        let mut sessions = self.sessions.write();
        Self::ensure_session_capacity(&mut sessions, session_key);
        let state = sessions.entry(session_key.to_string()).or_default();
        state.last_access = access;
        match state.active {
            None => {
                let home = self.router.select_home_with_sequence(
                    session_key,
                    &health,
                    self.home_sequence_for_new_session(),
                );
                state.active = Some(home);
                home
            }
            Some(current) => {
                let unhealthy = health.get(current).copied() == Some(false);
                if unhealthy
                    && self.switches_remain(state.switch_count)
                    && let Some(next) = self.router.select_failover(session_key, current, &health)
                {
                    self.record_switch(current, next, "member unavailable");
                    state.switch_count += 1;
                    state.active = Some(next);
                    return next;
                }
                current
            }
        }
    }

    /// Decide the next member after `current` failed with `err`, if a switch is
    /// warranted, the budget allows, and an untried healthy alternative exists.
    /// Updates active + switch count. `tried` excludes members already attempted
    /// in this call so a single call cannot loop on the same members.
    fn next_on_error(
        &self,
        session_key: &str,
        current: usize,
        err: &InferenceExecutionError,
        tried: &[bool],
    ) -> Option<usize> {
        if !self.router.should_switch_on_error(err) {
            return None;
        }
        let mut mask = self.health_mask();
        for (i, attempted) in tried.iter().enumerate() {
            if *attempted {
                mask[i] = false;
            }
        }
        let access = self.next_session_sequence();
        let mut sessions = self.sessions.write();
        Self::ensure_session_capacity(&mut sessions, session_key);
        let state = sessions.entry(session_key.to_string()).or_default();
        if state.active != Some(current) {
            state.last_access = access;
            return state
                .active
                .filter(|active| mask.get(*active).copied().unwrap_or(false));
        }
        if !self.switches_remain(state.switch_count) {
            state.last_access = access;
            return None;
        }
        let next = self.router.select_failover(session_key, current, &mask)?;
        self.record_switch(current, next, "error-driven");
        state.last_access = access;
        state.switch_count += 1;
        state.active = Some(next);
        Some(next)
    }

    fn next_on_unavailable(
        &self,
        session_key: &str,
        current: usize,
        tried: &[bool],
    ) -> Option<usize> {
        let mut mask = self.health_mask();
        for (i, attempted) in tried.iter().enumerate() {
            if *attempted {
                mask[i] = false;
            }
        }
        let access = self.next_session_sequence();
        let mut sessions = self.sessions.write();
        Self::ensure_session_capacity(&mut sessions, session_key);
        let state = sessions.entry(session_key.to_string()).or_default();
        if state.active != Some(current) {
            state.last_access = access;
            return state
                .active
                .filter(|active| mask.get(*active).copied().unwrap_or(false));
        }
        if !self.switches_remain(state.switch_count) {
            state.last_access = access;
            return None;
        }
        let next = self.router.select_failover(session_key, current, &mask)?;
        self.record_switch(current, next, "member unavailable");
        state.last_access = access;
        state.switch_count += 1;
        state.active = Some(next);
        Some(next)
    }

    fn check_member(&self, idx: usize) -> Result<(), InferenceExecutionError> {
        if self
            .permanent_quarantine
            .read()
            .get(idx)
            .copied()
            .unwrap_or(false)
        {
            return Err(InferenceExecutionError::Provider(format!(
                "model pool member {} is quarantined",
                self.members[idx].model_id
            )));
        }
        if self.router.switch_policy().on_circuit_open {
            self.breaker.check(&self.members[idx].model_id)
        } else {
            Ok(())
        }
    }

    fn error_driven_no_member_available_error(
        &self,
        fallback: InferenceExecutionError,
        tried: &[bool],
    ) -> InferenceExecutionError {
        if (0..self.members.len()).all(|idx| tried.get(idx).copied().unwrap_or(false)) {
            return InferenceExecutionError::PoolAttemptsExhausted;
        }
        self.no_member_available_error(fallback, tried)
    }

    fn no_member_available_error(
        &self,
        fallback: InferenceExecutionError,
        tried: &[bool],
    ) -> InferenceExecutionError {
        let health = self.health_mask();
        if !health.iter().any(|available| *available) {
            return InferenceExecutionError::AllModelsUnavailable;
        }
        let exhausted_untried = health
            .iter()
            .enumerate()
            .all(|(idx, available)| !*available || tried.get(idx).copied().unwrap_or(false));
        if exhausted_untried {
            InferenceExecutionError::PoolAttemptsExhausted
        } else {
            fallback
        }
    }

    fn reset_switch_budget(&self, session_key: &str) {
        let access = self.next_session_sequence();
        if let Some(state) = self.sessions.write().get_mut(session_key) {
            state.last_access = access;
            state.switch_count = 0;
        }
    }

    fn record_stream_member_failure(
        &self,
        request: &InferenceRequest,
        err: &InferenceExecutionError,
    ) {
        let session_key = self.session_key(request);
        let attempt_key = self.stream_attempt_key(&session_key, request);
        // A stream failure must be attributed to the member that actually
        // opened the stream, recorded in this attempt's `active` slot by
        // `mark_stream_active`. The precise per-item path
        // (`PoolObservedStream`) already records failures the inner stream
        // yields; the outer call only adds failures that path cannot see
        // (e.g. an idle stall where `next()` times out without an `Err`).
        //
        // If the originating member cannot be precisely resolved — no
        // attempt key, or the key is absent from the cache (the stream was
        // never opened through this pool, or the attempt was already
        // evicted) — we must NOT fall back to the currently active member:
        // a session-level failover may have moved `active` off the member
        // that opened the stream, so recording there would mis-attribute the
        // failure onto an innocent member's breaker. Skip recording instead.
        let Some(current) = attempt_key.as_deref().and_then(|key| {
            self.stream_attempts.read().get(key).and_then(|attempt| {
                if attempt.request_callbacks_ambiguous {
                    tracing::debug!(
                        pool = %self.pool_id,
                        attempt_key = key,
                        "model pool skipped ambiguous stream failure callback"
                    );
                    return None;
                }
                attempt.active
            })
        }) else {
            tracing::debug!(
                pool = %self.pool_id,
                has_attempt_key = attempt_key.is_some(),
                "model pool skipped stale stream failure callback"
            );
            return;
        };
        self.record_stream_attempt_failure_once(
            &session_key,
            attempt_key.as_deref(),
            current,
            err,
            false,
        );
    }

    fn record_stream_attempt_failure(
        &self,
        session_key: &str,
        attempt_key: Option<&str>,
        current: usize,
        err: &InferenceExecutionError,
    ) {
        self.record_failure(current, err);
        let tried = if let Some(attempt_key) = attempt_key {
            let mut attempts = self.stream_attempts.write();
            if Self::ensure_stream_attempt_capacity(&mut attempts, attempt_key) {
                let attempt = attempts
                    .entry(attempt_key.to_string())
                    .or_insert_with(|| PoolStreamAttemptState::new(self.members.len()));
                attempt.last_access = self.next_stream_attempt_sequence();
                if current < attempt.tried.len() {
                    attempt.tried[current] = true;
                }
                attempt.active = Some(current);
                attempt.in_flight = attempt.live_streams > 0;
                attempt.tried.clone()
            } else {
                let mut tried = vec![false; self.members.len()];
                tried[current] = true;
                tried
            }
        } else {
            let mut tried = vec![false; self.members.len()];
            tried[current] = true;
            tried
        };
        if self.router.should_switch_on_error(err) {
            let _ = self.next_on_error(session_key, current, err, &tried);
        } else if self.router.switch_policy().on_circuit_open
            && !self.breaker.is_available(&self.members[current].model_id)
        {
            let _ = self.next_on_unavailable(session_key, current, &tried);
        }
    }

    fn record_stream_attempt_success(
        &self,
        session_key: &str,
        attempt_key: Option<&str>,
        current: usize,
    ) {
        if let Some(attempt_key) = attempt_key {
            let mut attempts = self.stream_attempts.write();
            let Some(attempt) = attempts.get_mut(attempt_key) else {
                return;
            };
            attempt.live_streams = attempt.live_streams.saturating_sub(1);
            attempt.in_flight = attempt.live_streams > 0;
            if attempt.active != Some(current) {
                return;
            }
            attempts.remove(attempt_key);
        }
        self.breaker.record_success(&self.members[current].model_id);
        self.reset_switch_budget(session_key);
    }

    fn record_stream_attempt_failure_once(
        &self,
        session_key: &str,
        attempt_key: Option<&str>,
        current: usize,
        err: &InferenceExecutionError,
        stream_finished: bool,
    ) {
        if let Some(attempt_key) = attempt_key {
            let mut attempts = self.stream_attempts.write();
            let Some(attempt) = attempts.get_mut(attempt_key) else {
                return;
            };
            attempt.last_access = self.next_stream_attempt_sequence();
            if stream_finished {
                attempt.live_streams = attempt.live_streams.saturating_sub(1);
                attempt.in_flight = attempt.live_streams > 0;
            }
            if attempt.active != Some(current) {
                return;
            }
            if current < attempt.tried.len() {
                attempt.tried[current] = true;
            }
            let duplicate = attempt.failure_observed;
            attempt.failure_observed = true;
            attempt.in_flight = attempt.live_streams > 0;
            drop(attempts);
            if duplicate {
                return;
            }
        }
        self.record_stream_attempt_failure(session_key, attempt_key, current, err);
    }

    fn record_stream_attempt_abandoned(&self, attempt_key: Option<&str>, current: usize) {
        if let Some(attempt_key) = attempt_key {
            let mut attempts = self.stream_attempts.write();
            let Some(attempt) = attempts.get_mut(attempt_key) else {
                return;
            };
            attempt.live_streams = attempt.live_streams.saturating_sub(1);
            attempt.in_flight = attempt.live_streams > 0;
            if attempt.active != Some(current) {
                return;
            }
            attempt.last_access = self.next_stream_attempt_sequence();
            if !attempt.failure_observed {
                attempts.remove(attempt_key);
            }
        }
        self.breaker
            .record_abandoned_probe(&self.members[current].model_id);
    }

    fn record_switch(&self, from: usize, to: usize, reason: &str) {
        tracing::info!(
            pool = %self.pool_id,
            from = %self.members[from].model_id,
            to = %self.members[to].model_id,
            reason,
            "model pool switched member"
        );
    }

    fn record_failure(&self, idx: usize, err: &InferenceExecutionError) {
        if self.router.switch_policy().on_permanent
            && Self::is_member_permanent_error(err)
            && let Some(quarantined) = self.permanent_quarantine.write().get_mut(idx)
        {
            *quarantined = true;
        }
        if err.counts_toward_circuit_breaker() {
            self.breaker.record_failure(&self.members[idx].model_id);
        }
    }

    fn is_member_permanent_error(err: &InferenceExecutionError) -> bool {
        matches!(
            err,
            InferenceExecutionError::Unauthorized(_) | InferenceExecutionError::ModelNotFound(_)
        )
    }

    fn request_for(&self, idx: usize, base: &InferenceRequest) -> InferenceRequest {
        let mut req = base.clone();
        req.upstream_model = self.members[idx].upstream_model.clone();
        req
    }
}

#[cfg(test)]
#[path = "pool_executor_stale_stream_tests.rs"]
mod pool_executor_stale_stream_tests;
#[cfg(test)]
#[path = "pool_executor_stream_tests.rs"]
mod pool_executor_stream_tests;
#[cfg(test)]
#[path = "pool_executor_test_support.rs"]
mod pool_executor_test_support;
#[cfg(test)]
#[path = "pool_executor_tests.rs"]
mod pool_executor_tests;