skippy-scheduler 0.76.1

Iteration-level scheduler for concurrent staged serving with unified KV
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
use std::collections::BTreeMap;

/// Requests whose cache-plus-aging scores differ by fewer than this many
/// scheduler turns remain eligible for waiting-prefix grouping. The band keeps
/// locality reachable for naturally staggered arrivals without allowing a
/// prefix group to outrank materially older or more valuable work.
const PREFIX_GROUPING_SCORE_BAND_TURNS: u64 = 4;

/// Cache work saved at one split-model stage.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StageCacheAffinity {
    pub stage_index: u32,
    pub matched_tokens: usize,
    pub prefill_cost_per_token: u64,
    pub restore_cost: u64,
    pub cache_epoch: u64,
}

impl StageCacheAffinity {
    pub fn estimated_saved_cost(&self) -> u64 {
        u64::try_from(self.matched_tokens)
            .unwrap_or(u64::MAX)
            .saturating_mul(self.prefill_cost_per_token)
            .saturating_sub(self.restore_cost)
    }
}

/// Per-stage cache affinity for one waiting request.
///
/// Keeping the stages separate matters for split serving: a downstream stage
/// may have a useful prefix even when stage zero misses.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct CacheAffinity {
    pub stages: Vec<StageCacheAffinity>,
}

impl CacheAffinity {
    pub fn from_stage(stage: StageCacheAffinity) -> Self {
        Self {
            stages: vec![stage],
        }
    }

    pub fn estimated_saved_cost(&self) -> u64 {
        self.stages
            .iter()
            .map(StageCacheAffinity::estimated_saved_cost)
            .fold(0u64, u64::saturating_add)
    }

    pub fn matched_tokens(&self) -> usize {
        self.stages
            .iter()
            .map(|stage| stage.matched_tokens)
            .fold(0usize, usize::saturating_add)
    }
}

#[derive(Debug, Clone, Copy)]
pub struct CacheAwareCandidate<'a> {
    pub index: usize,
    pub priority: u64,
    pub affinity: &'a CacheAffinity,
    pub prompt_tokens: &'a [i32],
    pub enqueued_turn: u64,
    pub order: u64,
}

/// Order cache candidates by priority, saved work plus aging, then waiting
/// prefix locality.
///
/// Equal-priority requests gain `aging_cost_per_turn` for every turn they wait,
/// which bounds starvation even when hot-prefix requests keep arriving. The
/// Within a four-turn score band, the locality tie-break builds an ephemeral
/// radix order over waiting prompts and visits the heaviest shared-prefix
/// subtrees first. It never touches the materialized cache or its LRU recency.
pub fn order_cache_aware_candidates<'a>(
    candidates: impl IntoIterator<Item = CacheAwareCandidate<'a>>,
    current_turn: u64,
    aging_cost_per_turn: u64,
    group_waiting_prefixes: bool,
) -> Vec<usize> {
    order_cache_aware_candidates_with_anchor(
        candidates,
        current_turn,
        aging_cost_per_turn,
        group_waiting_prefixes,
        None,
    )
}

/// Order cache candidates while continuing the most recently selected waiting
/// prefix subtree inside the normal score band. This keeps a newly opened lane
/// wave on one shared family even before its first request has materialized a
/// cache entry; aging and cache value still outrank the locality anchor.
pub fn order_cache_aware_candidates_with_anchor<'a>(
    candidates: impl IntoIterator<Item = CacheAwareCandidate<'a>>,
    current_turn: u64,
    aging_cost_per_turn: u64,
    group_waiting_prefixes: bool,
    anchor_prompt: Option<&[i32]>,
) -> Vec<usize> {
    let candidates = candidates.into_iter().collect::<Vec<_>>();
    let mut dfs_ranks = vec![0usize; candidates.len()];
    if group_waiting_prefixes {
        let mut dfs_order = Vec::with_capacity(candidates.len());
        append_dfs_weight_order(
            &candidates,
            (0..candidates.len()).collect(),
            0,
            anchor_prompt,
            &mut dfs_order,
        );
        for (rank, position) in dfs_order.into_iter().enumerate() {
            dfs_ranks[position] = rank;
        }
    }

    let mut ranked = candidates
        .into_iter()
        .enumerate()
        .map(|(position, candidate)| (candidate, dfs_ranks[position]))
        .collect::<Vec<_>>();
    ranked.sort_by(|(left, left_dfs_rank), (right, right_dfs_rank)| {
        let left_score = effective_score(left, current_turn, aging_cost_per_turn);
        let right_score = effective_score(right, current_turn, aging_cost_per_turn);
        right
            .priority
            .cmp(&left.priority)
            .then_with(|| {
                if group_waiting_prefixes {
                    grouping_score(right, current_turn, aging_cost_per_turn).cmp(&grouping_score(
                        left,
                        current_turn,
                        aging_cost_per_turn,
                    ))
                } else {
                    right_score.cmp(&left_score)
                }
            })
            .then_with(|| {
                if group_waiting_prefixes && left.prompt_tokens != right.prompt_tokens {
                    left_dfs_rank.cmp(right_dfs_rank)
                } else {
                    std::cmp::Ordering::Equal
                }
            })
            .then_with(|| right_score.cmp(&left_score))
            .then_with(|| left.order.cmp(&right.order))
    });
    ranked
        .into_iter()
        .map(|(candidate, _)| candidate.index)
        .collect()
}

