octoroute 1.0.0

Intelligent multi-model router for self-hosted LLMs
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
//! Weighted selection distribution tests
//!
//! Tests weighted random selection algorithm, distribution validation,
//! and edge cases (zero weights, negative weights, heavily skewed weights).

use super::*;

/// Helper to create test metrics
fn test_metrics() -> Arc<crate::metrics::Metrics> {
    Arc::new(crate::metrics::Metrics::new().expect("should create metrics"))
}
use crate::models::endpoint_name::ExclusionSet;
use crate::models::selector::ModelSelector;
use crate::router::TargetModel;
use std::sync::Arc;

#[tokio::test]
async fn test_selector_weighted_fast_tier_both_endpoints_selectable() {
    let config = Arc::new(create_test_config());
    let selector = ModelSelector::new(config, test_metrics());

    // With equal weights (1.0 each), both endpoints should be selectable
    // Sample 100 times to verify both can be selected
    let mut fast1_seen = false;
    let mut fast2_seen = false;
    let no_exclude = ExclusionSet::new();

    for _ in 0..100 {
        let selected = selector
            .select(TargetModel::Fast, &no_exclude)
            .await
            .unwrap();
        if selected.name() == "fast-1" {
            fast1_seen = true;
        }
        if selected.name() == "fast-2" {
            fast2_seen = true;
        }

        if fast1_seen && fast2_seen {
            break; // Both have been selected, test passes
        }
    }

    assert!(
        fast1_seen,
        "fast-1 should be selected at least once in 100 attempts"
    );
    assert!(
        fast2_seen,
        "fast-2 should be selected at least once in 100 attempts"
    );
}

#[tokio::test]
#[should_panic(expected = "MEMORY CORRUPTION DETECTED")]
async fn test_selector_zero_weight_fallback() {
    // Create config via TOML with zero weights (config validation will reject this at load time,
    // but this test verifies the selector panics if it somehow gets zero weights during runtime)
    let toml_config = r#"
[server]
host = "127.0.0.1"
port = 3000
request_timeout_seconds = 30

[[models.fast]]
name = "fast-1"
base_url = "http://localhost:1234/v1"
max_tokens = 2048
weight = 0.0

[[models.fast]]
name = "fast-2"
base_url = "http://localhost:1235/v1"
max_tokens = 2048
weight = 0.0

[[models.balanced]]
name = "balanced-1"
base_url = "http://localhost:1236/v1"
max_tokens = 4096

[[models.deep]]
name = "deep-1"
base_url = "http://localhost:1237/v1"
max_tokens = 8192

[routing]
strategy = "rule"
router_tier = "balanced"
"#;
    let config: Config = toml::from_str(toml_config).expect("should parse TOML");
    let selector = ModelSelector::new(Arc::new(config), test_metrics());

    // Should panic when all weights are zero - this indicates memory corruption
    // Config validation prevents this at startup, so reaching this code is a critical error
    let no_exclude = ExclusionSet::new();
    let _result = selector.select(TargetModel::Fast, &no_exclude).await;
    // Panic expected - test fails if we reach here
}

#[tokio::test]
#[should_panic(expected = "MEMORY CORRUPTION DETECTED")]
async fn test_selector_negative_weight_fallback() {
    // Create config with negative weights via TOML (config validation will reject this,
    // but this test verifies the selector panics if it somehow gets negative weights during runtime)
    let toml_config = r#"
[server]
host = "127.0.0.1"
port = 3000
request_timeout_seconds = 30

[[models.fast]]
name = "fast-1"
base_url = "http://localhost:1234/v1"
max_tokens = 2048
weight = -1.0

[[models.fast]]
name = "fast-2"
base_url = "http://localhost:1235/v1"
max_tokens = 2048
weight = -2.0

[[models.balanced]]
name = "balanced-1"
base_url = "http://localhost:1236/v1"
max_tokens = 4096

[[models.deep]]
name = "deep-1"
base_url = "http://localhost:1237/v1"
max_tokens = 8192

[routing]
strategy = "rule"
router_tier = "balanced"
"#;
    let config: Config = toml::from_str(toml_config).expect("should parse TOML");
    let selector = ModelSelector::new(Arc::new(config), test_metrics());

    // Should panic when all weights are negative - this indicates memory corruption
    // Config validation prevents this at startup, so reaching this code is a critical error
    let no_exclude = ExclusionSet::new();
    let _result = selector.select(TargetModel::Fast, &no_exclude).await;
    // Panic expected - test fails if we reach here
}

