llm-bench 0.3.1

Send the same prompts to OpenAI, Anthropic, Ollama, OpenRouter, Gemini or any OpenAI-compatible server and compare time to first token, latency percentiles, tokens per second and cost; CLI and library
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
//! # Module: Runner
//!
//! Run every (provider, prompt, run) combination concurrently, bounded by a
//! semaphore, and collect the results and the failures. Failed requests can
//! be retried with backoff (`--retries`), using the `backon` crate.
//!
//! ## Guarantees
//! - Concurrent calls are bounded by `BenchConfig::concurrency`.
//! - Every task failure is captured as a [`BenchFailure`], never silently dropped.
//! - Progress callbacks are invoked once per completed task.
//! - This module never panics.

use std::sync::atomic::{AtomicU32, AtomicUsize, Ordering};
use std::sync::Arc;
use std::time::Duration;

use backon::{ExponentialBuilder, Retryable};
use futures::future::join_all;
use reqwest::Client;
use tokio::sync::Semaphore;
use tracing::{debug, instrument};

use crate::error::BenchError;
use crate::providers::{run_anthropic, run_openai};
use crate::types::{BenchConfig, BenchFailure, BenchResult, ProviderConfig};

/// Official OpenAI API base URL (used when no `--openai-base-url` is given).
pub const DEFAULT_OPENAI_BASE_URL: &str = "https://api.openai.com";
/// Official Anthropic API base URL.
pub const DEFAULT_ANTHROPIC_BASE_URL: &str = "https://api.anthropic.com";
/// Local Ollama server.
pub const DEFAULT_OLLAMA_BASE_URL: &str = "http://localhost:11434";
/// OpenRouter's OpenAI-compatible API.
pub const DEFAULT_OPENROUTER_BASE_URL: &str = "https://openrouter.ai/api/v1";
/// Google Gemini's OpenAI-compatible API.
pub const DEFAULT_GEMINI_BASE_URL: &str =
    "https://generativelanguage.googleapis.com/v1beta/openai";

/// Longest wait honoured from a `Retry-After` header.
const MAX_RETRY_AFTER: Duration = Duration::from_secs(60);

//  Runner

/// Drives a full benchmark run and returns all individual results.
pub struct BenchRunner {
    client: Client,
}

impl BenchRunner {
    /// Construct a runner with a shared HTTP client (120 s timeout per request).
    ///
    /// # Panics
    /// This function never panics.
    pub fn new() -> Result<Self, BenchError> {
        let client = Client::builder()
            .timeout(Duration::from_secs(120))
            .build()
            .map_err(BenchError::Http)?;
        Ok(Self { client })
    }

    /// Run the full benchmark suite described by `config`.
    ///
    /// Returns the successful results (one per provider, prompt and run)
    /// and one [`BenchFailure`] per request that failed, so callers can
    /// report real success rates. `on_progress` is invoked after each task
    /// completes with `(completed, total)`.
    ///
    /// # Panics
    /// This function never panics.
    #[instrument(skip(self, config, on_progress))]
    pub async fn run_detailed<F>(
        &self,
        config: &BenchConfig,
        on_progress: F,
    ) -> Result<(Vec<BenchResult>, Vec<BenchFailure>), BenchError>
    where
        F: Fn(usize, usize) + Send + Sync + 'static,
    {
        let semaphore = Arc::new(Semaphore::new(config.concurrency.max(1)));
        let on_progress = Arc::new(on_progress);

        let mut tasks = Vec::new();
        for provider in &config.providers {
            for prompt in &config.prompts {
                for run_idx in 0..config.runs_per_prompt {
                    tasks.push((provider.clone(), prompt.clone(), run_idx));
                }
            }
        }

        // Warm-up requests: sent one at a time per model, results discarded.
        for provider in &config.providers {
            for _ in 0..config.warmup {
                let prompt = config.prompts.first().map(String::as_str).unwrap_or("");
                let r = dispatch_call(&self.client, provider, prompt, 0, config.stream).await;
                debug!(model = %provider.model, ok = r.is_ok(), "warm-up request");
            }
        }

        let total = tasks.len();
        debug!(total_tasks = total, "starting benchmark run");

        let completed = Arc::new(AtomicUsize::new(0));
        let (stream, retries) = (config.stream, config.retries);

        let futures: Vec<_> = tasks
            .into_iter()
            .map(|(provider, prompt, run_idx)| {
                let sem = Arc::clone(&semaphore);
                let cb = Arc::clone(&on_progress);
                let done = Arc::clone(&completed);
                let client = self.client.clone();

                tokio::spawn(async move {
                    let _permit = sem.acquire().await.map_err(|e| BenchError::Concurrency {
                        reason: e.to_string(),
                    })?;

                    let result =
                        call_with_retries(&client, &provider, &prompt, run_idx, stream, retries)
                            .await;

                    let n = done.fetch_add(1, Ordering::Relaxed) + 1;
                    cb(n, total);

                    Ok::<_, BenchError>(result.map_err(|e| BenchFailure {
                        provider: provider.name.clone(),
                        model: provider.model.clone(),
                        error: e.to_string(),
                    }))
                })
            })
            .collect();

        let join_results = join_all(futures).await;

        let mut results = Vec::with_capacity(join_results.len());
        let mut failures = Vec::new();
        for jr in join_results {
            match jr {
                Ok(Ok(Ok(r))) => results.push(r),
                Ok(Ok(Err(f))) => {
                    debug!(error = %f.error, "benchmark task returned error");
                    failures.push(f);
                }
                Ok(Err(e)) => return Err(e),
                Err(e) => {
                    return Err(BenchError::Concurrency {
                        reason: format!("task panicked or was cancelled: {e}"),
                    });
                }
            }
        }

        Ok((results, failures))
    }
}

