zc2 0.0.53

P2P compute broker with yen-denominated billing, WAL, and broker mesh support
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
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
//! `zc serve --general` — the on-demand any-model loader (Phase 2).
//!
//! A general provider registers `served_models: ["*"]` and must therefore be
//! able to serve whatever model a request names. This module is the backing
//! for that promise: a small HTTP server that accepts the same OpenAI-style
//! `POST /v1/chat/completions` a broker forwards to any provider, reads the
//! `model` field (the broker sends the MODEL UUID to general providers —
//! specialized providers get the worker name, which a single-model
//! llama-server ignores), lazily downloads the gguf and launches a
//! `llama-server` for it, then proxies the request through.
//!
//! Loaded models are capped (`ZAKURO_GENERAL_MAX_MODELS`, default 2): at the
//! cap the least-recently-used server is killed before the next one spawns,
//! because each resident llama-server holds its whole model in memory and an
//! unbounded map is an OOM with extra steps.
//!
//! In-flight requests are capped too (`ZAKURO_GENERAL_MAX_CONCURRENT`,
//! default 8), and a request over that cap is *refused*, not queued — see
//! [`GeneralServerConfig`] and [`serve_general_on`] for why.

use std::collections::HashMap;
use std::process::Child;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};

use axum::response::IntoResponse;

/// Default cap on concurrently loaded llama-servers.
const DEFAULT_MAX_LOADED: usize = 2;

/// Default cap on requests in flight through the front server at once.
///
/// This is an admission limit, not a throughput knob. Real throughput is set
/// by the backends: at most `ZAKURO_GENERAL_MAX_MODELS` llama-servers, each
/// with its own slot count. Eight gives every resident backend a few requests
/// of depth — enough to absorb a burst from a broker whose forward client
/// keeps up to 32 idle connections per host — while keeping the worst case
/// finite and stateable: eight threads, each holding at most
/// [`DEFAULT_UPSTREAM_TIMEOUT`].
const DEFAULT_MAX_CONCURRENT: usize = 8;

/// How long the front server waits on a backend llama-server.
///
/// Unchanged from the serial server: it is a *single request's* budget, not a
/// queue's. Inference is slow and first-token on a cold model slower, and
/// nothing about serving requests concurrently makes one request finish
/// sooner. What concurrency changes is the exposure this budget creates —
/// serially it was one request at a time, so it capped everything; now it is
/// per request, which is exactly what [`DEFAULT_MAX_CONCURRENT`] bounds.
const DEFAULT_UPSTREAM_TIMEOUT: Duration = Duration::from_secs(600);

/// Largest request body the front server will read. A chat-completions body
/// is orders of magnitude below this; the cap exists because reading an
/// unbounded body from the network into memory is not a thing to do.
const MAX_BODY_BYTES: usize = 64 * 1024 * 1024;

/// How long to wait for a freshly spawned llama-server to answer /health.
/// Model load time dominates (GBs from disk), so this is generous.
const READY_TIMEOUT: Duration = Duration::from_secs(300);

/// One resident model: its llama-server child and the port it listens on.
struct Loaded {
    port: u16,
    child: Child,
    last_used: Instant,
}

/// Hooks the loader calls to touch the outside world, injected so tests can
/// run the eviction/reuse bookkeeping without a marketplace, a filesystem,
/// or a real llama-server.
///
/// `Sync` as well as `Send`: the front server shares one loader across the
/// threads serving concurrent requests. Every production hook closes over
/// `Sync` state already (a pooled `ureq::Agent`, a couple of `String`s), so
/// this costs nothing.
pub struct LoaderHooks {
    /// Resolve+download the model's gguf, returning its local path.
    pub fetch: FetchFn,
    /// Spawn a llama-server for `(gguf_path, port)`.
    pub spawn: SpawnFn,
    /// Block until the server on `port` answers /health (or time out).
    pub wait_ready: Box<dyn Fn(u16) -> Result<(), String> + Send + Sync>,
}

/// Resolve+download a model's gguf by uuid (see `LoaderHooks::fetch`).
pub type FetchFn = Box<dyn Fn(&str) -> Result<std::path::PathBuf, String> + Send + Sync>;
/// Spawn a backend server for `(gguf_path, port)` (see `LoaderHooks::spawn`).
pub type SpawnFn = Box<dyn Fn(&std::path::Path, u16) -> Result<Child, String> + Send + Sync>;

/// The on-demand model loader: uuid → running llama-server, LRU-capped.
pub struct GeneralLoader {
    hooks: LoaderHooks,
    state: Mutex<LoaderState>,
}

struct LoaderState {
    loaded: HashMap<String, Loaded>,
    next_port: u16,
    max_loaded: usize,
}

