troupekit-providers 0.4.0

Model providers for the Troupekit LLM agent framework: wire protocols, catalog, transports and middleware.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
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
use super::decide::{decide, BoundTarget, RoutePlan};
use super::policy::{NetworkMode, RoutePolicy};
use super::signals::{DeviceState, NetworkProbe, PassiveProbe, RouteTags, Signals};
use super::RouteError;
use crate::catalog::Price;
use crate::model::{FailedCall, Model};
use crate::request::{CompletionRequest, CompletionResponse, Delta};
use async_trait::async_trait;
use std::collections::HashMap;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use troupekit_core::clock::{Clock, SystemClock};
use troupekit_core::error::{CoreError, ProviderError, ProviderErrorKind};
use troupekit_core::event::Usage;
use troupekit_core::store::UsageLedger;
use troupekit_trace::{trace, trace_span, Span, Trace};

const DAY_MS: i64 = 86_400_000;

#[derive(Default)]
struct DayLedger(Mutex<HashMap<String, u64>>);

#[async_trait]
impl UsageLedger for DayLedger {
    async fn period_total(&self, key: &str) -> Result<u64, CoreError> {
        let totals = self.0.lock().unwrap_or_else(|p| p.into_inner());
        Ok(totals.get(key).copied().unwrap_or(0))
    }

    async fn record(&self, key: &str, usage: Usage) -> Result<(), CoreError> {
        let mut totals = self.0.lock().unwrap_or_else(|p| p.into_inner());
        let total = totals.entry(key.to_owned()).or_insert(0);
        *total = total.saturating_add(usage.cost_usd_micros);
        Ok(())
    }
}

struct Bound {
    target: BoundTarget,
    model: Arc<dyn Model>,
    price: Price,
}

struct Shared {
    policy: RoutePolicy,
    bound: Vec<Bound>,
    targets: Vec<BoundTarget>,
    app_probe: Option<Arc<dyn NetworkProbe>>,
    passive: PassiveProbe,
    device: Option<DeviceState>,
    ledger: Arc<dyn UsageLedger>,
    unrecorded: Mutex<HashMap<String, Usage>>,
    reserved: Mutex<u64>,
    admit: tokio::sync::Mutex<()>,
    ledger_io: Arc<tokio::sync::Mutex<()>>,
    drain_waiting: AtomicBool,
    clock: Arc<dyn Clock>,
}

/// Worst-case spend of one in-flight remote call, held against the daily
/// cap from dispatch until its reply is charged, so concurrent requests
/// see it. Dropping it releases the amount.
struct Reservation<'a> {
    shared: &'a Shared,
    amount: u64,
}

impl Drop for Reservation<'_> {
    fn drop(&mut self) {
        let mut reserved = self
            .shared
            .reserved
            .lock()
            .unwrap_or_else(|p| p.into_inner());
        assert!(
            *reserved >= self.amount,
            "a release never exceeds the reservations"
        );
        *reserved -= self.amount;
    }
}

/// Builds a `RoutedModel`: bind every policy target to a model, on the
/// device or remote, then `build`. Defaults: a passive network probe, no
/// device state, an in-memory spend ledger per UTC day, the wall clock.
pub struct RoutedModelBuilder {
    policy: RoutePolicy,
    bound: Vec<Bound>,
    app_probe: Option<Arc<dyn NetworkProbe>>,
    device: Option<DeviceState>,
    ledger: Option<Arc<dyn UsageLedger>>,
    clock: Arc<dyn Clock>,
}

impl RoutedModelBuilder {
    /// Binds target `id` to `model`, declared as running on the device.
    /// `price` prices its replies for views and the spend ledger.
    /// A model metered at another price never bills below it.
    /// Private and offline requests may reach it.
    pub fn on_device(mut self, id: &str, model: Arc<dyn Model>, price: Price) -> Self {
        self.bound.push(Bound {
            target: BoundTarget::on_device(id),
            model,
            price,
        });
        self
    }

    /// Binds target `id` to `model`, declared as remote.
    /// Its spend counts against the daily cap.
    /// `price` bills each reply; a model metered at another price never
    /// bills below it.
    /// Private and offline requests never reach it.
    pub fn remote(mut self, id: &str, model: Arc<dyn Model>, price: Price) -> Self {
        self.bound.push(Bound {
            target: BoundTarget::remote(id),
            model,
            price,
        });
        self
    }