#[tokio::test]
async fn test_weighted_selection_distribution() {
    // Create config with different weights: 2.0 vs 1.0 (2:1 ratio)
    let toml_config = r#"
[server]
host = "127.0.0.1"
port = 3000
request_timeout_seconds = 30

[[models.fast]]
name = "fast-1"
base_url = "http://localhost:1234/v1"
max_tokens = 2048
weight = 2.0

[[models.fast]]
name = "fast-2"
base_url = "http://localhost:1235/v1"
max_tokens = 2048
weight = 1.0

[[models.balanced]]
name = "balanced-1"
base_url = "http://localhost:1236/v1"
max_tokens = 4096

[[models.deep]]
name = "deep-1"
base_url = "http://localhost:1237/v1"
max_tokens = 8192

[routing]
strategy = "rule"
router_tier = "balanced"
"#;
    let config: Config = toml::from_str(toml_config).expect("should parse TOML");
    let selector = ModelSelector::new(Arc::new(config), test_metrics());

    // Sample 3000 times to get statistically significant distribution
    let no_exclude = ExclusionSet::new();
    let mut counts = std::collections::HashMap::new();
    for _ in 0..3000 {
        let endpoint = selector
            .select(TargetModel::Fast, &no_exclude)
            .await
            .unwrap();
        *counts.entry(endpoint.name()).or_insert(0) += 1;
    }

    let fast1_count = counts.get("fast-1").unwrap_or(&0);
    let fast2_count = counts.get("fast-2").unwrap_or(&0);

    // With 2:1 weight ratio, expect ~2000:1000 distribution
    // Allow 10% deviation for randomness (1800-2200 for fast-1, 800-1200 for fast-2)
    assert!(
        *fast1_count >= 1800 && *fast1_count <= 2200,
        "fast-1 (weight 2.0) should get ~2000/3000 selections, got {}",
        fast1_count
    );
    assert!(
        *fast2_count >= 800 && *fast2_count <= 1200,
        "fast-2 (weight 1.0) should get ~1000/3000 selections, got {}",
        fast2_count
    );
}

#[tokio::test]
async fn test_weighted_selection_heavily_skewed() {
    // Create config with heavily skewed weights: 9.0 vs 1.0 (9:1 ratio)
    let toml_config = r#"
[server]
host = "127.0.0.1"
port = 3000
request_timeout_seconds = 30

[[models.fast]]
name = "fast-1"
base_url = "http://localhost:1234/v1"
max_tokens = 2048
weight = 9.0

[[models.fast]]
name = "fast-2"
base_url = "http://localhost:1235/v1"
max_tokens = 2048
weight = 1.0

[[models.balanced]]
name = "balanced-1"
base_url = "http://localhost:1236/v1"
max_tokens = 4096

[[models.deep]]
name = "deep-1"
base_url = "http://localhost:1237/v1"
max_tokens = 8192

[routing]
strategy = "rule"
router_tier = "balanced"
"#;
    let config: Config = toml::from_str(toml_config).expect("should parse TOML");
    let selector = ModelSelector::new(Arc::new(config), test_metrics());

    // Sample 1000 times
    let no_exclude = ExclusionSet::new();
    let mut counts = std::collections::HashMap::new();
    for _ in 0..1000 {
        let endpoint = selector
            .select(TargetModel::Fast, &no_exclude)
            .await
            .unwrap();
        *counts.entry(endpoint.name()).or_insert(0) += 1;
    }

    let fast1_count = counts.get("fast-1").unwrap_or(&0);
    let fast2_count = counts.get("fast-2").unwrap_or(&0);

    // With 9:1 weight ratio, expect ~900:100 distribution
    // Allow 15% deviation (765-1035 for fast-1, 35-165 for fast-2)
    assert!(
        *fast1_count >= 765 && *fast1_count <= 1035,
        "fast-1 (weight 9.0) should get ~900/1000 selections, got {}",
        fast1_count
    );
    assert!(
        *fast2_count >= 35 && *fast2_count <= 165,
        "fast-2 (weight 1.0) should get ~100/1000 selections, got {}",
        fast2_count
    );
}