impl GeneralLoader {
    /// `first_backend_port` is the first port handed to a spawned
    /// llama-server; each subsequent spawn increments from there (ports are
    /// not reused after eviction — a killed server's socket may linger in
    /// TIME_WAIT, and a u16 of headroom costs nothing).
    pub fn new(hooks: LoaderHooks, first_backend_port: u16, max_loaded: usize) -> Self {
        GeneralLoader {
            hooks,
            state: Mutex::new(LoaderState {
                loaded: HashMap::new(),
                next_port: first_backend_port,
                max_loaded: max_loaded.max(1),
            }),
        }
    }

    /// Cap from `ZAKURO_GENERAL_MAX_MODELS`, defaulting when unset/garbage.
    pub fn max_loaded_from_env() -> usize {
        std::env::var("ZAKURO_GENERAL_MAX_MODELS")
            .ok()
            .and_then(|v| v.parse::<usize>().ok())
            .filter(|n| *n >= 1)
            .unwrap_or(DEFAULT_MAX_LOADED)
    }

    /// Make sure `model_uuid` has a live llama-server; return its port.
    ///
    /// Holds the state lock across fetch/spawn/wait on purpose: two
    /// concurrent first-requests for the same (or even different) models
    /// serialize rather than both spawning — a second multi-GB model load
    /// racing the first would only slow both down, and correctness of the
    /// LRU cap depends on evict-then-spawn being atomic.
    ///
    /// That is still true now that the front server is concurrent, and it is
    /// the one thing that remains serialized: a *cold* load blocks other
    /// requests for as long as it takes (up to [`READY_TIMEOUT`]). It stays
    /// that way deliberately — it is a capacity decision about multi-GB
    /// models, not an accident of the transport — and it is bounded by the
    /// front server's admission limit, so the caller that cannot be admitted
    /// is told so rather than left waiting.
    pub fn ensure_loaded(&self, model_uuid: &str) -> Result<u16, String> {
        let mut st = self
            .state
            .lock()
            .map_err(|_| "loader state poisoned".to_string())?;

        // Already resident and still alive? (A crashed llama-server must be
        // respawned, not proxied into — try_wait() is Some(_) once exited.)
        if let Some(entry) = st.loaded.get_mut(model_uuid) {
            let alive = entry.child.try_wait().map(|x| x.is_none()).unwrap_or(false);
            if alive {
                entry.last_used = Instant::now();
                return Ok(entry.port);
            }
            st.loaded.remove(model_uuid);
        }

        // At the cap: kill the least-recently-used resident first.
        while st.loaded.len() >= st.max_loaded {
            let lru = st
                .loaded
                .iter()
                .min_by_key(|(_, l)| l.last_used)
                .map(|(k, _)| k.clone());
            match lru {
                Some(uuid) => {
                    if let Some(mut old) = st.loaded.remove(&uuid) {
                        let _ = old.child.kill();
                        let _ = old.child.wait();
                    }
                }
                None => break,
            }
        }

        let gguf = (self.hooks.fetch)(model_uuid)?;
        let port = st.next_port;
        st.next_port = st.next_port.wrapping_add(1);
        let mut child = (self.hooks.spawn)(&gguf, port)?;
        if let Err(e) = (self.hooks.wait_ready)(port) {
            let _ = child.kill();
            let _ = child.wait();
            return Err(format!(
                "llama-server for {model_uuid} never became ready: {e}"
            ));
        }
        st.loaded.insert(
            model_uuid.to_string(),
            Loaded {
                port,
                child,
                last_used: Instant::now(),
            },
        );
        Ok(port)
    }

    /// Which models are currently resident (test/observability helper).
    pub fn resident(&self) -> Vec<String> {
        self.state
            .lock()
            .map(|st| st.loaded.keys().cloned().collect())
            .unwrap_or_default()
    }
}

/// Production hooks: marketplace fetch, real llama-server spawn, health poll.
pub fn production_hooks(
    agent: ureq::Agent,
    api_url: String,
    auth_bearer: Option<String>,
) -> LoaderHooks {
    LoaderHooks {
        fetch: Box::new(move |uuid| {
            crate::serve::fetch_model_gguf(&agent, &api_url, uuid, auth_bearer.as_deref())
        }),
        spawn: Box::new(|gguf, port| {
            std::process::Command::new("llama-server")
                .arg("--model")
                .arg(gguf)
                .arg("--host")
                .arg("0.0.0.0")
                .arg("--port")
                .arg(port.to_string())
                .spawn()
                .map_err(|e| format!("spawning llama-server: {e} (is it installed and on PATH?)"))
        }),
        wait_ready: Box::new(|port| {
            let deadline = Instant::now() + READY_TIMEOUT;
            let probe = ureq::Agent::new_with_config(
                ureq::Agent::config_builder()
                    .timeout_global(Some(Duration::from_secs(2)))
                    .build(),
            );
            loop {
                if probe
                    .get(&format!("http://127.0.0.1:{port}/health"))
                    .call()
                    .is_ok()
                {
                    return Ok(());
                }
                if Instant::now() >= deadline {
                    return Err(format!("no /health within {}s", READY_TIMEOUT.as_secs()));
                }
                std::thread::sleep(Duration::from_millis(500));
            }
        }),
    }
}