    /// Reads the network state from `probe`, for example the app's
    /// `NetworkState`. When it reports unknown, the passive probe decides.
    /// Ignored when the policy pins `[network] mode`.
    pub fn network(mut self, probe: Arc<dyn NetworkProbe>) -> Self {
        self.app_probe = Some(probe);
        self
    }

    /// Reads battery and thermal state from `device` at each call.
    /// Without it both are unknown and their rules are skipped.
    /// Keep a clone to update it.
    pub fn device(mut self, device: DeviceState) -> Self {
        self.device = Some(device);
        self
    }

    /// Keeps remote spend in `ledger`, one key per policy and UTC day.
    /// Default: in memory, lost on restart. A failed read counts as the cap
    /// reached; a failed write is kept in memory, counted and retried. Calls
    /// in flight and unwritten spend are seen only by this model and its
    /// views, so the cap is soft across models or processes sharing a ledger.
    pub fn ledger(mut self, ledger: Arc<dyn UsageLedger>) -> Self {
        self.ledger = Some(ledger);
        self
    }

    /// Reads time from `clock` for the UTC day and the passive probe.
    /// Default: the wall clock.
    /// Tests inject a `FixedClock`.
    pub fn clock(mut self, clock: Arc<dyn Clock>) -> Self {
        self.clock = clock;
        self
    }

    /// Checks the bindings and builds the routed model. Returns
    /// `RouteError::Bind` for an id the policy does not name, an id bound
    /// twice, or a policy target left unbound.
    pub fn build(self) -> Result<RoutedModel, RouteError> {
        let bind_error = |target: &str, message: &str| RouteError::Bind {
            target: target.to_owned(),
            message: message.to_owned(),
        };
        for (at, b) in self.bound.iter().enumerate() {
            if self.policy.target(b.target.id()).is_none() {
                return Err(bind_error(b.target.id(), "the policy names no such target"));
            }
            if self.bound[..at]
                .iter()
                .any(|o| o.target.id() == b.target.id())
            {
                return Err(bind_error(b.target.id(), "bound twice"));
            }
        }
        for t in self.policy.targets() {
            if !self.bound.iter().any(|b| b.target.id() == t.id()) {
                return Err(bind_error(t.id(), "the policy target is not bound"));
            }
        }
        assert_eq!(
            self.bound.len(),
            self.policy.targets().len(),
            "one binding per target"
        );
        let passive = PassiveProbe::new(self.policy.network()).with_clock(self.clock.clone());
        let id = format!("route/{}", self.policy.name());
        let shared = Shared {
            targets: self.bound.iter().map(|b| b.target.clone()).collect(),
            policy: self.policy,
            bound: self.bound,
            app_probe: self.app_probe,
            passive,
            device: self.device,
            ledger: self
                .ledger
                .unwrap_or_else(|| Arc::new(DayLedger::default())),
            unrecorded: Mutex::new(HashMap::new()),
            reserved: Mutex::new(0),
            admit: tokio::sync::Mutex::new(()),
            ledger_io: Arc::new(tokio::sync::Mutex::new(())),
            drain_waiting: AtomicBool::new(false),
            clock: self.clock,
        };
        Ok(RoutedModel {
            shared: Arc::new(shared),
            tags: RouteTags::default(),
            id,
        })
    }
}

/// A `Model` that routes each request by a `RoutePolicy`: it plans the
/// eligible targets with `decide` and tries them in order. A private
/// request never reaches a remote target, even when every local one fails.
#[derive(Clone)]
pub struct RoutedModel {
    shared: Arc<Shared>,
    tags: RouteTags,
    id: String,
}

fn max_price(prices: impl Iterator<Item = Price>) -> Price {
    let mut out = Price::FREE;
    for p in prices {
        let lc = p.long_context;
        let input = lc.map_or(0, |l| l.input_usd_micros_per_mtok);
        let output = lc.map_or(0, |l| l.output_usd_micros_per_mtok);
        out.input_usd_micros_per_mtok = out
            .input_usd_micros_per_mtok
            .max(p.input_usd_micros_per_mtok)
            .max(input);
        out.output_usd_micros_per_mtok = out
            .output_usd_micros_per_mtok
            .max(p.output_usd_micros_per_mtok)
            .max(output);
        out.search_usd_micros = out.search_usd_micros.max(p.search_usd_micros);
        out.verified = out.verified && p.verified;
    }
    assert!(
        out.long_context.is_none(),
        "a view price folds long-context rates in"
    );
    out
}

