zc2 0.0.51

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
//! Mesh placement policy and the routing decision record (zc#474).
//!
//! Before this, the publish-lock path in `/execute` ran `select_local_worker`
//! first and only reached the mesh when this broker had nothing that matched,
//! so a requester whose own broker had a worker never bought anyone else's
//! capacity. [`Placement`] makes that a choice on the request:
//!
//! * `own_first` (default, the behaviour before this change): local worker if
//!   one matches, otherwise the mesh.
//! * `best_price_mesh`: the best local worker is ranked at its LISTED
//!   `price_per_hour` (never 0 -- ranking only; billing for a self-owned,
//!   self-executed job stays free, see `execution_is_free`) against the
//!   cheapest eligible peer worker in this broker's roster. Strictly cheaper
//!   peer wins; a tie stays local.
//! * `mesh_only`: same as `remote_only` -- never run here.
//!
//! Peer prices are taken from the synced worker roster (workers with a
//! `source_node`), NOT from offers: offers only exist after publishing, and
//! publishing is the commitment. So `best_price_mesh` is a pre-publish
//! decision -- "publish when the best local listed price exceeds the cheapest
//! known peer price, else run local". Which peer then wins the publish is the
//! normal dispatch (pre-selection / race), so the cheapest roster peer is
//! what justifies going to the mesh, not a guaranteed destination.
//!
//! The default for a request that names no policy is the account-level one
//! the hub exposes (set through [`set_hub_default`]; also seedable from
//! `ZAKURO_DEFAULT_PLACEMENT` for operators), else `own_first`.

use super::router::{is_own_worker, meets_vram, runs_payload, ResourceRequirements};
use super::worker::Worker;
use serde::{Deserialize, Serialize};
use std::sync::RwLock;

/// Where a job may run relative to the broker that received it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum Placement {
    #[default]
    OwnFirst,
    BestPriceMesh,
    MeshOnly,
}

impl Placement {
    pub fn as_str(self) -> &'static str {
        match self {
            Placement::OwnFirst => "own_first",
            Placement::BestPriceMesh => "best_price_mesh",
            Placement::MeshOnly => "mesh_only",
        }
    }

    pub fn parse(s: &str) -> Result<Placement, String> {
        match s.trim() {
            "own_first" => Ok(Placement::OwnFirst),
            "best_price_mesh" => Ok(Placement::BestPriceMesh),
            "mesh_only" => Ok(Placement::MeshOnly),
            other => Err(format!(
                "unknown placement {other:?}: expected one of own_first, best_price_mesh, mesh_only"
            )),
        }
    }
}

impl<'de> Deserialize<'de> for Placement {
    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
        let s = String::deserialize(d)?;
        Placement::parse(&s).map_err(serde::de::Error::custom)
    }
}

static HUB_DEFAULT: RwLock<Option<Placement>> = RwLock::new(None);

/// Install (or clear) the account-level default read from the hub. The hub
/// sync calls this alongside the other broker settings it hands over.
pub fn set_hub_default(p: Option<Placement>) {
    if let Ok(mut g) = HUB_DEFAULT.write() {
        *g = p;
    }
}

fn hub_default() -> Option<Placement> {
    if let Some(p) = HUB_DEFAULT.read().ok().and_then(|g| *g) {
        return Some(p);
    }
    std::env::var("ZAKURO_DEFAULT_PLACEMENT")
        .ok()
        .and_then(|v| Placement::parse(&v).ok())
}

/// Resolve the effective policy and where it came from:
/// request, then hub default, then `own_first`.
pub fn resolve(requested: Option<Placement>) -> (Placement, &'static str) {
    resolve_with(requested, hub_default())
}

fn resolve_with(requested: Option<Placement>, hub: Option<Placement>) -> (Placement, &'static str) {
    match (requested, hub) {
        (Some(p), _) => (p, "request"),
        (None, Some(p)) => (p, "hub_default"),
        (None, None) => (Placement::OwnFirst, "default"),
    }
}