#[tokio::test]
async fn test_weighted_selection_all_equal_weights() {
    // When all weights are equal, should behave like uniform distribution
    let config = create_test_config(); // Both have weight 1.0

    let selector = ModelSelector::new(Arc::new(config), test_metrics());

    // Sample 2000 times
    let no_exclude = ExclusionSet::new();
    let mut counts = std::collections::HashMap::new();
    for _ in 0..2000 {
        let endpoint = selector
            .select(TargetModel::Fast, &no_exclude)
            .await
            .unwrap();
        *counts.entry(endpoint.name()).or_insert(0) += 1;
    }

    let fast1_count = counts.get("fast-1").unwrap_or(&0);
    let fast2_count = counts.get("fast-2").unwrap_or(&0);

    // With equal weights, expect ~1000:1000 distribution
    // Allow 15% deviation for randomness (850-1150 for each)
    assert!(
        *fast1_count >= 850 && *fast1_count <= 1150,
        "fast-1 (weight 1.0) should get ~1000/2000 selections, got {}",
        fast1_count
    );
    assert!(
        *fast2_count >= 850 && *fast2_count <= 1150,
        "fast-2 (weight 1.0) should get ~1000/2000 selections, got {}",
        fast2_count
    );
}

#[tokio::test]
async fn test_weighted_selection_three_endpoints() {
    // Test with three endpoints with weights 3.0, 2.0, 1.0 (3:2:1 ratio)
    let toml_config = r#"
[server]
host = "127.0.0.1"
port = 3000
request_timeout_seconds = 30

[[models.fast]]
name = "fast-1"
base_url = "http://localhost:1234/v1"
max_tokens = 2048
weight = 3.0

[[models.fast]]
name = "fast-2"
base_url = "http://localhost:1235/v1"
max_tokens = 2048
weight = 2.0

[[models.fast]]
name = "fast-3"
base_url = "http://localhost:1236/v1"
max_tokens = 2048
weight = 1.0

[[models.balanced]]
name = "balanced-1"
base_url = "http://localhost:1236/v1"
max_tokens = 4096

[[models.deep]]
name = "deep-1"
base_url = "http://localhost:1237/v1"
max_tokens = 8192

[routing]
strategy = "rule"
router_tier = "balanced"
"#;
    let config: Config = toml::from_str(toml_config).expect("should parse TOML");
    let selector = ModelSelector::new(Arc::new(config), test_metrics());

    // Sample 6000 times (divisible by 6 for clean expected values)
    let no_exclude = ExclusionSet::new();
    let mut counts = std::collections::HashMap::new();
    for _ in 0..6000 {
        let endpoint = selector
            .select(TargetModel::Fast, &no_exclude)
            .await
            .unwrap();
        *counts.entry(endpoint.name()).or_insert(0) += 1;
    }

    let fast1_count = counts.get("fast-1").unwrap_or(&0);
    let fast2_count = counts.get("fast-2").unwrap_or(&0);
    let fast3_count = counts.get("fast-3").unwrap_or(&0);

    // Total weight = 6.0, so expect: fast-1: 3000, fast-2: 2000, fast-3: 1000
    // Allow 10% deviation
    assert!(
        *fast1_count >= 2700 && *fast1_count <= 3300,
        "fast-1 (weight 3.0) should get ~3000/6000 selections, got {}",
        fast1_count
    );
    assert!(
        *fast2_count >= 1800 && *fast2_count <= 2200,
        "fast-2 (weight 2.0) should get ~2000/6000 selections, got {}",
        fast2_count
    );
    assert!(
        *fast3_count >= 900 && *fast3_count <= 1100,
        "fast-3 (weight 1.0) should get ~1000/6000 selections, got {}",
        fast3_count
    );
}

// Priority-based selection tests