fn grouping_score(
    candidate: &CacheAwareCandidate<'_>,
    current_turn: u64,
    aging_cost_per_turn: u64,
) -> u64 {
    let width = aging_cost_per_turn
        .max(1)
        .saturating_mul(PREFIX_GROUPING_SCORE_BAND_TURNS);
    let age = current_turn.saturating_sub(candidate.enqueued_turn);
    let banded_age = age.saturating_add(PREFIX_GROUPING_SCORE_BAND_TURNS.saturating_sub(1))
        / PREFIX_GROUPING_SCORE_BAND_TURNS;
    candidate
        .affinity
        .estimated_saved_cost()
        .saturating_add(banded_age.saturating_mul(width))
}

/// Select the first candidate from [`order_cache_aware_candidates`].
pub fn select_cache_aware_candidate<'a>(
    candidates: impl IntoIterator<Item = CacheAwareCandidate<'a>>,
    current_turn: u64,
    aging_cost_per_turn: u64,
    group_waiting_prefixes: bool,
) -> Option<usize> {
    order_cache_aware_candidates(
        candidates,
        current_turn,
        aging_cost_per_turn,
        group_waiting_prefixes,
    )
    .into_iter()
    .next()
}

fn effective_score(
    candidate: &CacheAwareCandidate<'_>,
    current_turn: u64,
    aging_cost_per_turn: u64,
) -> u64 {
    let age = current_turn.saturating_sub(candidate.enqueued_turn);
    candidate
        .affinity
        .estimated_saved_cost()
        .saturating_add(age.saturating_mul(aging_cost_per_turn))
}