/// Extract the model uuid from a chat-completions request body's `model`
/// field. The broker addresses a general provider by uuid; accept the zc://
/// spellings too so a direct curl against the provider also works.
pub fn model_uuid_from_body(body: &serde_json::Value) -> Option<String> {
    body.get("model")
        .and_then(|m| m.as_str())
        .and_then(crate::model_uri::parse_model_uri)
}

/// How the front server is allowed to behave: how many requests it will have
/// in flight at once, and how long it waits on a backend for each.
///
/// `max_concurrent` is the load-shedding decision. Over it, a caller gets an
/// immediate 503 with `Retry-After` rather than being queued somewhere it
/// cannot see. That is the whole of #300: the complaint was never "too slow",
/// it was "no answer and no error", and a queue a caller cannot observe is
/// indistinguishable from a hang.
pub struct GeneralServerConfig {
    /// Chat completions in flight at once before the provider starts refusing.
    pub max_concurrent: usize,
    /// Per-request budget for the proxied call to the backend llama-server.
    pub upstream_timeout: Duration,
}

impl Default for GeneralServerConfig {
    fn default() -> Self {
        GeneralServerConfig {
            max_concurrent: DEFAULT_MAX_CONCURRENT,
            upstream_timeout: DEFAULT_UPSTREAM_TIMEOUT,
        }
    }
}

impl GeneralServerConfig {
    /// Config from the environment (`ZAKURO_GENERAL_MAX_CONCURRENT`).
    pub fn from_env() -> Self {
        GeneralServerConfig {
            max_concurrent: max_concurrent_from(
                std::env::var("ZAKURO_GENERAL_MAX_CONCURRENT")
                    .ok()
                    .as_deref(),
            ),
            ..GeneralServerConfig::default()
        }
    }
}

/// Parse the concurrency cap, defaulting when unset or garbage. Zero is a
/// server that refuses everything, so it counts as garbage too.
pub fn max_concurrent_from(raw: Option<&str>) -> usize {
    raw.and_then(|v| v.trim().parse::<usize>().ok())
        .filter(|n| *n >= 1)
        .unwrap_or(DEFAULT_MAX_CONCURRENT)
}

/// Everything a request needs, shared across the threads serving them.
struct Front {
    loader: GeneralLoader,
    proxy: ureq::Agent,
    /// Admission permits — one per in-flight completion.
    permits: Arc<tokio::sync::Semaphore>,
    max_concurrent: usize,
}

/// Run the general provider's front server (blocking): accept the broker's
/// forwarded chat completions on `bind_port`, load on demand, proxy through.
pub fn run_general_server(loader: GeneralLoader, bind_port: u16) -> Result<(), String> {
    let listener = std::net::TcpListener::bind(("0.0.0.0", bind_port))
        .map_err(|e| format!("binding general provider on :{bind_port}: {e}"))?;
    let config = GeneralServerConfig::from_env();
    println!(
        "  general provider listening on :{bind_port} \
         (on-demand model loading, up to {} requests in flight)",
        config.max_concurrent
    );
    serve_general_on(listener, loader, config)
}

