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
//! L'Atelier relay (ZC-0028): the hub reaches a runner through this broker,
//! never at the runner's own URL.
//!
//! `ANY /atelier/workers/{worker}/{runner path}` is forwarded to the runner
//! registered as `{worker}` (a broker worker id, or a worker name when exactly
//! one Atelier worker carries it). The broker checks the caller's bearer
//! against its relay token and sends the runner its own token, so a runner
//! only ever needs to trust its broker. A relayed `POST run` that the runner
//! accepts marks the worker busy at once, instead of waiting for its next
//! heartbeat: that is what makes the broker see hub dispatches.
//!
//! Every call is a short request or a streamed body. The runner claims a job
//! asynchronously (FORGE-0003), so nothing here is held open for a run.

use std::sync::Arc;
use std::time::Duration;

use axum::body::Body;
use axum::http::{header, HeaderMap, Method, Response, StatusCode};
use futures_util::stream;

use super::worker::{Worker, WorkerRegistry};
use super::BrokerState;

/// Largest request body relayed to a runner (a `/run` payload or an `/infer`
/// upload). Artifacts flow the other way and are streamed without a cap.
pub const MAX_RELAY_BODY_BYTES: usize = 64 * 1024 * 1024;

const PREFIX: &str = "/atelier/workers/";

/// Tokens of the relay, read once at start-up.
#[derive(Clone, Default)]
pub struct RelayConfig {
    /// What a caller (the hub) must present. `None` turns the relay off.
    relay_token: Option<String>,
    /// What the broker presents to a runner. Defaults to the relay token.
    runner_token: Option<String>,
}

fn env_or_file(name: &str) -> Option<String> {
    let inline = std::env::var(name).ok();
    let from_file = std::env::var(format!("{name}_FILE"))
        .ok()
        .and_then(|p| std::fs::read_to_string(p).ok());
    inline
        .or(from_file)
        .map(|v| v.trim().to_string())
        .filter(|v| !v.is_empty())
}

impl RelayConfig {
    /// `ZAKURO_ATELIER_RELAY_TOKEN[_FILE]` and `ZAKURO_ATELIER_RUNNER_TOKEN[_FILE]`.
    pub fn from_env() -> Self {
        let relay_token = env_or_file("ZAKURO_ATELIER_RELAY_TOKEN");
        let runner_token = env_or_file("ZAKURO_ATELIER_RUNNER_TOKEN").or(relay_token.clone());
        Self {
            relay_token,
            runner_token,
        }
    }

    #[cfg(test)]
    pub fn with_tokens(relay: &str, runner: &str) -> Self {
        Self {
            relay_token: Some(relay.to_string()),
            runner_token: Some(runner.to_string()),
        }
    }

    pub fn enabled(&self) -> bool {
        self.relay_token.is_some()
    }
}

fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
    if a.len() != b.len() {
        return false;
    }
    a.iter().zip(b).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0
}

/// The runner routes the relay forwards. Anything else is refused here, so the
/// relay cannot be used to reach other paths on a worker's host.
pub fn allowed(method: &Method, rest: &str) -> bool {
    let seg: Vec<&str> = rest.split('/').collect();
    // Every segment is a route name or an id: letters, digits, `_`, `.`, `-`
    // and nothing else, so no encoded separator or dot-dot reaches the runner.
    let plain = |s: &str| {
        !s.is_empty()
            && s.chars().any(|c| c != '.')
            && s.chars()
                .all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '.' | '-'))
    };
    if !seg.iter().all(|s| plain(s)) {
        return false;
    }
    let get = method == Method::GET;
    let post = method == Method::POST;
    match seg.as_slice() {
        ["run"] => post,
        ["health"] | ["benchmark"] | ["status"] => get,
        ["jobs", _] => get,
        ["jobs", _, "logs" | "metrics" | "spec"] => get,
        ["jobs", _, "cancel" | "wrap-up" | "budget"] => post,
        ["artifacts", _] => get,
        ["infer", _] => post,
        // The engineer's job supervisor and eval harness (zak-forge#136), as
        // the hub's `forge/runner_ops.py` calls them: these seven and no other
        // path under either prefix.
        ["supervisor", "jobs"] => post,
        ["supervisor", "jobs", _] => get,
        ["supervisor", "jobs", _, "logs"] => get,
        ["supervisor", "jobs", _, "cancel"] => post,
        ["harness", _, "evaluate" | "compare" | "score-test"] => post,
        _ => false,
    }
}