/// Whether a failed request is worth retrying: rate limits, timeouts,
/// server errors and connection failures. Bad keys, unknown models and
/// malformed responses are not.
pub fn is_retryable(e: &BenchError) -> bool {
    match e {
        BenchError::RateLimited { .. } => true,
        BenchError::ApiError { status, .. } => {
            matches!(status, 408 | 409 | 500 | 502 | 503 | 504 | 529)
        }
        BenchError::Http(e) => e.is_timeout() || e.is_connect(),
        _ => false,
    }
}

/// One request with up to `retries` retries (exponential backoff with
/// jitter, starting at 500 ms; a `Retry-After` on a 429 sets the wait, up
/// to 60 s). Latency is that of the attempt that succeeded.
async fn call_with_retries(
    client: &Client,
    provider: &ProviderConfig,
    prompt: &str,
    run_idx: u32,
    stream: bool,
    retries: u32,
) -> Result<BenchResult, BenchError> {
    let attempts = AtomicU32::new(0);
    let backoff = ExponentialBuilder::default()
        .with_min_delay(Duration::from_millis(500))
        .with_max_delay(Duration::from_secs(30))
        .with_max_times(retries as usize)
        .with_jitter();
    let mut result = (|| {
        attempts.fetch_add(1, Ordering::Relaxed);
        dispatch_call(client, provider, prompt, run_idx, stream)
    })
    .retry(backoff)
    .when(is_retryable)
    .adjust(|e: &BenchError, dur| match (dur, e) {
        (None, _) => None,
        (
            Some(_),
            BenchError::RateLimited {
                retry_after_secs: Some(s),
                ..
            },
        ) => Some(Duration::from_secs(*s).min(MAX_RETRY_AFTER)),
        (d, _) => d,
    })
    .await;
    if let Ok(r) = result.as_mut() {
        r.retries = attempts.load(Ordering::Relaxed).saturating_sub(1);
    }
    result
}

/// The base URL a provider uses when none was configured.
pub fn default_base_url(provider: &str) -> Option<&'static str> {
    Some(match provider {
        "openai" => DEFAULT_OPENAI_BASE_URL,
        "anthropic" => DEFAULT_ANTHROPIC_BASE_URL,
        "ollama" => DEFAULT_OLLAMA_BASE_URL,
        "openrouter" => DEFAULT_OPENROUTER_BASE_URL,
        "gemini" => DEFAULT_GEMINI_BASE_URL,
        _ => return None,
    })
}

/// Send one request to the right API for `provider.name`.
async fn dispatch_call(
    client: &Client,
    provider: &ProviderConfig,
    prompt: &str,
    run_idx: u32,
    stream: bool,
) -> Result<BenchResult, BenchError> {
    let Some(default) = default_base_url(&provider.name) else {
        return Err(BenchError::InvalidConfig {
            reason: format!(
                "unknown provider '{}'; supported: openai, anthropic, ollama, openrouter, gemini",
                provider.name
            ),
        });
    };
    let url = if provider.base_url.is_empty() {
        default.to_owned()
    } else {
        provider.base_url.clone()
    };
    if provider.name == "anthropic" {
        run_anthropic(client, provider, &url, prompt, run_idx, stream).await
    } else {
        run_openai(client, provider, &url, prompt, run_idx, stream).await
    }
}