fn estimate_prompt_tokens(req: &CompletionRequest) -> u64 {
    let bytes = req.system.as_ref().map_or(0, String::len)
        + serde_json::to_string(&req.messages).map_or(0, |s| s.len())
        + serde_json::to_string(&req.tools).map_or(0, |s| s.len());
    u64::try_from(bytes.div_ceil(4)).unwrap_or(u64::MAX)
}

impl RoutedModel {
    /// Starts a builder for `policy`. Every policy target must be bound
    /// with `on_device` or `remote` before `build`.
    /// Returns the builder.
    pub fn builder(policy: RoutePolicy) -> RoutedModelBuilder {
        RoutedModelBuilder {
            policy,
            bound: Vec::new(),
            app_probe: None,
            device: None,
            ledger: None,
            clock: Arc::new(SystemClock),
        }
    }

    /// The policy this model routes by.
    /// Never changes after `build`.
    /// Shared by every view.
    pub fn policy(&self) -> &RoutePolicy {
        &self.shared.policy
    }

    /// Returns a view of this model with `tags` added: a cheap clone that
    /// shares targets, probe and ledger. `private` is sticky, so a view of
    /// a private view stays private; a missing tier keeps the current one.
    pub fn view(&self, tags: RouteTags) -> RoutedModel {
        let private = self.tags.private || tags.private;
        let tier = tags.tier.or_else(|| self.tags.tier.clone());
        let mut id = format!("route/{}", self.shared.policy.name());
        if private {
            id.push_str(":private");
        }
        if let Some(t) = &tier {
            id.push(':');
            id.push_str(t);
        }
        let tags = RouteTags { private, tier };
        assert!(
            !self.tags.private || tags.private,
            "a view never clears private"
        );
        RoutedModel {
            shared: self.shared.clone(),
            tags,
            id,
        }
    }

    /// Lists the views to register under `prefix`: `prefix`,
    /// `prefix:private` and `prefix:<tier>` per policy tier, each with the
    /// highest price among the targets it can reach, so budgets stay safe.
    pub fn views(&self, prefix: &str) -> Vec<(String, Arc<dyn Model>, Price)> {
        let base = self.view(RouteTags::default());
        let mut tagged = vec![
            (String::new(), base.clone()),
            (
                ":private".to_owned(),
                base.view(RouteTags::default().with_private(true)),
            ),
        ];
        for tier in self.shared.policy.tiers() {
            let view = base.view(RouteTags::default().with_tier(tier.clone()));
            tagged.push((format!(":{tier}"), view));
        }
        let out: Vec<(String, Arc<dyn Model>, Price)> = tagged
            .into_iter()
            .map(|(suffix, view)| {
                let name = format!("{prefix}{suffix}");
                let price = view.price();
                let view = RoutedModel {
                    id: name.clone(),
                    ..view
                };
                (name, Arc::new(view) as Arc<dyn Model>, price)
            })
            .collect();
        assert_eq!(
            out.len(),
            2 + self.shared.policy.tiers().len(),
            "one view per name"
        );
        out
    }

    /// The highest price among the targets this view can reach: on-device
    /// only when private, only targets serving the tier when one is set.
    /// Budgets charge it, so they never under-count.
    pub fn price(&self) -> Price {
        let shared = &self.shared;
        let reaches = |b: &&Bound| {
            let serves = self.tags.tier.as_ref().is_none_or(|tier| {
                shared
                    .policy
                    .target(b.target.id())
                    .is_some_and(|t| t.tiers().contains(tier))
            });
            serves && (!self.tags.private || b.target.is_on_device())
        };
        max_price(shared.bound.iter().filter(reaches).map(|b| b.price))
    }

    fn day_key(&self) -> String {
        let day = self.shared.clock.now_ms().div_euclid(DAY_MS);
        format!("route/{}/remote/{day}", self.shared.policy.name())
    }

    /// Reads today's remote spend: the ledger total plus spend parked for
    /// today. Both are read under the ledger lock every write holds, so an
    /// amount is counted parked or written, once. Output: the total.
    async fn spent_today(&self) -> u64 {
        let (spent, key, _io) = self.ledger_today().await;
        spent.saturating_add(self.unrecorded(&key).cost_usd_micros)
    }