/// Split `/atelier/workers/{worker}/{rest}`.
pub fn split_path(path: &str) -> Option<(&str, &str)> {
    let tail = path.strip_prefix(PREFIX)?;
    let (worker, rest) = tail.split_once('/')?;
    if worker.is_empty() || rest.is_empty() {
        return None;
    }
    Some((worker, rest))
}

#[derive(Debug, PartialEq, Eq)]
pub enum ResolveError {
    Unknown,
    Ambiguous,
    NotAtelier,
}

/// The runner URL a worker advertises: its `atelier-runner=<url>` tag, else
/// its registered uri. Only a worker tagged `atelier` has one.
pub fn runner_base(worker: &Worker) -> Option<String> {
    if !worker.tags.iter().any(|t| t == "atelier") {
        return None;
    }
    let base = worker
        .tags
        .iter()
        .find_map(|t| t.strip_prefix("atelier-runner="))
        .unwrap_or(&worker.uri);
    let base = base.trim_end_matches('/');
    (base.starts_with("http://") || base.starts_with("https://")).then(|| base.to_string())
}

/// A worker by broker id, else by name when one Atelier worker has that name.
/// The id changes when a runner re-registers; the name does not, so a caller
/// that stored the name keeps reaching a job across a broker restart.
pub fn resolve_worker(workers: &WorkerRegistry, key: &str) -> Result<Worker, ResolveError> {
    if let Some(w) = workers.get(key) {
        return if runner_base(&w).is_some() {
            Ok(w)
        } else {
            Err(ResolveError::NotAtelier)
        };
    }
    let mut named: Vec<Worker> = workers
        .list()
        .into_iter()
        .filter(|w| w.name == key && runner_base(w).is_some())
        .collect();
    match named.len() {
        0 => Err(ResolveError::Unknown),
        1 => Ok(named.remove(0)),
        _ => Err(ResolveError::Ambiguous),
    }
}

fn json_error(status: StatusCode, error: &str, code: &str) -> Response<Body> {
    let body = serde_json::json!({"error": error, "code": code}).to_string();
    Response::builder()
        .status(status)
        .header(header::CONTENT_TYPE, "application/json")
        .body(Body::from(body))
        .expect("static response")
}

fn bearer(headers: &HeaderMap) -> Option<&str> {
    headers
        .get(header::AUTHORIZATION)?
        .to_str()
        .ok()?
        .strip_prefix("Bearer ")
}

/// How long a runner may go without sending a byte, for most routes.
pub const READ_BOUND: Duration = Duration::from_secs(120);
/// `harness/{project}/evaluate|compare` answer once, after a paired bootstrap
/// the hub waits 120 s for: the relay must not give up first.
pub const HARNESS_READ_BOUND: Duration = Duration::from_secs(300);
/// `harness/{project}/score-test` scores the frozen test split inside the
/// request and sends nothing until it is done; the hub waits 3600 s, and a
/// look the relay cut short is still a spent look.
pub const SCORE_TEST_READ_BOUND: Duration = Duration::from_secs(3900);

/// The read bound of a relayed route (`rest` as `allowed` takes it).
pub fn read_bound(rest: &str) -> Duration {
    match rest.split('/').collect::<Vec<_>>().as_slice() {
        ["harness", _, "score-test"] => SCORE_TEST_READ_BOUND,
        ["harness", _, _] => HARNESS_READ_BOUND,
        _ => READ_BOUND,
    }
}

/// The clients of the relay, one per read bound: the bound is a property of
/// a `reqwest` client, not of a request.
#[derive(Clone)]
pub struct RelayClients {
    default: reqwest::Client,
    harness: reqwest::Client,
    score_test: reqwest::Client,
}

impl Default for RelayClients {
    fn default() -> Self {
        Self::new()
    }
}

impl RelayClients {
    pub fn new() -> Self {
        Self {
            default: http_client(READ_BOUND),
            harness: http_client(HARNESS_READ_BOUND),
            score_test: http_client(SCORE_TEST_READ_BOUND),
        }
    }