//  Tests

#[cfg(test)]
mod tests {
    use super::*;
    use wiremock::matchers::{method, path};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    use crate::types::BenchConfig;

    fn openai_provider(base_url: &str) -> ProviderConfig {
        // We abuse the api_key field to also carry the base_url in tests.
        // In production the base_url is hardcoded; in tests we override via a
        // helper that calls run_openai directly with the mock server URI.
        let _ = base_url; // used in direct provider tests, not runner tests
        ProviderConfig {
            name: "openai".into(),
            model: "gpt-4o-mini".into(),
            api_key: "test-key".into(),
            base_url: String::new(),
            max_tokens: 32,
        }
    }

    //  BenchRunner::new

    #[test]
    fn test_bench_runner_new_succeeds() {
        let runner = BenchRunner::new();
        assert!(runner.is_ok(), "BenchRunner::new should succeed");
    }

    //  dispatch_call unknown provider

    #[tokio::test]
    async fn test_dispatch_call_unknown_provider_returns_invalid_config() {
        let client = Client::new();
        let provider = ProviderConfig {
            name: "unknown-provider".into(),
            model: "model-x".into(),
            api_key: "key".into(),
            base_url: String::new(),
            max_tokens: 32,
        };
        let result = dispatch_call(&client, &provider, "hello", 0, false).await;
        assert!(result.is_err());
        assert!(
            matches!(result.unwrap_err(), BenchError::InvalidConfig { .. }),
            "expected InvalidConfig for unknown provider"
        );
    }

    //  Full runner with mock server

    // Note: runner.run() hardcodes API base URLs for production use.
    // We test the runner's concurrency and aggregation logic using the
    // providers directly with mock servers (see providers.rs tests).
    // Here we verify the runner builds a correct task list.

    #[tokio::test]
    async fn test_runner_task_count_equals_providers_times_prompts_times_runs() {
        // We can't intercept the hardcoded URLs in runner.run(), so we test
        // the math by checking the formula directly.
        let num_providers = 2usize;
        let num_prompts = 3usize;
        let runs_per_prompt = 4u32;
        let expected = num_providers * num_prompts * runs_per_prompt as usize;
        assert_eq!(expected, 24);
    }

    #[tokio::test]
    async fn test_runner_empty_providers_returns_empty_results() {
        let runner = BenchRunner::new().unwrap_or_else(|_| unreachable!());
        let config = BenchConfig {
            prompts: vec!["hello".into()],
            runs_per_prompt: 2,
            concurrency: 4,
            providers: vec![], // no providers → no tasks
            stream: false,
            retries: 0,
            warmup: 0,
        };
        let results = runner
            .run_detailed(&config, |_, _| {})
            .await
            .map(|(r, _)| r);
        assert!(results.is_ok());
        assert!(results.unwrap_or_default().is_empty());
    }

    #[tokio::test]
    async fn test_runner_empty_prompts_returns_empty_results() {
        let runner = BenchRunner::new().unwrap_or_else(|_| unreachable!());
        let config = BenchConfig {
            prompts: vec![], // no prompts → no tasks
            runs_per_prompt: 2,
            concurrency: 4,
            providers: vec![openai_provider("")],
            stream: false,
            retries: 0,
            warmup: 0,
        };
        let results = runner
            .run_detailed(&config, |_, _| {})
            .await
            .map(|(r, _)| r);
        assert!(results.is_ok());
        assert!(results.unwrap_or_default().is_empty());
    }