/// Reject an unknown `placement` in a raw requirements document with a
/// message naming the allowed values. The requirements header is otherwise
/// parsed leniently (a malformed one falls back to defaults), but silently
/// ignoring a typo'd policy would put the job on the wrong node.
pub fn validate_raw(raw: &str) -> Result<(), String> {
    let Ok(v) = serde_json::from_str::<serde_json::Value>(raw) else {
        return Ok(());
    };
    match v.get("placement") {
        None | Some(serde_json::Value::Null) => Ok(()),
        Some(serde_json::Value::String(s)) => Placement::parse(s).map(|_| ()),
        Some(other) => Err(format!(
            "placement must be a string, got {other}: expected one of own_first, best_price_mesh, mesh_only"
        )),
    }
}

/// One worker the placement considered.
#[derive(Debug, Clone, Serialize)]
pub struct Candidate {
    pub worker_id: String,
    pub worker: String,
    /// `local` (this broker's own) or `mesh` (synced from a peer).
    pub scope: &'static str,
    /// The owning peer node for a `mesh` worker.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub broker: Option<String>,
    /// Listed price, ¥/h -- the ranking input, not the billed amount.
    pub price_per_hour: f64,
    /// Why it was ruled out: capability, vram, runtime, price, not_local,
    /// pinned_elsewhere, policy. `None` for the chosen one and for eligible
    /// alternatives that were simply not picked.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub excluded: Option<&'static str>,
    pub chosen: bool,
}

#[derive(Debug, Clone, Serialize)]
pub struct Chosen {
    pub scope: &'static str,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub worker: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub broker: Option<String>,
}

/// The routing decision returned with the response (`X-Zakuro-Routing`).
#[derive(Debug, Clone, Serialize)]
pub struct RoutingRecord {
    pub policy: &'static str,
    /// `request`, `hub_default` or `default`.
    pub policy_source: &'static str,
    /// Whether this broker actually applied `policy` when it chose the worker.
    /// False on the paths that only record what the routing strategy picked
    /// (zc#481): the policy is then reported, never claimed.
    pub enforced: bool,
    pub candidates: Vec<Candidate>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub chosen: Option<Chosen>,
    pub note: String,
}

/// Candidates beyond this are counted, not listed, so the header stays small.
const MAX_CANDIDATES: usize = 24;

impl RoutingRecord {
    /// Compact, ASCII-only JSON safe to use as a header value.
    pub fn to_header(&self) -> String {
        let mut r = self.clone();
        if r.candidates.len() > MAX_CANDIDATES {
            let extra = r.candidates.len() - MAX_CANDIDATES;
            r.candidates.truncate(MAX_CANDIDATES);
            r.note
                .push_str(&format!(" (+{extra} candidates not listed)"));
        }
        let json = serde_json::to_string(&r).unwrap_or_default();
        let mut out = String::with_capacity(json.len());
        for c in json.chars() {
            if c.is_ascii() && !c.is_ascii_control() {
                out.push(c);
            } else {
                let mut buf = [0u16; 2];
                for u in c.encode_utf16(&mut buf) {
                    out.push_str(&format!("\\u{u:04x}"));
                }
            }
        }
        out
    }

    /// The job ran on one of this broker's own workers.
    pub fn finish_local(&mut self, worker_id: &str, broker: &str) {
        let mut name = None;
        for c in &mut self.candidates {
            if c.worker_id == worker_id {
                c.chosen = true;
                c.excluded = None;
                name = Some(c.worker.clone());
            }
        }
        self.chosen = Some(Chosen {
            scope: "local",
            worker: name,
            broker: Some(broker.to_string()),
        });
    }