/// Append a compressed-radix DFS order for candidate positions.
///
/// Common token runs are skipped before branching, so recursion depth follows
/// radix branch points rather than prompt length.
fn append_dfs_weight_order(
    candidates: &[CacheAwareCandidate<'_>],
    positions: Vec<usize>,
    mut depth: usize,
    anchor_prompt: Option<&[i32]>,
    output: &mut Vec<usize>,
) {
    if positions.len() <= 1 {
        output.extend(positions);
        return;
    }

    let common_limit = positions
        .iter()
        .map(|position| candidates[*position].prompt_tokens.len())
        .min()
        .unwrap_or(depth);
    while depth < common_limit {
        let token = candidates[positions[0]].prompt_tokens[depth];
        if positions
            .iter()
            .all(|position| candidates[*position].prompt_tokens[depth] == token)
        {
            depth += 1;
        } else {
            break;
        }
    }

    let mut terminal = Vec::new();
    let mut children = BTreeMap::<i32, Vec<usize>>::new();
    for position in positions {
        match candidates[position].prompt_tokens.get(depth).copied() {
            Some(token) => children.entry(token).or_default().push(position),
            None => terminal.push(position),
        }
    }
    let mut children = children.into_iter().collect::<Vec<_>>();
    children.sort_by(|(left_token, left), (right_token, right)| {
        let anchor_token = anchor_prompt.and_then(|prompt| prompt.get(depth)).copied();
        (Some(*right_token) == anchor_token)
            .cmp(&(Some(*left_token) == anchor_token))
            .then_with(|| right.len().cmp(&left.len()))
            .then_with(|| {
                minimum_enqueue_order(candidates, left)
                    .cmp(&minimum_enqueue_order(candidates, right))
            })
            .then_with(|| left_token.cmp(right_token))
    });
    for (_, child) in children {
        append_dfs_weight_order(
            candidates,
            child,
            depth.saturating_add(1),
            anchor_prompt,
            output,
        );
    }
    terminal.sort_by_key(|position| candidates[*position].order);
    output.extend(terminal);
}

fn minimum_enqueue_order(candidates: &[CacheAwareCandidate<'_>], positions: &[usize]) -> u64 {
    positions
        .iter()
        .map(|position| candidates[*position].order)
        .min()
        .unwrap_or(u64::MAX)
}

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

    fn affinity(saved_cost: u64) -> CacheAffinity {
        CacheAffinity::from_stage(StageCacheAffinity {
            stage_index: 0,
            matched_tokens: 1,
            prefill_cost_per_token: saved_cost,
            restore_cost: 0,
            cache_epoch: 0,
        })
    }

    #[test]
    fn cache_value_orders_equal_priority_candidates() {
        let cold = affinity(0);
        let hot = affinity(100);
        let selected = select_cache_aware_candidate(
            [
                CacheAwareCandidate {
                    index: 0,
                    priority: 0,
                    affinity: &cold,
                    prompt_tokens: &[1, 2, 3],
                    enqueued_turn: 0,
                    order: 0,
                },
                CacheAwareCandidate {
                    index: 1,
                    priority: 0,
                    affinity: &hot,
                    prompt_tokens: &[4, 5, 6],
                    enqueued_turn: 0,
                    order: 1,
                },
            ],
            0,
            10,
            true,
        );
        assert_eq!(selected, Some(1));
    }

    #[test]
    fn anchor_keeps_a_selected_prefix_group_contiguous() {
        let cold = CacheAffinity::default();
        let prompts = [&[9, 9, 9][..], &[1, 2, 3][..], &[1, 2, 4][..]];
        let first = order_cache_aware_candidates_with_anchor(
            prompts
                .iter()
                .enumerate()
                .map(|(index, prompt_tokens)| CacheAwareCandidate {
                    index,
                    priority: 0,
                    affinity: &cold,
                    prompt_tokens,
                    enqueued_turn: 0,
                    order: index as u64,
                }),
            0,
            10,
            true,
            None,
        );
        assert_eq!(first[0], 1);

        let second = order_cache_aware_candidates_with_anchor(
            [0usize, 2].into_iter().map(|index| CacheAwareCandidate {
                index,
                priority: 0,
                affinity: &cold,
                prompt_tokens: prompts[index],
                enqueued_turn: 0,
                order: index as u64,
            }),
            1,
            10,
            true,
            Some(prompts[1]),
        );
        assert_eq!(second[0], 2);
    }

    #[test]
    fn aging_eventually_promotes_a_cold_request() {
        let cold = affinity(0);
        let hot = affinity(100);
        let selected = select_cache_aware_candidate(
            [
                CacheAwareCandidate {
                    index: 0,
                    priority: 0,
                    affinity: &cold,
                    prompt_tokens: &[1, 2, 3],
                    enqueued_turn: 0,
                    order: 0,
                },
                CacheAwareCandidate {
                    index: 1,
                    priority: 0,
                    affinity: &hot,
                    prompt_tokens: &[4, 5, 6],
                    enqueued_turn: 11,
                    order: 1,
                },
            ],
            11,
            10,
            true,
        );
        assert_eq!(selected, Some(0));
    }

    #[test]
    fn explicit_priority_precedes_cache_value() {
        let cold = affinity(0);
        let hot = affinity(1_000);
        let selected = select_cache_aware_candidate(
            [
                CacheAwareCandidate {
                    index: 0,
                    priority: 1,
                    affinity: &cold,
                    prompt_tokens: &[1, 2, 3],
                    enqueued_turn: 0,
                    order: 0,
                },
                CacheAwareCandidate {
                    index: 1,
                    priority: 0,
                    affinity: &hot,
                    prompt_tokens: &[4, 5, 6],
                    enqueued_turn: 0,
                    order: 1,
                },
            ],
            0,
            10,
            true,
        );
        assert_eq!(selected, Some(0));
    }

    #[test]
    fn dfs_weight_groups_the_heaviest_equal_score_prefix_subtree() {
        let affinity = CacheAffinity::default();
        let ordered = order_cache_aware_candidates(
            [
                CacheAwareCandidate {
                    index: 0,
                    priority: 0,
                    affinity: &affinity,
                    prompt_tokens: &[9, 9, 9],
                    enqueued_turn: 0,
                    order: 0,
                },
                CacheAwareCandidate {
                    index: 1,
                    priority: 0,
                    affinity: &affinity,
                    prompt_tokens: &[1, 2, 3],
                    enqueued_turn: 0,
                    order: 1,
                },
                CacheAwareCandidate {
                    index: 2,
                    priority: 0,
                    affinity: &affinity,
                    prompt_tokens: &[1, 2, 4],
                    enqueued_turn: 0,
                    order: 2,
                },
            ],
            0,
            10,
            true,
        );

        assert_eq!(ordered, [1, 2, 0]);
    }

    #[test]
    fn dfs_weight_groups_staggered_arrivals_within_score_band() {
        let affinity = CacheAffinity::default();
        let ordered = order_cache_aware_candidates(
            [
                CacheAwareCandidate {
                    index: 0,
                    priority: 0,
                    affinity: &affinity,
                    prompt_tokens: &[9, 9, 9],
                    enqueued_turn: 0,
                    order: 0,
                },
                CacheAwareCandidate {
                    index: 1,
                    priority: 0,
                    affinity: &affinity,
                    prompt_tokens: &[1, 2, 3],
                    enqueued_turn: 1,
                    order: 1,
                },
                CacheAwareCandidate {
                    index: 2,
                    priority: 0,
                    affinity: &affinity,
                    prompt_tokens: &[1, 2, 4],
                    enqueued_turn: 2,
                    order: 2,
                },
            ],
            3,
            4_096,
            true,
        );

        assert_eq!(ordered, [1, 2, 0]);
    }

    #[test]
    fn materially_older_work_precedes_prefix_group() {
        let affinity = CacheAffinity::default();
        let ordered = order_cache_aware_candidates(
            [
                CacheAwareCandidate {
                    index: 0,
                    priority: 0,
                    affinity: &affinity,
                    prompt_tokens: &[9, 9, 9],
                    enqueued_turn: 0,
                    order: 0,
                },
                CacheAwareCandidate {
                    index: 1,
                    priority: 0,
                    affinity: &affinity,
                    prompt_tokens: &[1, 2, 3],
                    enqueued_turn: 9,
                    order: 1,
                },
                CacheAwareCandidate {
                    index: 2,
                    priority: 0,
                    affinity: &affinity,
                    prompt_tokens: &[1, 2, 4],
                    enqueued_turn: 10,
                    order: 2,
                },
            ],
            10,
            4_096,
            true,
        );

        assert_eq!(ordered[0], 0);
    }

    #[test]
    fn disabling_prefix_grouping_restores_enqueue_order() {
        let affinity = CacheAffinity::default();
        let ordered = order_cache_aware_candidates(
            [
                CacheAwareCandidate {
                    index: 0,
                    priority: 0,
                    affinity: &affinity,
                    prompt_tokens: &[9, 9, 9],
                    enqueued_turn: 0,
                    order: 0,
                },
                CacheAwareCandidate {
                    index: 1,
                    priority: 0,
                    affinity: &affinity,
                    prompt_tokens: &[1, 2, 3],
                    enqueued_turn: 0,
                    order: 1,
                },
                CacheAwareCandidate {
                    index: 2,
                    priority: 0,
                    affinity: &affinity,
                    prompt_tokens: &[1, 2, 4],
                    enqueued_turn: 0,
                    order: 2,
                },
            ],
            0,
            10,
            false,
        );

        assert_eq!(ordered, [0, 1, 2]);
    }

    #[test]
    fn materialized_cache_value_precedes_waiting_prefix_weight() {
        let cold = affinity(0);
        let hot = affinity(100);
        let ordered = order_cache_aware_candidates(
            [
                CacheAwareCandidate {
                    index: 0,
                    priority: 0,
                    affinity: &cold,
                    prompt_tokens: &[1, 2, 3],
                    enqueued_turn: 0,
                    order: 0,
                },
                CacheAwareCandidate {
                    index: 1,
                    priority: 0,
                    affinity: &cold,
                    prompt_tokens: &[1, 2, 4],
                    enqueued_turn: 0,
                    order: 1,
                },
                CacheAwareCandidate {
                    index: 2,
                    priority: 0,
                    affinity: &hot,
                    prompt_tokens: &[9, 9, 9],
                    enqueued_turn: 0,
                    order: 2,
                },
            ],
            0,
            10,
            true,
        );

        assert_eq!(ordered[0], 2);
    }

    #[test]
    fn long_common_prefix_does_not_drive_recursion_depth() {
        let affinity = CacheAffinity::default();
        let mut left = vec![1; 100_000];
        let mut right = left.clone();
        left.push(2);
        right.push(3);
        let ordered = order_cache_aware_candidates(
            [
                CacheAwareCandidate {
                    index: 0,
                    priority: 0,
                    affinity: &affinity,
                    prompt_tokens: &left,
                    enqueued_turn: 0,
                    order: 0,
                },
                CacheAwareCandidate {
                    index: 1,
                    priority: 0,
                    affinity: &affinity,
                    prompt_tokens: &right,
                    enqueued_turn: 0,
                    order: 1,
                },
            ],
            0,
            10,
            true,
        );

        assert_eq!(ordered, [0, 1]);
    }
}