    #[tokio::test]
    async fn test_runner_progress_callback_called_correct_times() {
        // Use a mock that returns 200 so tasks succeed.
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/v1/chat/completions"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "choices": [{"message": {"role": "assistant", "content": "hi"}}],
                "usage": {"prompt_tokens": 5, "completion_tokens": 3}
            })))
            .mount(&server)
            .await;

        // We can't inject the mock URL into runner.run() since it hardcodes the
        // production URL.  Instead we test the progress counter logic directly:
        let call_count = Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let cc = Arc::clone(&call_count);
        let cb = move |_done: usize, _total: usize| {
            cc.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        };

        // Simulate three task completions
        for i in 1..=3usize {
            cb(i, 3);
        }

        assert_eq!(call_count.load(std::sync::atomic::Ordering::Relaxed), 3);
    }

    //  Semaphore concurrency cap

    #[tokio::test]
    async fn test_semaphore_limits_concurrency() {
        // Build a semaphore with capacity 2 and acquire all 2 permits.
        // The 3rd acquisition must not succeed without releasing one.
        let sem = Arc::new(Semaphore::new(2));
        let p1 = sem.try_acquire();
        let p2 = sem.try_acquire();
        let p3 = sem.try_acquire();

        assert!(p1.is_ok(), "first permit should succeed");
        assert!(p2.is_ok(), "second permit should succeed");
        assert!(p3.is_err(), "third permit should fail (semaphore full)");
    }

    //  Provider config validation

    #[test]
    fn test_bench_config_with_multiple_providers_is_valid() {
        let config = BenchConfig {
            prompts: vec!["p1".into()],
            runs_per_prompt: 1,
            concurrency: 2,
            providers: vec![
                ProviderConfig {
                    name: "openai".into(),
                    model: "gpt-4o-mini".into(),
                    api_key: "k1".into(),
                    base_url: String::new(),
                    max_tokens: 128,
                },
                ProviderConfig {
                    name: "anthropic".into(),
                    model: "claude-haiku-4-5".into(),
                    api_key: "k2".into(),
                    base_url: String::new(),
                    max_tokens: 128,
                },
            ],
            stream: false,
            retries: 0,
            warmup: 0,
        };
        assert_eq!(config.providers.len(), 2);
    }

    #[tokio::test]
    async fn test_dispatch_openai_hits_openai_endpoint() {
        let server = MockServer::start().await;

        Mock::given(method("POST"))
            .and(path("/v1/chat/completions"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "choices": [{"message": {"role": "assistant", "content": "ok"}}],
                "usage": {"prompt_tokens": 2, "completion_tokens": 1}
            })))
            .mount(&server)
            .await;

        let client = Client::new();
        let provider = ProviderConfig {
            name: "openai".into(),
            model: "gpt-4o-mini".into(),
            api_key: "k".into(),
            base_url: String::new(),
            max_tokens: 16,
        };
        // Direct call to run_openai with mock base URL
        let result = run_openai(&client, &provider, &server.uri(), "hi", 0, false).await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_dispatch_anthropic_hits_anthropic_endpoint() {
        let server = MockServer::start().await;

        Mock::given(method("POST"))
            .and(path("/v1/messages"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "content": [{"type": "text", "text": "ok"}],
                "usage": {"input_tokens": 2, "output_tokens": 1}
            })))
            .mount(&server)
            .await;

        let client = Client::new();
        let provider = ProviderConfig {
            name: "anthropic".into(),
            model: "claude-haiku-4-5".into(),
            api_key: "k".into(),
            base_url: String::new(),
            max_tokens: 16,
        };
        let result = run_anthropic(&client, &provider, &server.uri(), "hi", 0, false).await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_run_detailed_uses_custom_base_url_and_counts_failures() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/v1/chat/completions"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "choices": [{"message": {"role": "assistant", "content": "ok"}}],
                "usage": {"prompt_tokens": 4, "completion_tokens": 2}
            })))
            .mount(&server)
            .await;

        let good = ProviderConfig {
            name: "openai".into(),
            model: "local-model".into(),
            api_key: String::new(),
            base_url: server.uri(),
            max_tokens: 16,
        };
        let bad = ProviderConfig {
            name: "anthropic".into(),
            model: "claude-haiku-4-5".into(),
            api_key: String::new(),
            base_url: server.uri(), // no /v1/messages mock: 404
            max_tokens: 16,
        };
        let config = BenchConfig {
            prompts: vec!["hi".into()],
            runs_per_prompt: 2,
            concurrency: 2,
            providers: vec![good, bad],
            stream: false,
            retries: 0,
            warmup: 0,
        };
        let runner = BenchRunner::new().unwrap_or_else(|_| unreachable!());
        let (results, failures) = runner
            .run_detailed(&config, |_, _| {})
            .await
            .unwrap_or_default();
        assert_eq!(results.len(), 2);
        assert_eq!(failures.len(), 2);
        assert!(failures.iter().all(|f| f.error.contains("404")));
    }

    //  Atomic progress tracking

    #[test]
    fn test_atomic_counter_increments_correctly() {
        let counter = Arc::new(std::sync::atomic::AtomicUsize::new(0));
        for _ in 0..10 {
            counter.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        }
        assert_eq!(counter.load(std::sync::atomic::Ordering::Relaxed), 10);
    }

    //  Retries

    fn local_openai(server: &MockServer) -> ProviderConfig {
        ProviderConfig {
            name: "openai".into(),
            model: "local".into(),
            api_key: String::new(),
            base_url: server.uri(),
            max_tokens: 8,
        }
    }

    fn ok_body() -> ResponseTemplate {
        ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "choices": [{"message": {"role": "assistant", "content": "ok"}}],
            "usage": {"prompt_tokens": 1, "completion_tokens": 1}
        }))
    }

    fn one_request(provider: ProviderConfig, retries: u32) -> BenchConfig {
        BenchConfig {
            prompts: vec!["hi".into()],
            runs_per_prompt: 1,
            concurrency: 1,
            providers: vec![provider],
            stream: false,
            retries,
            warmup: 0,
        }
    }

    #[tokio::test]
    async fn test_rate_limit_is_retried_after_retry_after() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/v1/chat/completions"))
            .respond_with(ResponseTemplate::new(429).insert_header("retry-after", "1"))
            .up_to_n_times(1)
            .expect(1)
            .mount(&server)
            .await;
        Mock::given(method("POST"))
            .and(path("/v1/chat/completions"))
            .respond_with(ok_body())
            .expect(1)
            .mount(&server)
            .await;

        let start = std::time::Instant::now();
        let (results, failures) = BenchRunner::new()
            .unwrap()
            .run_detailed(&one_request(local_openai(&server), 2), |_, _| {})
            .await
            .unwrap();
        assert_eq!((results.len(), failures.len()), (1, 0));
        assert_eq!(results[0].retries, 1);
        assert!(start.elapsed() >= Duration::from_millis(950), "{:?}", start.elapsed());
    }

    #[tokio::test]
    async fn test_without_retries_a_429_is_a_failure() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/v1/chat/completions"))
            .respond_with(ResponseTemplate::new(429))
            .expect(1)
            .mount(&server)
            .await;
        let (results, failures) = BenchRunner::new()
            .unwrap()
            .run_detailed(&one_request(local_openai(&server), 0), |_, _| {})
            .await
            .unwrap();
        assert_eq!((results.len(), failures.len()), (0, 1));
    }

    #[tokio::test]
    async fn test_server_errors_retry_but_bad_requests_do_not() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/v1/chat/completions"))
            .respond_with(ResponseTemplate::new(503))
            .expect(3)
            .mount(&server)
            .await;
        let (_, failures) = BenchRunner::new()
            .unwrap()
            .run_detailed(&one_request(local_openai(&server), 2), |_, _| {})
            .await
            .unwrap();
        assert_eq!(failures.len(), 1);
        assert!(failures[0].error.contains("503"), "{}", failures[0].error);

        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/v1/chat/completions"))
            .respond_with(ResponseTemplate::new(404))
            .expect(1)
            .mount(&server)
            .await;
        let (_, failures) = BenchRunner::new()
            .unwrap()
            .run_detailed(&one_request(local_openai(&server), 3), |_, _| {})
            .await
            .unwrap();
        assert_eq!(failures.len(), 1);
    }

    #[tokio::test]
    async fn test_transport_errors_say_why() {
        // Nothing listens on port 9 of localhost.
        let mut p = local_openai_unreachable();
        p.base_url = "http://127.0.0.1:9".into();
        let (_, failures) = BenchRunner::new()
            .unwrap()
            .run_detailed(&one_request(p, 0), |_, _| {})
            .await
            .unwrap();
        let msg = &failures[0].error;
        assert!(msg.contains("error sending request"), "{msg}");
        // The cause chain is included (connection refused / actively refused).
        assert!(msg.matches(": ").count() >= 2, "{msg}");
    }

    fn local_openai_unreachable() -> ProviderConfig {
        ProviderConfig {
            name: "openai".into(),
            model: "local".into(),
            api_key: String::new(),
            base_url: String::new(),
            max_tokens: 8,
        }
    }

    #[test]
    fn test_default_base_urls() {
        assert_eq!(default_base_url("ollama"), Some(DEFAULT_OLLAMA_BASE_URL));
        assert_eq!(default_base_url("gemini"), Some(DEFAULT_GEMINI_BASE_URL));
        assert_eq!(default_base_url("nope"), None);
    }
}