    /// Reads today's ledger total, after starting a write of parked spend,
    /// and keeps the ledger lock so no write moves parked spend into the
    /// ledger before the caller reads it. When the UTC day changes during
    /// the read the new day is read, so yesterday's spend never routes
    /// today. A failed read is `u64::MAX`. Output: total, day key, lock.
    async fn ledger_today(&self) -> (u64, String, tokio::sync::OwnedMutexGuard<()>) {
        let parked = !self
            .shared
            .unrecorded
            .lock()
            .unwrap_or_else(|p| p.into_inner())
            .is_empty();
        if parked {
            self.flush().await;
        }
        let io = Arc::clone(&self.shared.ledger_io).lock_owned().await;
        let ledger = &self.shared.ledger;
        let key = self.day_key();
        let spent = ledger.period_total(&key).await.unwrap_or(u64::MAX);
        let now = self.day_key();
        if now == key {
            return (spent, key, io);
        }
        let spent = ledger.period_total(&now).await.unwrap_or(u64::MAX);
        (spent, now, io)
    }

    fn unrecorded(&self, key: &str) -> Usage {
        let owed = self
            .shared
            .unrecorded
            .lock()
            .unwrap_or_else(|p| p.into_inner());
        owed.get(key).copied().unwrap_or_default()
    }

    /// Parks one remote reply's `usage` under today's key before any await,
    /// so a cancelled call never drops it, then writes the parked totals and
    /// releases `held` under the admission lock, so an admission sees the
    /// charge or the reservation. Reads count parked spend until written.
    async fn charge(&self, usage: Usage, held: Reservation<'_>) {
        let key = self.day_key();
        *self
            .shared
            .unrecorded
            .lock()
            .unwrap_or_else(|p| p.into_inner())
            .entry(key)
            .or_default() += usage;
        let _admit = self.shared.admit.lock().await;
        self.flush().await;
        drop(held);
    }

    /// Writes every parked total to the ledger under the ledger lock. The
    /// writes run in their own task, so a cancelled caller never leaves a
    /// written amount parked to be written again. While a write or a read
    /// holds the lock it returns at once and leaves one task waiting for
    /// the lock to write, so parked spend never waits for another request.
    async fn flush(&self) {
        let lock = Arc::clone(&self.shared.ledger_io);
        let held = lock.clone().try_lock_owned().ok();
        let waits = held.is_none();
        if waits && self.shared.drain_waiting.swap(true, Ordering::SeqCst) {
            return;
        }
        let shared = Arc::clone(&self.shared);
        let scope = troupekit_trace::current();
        let write = tokio::spawn(async move {
            let busy = match held {
                Some(busy) => busy,
                None => {
                    let busy = lock.lock_owned().await;
                    shared.drain_waiting.store(false, Ordering::SeqCst);
                    busy
                }
            };
            let parked = write_parked(&shared);
            match scope {
                Some(scope) => scope.in_scope(parked).await,
                None => parked.await,
            }
            drop(busy);
        });
        if waits {
            return;
        }
        if let Err(e) = write.await {
            if e.is_panic() {
                std::panic::resume_unwind(e.into_panic());
            }
        }
    }
}

/// Writes every parked total in `shared` to its ledger. An amount leaves
/// the parked map only after its write succeeds; a failed write stays
/// parked, is retried on the next read or charge, and traces
/// `law.check route_spend_recorded held=false`. Output: none.
async fn write_parked(shared: &Shared) {
    let parked: Vec<(String, Usage)> = shared
        .unrecorded
        .lock()
        .unwrap_or_else(|p| p.into_inner())
        .iter()
        .map(|(k, u)| (k.clone(), *u))
        .collect();
    for (key, usage) in parked {
        if shared.ledger.record(&key, usage).await.is_err() {
            trace!(
                Trace::Laws,
                "law.check",
                law = "route_spend_recorded",
                held = false,
                owed_usd_micros = usage.cost_usd_micros,
            );
            continue;
        }
        let mut owed = shared.unrecorded.lock().unwrap_or_else(|p| p.into_inner());
        let left = owed.get(&key).copied().unwrap_or_default();
        assert!(
            left.cost_usd_micros >= usage.cost_usd_micros,
            "only the flush removes parked spend"
        );
        let rest = Usage {
            input_tokens: left.input_tokens.saturating_sub(usage.input_tokens),
            output_tokens: left.output_tokens.saturating_sub(usage.output_tokens),
            cost_usd_micros: left.cost_usd_micros - usage.cost_usd_micros,
        };
        if rest.cost_usd_micros == 0 && rest.input_tokens == 0 && rest.output_tokens == 0 {
            owed.remove(&key);
        } else {
            owed.insert(key, rest);
        }
    }
}