/// The front server proper, on an already-bound listener so a test can take an
/// ephemeral port and a caller can choose the config.
///
/// **Why axum/tokio and not the obvious alternatives.** The old server was
/// `for request in server.incoming_requests()` — `tiny_http`'s serial
/// iterator, one request at a time on this thread, with a multi-minute
/// inference behind each. Three shapes could replace it:
///
/// - *More `tiny_http`.* Calling `recv()` from N threads buys handler
///   concurrency and leaves the real hazard in place: `tiny_http` dispatches
///   each accepted connection through a `TaskPool` whose `spawn` reads a
///   `waiting_tasks` counter a just-notified thread has not decremented yet,
///   so a burst can leave a connection queued — *unread*, not merely answered
///   late — until an existing connection closes, and below `MIN_THREADS` the
///   waiter blocks on an untimed condvar. #265 measured exactly that. Nor can
///   a `tiny_http` server shed load by hanging up: `Response::add_header`
///   silently drops `Connection`, so `Connection: close` never reaches the
///   wire. Ruled out.
/// - *An accept loop with a thread per connection over a hand-rolled
///   HTTP/1.1 reader/writer*, which is what #265 did for the test fixtures.
///   Right for a fixture, wrong here: that reader honours `Content-Length`
///   and ignores `Transfer-Encoding: chunked`, has no header-size or
///   header-count limit and no read timeout, so one slow sender holds a
///   thread indefinitely. A fixture's peer is the test; this port is reached
///   from the network.
/// - *axum on tokio*, which is what the broker's own front end already is —
///   it left `tiny_http` for exactly this pairing, and the `tiny_http`
///   dependency is annotated in `Cargo.toml` as an interim frontend. hyper
///   owns the HTTP/1.1 parsing that the hand-rolled reader would have to get
///   right, connection handling is per-connection tasks with no pool to
///   misread, and admission control is a semaphore rather than a hope.
///
/// The blocking half — `ensure_loaded` holds a mutex across a multi-GB
/// download, and the proxy call is synchronous `ureq` — runs on
/// `spawn_blocking`, never on an async worker thread. The blocking pool is
/// sized to `max_concurrent`, and the semaphore admits at most that many, so
/// the pool can never build a queue of its own: the semaphore is the only
/// queue and it is the one that answers.
pub fn serve_general_on(
    listener: std::net::TcpListener,
    loader: GeneralLoader,
    config: GeneralServerConfig,
) -> Result<(), String> {
    let max_concurrent = config.max_concurrent.max(1);
    listener
        .set_nonblocking(true)
        .map_err(|e| format!("general provider listener: {e}"))?;

    let front = Arc::new(Front {
        loader,
        proxy: ureq::Agent::new_with_config(
            ureq::Agent::config_builder()
                .timeout_global(Some(config.upstream_timeout))
                .build(),
        ),
        permits: Arc::new(tokio::sync::Semaphore::new(max_concurrent)),
        max_concurrent,
    });

    // Two async workers: everything they do is parse a request line and move
    // bytes — the work that costs anything is on the blocking pool.
    let runtime = tokio::runtime::Builder::new_multi_thread()
        .worker_threads(2)
        .max_blocking_threads(max_concurrent)
        .enable_all()
        .build()
        .map_err(|e| format!("general provider runtime: {e}"))?;

    runtime.block_on(async move {
        let listener = tokio::net::TcpListener::from_std(listener)
            .map_err(|e| format!("general provider listener: {e}"))?;
        let app = axum::Router::new()
            .fallback(axum::routing::any(route))
            .with_state(front);
        axum::serve(listener, app)
            .await
            .map_err(|e| format!("general provider server: {e}"))
    })
}

/// One request. Routing mirrors the serial server's: `/health` unconditionally,
/// anything under `/v1/chat/completions` proxied, everything else a 404.
async fn route(
    axum::extract::State(front): axum::extract::State<Arc<Front>>,
    request: axum::extract::Request,
) -> axum::response::Response {
    let (parts, body) = request.into_parts();
    let path = parts.uri.path().to_string();

    // Answered without touching the loader and without an admission permit.
    // The broker expires a worker on a staleness clock, so a provider that
    // cannot say "ok" during a ten-minute inference de-registers itself in
    // the middle of serving one.
    if path == "/health" {
        return json_response(200, serde_json::json!({"status": "ok"}));
    }
    if !path.starts_with("/v1/chat/completions") {
        return json_response(404, serde_json::json!({"error": "not found"}));
    }

    // Read the body first — it is cheap and async — so a permit is held only
    // for the expensive part, and never by a peer that is still uploading.
    let Ok(bytes) = axum::body::to_bytes(body, MAX_BODY_BYTES).await else {
        return json_response(400, serde_json::json!({"error": "unreadable body"}));
    };
    let Ok(body_str) = String::from_utf8(bytes.to_vec()) else {
        return json_response(400, serde_json::json!({"error": "unreadable body"}));
    };

    let Ok(permit) = front.permits.clone().try_acquire_owned() else {
        return busy_response(front.max_concurrent);
    };

    let work = front.clone();
    match tokio::task::spawn_blocking(move || {
        // The permit covers load-and-proxy and is released when this returns.
        let _permit = permit;
        complete(&work, &body_str)
    })
    .await
    {
        Ok((status, body)) => json_response(status, body),
        Err(_) => json_response(
            500,
            serde_json::json!({"error": "general provider handler panicked"}),
        ),
    }
}

