swadhinbiswas WIP save-point: production hardening, H3 removal, fmt gate, and accumulated phase work · 7/15/2026
2080d40
243 lines · 8.1 KB
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
//! LLM-specific autoscaler — scaling decisions from LLM health signals.
//!
//! Unlike a generic HTTP autoscaler (which watches QPS), this watches the
//! signals that actually matter for LLM serving:
//!
//! - **TTFT** (time to first token) — prefill latency / saturation.
//! - **tokens/sec** — decode throughput per replica.
//! - **queue depth** — pending requests waiting for a slot.
//! - **KV-cache pressure** — the binding memory constraint for long contexts.
//!
//! Pure decision logic (no timers, no metrics collection, no orchestration).
//! The [`Autoscaler`] is stateful only for cooldown/flap protection; pair it
//! with the metrics pipeline and the multi-replica supervisor.

/// Live LLM-serving signals fed to the autoscaler each tick.
#[derive(Debug, Clone, Copy)]
pub struct LlmMetrics {
    /// Decode throughput per replica (tokens/sec).
    pub tokens_per_sec: f32,
    /// Time to first token, milliseconds.
    pub ttft_ms: f32,
    /// Number of requests waiting for a free slot.
    pub queue_depth: usize,
    /// KV-cache pressure across replicas (0–100%).
    pub kv_pressure_pct: f32,
}

/// Tuning for the autoscaler.
#[derive(Debug, Clone, Copy)]
pub struct AutoscalerConfig {
    /// Never scale below this many replicas.
    pub min_replicas: usize,
    /// Never scale above this many replicas.
    pub max_replicas: usize,
    /// TTFT above which we consider the fleet saturated.
    pub target_ttft_ms: f32,
    /// KV-cache pressure (0–100) above which we consider the fleet saturated.
    pub target_kv_pressure_pct: f32,
    /// Queue depth at/above which we scale up.
    pub queue_depth_scale_up: usize,
    /// Queue depth at/below which we may scale down.
    pub queue_depth_scale_down: usize,
    /// Ticks to wait after a scaling action before another is allowed
    /// (prevents flapping on noisy metrics).
    pub cooldown_ticks: usize,
}

impl Default for AutoscalerConfig {
    fn default() -> Self {
        Self {
            min_replicas: 1,
            max_replicas: 8,
            target_ttft_ms: 500.0,
            target_kv_pressure_pct: 80.0,
            queue_depth_scale_up: 16,
            queue_depth_scale_down: 2,
            cooldown_ticks: 10,
        }
    }
}

/// What the autoscaler wants the supervisor to do.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ScaleDecision {
    /// Add replicas up to `desired`.
    ScaleUp(usize),
    /// Remove replicas down to `desired`.
    ScaleDown(usize),
    /// Keep `desired` replicas (no change).
    Hold(usize),
}

/// Stateful LLM autoscaler.
pub struct Autoscaler {
    config: AutoscalerConfig,
    current: usize,
    cooldown: usize,
}

impl Autoscaler {
    /// Create an autoscaler starting at `config.min_replicas`.
    pub fn new(config: AutoscalerConfig) -> Self {
        let current = config.min_replicas.max(1).min(config.max_replicas.max(1));
        Self { config, current, cooldown: 0 }
    }

    /// Current desired replica count.
    pub fn current(&self) -> usize {
        self.current
    }

    /// Whether the fleet is currently in a cooldown window.
    pub fn in_cooldown(&self) -> bool {
        self.cooldown > 0
    }