impl RoutedModel {
    /// Admits planned target `at`. Under a cap, a remote target is skipped
    /// when today's spend plus in-flight reservations reached it, and else
    /// reserves its worst-case cost. The spend is read under the admission
    /// lock `charge` holds and the ledger lock, and parked spend is read
    /// after the reservations are locked: a charge parks before it releases
    /// its reservation, so a cancelled charge is seen as one or the other.
    /// Emits `route.fallback` after a failure.
    /// Output: the reservation to hold until the reply is charged, or `None`.
    async fn starts(
        &self,
        at: usize,
        b: &Bound,
        req: &CompletionRequest,
        failed: Option<&(&BoundTarget, ProviderError)>,
    ) -> Option<Reservation<'_>> {
        assert!(
            at > 0 || failed.is_none(),
            "only a fallback follows a failure"
        );
        let shared = &self.shared;
        let mut amount = 0;
        if let (false, Some(cap)) = (
            b.target.is_on_device(),
            shared.policy.budget().cloud_usd_micros_per_day(),
        ) {
            let _admit = shared.admit.lock().await;
            let (spent, key, _io) = self.ledger_today().await;
            let worst = Usage {
                input_tokens: estimate_prompt_tokens(req),
                output_tokens: u64::from(req.max_tokens),
                cost_usd_micros: 0,
            };
            let mut reserved = shared.reserved.lock().unwrap_or_else(|p| p.into_inner());
            let spent = spent.saturating_add(self.unrecorded(&key).cost_usd_micros);
            if spent.saturating_add(*reserved) >= cap {
                return None;
            }
            amount = b.price.cost_usd_micros(&worst).min(cap);
            *reserved = reserved.saturating_add(amount);
        }
        if let Some((from, err)) = failed {
            trace_fallback(from, err);
        }
        Some(Reservation { shared, amount })
    }

    fn online(&self) -> Option<bool> {
        let shared = &self.shared;
        match shared.policy.network().mode() {
            NetworkMode::Online => Some(true),
            NetworkMode::Offline => Some(false),
            _ => shared
                .app_probe
                .as_ref()
                .and_then(|p| p.online())
                .or_else(|| shared.passive.online()),
        }
    }

    async fn plan(
        &self,
        req: &CompletionRequest,
        stats: &mut RouteStats,
    ) -> Result<RoutePlan, ProviderError> {
        let shared = &self.shared;
        let spent = match shared.policy.budget().cloud_usd_micros_per_day() {
            Some(_) if !self.tags.private => Some(self.spent_today().await),
            _ => None,
        };
        stats.spent_read = spent.is_some();
        let mut signals = Signals::default()
            .with_online(self.online())
            .with_cloud_spent_today_usd_micros(spent.unwrap_or(0))
            .with_prompt_tokens(estimate_prompt_tokens(req))
            .with_max_tokens(u64::from(req.max_tokens));
        if let Some(device) = &shared.device {
            signals = signals
                .with_battery_percent(device.battery_percent())
                .with_thermal(device.thermal());
        }
        let plan = decide(&shared.policy, &shared.targets, &self.tags, &signals);
        let held = !self.tags.private || plan.targets().iter().all(BoundTarget::is_on_device);
        trace!(
            Trace::Laws,
            "law.check",
            law = "private_plan_has_only_on_device_targets",
            held = held,
            private = self.tags.private,
            targets = plan.targets().len(),
        );
        plan.assert_lawful(&self.tags);
        stats.planned(&plan, signals);
        if plan.is_empty() {
            let message = format!("no route: {}", plan.reason());
            return Err(ProviderError::new(ProviderErrorKind::Network, message));
        }
        Ok(plan)
    }

    fn decide_span(&self) -> Span {
        let mut span = trace_span!(
            Trace::Routing,
            "route.decide",
            model = self.id.as_str(),
            private = self.tags.private,
        );
        if let Some(tier) = &self.tags.tier {
            span.record("tier", tier.as_str());
        }
        span
    }

    async fn complete_routed(
        &self,
        req: &CompletionRequest,
        stats: &mut RouteStats,
    ) -> Result<CompletionResponse, FailedCall> {
        let plan = self.plan(req, stats).await?;
        let fallback = self.shared.policy.fallback().on_error();
        let mut spent = Usage::default();
        let mut last = None;
        for (at, target) in plan.targets().iter().enumerate() {
            let b = self.bound(target);
            let Some(held) = self.starts(at, b, req, last.as_ref()).await else {
                continue;
            };
            let result = b.model.complete_billed(req).await;
            let result = self.settle(b, held, result).await;
            match result {
                Ok(mut reply) => {
                    stats.chosen = Some(target.id().to_owned());
                    reply.usage += spent;
                    return Ok(reply);
                }
                Err(failed) => {
                    spent += failed.usage;
                    if !fallback {
                        return Err(FailedCall { error: failed.error, usage: spent });
                    }
                    last = Some((target, failed.error));
                }
            }
        }
        let error = last.map_or_else(over_cap, |(_, err)| err);
        Err(FailedCall { error, usage: spent })
    }

    async fn stream_routed(
        &self,
        req: &CompletionRequest,
        on_delta: &mut (dyn for<'d> FnMut(&'d Delta) + Send),
        stats: &mut RouteStats,
    ) -> Result<CompletionResponse, FailedCall> {
        let plan = self.plan(req, stats).await?;
        let fallback = self.shared.policy.fallback().on_error();
        let mut spent = Usage::default();
        let mut last = None;
        for (at, target) in plan.targets().iter().enumerate() {
            let b = self.bound(target);
            let Some(held) = self.starts(at, b, req, last.as_ref()).await else {
                continue;
            };
            let mut emitted = false;
            let result = b
                .model
                .stream_billed(req, &mut |d: &Delta| {
                    emitted = true;
                    on_delta(d);
                })
                .await;
            let result = self.settle(b, held, result).await;
            match result {
                Ok(mut reply) => {
                    stats.chosen = Some(target.id().to_owned());
                    reply.usage += spent;
                    return Ok(reply);
                }
                Err(failed) => {
                    spent += failed.usage;
                    if emitted || !fallback {
                        return Err(FailedCall { error: failed.error, usage: spent });
                    }
                    last = Some((target, failed.error));
                }
            }
        }
        let error = last.map_or_else(over_cap, |(_, err)| err);
        Err(FailedCall { error, usage: spent })
    }

    fn bound(&self, target: &BoundTarget) -> &Bound {
        assert!(
            !self.tags.private || target.is_on_device(),
            "private request about to call a remote target"
        );
        let b = self
            .shared
            .bound
            .iter()
            .find(|b| b.target.id() == target.id());
        let b = b.expect("a planned target is bound");
        assert_eq!(
            b.target.is_on_device(),
            target.is_on_device(),
            "plan keeps locality"
        );
        b
    }

    /// Prices a reply, or the usage a failed call reported, at the target
    /// that served it, so the run bills that target and not the view's
    /// highest price, then charges remote spend and tells the probes. A
    /// target metered at its declared price keeps its cost, so a retried
    /// target is billed the sum of its tries at that price; any other
    /// target is never billed below its declared price. `held` is released
    /// with the charge. Output: `result` with the cost set.
    async fn settle(
        &self,
        b: &Bound,
        held: Reservation<'_>,
        result: Result<CompletionResponse, FailedCall>,
    ) -> Result<CompletionResponse, FailedCall> {
        let shared = &self.shared;
        let remote = !b.target.is_on_device();
        let own = b.model.meter_price() == Some(b.price);
        let mut reply = match result {
            Ok(reply) => reply,
            Err(mut failed) => {
                if remote && failed.error.kind == ProviderErrorKind::Network {
                    shared.passive.record_remote(true);
                    if let Some(p) = &shared.app_probe {
                        p.record_remote(true);
                    }
                }
                if !own {
                    let cost = b.price.cost_usd_micros(&failed.usage);
                    failed.usage.cost_usd_micros = failed.usage.cost_usd_micros.max(cost);
                    assert!(
                        failed.usage.cost_usd_micros >= cost,
                        "never bill a failed call below the target's price"
                    );
                }
                if remote && failed.usage != Usage::default() {
                    self.charge(failed.usage, held).await;
                }
                return Err(failed);
            }
        };
        if !own {
            let cost = b.price.reply_cost_usd_micros(&reply);
            reply.usage.cost_usd_micros = reply.usage.cost_usd_micros.max(cost);
            assert!(
                reply.usage.cost_usd_micros >= cost,
                "never bill below the target's price"
            );
        }
        if remote {
            shared.passive.record_remote(false);
            if let Some(p) = &shared.app_probe {
                p.record_remote(false);
            }
            self.charge(reply.usage, held).await;
        }
        Ok(reply)
    }
}