    /// The job was published to the mesh; `worker` is the name the executing
    /// peer reported, when it did.
    pub fn finish_remote(&mut self, worker: Option<&str>) {
        let mut broker = None;
        let mut name = worker.map(str::to_string);
        if let Some(w) = worker {
            for c in &mut self.candidates {
                if c.scope == "mesh" && c.worker == w {
                    c.chosen = true;
                    c.excluded = None;
                    broker = c.broker.clone();
                    name = Some(c.worker.clone());
                }
            }
        }
        self.chosen = Some(Chosen {
            scope: "mesh",
            worker: name,
            broker,
        });
    }
}

/// The pre-publish verdict.
#[derive(Debug, Clone)]
pub struct Plan {
    /// True when the job must go to the mesh rather than a local worker.
    pub route_remote: bool,
    pub record: RoutingRecord,
}

/// Does a node pin send the job to a broker other than this one?
pub fn pin_is_elsewhere(
    node_key: &super::node_identity::NodeKey,
    target_node: Option<&str>,
) -> bool {
    target_node.is_some_and(|tn| !super::node_identity::node_filter_matches(node_key, tn))
}

/// Why `w` cannot take `req`, in the order a requester would want to fix it.
/// Local workers are held to what `select_local_worker` enforces (tags and
/// interpreter); peer workers to the full `select_worker` set, since nobody
/// has vouched for their free capacity.
fn ineligible(w: &Worker, local: bool, req: &ResourceRequirements) -> Option<&'static str> {
    if !runs_payload(w, req.python.as_deref()) {
        return Some("runtime");
    }
    if !req.tags.iter().all(|t| w.tags.contains(t)) {
        return Some("capability");
    }
    if local {
        return None;
    }
    if req
        .worker_type
        .as_deref()
        .is_some_and(|t| w.worker_type != t)
    {
        return Some("capability");
    }
    if !meets_vram(w, req.min_vram_gb) {
        return Some("vram");
    }
    if !w.can_handle(req.cpus, req.memory_bytes, req.gpus) {
        return Some("capability");
    }
    if req.timeout_secs > 0.0 && w.max_timeout_secs > 0.0 && w.max_timeout_secs < req.timeout_secs {
        return Some("capability");
    }
    None
}

/// Decide, before anything is published, whether this job stays on a local
/// worker. `healthy` is the registry's healthy workers (peer-synced included).
pub fn plan(
    policy: Placement,
    source: &'static str,
    healthy: &[Worker],
    own_ip: Option<&str>,
    req: &ResourceRequirements,
    pinned_elsewhere: bool,
) -> Plan {
    let mut candidates: Vec<Candidate> = healthy
        .iter()
        .map(|w| {
            let local = is_own_worker(w, own_ip);
            Candidate {
                worker_id: w.id.clone(),
                worker: w.name.clone(),
                scope: if local { "local" } else { "mesh" },
                broker: if local { None } else { w.source_node.clone() },
                price_per_hour: w.pricing.price_per_hour,
                excluded: ineligible(w, local, req),
                chosen: false,
            }
        })
        .collect();

    let cheapest = |scope: &str, cands: &[Candidate]| {
        cands
            .iter()
            .filter(|c| c.scope == scope && c.excluded.is_none())
            .map(|c| c.price_per_hour)
            .fold(None, |m: Option<f64>, p| Some(m.map_or(p, |m| m.min(p))))
    };
    let local_best = cheapest("local", &candidates);
    let peer_best = cheapest("mesh", &candidates);

    let (route_remote, note) = if pinned_elsewhere {
        (
            true,
            "target_node pins another broker; local workers excluded".to_string(),
        )
    } else {
        match policy {
            Placement::MeshOnly => (true, "mesh_only: never run on this broker".to_string()),
            Placement::OwnFirst => (
                false,
                "own_first: local worker if one matches, else the mesh".to_string(),
            ),
            Placement::BestPriceMesh => match (local_best, peer_best) {
                (Some(l), Some(p)) if p < l => (
                    true,
                    format!("best_price_mesh: cheapest peer {p} < best local {l} ¥/h"),
                ),
                (Some(l), Some(p)) => (
                    false,
                    format!("best_price_mesh: best local {l} <= cheapest peer {p} ¥/h (tie stays local)"),
                ),
                (Some(_), None) => (
                    false,
                    "best_price_mesh: no eligible peer worker, staying local".to_string(),
                ),
                (None, _) => (
                    true,
                    "best_price_mesh: no eligible local worker, publishing to the mesh".to_string(),
                ),
            },
        }
    };

    // Reasons for the workers the verdict leaves out.
    for c in candidates.iter_mut().filter(|c| c.excluded.is_none()) {
        c.excluded = match (c.scope, route_remote) {
            ("local", true) if pinned_elsewhere => Some("pinned_elsewhere"),
            ("local", true) if policy == Placement::MeshOnly => Some("policy"),
            ("local", true) => Some("price"),
            ("mesh", false) if policy == Placement::BestPriceMesh => Some("price"),
            ("mesh", false) => Some("not_local"),
            _ => None,
        };
    }
    // A worker that could never run the job keeps its concrete reason
    // (runtime/capability/vram) -- only eligible ones get a policy reason.
    Plan {
        route_remote,
        record: RoutingRecord {
            policy: policy.as_str(),
            policy_source: source,
            enforced: true,
            candidates,
            chosen: None,
            note,
        },
    }
}