    /// Decide the next action from the latest metrics.
    ///
    /// - **Scale up** when KV pressure, TTFT, or queue depth breach their
    ///   saturation thresholds.
    /// - **Scale down** when all signals are comfortably under half their
    ///   targets and queue depth is low.
    /// - **Hold** otherwise, or while in cooldown.
    pub fn decide(&mut self, m: &LlmMetrics) -> ScaleDecision {
        if self.cooldown > 0 {
            self.cooldown -= 1;
            return ScaleDecision::Hold(self.current);
        }

        let saturated = m.kv_pressure_pct >= self.config.target_kv_pressure_pct
            || m.ttft_ms >= self.config.target_ttft_ms
            || m.queue_depth >= self.config.queue_depth_scale_up;

        let underused = m.kv_pressure_pct <= self.config.target_kv_pressure_pct * 0.5
            && m.ttft_ms <= self.config.target_ttft_ms * 0.5
            && m.queue_depth <= self.config.queue_depth_scale_down;

        let desired = if saturated {
            (self.current + 1).min(self.config.max_replicas)
        } else if underused {
            self.current.saturating_sub(1).max(self.config.min_replicas)
        } else {
            self.current
        };

        if desired == self.current {
            ScaleDecision::Hold(self.current)
        } else if desired > self.current {
            self.current = desired;
            self.cooldown = self.config.cooldown_ticks;
            ScaleDecision::ScaleUp(desired)
        } else {
            self.current = desired;
            self.cooldown = self.config.cooldown_ticks;
            ScaleDecision::ScaleDown(desired)
        }
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    fn cfg() -> AutoscalerConfig {
        AutoscalerConfig {
            min_replicas: 1,
            max_replicas: 4,
            target_ttft_ms: 500.0,
            target_kv_pressure_pct: 80.0,
            queue_depth_scale_up: 16,
            queue_depth_scale_down: 2,
            cooldown_ticks: 2,
        }
    }

    fn metrics(kv: f32, ttft: f32, q: usize) -> LlmMetrics {
        LlmMetrics { tokens_per_sec: 50.0, ttft_ms: ttft, queue_depth: q, kv_pressure_pct: kv }
    }

    #[test]
    fn scales_up_on_kv_pressure() {
        let mut a = Autoscaler::new(cfg());
        let d = a.decide(&metrics(95.0, 100.0, 0));
        assert_eq!(d, ScaleDecision::ScaleUp(2));
        assert!(a.in_cooldown());
    }

    #[test]
    fn scales_up_on_ttft() {
        let mut a = Autoscaler::new(cfg());
        let d = a.decide(&metrics(10.0, 1200.0, 0));
        assert_eq!(d, ScaleDecision::ScaleUp(2));
    }

    #[test]
    fn scales_up_on_queue_depth() {
        let mut a = Autoscaler::new(cfg());
        let d = a.decide(&metrics(10.0, 100.0, 40));
        assert_eq!(d, ScaleDecision::ScaleUp(2));
    }

    #[test]
    fn holds_when_healthy() {
        let mut a = Autoscaler::new(cfg());
        let d = a.decide(&metrics(40.0, 200.0, 1));
        assert_eq!(d, ScaleDecision::Hold(1));
    }

    #[test]
    fn scales_down_when_underused() {
        let mut a = Autoscaler::new(cfg());
        // First bump to 2, then drain metrics to trigger a scale down.
        let _ = a.decide(&metrics(95.0, 100.0, 0));
        // cooldown ticks
        let _ = a.decide(&metrics(10.0, 100.0, 0));
        let _ = a.decide(&metrics(10.0, 100.0, 0));
        let d = a.decide(&metrics(10.0, 100.0, 0));
        // still underused and out of cooldown → ScaleDown back to 1
        assert_eq!(d, ScaleDecision::ScaleDown(1));
    }

    #[test]
    fn never_exceeds_max() {
        let mut a = Autoscaler::new(cfg());
        // Drive up to max with cooldown ticks between.
        for _ in 0..10 {
            let _ = a.decide(&metrics(99.0, 2000.0, 100));
        }
        assert_eq!(a.current(), 4);
        let d = a.decide(&metrics(99.0, 2000.0, 100));
        assert_eq!(d, ScaleDecision::Hold(4));
    }

    #[test]
    fn never_below_min() {
        let mut a = Autoscaler::new(cfg());
        // Underused from the start → stays at min.
        for _ in 0..6 {
            let _ = a.decide(&metrics(5.0, 50.0, 0));
        }
        assert_eq!(a.current(), 1);
        let d = a.decide(&metrics(5.0, 50.0, 0));
        assert_eq!(d, ScaleDecision::Hold(1));
    }

    #[test]
    fn cooldown_prevents_flapping() {
        let mut a = Autoscaler::new(cfg());
        assert_eq!(a.decide(&metrics(95.0, 100.0, 0)), ScaleDecision::ScaleUp(2));
        // Immediately after scaling up we are in cooldown; metrics flipping to
        // healthy must NOT trigger an instant scale-down.
        assert_eq!(a.decide(&metrics(5.0, 50.0, 0)), ScaleDecision::Hold(2));
        assert_eq!(a.decide(&metrics(5.0, 50.0, 0)), ScaleDecision::Hold(2));
        // After cooldown expires, healthy metrics can scale down.
        let d = a.decide(&metrics(5.0, 50.0, 0));
        assert_eq!(d, ScaleDecision::ScaleDown(1));
    }
}