fn over_cap() -> ProviderError {
    ProviderError::new(
        ProviderErrorKind::Network,
        "no route: budget, in-flight remote calls hold the cap",
    )
}

fn trace_fallback(target: &BoundTarget, err: &ProviderError) {
    trace!(
        Trace::Routing,
        "route.fallback",
        from = target.id(),
        on_device = target.is_on_device(),
        kind = format!("{:?}", err.kind),
    );
}

#[derive(Default)]
struct RouteStats {
    plan: String,
    reason: String,
    signals: Option<Signals>,
    spent_read: bool,
    chosen: Option<String>,
}

impl RouteStats {
    fn planned(&mut self, plan: &RoutePlan, signals: Signals) {
        let ids: Vec<&str> = plan.targets().iter().map(BoundTarget::id).collect();
        self.plan = ids.join(",");
        self.reason = plan.reason().to_owned();
        self.signals = Some(signals);
    }

    fn finish(&self, span: &mut Span, error: Option<&ProviderError>) {
        if !span.is_enabled() {
            return;
        }
        span.record("plan", self.plan.as_str());
        span.record("reason", self.reason.as_str());
        if let Some(signals) = &self.signals {
            if let Some(online) = signals.online {
                span.record("online", online);
            }
            if let Some(battery) = signals.battery_percent {
                span.record("battery_percent", battery);
            }
            if let Some(thermal) = signals.thermal {
                span.record("thermal", format!("{thermal:?}").to_ascii_lowercase());
            }
            if self.spent_read {
                span.record(
                    "spent_today_usd_micros",
                    signals.cloud_spent_today_usd_micros,
                );
            }
            span.record("prompt_tokens", signals.prompt_tokens);
            span.record("max_tokens", signals.max_tokens);
        }
        if let Some(chosen) = &self.chosen {
            span.record("chosen", chosen.as_str());
        }
        if let Some(e) = error {
            span.fail("no route target answered");
            span.record("kind", format!("{:?}", e.kind));
        }
    }
}