    /// Shorter bounds, in the same three roles, for a test that waits them out.
    #[cfg(test)]
    fn with_bounds(default: Duration, harness: Duration, score_test: Duration) -> Self {
        Self {
            default: http_client(default),
            harness: http_client(harness),
            score_test: http_client(score_test),
        }
    }

    fn for_route(&self, rest: &str) -> &reqwest::Client {
        match read_bound(rest) {
            SCORE_TEST_READ_BOUND => &self.score_test,
            HARNESS_READ_BOUND => &self.harness,
            _ => &self.default,
        }
    }
}

/// A client for relayed calls: a tight connect bound, a read bound per chunk
/// (a stalled runner must not pin a connection), no total timeout (an
/// artifact can be large).
pub fn http_client(read_bound: Duration) -> reqwest::Client {
    reqwest::Client::builder()
        .connect_timeout(Duration::from_secs(10))
        .read_timeout(read_bound)
        // A runner answers for itself: a redirect is relayed to the caller,
        // never followed to wherever the runner points.
        .redirect(reqwest::redirect::Policy::none())
        .build()
        .expect("reqwest client")
}

const FORWARDED_REQUEST_HEADERS: [&str; 4] =
    ["content-type", "accept", "x-forge-async", "x-forge-grant"];
const FORWARDED_RESPONSE_HEADERS: [&str; 4] = [
    "content-type",
    "content-length",
    "content-disposition",
    "x-forge-sha256",
];