#[tokio::test]
async fn test_weighted_selection_statistical_validation() {
    // Statistical validation of weighted selection using chi-squared test
    //
    // This test verifies that weighted selection actually produces a distribution
    // that matches the configured weights, not just that it CAN select each endpoint.
    //
    // Setup: Two endpoints with 1:3 weight ratio (0.25 vs 0.75)
    // Run 10,000 selections and verify distribution matches weights statistically
    // Use chi-squared test with significance level α = 0.05

    let toml_config = r#"
[server]
host = "127.0.0.1"
port = 3000
request_timeout_seconds = 30

[[models.fast]]
name = "fast-light"
base_url = "http://localhost:1234/v1"
max_tokens = 2048
weight = 1.0
priority = 1

[[models.fast]]
name = "fast-heavy"
base_url = "http://localhost:1235/v1"
max_tokens = 2048
weight = 3.0
priority = 1

[[models.balanced]]
name = "balanced-1"
base_url = "http://localhost:1236/v1"
max_tokens = 4096

[[models.deep]]
name = "deep-1"
base_url = "http://localhost:1237/v1"
max_tokens = 8192

[routing]
strategy = "rule"
router_tier = "balanced"
"#;
    let config: Config = toml::from_str(toml_config).expect("should parse TOML");
    let selector = ModelSelector::new(Arc::new(config), test_metrics());

    // Run 10,000 selections
    const SAMPLE_SIZE: usize = 10_000;
    let mut light_count = 0;
    let mut heavy_count = 0;

    let no_exclude = ExclusionSet::new();
    for _ in 0..SAMPLE_SIZE {
        let endpoint = selector
            .select(TargetModel::Fast, &no_exclude)
            .await
            .unwrap();

        match endpoint.name() {
            "fast-light" => light_count += 1,
            "fast-heavy" => heavy_count += 1,
            other => panic!("Unexpected endpoint selected: {}", other),
        }
    }

    // Calculate expected counts based on weights
    // Total weight = 1.0 + 3.0 = 4.0
    // Expected light: 10,000 * (1.0 / 4.0) = 2,500
    // Expected heavy: 10,000 * (3.0 / 4.0) = 7,500
    let expected_light = SAMPLE_SIZE as f64 * 0.25;
    let expected_heavy = SAMPLE_SIZE as f64 * 0.75;

    // Chi-squared test: χ² = Σ((observed - expected)² / expected)
    let chi_squared = ((light_count as f64 - expected_light).powi(2) / expected_light)
        + ((heavy_count as f64 - expected_heavy).powi(2) / expected_heavy);

    // For 1 degree of freedom (2 categories - 1), critical value at α=0.05 is 3.841
    // If χ² < 3.841, we accept the null hypothesis (distribution matches weights)
    //
    // We use a more lenient threshold of 10.0 to account for random variation
    // in test runs while still catching gross distribution errors
    const CHI_SQUARED_THRESHOLD: f64 = 10.0;

    assert!(
        chi_squared < CHI_SQUARED_THRESHOLD,
        "Chi-squared test failed: χ² = {:.2} (threshold = {}). \
            Distribution does not match configured weights. \
            Observed: light={} ({:.1}%), heavy={} ({:.1}%). \
            Expected: light={:.0} (25.0%), heavy={:.0} (75.0%)",
        chi_squared,
        CHI_SQUARED_THRESHOLD,
        light_count,
        (light_count as f64 / SAMPLE_SIZE as f64) * 100.0,
        heavy_count,
        (heavy_count as f64 / SAMPLE_SIZE as f64) * 100.0,
        expected_light,
        expected_heavy
    );

    // Also verify we got a reasonable distribution (sanity check)
    // Light should be roughly 20-30% (2,000 - 3,000 selections)
    // Heavy should be roughly 70-80% (7,000 - 8,000 selections)
    assert!(
        (2_000..=3_000).contains(&light_count),
        "Light endpoint selected {} times, expected ~2,500 (20-30%)",
        light_count
    );
    assert!(
        (7_000..=8_000).contains(&heavy_count),
        "Heavy endpoint selected {} times, expected ~7,500 (70-80%)",
        heavy_count
    );

    println!(
        "✓ Statistical validation passed: χ² = {:.2}, light={} ({:.1}%), heavy={} ({:.1}%)",
        chi_squared,
        light_count,
        (light_count as f64 / SAMPLE_SIZE as f64) * 100.0,
        heavy_count,
        (heavy_count as f64 / SAMPLE_SIZE as f64) * 100.0
    );
}