#[async_trait]
impl Model for RoutedModel {
    fn id(&self) -> &str {
        &self.id
    }

    fn prices_replies(&self) -> bool {
        true
    }

    async fn complete(&self, req: &CompletionRequest) -> Result<CompletionResponse, ProviderError> {
        self.complete_billed(req).await.map_err(|failed| failed.error)
    }

    async fn stream(
        &self,
        req: &CompletionRequest,
        on_delta: &mut (dyn for<'d> FnMut(&'d Delta) + Send),
    ) -> Result<CompletionResponse, ProviderError> {
        self.stream_billed(req, on_delta)
            .await
            .map_err(|failed| failed.error)
    }

    async fn complete_billed(
        &self,
        req: &CompletionRequest,
    ) -> Result<CompletionResponse, FailedCall> {
        let mut span = self.decide_span();
        let mut stats = RouteStats::default();
        let result = span.instrument(self.complete_routed(req, &mut stats)).await;
        stats.finish(&mut span, result.as_ref().err().map(|f| &f.error));
        result
    }

    async fn stream_billed(
        &self,
        req: &CompletionRequest,
        on_delta: &mut (dyn for<'d> FnMut(&'d Delta) + Send),
    ) -> Result<CompletionResponse, FailedCall> {
        let mut span = self.decide_span();
        let mut stats = RouteStats::default();
        let result = span
            .instrument(self.stream_routed(req, on_delta, &mut stats))
            .await;
        stats.finish(&mut span, result.as_ref().err().map(|f| &f.error));
        result
    }
}