/// The policy that applies on the paths that select over every worker without
/// publishing (local mode, non-P2P billing). Only `mesh_only` can be enforced
/// there: it narrows the selection to peer workers.
pub fn enforced_on_direct_paths(policy: Placement) -> bool {
    policy == Placement::MeshOnly
}

/// Record for a job the direct (non-publishing) paths routed to `chosen`.
///
/// `mesh_only` was enforced by narrowing the selection to peer workers, so
/// the plan's own reasons are true. For `own_first` / `best_price_mesh` the
/// selection ignores the policy (it ranks by the request's strategy), so the
/// record says so and drops the policy-derived exclusion reasons, keeping
/// only the concrete ones (runtime, capability, vram). `own_first` is marked
/// enforced only when the worker that was picked is in fact a local one.
pub fn record_direct(
    policy: Placement,
    source: &'static str,
    healthy: &[Worker],
    own_ip: Option<&str>,
    req: &ResourceRequirements,
    chosen: &Worker,
    broker: &str,
) -> RoutingRecord {
    let mut plan = plan(policy, source, healthy, own_ip, req, false);
    let local = is_own_worker(chosen, own_ip);
    let mut rec = plan.record.clone();
    match policy {
        Placement::MeshOnly => {
            rec.note = "mesh_only: enforced, selection limited to peer workers".to_string();
        }
        Placement::OwnFirst => {
            rec.enforced = local;
            rec.note = if local {
                "own_first: not applied on this path (no mesh dispatch); the chosen worker is local"
                    .to_string()
            } else {
                "own_first: not applied on this path (no mesh dispatch); the worker was chosen by the routing strategy over all workers and is a peer worker".to_string()
            };
        }
        Placement::BestPriceMesh => {
            rec.enforced = false;
            rec.note = "best_price_mesh: not applied on this path; the worker was chosen by the routing strategy over all workers".to_string();
        }
    }
    if policy != Placement::MeshOnly {
        for c in &mut rec.candidates {
            if matches!(c.excluded, Some("policy" | "price" | "not_local")) {
                c.excluded = None;
            }
        }
    }
    if local {
        rec.finish_local(&chosen.id, broker);
    } else {
        rec.finish_remote(Some(&chosen.name));
    }
    plan.record = rec;
    plan.record
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::broker::worker::{test_registration, WorkerRegistry};

    fn reg(name: &str, uri: &str, price: f64, source: Option<&str>) -> Worker {
        let r = WorkerRegistry::new();
        let mut w = r.register(test_registration(name, uri.to_string(), price));
        w.source_node = source.map(str::to_string);
        w
    }

    fn req() -> ResourceRequirements {
        ResourceRequirements::default()
    }

    #[test]
    fn parses_known_values_and_rejects_unknown_with_a_clear_message() {
        assert_eq!(Placement::parse("own_first"), Ok(Placement::OwnFirst));
        assert_eq!(Placement::parse("mesh_only"), Ok(Placement::MeshOnly));
        let e = Placement::parse("cheapest").unwrap_err();
        assert!(
            e.contains("own_first") && e.contains("best_price_mesh") && e.contains("mesh_only")
        );
        assert!(validate_raw(r#"{"placement":"nope"}"#).is_err());
        assert!(validate_raw(r#"{"placement":7}"#).is_err());
        assert!(validate_raw(r#"{"placement":"mesh_only"}"#).is_ok());
        assert!(validate_raw(r#"{"cpus":2}"#).is_ok());
        let r: ResourceRequirements = serde_json::from_str(r#"{"placement":"mesh_only"}"#).unwrap();
        assert_eq!(r.placement, Some(Placement::MeshOnly));
        assert!(serde_json::from_str::<ResourceRequirements>(r#"{"placement":"x"}"#).is_err());
    }

    #[test]
    fn precedence_is_request_then_hub_then_own_first() {
        use Placement::*;
        assert_eq!(
            resolve_with(Some(MeshOnly), Some(BestPriceMesh)),
            (MeshOnly, "request")
        );
        assert_eq!(
            resolve_with(None, Some(BestPriceMesh)),
            (BestPriceMesh, "hub_default")
        );
        assert_eq!(resolve_with(None, None), (OwnFirst, "default"));
        assert_eq!(Placement::default(), OwnFirst);
    }

    #[test]
    fn mesh_only_never_goes_local() {
        let ws = vec![
            reg("mine", "http://127.0.0.1:1", 1.0, None),
            reg("theirs", "http://10.0.0.9:1", 9.0, Some("peer-a")),
        ];
        let p = plan(Placement::MeshOnly, "request", &ws, None, &req(), false);
        assert!(p.route_remote);
        let local = p
            .record
            .candidates
            .iter()
            .find(|c| c.scope == "local")
            .unwrap();
        assert_eq!(local.excluded, Some("policy"));
    }

    #[test]
    fn own_first_stays_local_and_marks_peers_not_local() {
        let ws = vec![
            reg("mine", "http://127.0.0.1:1", 50.0, None),
            reg("theirs", "http://10.0.0.9:1", 1.0, Some("peer-a")),
        ];
        let p = plan(Placement::OwnFirst, "default", &ws, None, &req(), false);
        assert!(!p.route_remote);
        let peer = p
            .record
            .candidates
            .iter()
            .find(|c| c.scope == "mesh")
            .unwrap();
        assert_eq!(peer.excluded, Some("not_local"));
    }

    #[test]
    fn best_price_mesh_goes_remote_only_when_a_peer_is_strictly_cheaper() {
        let cheaper_peer = vec![
            reg("mine", "http://127.0.0.1:1", 40.0, None),
            reg("theirs", "http://10.0.0.9:1", 3.6, Some("peer-a")),
        ];
        let p = plan(
            Placement::BestPriceMesh,
            "request",
            &cheaper_peer,
            None,
            &req(),
            false,
        );
        assert!(p.route_remote, "{}", p.record.note);
        assert_eq!(
            p.record
                .candidates
                .iter()
                .find(|c| c.scope == "local")
                .unwrap()
                .excluded,
            Some("price")
        );

        let dearer_peer = vec![
            reg("mine", "http://127.0.0.1:1", 3.6, None),
            reg("theirs", "http://10.0.0.9:1", 40.0, Some("peer-a")),
        ];
        let p = plan(
            Placement::BestPriceMesh,
            "request",
            &dearer_peer,
            None,
            &req(),
            false,
        );
        assert!(!p.route_remote);
        assert_eq!(
            p.record
                .candidates
                .iter()
                .find(|c| c.scope == "mesh")
                .unwrap()
                .excluded,
            Some("price")
        );

        // The local worker is ranked at its LISTED price, not at 0: a free
        // execution does not make it unbeatable.
        let tie = vec![
            reg("mine", "http://127.0.0.1:1", 3.6, None),
            reg("theirs", "http://10.0.0.9:1", 3.6, Some("peer-a")),
        ];
        assert!(
            !plan(
                Placement::BestPriceMesh,
                "request",
                &tie,
                None,
                &req(),
                false
            )
            .route_remote
        );
    }

    #[test]
    fn best_price_mesh_ignores_ineligible_peers_and_reports_why() {
        let mut gpu_less = reg("cheap-no-vram", "http://10.0.0.9:1", 1.0, Some("peer-a"));
        gpu_less.hardware.gpu_vram_gb = Some(8);
        let ws = vec![reg("mine", "http://127.0.0.1:1", 40.0, None), gpu_less];
        let mut r = req();
        r.min_vram_gb = Some(24);
        let p = plan(Placement::BestPriceMesh, "request", &ws, None, &r, false);
        assert!(!p.route_remote);
        assert_eq!(
            p.record
                .candidates
                .iter()
                .find(|c| c.scope == "mesh")
                .unwrap()
                .excluded,
            Some("vram")
        );
        let mut r = req();
        r.python = Some("3.99".into());
        let p = plan(Placement::OwnFirst, "default", &ws, None, &r, false);
        assert!(p
            .record
            .candidates
            .iter()
            .all(|c| c.excluded == Some("runtime")));
    }

    #[test]
    fn a_pin_to_another_broker_excludes_local_workers_under_any_policy() {
        let ws = vec![reg("mine", "http://127.0.0.1:1", 1.0, None)];
        let p = plan(Placement::OwnFirst, "default", &ws, None, &req(), true);
        assert!(p.route_remote);
        assert_eq!(p.record.candidates[0].excluded, Some("pinned_elsewhere"));
    }

    #[test]
    fn decision_payload_is_ascii_json_with_the_choice() {
        let ws = vec![
            reg("m\u{00fc}ne", "http://127.0.0.1:1", 5.0, None),
            reg("theirs", "http://10.0.0.9:1", 1.0, Some("peer-a")),
        ];
        let mut p = plan(
            Placement::BestPriceMesh,
            "hub_default",
            &ws,
            None,
            &req(),
            false,
        );
        assert!(p.route_remote);
        p.record.finish_remote(Some("theirs"));
        let h = p.record.to_header();
        assert!(h.is_ascii());
        assert!(axum_free_header_ok(&h));
        let v: serde_json::Value = serde_json::from_str(&h).unwrap();
        assert_eq!(v["policy"], "best_price_mesh");
        assert_eq!(v["policy_source"], "hub_default");
        assert_eq!(v["chosen"]["scope"], "mesh");
        assert_eq!(v["chosen"]["worker"], "theirs");
        assert_eq!(v["chosen"]["broker"], "peer-a");
        let cands = v["candidates"].as_array().unwrap();
        assert_eq!(cands.len(), 2);
        let local = cands.iter().find(|c| c["scope"] == "local").unwrap();
        assert_eq!(local["excluded"], "price");
        assert_eq!(local["worker"], "m\u{00fc}ne");

        let mut l = plan(Placement::OwnFirst, "default", &ws, None, &req(), false);
        let id = ws[0].id.clone();
        l.record.finish_local(&id, "node-x");
        assert_eq!(l.record.chosen.as_ref().unwrap().scope, "local");
        assert!(l.record.candidates.iter().any(|c| c.chosen));
    }

    fn axum_free_header_ok(h: &str) -> bool {
        tiny_http::Header::from_bytes(b"X-Zakuro-Routing".as_slice(), h.as_bytes()).is_ok()
    }
}