/// Handle one relayed request.
pub async fn relay(
    state: Arc<BrokerState>,
    config: RelayConfig,
    clients: RelayClients,
    req: axum::extract::Request,
) -> Response<Body> {
    let Some(expected) = config.relay_token.as_deref() else {
        return json_error(
            StatusCode::NOT_FOUND,
            "the Atelier relay is not enabled on this broker",
            "RELAY_DISABLED",
        );
    };
    let presented = bearer(req.headers()).unwrap_or("");
    if !constant_time_eq(presented.as_bytes(), expected.as_bytes()) {
        return json_error(
            StatusCode::UNAUTHORIZED,
            "relay token required",
            "UNAUTHORIZED",
        );
    }

    let method = req.method().clone();
    let path = req.uri().path().to_string();
    let query = req.uri().query().map(str::to_string);
    let Some((key, rest)) = split_path(&path) else {
        return json_error(StatusCode::NOT_FOUND, "no such relay path", "NOT_FOUND");
    };
    if !allowed(&method, rest) {
        return json_error(
            StatusCode::FORBIDDEN,
            "this runner route is not relayed",
            "FORBIDDEN",
        );
    }
    let worker = match resolve_worker(&state.workers, key) {
        Ok(w) => w,
        Err(ResolveError::Ambiguous) => {
            return json_error(
                StatusCode::CONFLICT,
                "several Atelier workers carry this name; use the worker id",
                "AMBIGUOUS_WORKER",
            )
        }
        Err(_) => {
            return json_error(
                StatusCode::NOT_FOUND,
                "no Atelier worker registered under this id or name",
                "UNKNOWN_WORKER",
            )
        }
    };
    let base = runner_base(&worker).expect("resolve_worker returns Atelier workers only");
    let mut url = format!("{base}/{rest}");
    if let Some(q) = query {
        url.push('?');
        url.push_str(&q);
    }

    let mut out = clients.for_route(rest).request(method.clone(), &url);
    for name in FORWARDED_REQUEST_HEADERS {
        if let Some(v) = req.headers().get(name) {
            out = out.header(name, v);
        }
    }
    if let Some(token) = config.runner_token.as_deref() {
        out = out.bearer_auth(token);
    }
    let body = match axum::body::to_bytes(req.into_body(), MAX_RELAY_BODY_BYTES).await {
        Ok(b) => b,
        Err(_) => {
            return json_error(
                StatusCode::PAYLOAD_TOO_LARGE,
                "request body too large for the relay",
                "PAYLOAD_TOO_LARGE",
            )
        }
    };
    if !body.is_empty() {
        out = out.body(body);
    }

    let upstream = match out.send().await {
        Ok(r) => r,
        Err(e) => {
            // No runner URL in the message: callers never learn a worker's address.
            // Two codes, because the caller acts differently on them. A
            // connection that was never made (refused, or the connect itself
            // timed out: the host is down or off the network) sent nothing,
            // so the job cannot be running there and may go to another
            // machine. Anything after that may have reached the runner.
            let (reason, code) = if e.is_connect() {
                ("could not be reached", "RUNNER_UNREACHABLE")
            } else if e.is_timeout() {
                ("did not answer in time", "RUNNER_NO_ANSWER")
            } else {
                ("did not answer", "RUNNER_NO_ANSWER")
            };
            return json_error(
                StatusCode::BAD_GATEWAY,
                &format!("the runner {reason}"),
                code,
            );
        }
    };

    let status = upstream.status();
    if method == Method::POST && rest == "run" && status.is_success() {
        state.workers.mark_busy(&worker.id);
    }

    let mut builder = Response::builder().status(status.as_u16());
    for name in FORWARDED_RESPONSE_HEADERS {
        if let Some(v) = upstream.headers().get(name) {
            builder = builder.header(name, v.as_bytes());
        }
    }
    builder = builder.header("x-zakuro-worker-id", worker.id.as_str());
    let chunks = stream::unfold(upstream, |mut r| async move {
        match r.chunk().await {
            Ok(Some(c)) => Some((Ok::<_, std::io::Error>(c), r)),
            Ok(None) => None,
            Err(e) => Some((Err(std::io::Error::other(e.to_string())), r)),
        }
    });
    builder.body(Body::from_stream(chunks)).unwrap_or_else(|_| {
        json_error(
            StatusCode::BAD_GATEWAY,
            "bad runner response",
            "BAD_GATEWAY",
        )
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::broker::worker::WorkerRegistration;

    fn register(reg: &WorkerRegistry, name: &str, uri: &str, tags: &[&str]) -> Worker {
        let body = serde_json::json!({
            "name": name,
            "uri": uri,
            "worker_type": "atelier",
            "tags": tags,
        });
        let registration: WorkerRegistration = serde_json::from_value(body).unwrap();
        reg.register(registration)
    }

    #[test]
    fn only_runner_contract_routes_are_relayed() {
        for (m, p) in [
            (Method::POST, "run"),
            (Method::GET, "health"),
            (Method::GET, "benchmark"),
            (Method::GET, "jobs/j1"),
            (Method::GET, "jobs/j1/logs"),
            (Method::GET, "jobs/j1/metrics"),
            (Method::GET, "jobs/j1/spec"),
            (Method::POST, "jobs/j1/cancel"),
            (Method::POST, "jobs/j1/wrap-up"),
            (Method::POST, "jobs/j1/budget"),
            (Method::GET, "artifacts/j1"),
            (Method::POST, "infer/j1"),
        ] {
            assert!(allowed(&m, p), "{m} {p}");
        }
        for (m, p) in [
            (Method::GET, "run"),
            (Method::POST, "drain"),
            (Method::DELETE, "jobs/j1"),
            (Method::GET, "jobs/../../etc/passwd"),
            (Method::GET, "jobs//logs"),
            (Method::GET, "jobs/%2e%2e/logs"),
            (Method::GET, "jobs/a%2Fb"),
            (Method::GET, "jobs/..."),
            (Method::GET, "artifacts/j 1"),
            (Method::GET, "jobs/j1/logs/extra"),
            (Method::GET, ""),
            (Method::POST, "artifacts/j1"),
        ] {
            assert!(!allowed(&m, p), "{m} {p}");
        }
    }

    #[test]
    fn the_supervisor_and_harness_routes_are_the_seven_the_hub_calls() {
        for (m, p) in [
            (Method::POST, "supervisor/jobs"),
            (Method::GET, "supervisor/jobs/20261116T101500-train-ab12"),
            (Method::GET, "supervisor/jobs/j1/logs"),
            (Method::POST, "supervisor/jobs/j1/cancel"),
            (Method::POST, "harness/avm-2026/evaluate"),
            (Method::POST, "harness/avm-2026/compare"),
            (Method::POST, "harness/avm-2026/score-test"),
        ] {
            assert!(allowed(&m, p), "{m} {p}");
        }
        for (m, p) in [
            // The right path under the wrong method.
            (Method::GET, "supervisor/jobs"),
            (Method::POST, "supervisor/jobs/j1"),
            (Method::DELETE, "supervisor/jobs/j1"),
            (Method::POST, "supervisor/jobs/j1/logs"),
            (Method::GET, "supervisor/jobs/j1/cancel"),
            (Method::GET, "harness/p/evaluate"),
            (Method::GET, "harness/p/compare"),
            (Method::GET, "harness/p/score-test"),
            (Method::PUT, "harness/p/evaluate"),
            // Anything else under either prefix.
            (Method::GET, "supervisor"),
            (Method::POST, "supervisor"),
            (Method::GET, "supervisor/volumes"),
            (Method::POST, "supervisor/jobs/j1/retry"),
            (Method::GET, "supervisor/jobs/j1/logs/extra"),
            (Method::POST, "supervisor/jobs/j1/cancel/now"),
            (Method::GET, "harness"),
            (Method::POST, "harness/p"),
            (Method::POST, "harness/p/run"),
            (Method::POST, "harness/p/score_test"),
            (Method::POST, "harness/p/evaluate/extra"),
            (Method::POST, "harness/evaluate"),
            // An id or a project is one plain segment, as for a job's routes.
            (Method::GET, "supervisor/jobs/.."),
            (Method::GET, "supervisor/jobs//logs"),
            (Method::GET, "supervisor/jobs/%2e%2e/logs"),
            (Method::GET, "supervisor/jobs/a%2Fb"),
            (Method::POST, "harness/../evaluate"),
            (Method::POST, "harness//evaluate"),
            (Method::POST, "harness/a%2Fb/evaluate"),
            (Method::POST, "harness/my project/evaluate"),
        ] {
            assert!(!allowed(&m, p), "{m} {p}");
        }
    }

    #[test]
    fn path_splits_into_worker_and_runner_route() {
        assert_eq!(
            split_path("/atelier/workers/w1/jobs/j1/logs"),
            Some(("w1", "jobs/j1/logs"))
        );
        assert_eq!(split_path("/atelier/workers/w1"), None);
        assert_eq!(split_path("/atelier/workers//run"), None);
        assert_eq!(split_path("/workers/w1/run"), None);
    }

    #[test]
    fn runner_url_comes_from_the_tag_then_the_uri_and_only_for_atelier_workers() {
        let reg = WorkerRegistry::new();
        let tagged = register(
            &reg,
            "a",
            "http://10.0.0.1:1",
            &["atelier", "atelier-runner=http://10.0.0.2:8102/"],
        );
        assert_eq!(
            runner_base(&tagged).as_deref(),
            Some("http://10.0.0.2:8102")
        );
        let plain = register(&reg, "b", "http://10.0.0.3:8102", &["atelier"]);
        assert_eq!(runner_base(&plain).as_deref(), Some("http://10.0.0.3:8102"));
        let other = register(&reg, "c", "http://10.0.0.4:3960", &[]);
        assert_eq!(runner_base(&other), None);
    }

    #[test]
    fn a_worker_resolves_by_id_then_by_unique_name() {
        let reg = WorkerRegistry::new();
        let a = register(&reg, "x399", "http://10.0.0.1:8102", &["atelier"]);
        let id = |key: &str| resolve_worker(&reg, key).map(|w| w.id);
        assert_eq!(id(&a.id), Ok(a.id.clone()));
        assert_eq!(id("x399"), Ok(a.id.clone()));
        assert_eq!(id("nope"), Err(ResolveError::Unknown));
        let plain = register(&reg, "cpu", "http://10.0.0.9:3960", &[]);
        assert_eq!(id(&plain.id), Err(ResolveError::NotAtelier));
        assert_eq!(id("cpu"), Err(ResolveError::Unknown));
        register(&reg, "x399", "http://10.0.0.5:8102", &["atelier"]);
        assert_eq!(id("x399"), Err(ResolveError::Ambiguous));
    }

    #[test]
    fn token_comparison_is_exact() {
        assert!(constant_time_eq(b"abc", b"abc"));
        assert!(!constant_time_eq(b"abc", b"abd"));
        assert!(!constant_time_eq(b"abc", b"ab"));
        assert!(!constant_time_eq(b"", b"a"));
    }

    /// A fake runner: checks the broker's token, echoes what it was asked.
    async fn fake_runner() -> std::net::SocketAddr {
        use axum::routing::{get, post};
        let authed = |h: &HeaderMap| bearer(h) == Some("runner-secret");
        let app = axum::Router::new()
            .route(
                "/run",
                post(move |h: HeaderMap, body: String| async move {
                    if !authed(&h) {
                        return (StatusCode::UNAUTHORIZED, String::new());
                    }
                    let is_async = h.get("x-forge-async").is_some();
                    (
                        StatusCode::ACCEPTED,
                        format!("async={is_async} body={body}"),
                    )
                }),
            )
            .route(
                "/jobs/j1/logs",
                get(move |h: HeaderMap, uri: axum::http::Uri| async move {
                    if !authed(&h) {
                        return (StatusCode::UNAUTHORIZED, String::new());
                    }
                    (StatusCode::OK, uri.query().unwrap_or("").to_string())
                }),
            )
            .route(
                "/supervisor/jobs/s1/logs",
                get(move |h: HeaderMap, uri: axum::http::Uri| async move {
                    if !authed(&h) {
                        return (StatusCode::UNAUTHORIZED, String::new());
                    }
                    (StatusCode::OK, uri.query().unwrap_or("").to_string())
                }),
            )
            .route(
                "/harness/p1/score-test",
                post(move |h: HeaderMap, body: String| async move {
                    if !authed(&h) {
                        return (StatusCode::UNAUTHORIZED, String::new());
                    }
                    (StatusCode::OK, format!("scored {body}"))
                }),
            )
            .route(
                "/harness/p1/elsewhere",
                post(|| async {
                    (
                        StatusCode::TEMPORARY_REDIRECT,
                        [(header::LOCATION, "http://127.0.0.1:1/away")],
                    )
                }),
            )
            .route(
                "/harness/p1/compare",
                post(|| async {
                    (
                        StatusCode::TEMPORARY_REDIRECT,
                        [(header::LOCATION, "/harness/p1/score-test")],
                    )
                }),
            )
            .route(
                "/artifacts/j1",
                get(|| async { vec![7u8; 6 * 1024 * 1024] }),
            );
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
        addr
    }

    fn request(
        method: Method,
        path: &str,
        token: Option<&str>,
        body: &str,
    ) -> axum::extract::Request {
        let mut b = axum::http::Request::builder().method(method).uri(path);
        if let Some(t) = token {
            b = b.header(header::AUTHORIZATION, format!("Bearer {t}"));
        }
        b.header("x-forge-async", "1")
            .body(Body::from(body.to_string()))
            .unwrap()
    }

    async fn text(resp: Response<Body>) -> (u16, Vec<u8>) {
        let status = resp.status().as_u16();
        let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)
            .await
            .unwrap();
        (status, bytes.to_vec())
    }

    #[tokio::test]
    async fn a_call_reaches_the_runner_with_the_brokers_token_and_marks_it_busy() {
        let addr = fake_runner().await;
        let state = Arc::new(BrokerState::new());
        let w = register(
            &state.workers,
            "x399",
            &format!("http://{addr}"),
            &["atelier"],
        );
        let cfg = RelayConfig::with_tokens("hub-secret", "runner-secret");
        let go = |req| relay(state.clone(), cfg.clone(), RelayClients::new(), req);

        // The caller's token is checked by the broker, not forwarded.
        let (status, _) = text(
            go(request(
                Method::GET,
                "/atelier/workers/x399/jobs/j1/logs",
                None,
                "",
            ))
            .await,
        )
        .await;
        assert_eq!(status, 401);
        let (status, _) = text(
            go(request(
                Method::GET,
                "/atelier/workers/x399/jobs/j1/logs",
                Some("runner-secret"),
                "",
            ))
            .await,
        )
        .await;
        assert_eq!(status, 401);

        // Query strings survive; a read does not mark the worker busy.
        let (status, body) = text(
            go(request(
                Method::GET,
                "/atelier/workers/x399/jobs/j1/logs?tail_bytes=9",
                Some("hub-secret"),
                "",
            ))
            .await,
        )
        .await;
        assert_eq!((status, body.as_slice()), (200, b"tail_bytes=9".as_slice()));
        assert_eq!(state.workers.get(&w.id).unwrap().active_requests, 0);

        // An accepted run marks it busy before its next heartbeat.
        let (status, body) = text(
            go(request(
                Method::POST,
                &format!("/atelier/workers/{}/run", w.id),
                Some("hub-secret"),
                "{\"job_id\":\"j1\"}",
            ))
            .await,
        )
        .await;
        assert_eq!(status, 202);
        assert_eq!(body, b"async=true body={\"job_id\":\"j1\"}");
        let busy = state.workers.get(&w.id).unwrap();
        assert_eq!(busy.active_requests, 1);
        assert_eq!(busy.resources.gpus_available, 0);

        // An artifact larger than the broker's request cap streams through whole.
        let (status, body) = text(
            go(request(
                Method::GET,
                "/atelier/workers/x399/artifacts/j1",
                Some("hub-secret"),
                "",
            ))
            .await,
        )
        .await;
        assert_eq!((status, body.len()), (200, 6 * 1024 * 1024));

        // The engineer's routes: same tokens, the query kept, the body sent,
        // and a supervisor or harness call does not mark the worker busy.
        let before = state.workers.get(&w.id).unwrap().active_requests;
        let (status, body) = text(
            go(request(
                Method::GET,
                "/atelier/workers/x399/supervisor/jobs/s1/logs?tail=200",
                Some("hub-secret"),
                "",
            ))
            .await,
        )
        .await;
        assert_eq!((status, body.as_slice()), (200, b"tail=200".as_slice()));
        let (status, body) = text(
            go(request(
                Method::POST,
                "/atelier/workers/x399/harness/p1/score-test",
                Some("hub-secret"),
                "{\"system\":\"s\"}",
            ))
            .await,
        )
        .await;
        assert_eq!(
            (status, body.as_slice()),
            (200, b"scored {\"system\":\"s\"}".as_slice())
        );
        let (status, _) = text(
            go(request(
                Method::POST,
                "/atelier/workers/x399/harness/p1/score-test",
                Some("runner-secret"),
                "",
            ))
            .await,
        )
        .await;
        assert_eq!(status, 401);
        // A redirect from a harness route is handed back, not followed.
        let (status, body) = text(
            go(request(
                Method::POST,
                "/atelier/workers/x399/harness/p1/compare",
                Some("hub-secret"),
                "{}",
            ))
            .await,
        )
        .await;
        assert_eq!(status, 307);
        assert!(!body.starts_with(b"scored"));
        // Outside the seven: refused before anything is sent to the runner.
        for (m, p) in [
            (Method::GET, "/atelier/workers/x399/harness/p1/score-test"),
            (Method::POST, "/atelier/workers/x399/harness/p1/elsewhere"),
            (
                Method::POST,
                "/atelier/workers/x399/supervisor/jobs/s1/logs",
            ),
        ] {
            let (status, _) = text(go(request(m, p, Some("hub-secret"), "")).await).await;
            assert_eq!(status, 403, "{p}");
        }
        assert_eq!(state.workers.get(&w.id).unwrap().active_requests, before);

        // Refusals: a route outside the contract, an unknown worker.
        let (status, _) = text(
            go(request(
                Method::POST,
                "/atelier/workers/x399/drain",
                Some("hub-secret"),
                "",
            ))
            .await,
        )
        .await;
        assert_eq!(status, 403);
        let (status, _) = text(
            go(request(
                Method::GET,
                "/atelier/workers/nobody/health",
                Some("hub-secret"),
                "",
            ))
            .await,
        )
        .await;
        assert_eq!(status, 404);
    }

    #[test]
    fn a_harness_call_may_be_silent_for_longer_than_any_other() {
        for p in [
            "run",
            "health",
            "jobs/j1/logs",
            "artifacts/j1",
            "infer/j1",
            "supervisor/jobs",
            "supervisor/jobs/j1",
            "supervisor/jobs/j1/logs",
            "supervisor/jobs/j1/cancel",
        ] {
            assert_eq!(read_bound(p), Duration::from_secs(120), "{p}");
        }
        assert_eq!(read_bound("harness/p/evaluate"), HARNESS_READ_BOUND);
        assert_eq!(read_bound("harness/p/compare"), HARNESS_READ_BOUND);
        assert_eq!(read_bound("harness/p/score-test"), SCORE_TEST_READ_BOUND);
        // Above what the hub itself waits (runner_ops: 120 s and 3600 s).
        assert!(HARNESS_READ_BOUND > Duration::from_secs(120));
        assert!(SCORE_TEST_READ_BOUND > Duration::from_secs(3600));
    }

    #[tokio::test]
    async fn each_route_is_cut_at_its_own_read_bound() {
        use axum::routing::{get, post};
        let slow = || async {
            tokio::time::sleep(Duration::from_millis(600)).await;
            "done"
        };
        let app = axum::Router::new()
            .route("/jobs/j1", get(slow))
            .route("/supervisor/jobs/s1", get(slow))
            .route("/harness/p1/evaluate", post(slow))
            .route("/harness/p1/score-test", post(slow));
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });

        let state = Arc::new(BrokerState::new());
        register(
            &state.workers,
            "x399",
            &format!("http://{addr}"),
            &["atelier"],
        );
        let cfg = RelayConfig::with_tokens("hub-secret", "runner-secret");
        let ms = Duration::from_millis;
        let call = |clients: RelayClients, method: Method, route: &str| {
            let path = format!("/atelier/workers/x399/{route}");
            let (state, cfg) = (state.clone(), cfg.clone());
            async move {
                let resp = relay(
                    state,
                    cfg,
                    clients,
                    request(method, &path, Some("hub-secret"), ""),
                );
                let (status, body) = text(resp.await).await;
                (status, String::from_utf8(body).unwrap())
            }
        };

        // The runner answers after 600 ms. Only score-test is given that long.
        let clients = RelayClients::with_bounds(ms(150), ms(150), ms(5000));
        let (status, body) = call(clients.clone(), Method::POST, "harness/p1/score-test").await;
        assert_eq!((status, body.as_str()), (200, "done"));
        for (m, route) in [
            (Method::GET, "jobs/j1"),
            (Method::GET, "supervisor/jobs/s1"),
            (Method::POST, "harness/p1/evaluate"),
        ] {
            let (status, body) = call(clients.clone(), m, route).await;
            assert_eq!(status, 502, "{route}");
            assert!(body.contains("RUNNER_NO_ANSWER"), "{route}: {body}");
        }

        // evaluate has its own bound, apart from both others.
        let clients = RelayClients::with_bounds(ms(150), ms(5000), ms(150));
        let (status, _) = call(clients.clone(), Method::POST, "harness/p1/evaluate").await;
        assert_eq!(status, 200);
        let (status, _) = call(clients.clone(), Method::GET, "supervisor/jobs/s1").await;
        assert_eq!(status, 502);
        let (status, _) = call(clients, Method::POST, "harness/p1/score-test").await;
        assert_eq!(status, 502);
    }

    #[tokio::test]
    async fn the_relay_is_off_without_a_token_and_hides_a_dead_runners_address() {
        let state = Arc::new(BrokerState::new());
        register(&state.workers, "gone", "http://127.0.0.1:1", &["atelier"]);
        let off = relay(
            state.clone(),
            RelayConfig::default(),
            RelayClients::new(),
            request(Method::GET, "/atelier/workers/gone/health", Some("x"), ""),
        )
        .await;
        assert_eq!(off.status(), 404);
        let cfg = RelayConfig::with_tokens("hub-secret", "runner-secret");
        let (status, body) = text(
            relay(
                state,
                cfg,
                RelayClients::new(),
                request(
                    Method::GET,
                    "/atelier/workers/gone/health",
                    Some("hub-secret"),
                    "",
                ),
            )
            .await,
        )
        .await;
        assert_eq!(status, 502);
        let body = String::from_utf8(body).unwrap();
        assert!(body.contains("RUNNER_UNREACHABLE"), "{body}");
        assert!(!body.contains("127.0.0.1"), "{body}");
    }
}