/// Load the named model if needed and proxy the request to its llama-server.
/// Blocking from end to end — `ensure_loaded` may download gigabytes and the
/// proxy call may take minutes — so it only ever runs on the blocking pool.
fn complete(front: &Front, body_str: &str) -> (u16, serde_json::Value) {
    let body: serde_json::Value = match serde_json::from_str(body_str) {
        Ok(v) => v,
        Err(_) => return (400, serde_json::json!({"error": "invalid json"})),
    };
    let uuid = match model_uuid_from_body(&body) {
        Some(u) => u,
        None => {
            return (
                400,
                serde_json::json!({"error": "model field must be a model uuid (zc://<uuid> or bare)"}),
            )
        }
    };
    let port = match front.loader.ensure_loaded(&uuid) {
        Ok(p) => p,
        Err(e) => {
            eprintln!("  [GENERAL] load failed for {uuid}: {e}");
            return (
                503,
                serde_json::json!({"error": format!("model load failed: {e}")}),
            );
        }
    };
    match front
        .proxy
        .post(&format!("http://127.0.0.1:{port}/v1/chat/completions"))
        .header("Content-Type", "application/json")
        .send(body_str)
    {
        Ok(mut upstream) => {
            let status = upstream.status().as_u16();
            let text = upstream.body_mut().read_to_string().unwrap_or_default();
            let json: serde_json::Value = serde_json::from_str(&text)
                .unwrap_or_else(|_| serde_json::json!({"error": "bad upstream body"}));
            (status, json)
        }
        Err(e) => {
            eprintln!("  [GENERAL] proxy to :{port} failed: {e}");
            (502, serde_json::json!({"error": "backend request failed"}))
        }
    }
}

fn json_response(status: u16, body: serde_json::Value) -> axum::response::Response {
    let code = axum::http::StatusCode::from_u16(status)
        .unwrap_or(axum::http::StatusCode::INTERNAL_SERVER_ERROR);
    (
        code,
        [(
            axum::http::header::CONTENT_TYPE,
            axum::http::HeaderValue::from_static("application/json"),
        )],
        body.to_string(),
    )
        .into_response()
}

/// The over-the-limit answer. It is an answer, immediately, naming the limit —
/// a broker can retry it elsewhere, which is more than it can do with silence.
fn busy_response(max_concurrent: usize) -> axum::response::Response {
    let mut response = json_response(
        503,
        serde_json::json!({
            "error": format!(
                "general provider busy: {max_concurrent} requests already in flight"
            ),
            "code": "GENERAL_PROVIDER_BUSY",
        }),
    );
    response.headers_mut().insert(
        axum::http::header::RETRY_AFTER,
        axum::http::HeaderValue::from_static("1"),
    );
    response
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::atomic::{AtomicUsize, Ordering};
    use std::sync::Arc;

    /// A real child process that just sleeps — gives the loader a killable,
    /// liveness-checkable pid without any llama-server.
    fn sleeper() -> Child {
        std::process::Command::new("sleep")
            .arg("300")
            .spawn()
            .expect("spawn sleep")
    }

    fn test_loader(
        max: usize,
        fetches: Arc<AtomicUsize>,
        spawns: Arc<AtomicUsize>,
    ) -> GeneralLoader {
        let hooks = LoaderHooks {
            fetch: Box::new(move |_uuid| {
                fetches.fetch_add(1, Ordering::SeqCst);
                Ok(std::path::PathBuf::from("/dev/null"))
            }),
            spawn: Box::new(move |_path, _port| {
                spawns.fetch_add(1, Ordering::SeqCst);
                Ok(sleeper())
            }),
            wait_ready: Box::new(|_port| Ok(())),
        };
        GeneralLoader::new(hooks, 9500, max)
    }

    const A: &str = "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa";
    const B: &str = "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb";
    const C: &str = "cccccccc-cccc-cccc-cccc-cccccccccccc";

    #[test]
    fn second_request_reuses_the_resident_server() {
        let fetches = Arc::new(AtomicUsize::new(0));
        let spawns = Arc::new(AtomicUsize::new(0));
        let loader = test_loader(2, fetches.clone(), spawns.clone());
        let p1 = loader.ensure_loaded(A).unwrap();
        let p2 = loader.ensure_loaded(A).unwrap();
        assert_eq!(p1, p2);
        assert_eq!(fetches.load(Ordering::SeqCst), 1, "one fetch, then cache");
        assert_eq!(spawns.load(Ordering::SeqCst), 1, "one spawn, then reuse");
    }

    #[test]
    fn lru_eviction_at_the_cap() {
        let loader = test_loader(
            2,
            Arc::new(AtomicUsize::new(0)),
            Arc::new(AtomicUsize::new(0)),
        );
        loader.ensure_loaded(A).unwrap();
        loader.ensure_loaded(B).unwrap();
        // Touch A so B is the LRU.
        loader.ensure_loaded(A).unwrap();
        loader.ensure_loaded(C).unwrap();
        let mut resident = loader.resident();
        resident.sort();
        assert_eq!(
            resident,
            vec![A.to_string(), C.to_string()],
            "B evicted as LRU"
        );
    }

    #[test]
    fn dead_backend_is_respawned_not_proxied_into() {
        let spawns = Arc::new(AtomicUsize::new(0));
        let loader = test_loader(2, Arc::new(AtomicUsize::new(0)), spawns.clone());
        loader.ensure_loaded(A).unwrap();
        // Kill the resident child behind the loader's back.
        {
            let mut st = loader.state.lock().unwrap();
            let entry = st.loaded.get_mut(A).unwrap();
            entry.child.kill().unwrap();
            entry.child.wait().unwrap();
        }
        let p = loader.ensure_loaded(A).unwrap();
        assert_eq!(spawns.load(Ordering::SeqCst), 2, "dead server respawned");
        assert!(p >= 9500);
    }

    #[test]
    fn failed_readiness_kills_the_spawn_and_errors() {
        let hooks = LoaderHooks {
            fetch: Box::new(|_| Ok(std::path::PathBuf::from("/dev/null"))),
            spawn: Box::new(|_, _| Ok(sleeper())),
            wait_ready: Box::new(|_| Err("never healthy".into())),
        };
        let loader = GeneralLoader::new(hooks, 9500, 2);
        assert!(loader.ensure_loaded(A).is_err());
        assert!(
            loader.resident().is_empty(),
            "failed spawn must not stay resident"
        );
    }

    #[test]
    fn model_uuid_accepted_in_all_spellings() {
        for m in [
            format!("\"{A}\""),
            format!("\"zc://{A}\""),
            format!("\"zc://model-{A}\""),
        ] {
            let body: serde_json::Value =
                serde_json::from_str(&format!("{{\"model\":{m}}}")).unwrap();
            assert_eq!(model_uuid_from_body(&body).as_deref(), Some(A));
        }
        let bad: serde_json::Value = serde_json::json!({"model": "llama-3-8b"});
        assert_eq!(model_uuid_from_body(&bad), None);
    }

    // ── The front server under two callers at once (#300) ──────────────────

    const SLOW_MODEL: &str = "11111111-1111-1111-1111-111111111111";
    const FAST_MODEL: &str = "22222222-2222-2222-2222-222222222222";
    /// How long the slow model's stand-in backend sits on a request. Short
    /// enough to keep the test quick, long enough that a second request
    /// queued behind it is unmistakable.
    const SLOW_BACKEND: Duration = Duration::from_secs(5);

    /// These tests each run a front server, a loader and fake backends on
    /// loopback ports and hold a request in flight for seconds. Run in
    /// parallel they collided at random (`Address already in use`, a client
    /// `Invalid argument`), so they take turns.
    fn serial() -> std::sync::MutexGuard<'static, ()> {
        static LOCK: Mutex<()> = Mutex::new(());
        LOCK.lock().unwrap_or_else(|e| e.into_inner())
    }

    /// Find a base port with `n` consecutive free ports from it, probed in a
    /// fixed band BELOW the OS ephemeral range (macOS 49152+, Linux 32768+).
    ///
    /// Asking the OS for port 0 hands out ephemeral ports, and those are also
    /// what this process's own HTTP clients take as source ports: a client
    /// connecting to the front server could be given the very port the fake
    /// backend was about to bind (`Address already in use`), failing the test
    /// at random. The band is stepped by an atomic so parallel tests never
    /// probe the same ports.
    fn reserve_ports(n: u16) -> u16 {
        use std::sync::atomic::AtomicU16;
        static NEXT: AtomicU16 = AtomicU16::new(30_000);
        for _ in 0..2_000 {
            let base = NEXT.fetch_add(n, Ordering::Relaxed);
            assert!(base < 32_000, "reserve_ports exhausted its band");
            let held: Vec<_> = (0..n)
                .filter_map(|i| std::net::TcpListener::bind(("127.0.0.1", base + i)).ok())
                .collect();
            if held.len() == n as usize {
                return base;
            }
        }
        panic!("no run of {n} consecutive free ports");
    }

    /// Bind `port` just after `reserve_ports` let it go. macOS can take a
    /// moment to release a listening socket, so a bind straight after the
    /// release fails with `Address already in use` now and then; retry for a
    /// second instead of failing the test on the OS's timing.
    fn bind_when_released(port: u16) -> std::net::TcpListener {
        let deadline = Instant::now() + Duration::from_secs(1);
        loop {
            match std::net::TcpListener::bind(("127.0.0.1", port)) {
                Ok(l) => return l,
                Err(e) if Instant::now() >= deadline => panic!("front bind :{port}: {e}"),
                Err(_) => std::thread::sleep(Duration::from_millis(20)),
            }
        }
    }

    /// A stand-in for llama-server on `port`: answers any request after
    /// `delay` with a chat-completions-shaped 200, one thread per connection,
    /// bumping `arrived` the moment a request has been fully read — which is
    /// how a test knows a request is genuinely in flight rather than merely
    /// sent.
    fn spawn_fake_backend(
        port: u16,
        delay: Duration,
        arrived: Arc<AtomicUsize>,
    ) -> Result<(), String> {
        let listener = std::net::TcpListener::bind(("127.0.0.1", port))
            .map_err(|e| format!("fake backend bind :{port}: {e}"))?;
        std::thread::spawn(move || {
            for stream in listener.incoming() {
                let Ok(stream) = stream else { continue };
                let arrived = arrived.clone();
                std::thread::spawn(move || serve_fake_backend_conn(stream, delay, arrived));
            }
        });
        Ok(())
    }

    fn serve_fake_backend_conn(
        stream: std::net::TcpStream,
        delay: Duration,
        arrived: Arc<AtomicUsize>,
    ) {
        use std::io::{BufRead, Read, Write};
        let Ok(mut writer) = stream.try_clone() else {
            return;
        };
        let mut reader = std::io::BufReader::new(stream);
        let mut length = 0usize;
        loop {
            let mut line = String::new();
            match reader.read_line(&mut line) {
                Ok(0) | Err(_) => return,
                Ok(_) => {}
            }
            let line = line.trim_end().to_ascii_lowercase();
            if line.is_empty() {
                break;
            }
            if let Some(v) = line.strip_prefix("content-length:") {
                length = v.trim().parse().unwrap_or(0);
            }
        }
        let mut body = vec![0u8; length];
        if reader.read_exact(&mut body).is_err() {
            return;
        }
        arrived.fetch_add(1, Ordering::SeqCst);
        std::thread::sleep(delay);
        let payload = br#"{"choices":[{"message":{"content":"ok"}}]}"#;
        let head = format!(
            "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n\
             Content-Length: {}\r\nConnection: close\r\n\r\n",
            payload.len()
        );
        let _ = writer.write_all(head.as_bytes());
        let _ = writer.write_all(payload);
        let _ = writer.flush();
    }

    /// Loader hooks whose "llama-server" is [`spawn_fake_backend`]. The model
    /// uuid rides through as `fetch`'s gguf path so `spawn` can hand the slow
    /// model a slow backend and the fast one an instant backend.
    fn fake_backend_hooks(arrived: Arc<AtomicUsize>) -> LoaderHooks {
        LoaderHooks {
            fetch: Box::new(|uuid| Ok(std::path::PathBuf::from(uuid))),
            spawn: Box::new(move |gguf, port| {
                let delay = if gguf.to_string_lossy() == SLOW_MODEL {
                    SLOW_BACKEND
                } else {
                    Duration::ZERO
                };
                spawn_fake_backend(port, delay, arrived.clone())?;
                Ok(sleeper())
            }),
            wait_ready: Box::new(|_| Ok(())),
        }
    }

    fn client() -> ureq::Agent {
        ureq::Agent::new_with_config(
            ureq::Agent::config_builder()
                .timeout_global(Some(Duration::from_secs(30)))
                .http_status_as_error(false)
                .build(),
        )
    }

    fn post_completion(front: u16, model: &str) -> (u16, String) {
        let body = serde_json::json!({"model": model, "messages": []}).to_string();
        let mut r = client()
            .post(&format!("http://127.0.0.1:{front}/v1/chat/completions"))
            .header("Content-Type", "application/json")
            .send(&body[..])
            .expect("the front server answered the completion");
        (
            r.status().as_u16(),
            r.body_mut().read_to_string().unwrap_or_default(),
        )
    }

    fn get_health(front: u16) -> u16 {
        client()
            .get(&format!("http://127.0.0.1:{front}/health"))
            .call()
            .expect("the front server answered /health")
            .status()
            .as_u16()
    }

    fn wait_until_listening(port: u16) {
        let deadline = Instant::now() + Duration::from_secs(10);
        while Instant::now() < deadline {
            if std::net::TcpStream::connect(("127.0.0.1", port)).is_ok() {
                return;
            }
            std::thread::sleep(Duration::from_millis(10));
        }
        panic!("front server never came up on :{port}");
    }

    fn wait_for(mut cond: impl FnMut() -> bool, within: Duration, what: &str) {
        let deadline = Instant::now() + within;
        while Instant::now() < deadline {
            if cond() {
                return;
            }
            std::thread::sleep(Duration::from_millis(10));
        }
        panic!("timed out waiting for {what}");
    }

    #[test]
    fn a_slow_request_does_not_hold_the_next_one_at_the_socket() {
        let _serial = serial();
        let base = reserve_ports(3);
        let front = base;
        let front_listener = bind_when_released(front);
        let arrived = Arc::new(AtomicUsize::new(0));
        let loader = GeneralLoader::new(fake_backend_hooks(arrived.clone()), base + 1, 2);
        std::thread::spawn(move || {
            let _ = serve_general_on(front_listener, loader, GeneralServerConfig::default());
        });
        wait_until_listening(front);

        let slow = std::thread::spawn(move || post_completion(front, SLOW_MODEL));
        wait_for(
            || arrived.load(Ordering::SeqCst) >= 1,
            Duration::from_secs(10),
            "the slow request to reach its backend",
        );

        let started = Instant::now();
        let (status, _) = post_completion(front, FAST_MODEL);
        let waited = started.elapsed();
        assert_eq!(status, 200, "the second caller got a real answer");
        assert!(
            waited < Duration::from_secs(2),
            "the second request waited {waited:?} behind a {SLOW_BACKEND:?} first one"
        );
        let (slow_status, _) = slow.join().expect("slow request thread");
        assert_eq!(slow_status, 200, "and the slow one still got its answer");
    }

    #[test]
    fn health_is_answered_while_an_inference_is_in_flight() {
        let _serial = serial();
        let base = reserve_ports(3);
        let front = base;
        let front_listener = bind_when_released(front);
        let arrived = Arc::new(AtomicUsize::new(0));
        let loader = GeneralLoader::new(fake_backend_hooks(arrived.clone()), base + 1, 2);
        std::thread::spawn(move || {
            let _ = serve_general_on(front_listener, loader, GeneralServerConfig::default());
        });
        wait_until_listening(front);

        let slow = std::thread::spawn(move || post_completion(front, SLOW_MODEL));
        wait_for(
            || arrived.load(Ordering::SeqCst) >= 1,
            Duration::from_secs(10),
            "the slow request to reach its backend",
        );

        // The broker expires a worker on its staleness clock, so a provider
        // that cannot answer /health during a long inference eventually
        // de-registers itself mid-request.
        let started = Instant::now();
        let status = get_health(front);
        let waited = started.elapsed();
        assert_eq!(status, 200);
        assert!(
            waited < Duration::from_secs(2),
            "/health waited {waited:?} behind an inference"
        );
        let _ = slow.join();
    }

    #[test]
    fn a_caller_over_the_concurrency_bound_is_refused_immediately() {
        let _serial = serial();
        let base = reserve_ports(3);
        let front = base;
        let front_listener = bind_when_released(front);
        let arrived = Arc::new(AtomicUsize::new(0));
        let loader = GeneralLoader::new(fake_backend_hooks(arrived.clone()), base + 1, 2);
        std::thread::spawn(move || {
            let _ = serve_general_on(
                front_listener,
                loader,
                GeneralServerConfig {
                    max_concurrent: 1,
                    ..GeneralServerConfig::default()
                },
            );
        });
        wait_until_listening(front);

        let slow = std::thread::spawn(move || post_completion(front, SLOW_MODEL));
        wait_for(
            || arrived.load(Ordering::SeqCst) >= 1,
            Duration::from_secs(10),
            "the slow request to reach its backend",
        );

        let started = Instant::now();
        let (status, body) = post_completion(front, FAST_MODEL);
        let waited = started.elapsed();
        assert_eq!(status, 503, "over the bound the caller is told, not queued");
        assert!(
            body.contains("GENERAL_PROVIDER_BUSY"),
            "the refusal names itself: {body}"
        );
        assert!(
            waited < Duration::from_secs(2),
            "the refusal took {waited:?} — that is a stall with a status code on it"
        );

        let (slow_status, _) = slow.join().expect("slow request thread");
        assert_eq!(slow_status, 200);
        let (status, _) = post_completion(front, FAST_MODEL);
        assert_eq!(
            status, 200,
            "the permit came back when the slow request finished"
        );
    }

    #[test]
    fn the_concurrency_cap_defaults_when_unset_or_unusable() {
        assert_eq!(max_concurrent_from(Some("3")), 3);
        assert_eq!(max_concurrent_from(Some(" 3 ")), 3);
        assert_eq!(max_concurrent_from(None), DEFAULT_MAX_CONCURRENT);
        assert_eq!(max_concurrent_from(Some("")), DEFAULT_MAX_CONCURRENT);
        assert_eq!(max_concurrent_from(Some("plenty")), DEFAULT_MAX_CONCURRENT);
        assert_eq!(
            max_concurrent_from(Some("0")),
            DEFAULT_MAX_CONCURRENT,
            "a server that admits nobody is not what an operator meant"
        );
    }
}