Skip to main content

adk_vision/runtime/
mod.rs

1//! [`VisionRuntime`]: routing, image preparation, the egress gate, metering and escalation
2//! (spec 3.7 §7.5).
3//!
4//! The runtime is the only place a [`SentImage`] is made. For each call it picks the route's
5//! backend; prepares the image — downscaled to the backend's limit for an on-device
6//! backend, released through the [`EgressGate`] for a remote one; meters the call against
7//! the context's scope (units always, cost for priced backends, zero for local ones);
8//! honours cancellation; maps every answer to source pixels; and escalates by cropping the
9//! uncertain region, never sending a whole image when a region will do.
10
11mod calls;
12mod route;
13mod video;
14
15use std::collections::BTreeMap;
16use std::future::Future;
17use std::sync::Arc;
18use std::time::Instant;
19
20use adk_core::{MeteredUsage, UsageCall, UsageHold, UsageUnit, UsageVector};
21
22pub use calls::Edited;
23pub use route::{CallOptions, CallRecord, Escalation, Route, Trigger, VisionOutput};
24pub use video::VideoSource;
25
26use crate::backend::{BackendDescriptor, BackendId, InputLimits, Locality, Oversize};
27use crate::cx::VisionCx;
28use crate::digest::Digest;
29use crate::edit::ops;
30use crate::egress::{EgressGate, ReleaseRequest, ReleasedImage};
31use crate::error::{Result, VisionError};
32use crate::geometry::{BBox, RegionNormalizer, Transform, TransformChain};
33use crate::manifest::VisionTask;
34use crate::media::{MediaStore, SourceImage};
35use crate::sent::SentImage;
36use crate::traits::{
37    Describer, Detector, DocumentReader, Editor, Embedder, EmbeddingSpace, Segmenter, VideoAnalyzer,
38};
39
40/// A registered backend: on-device, handed [`SentImage`]s, or remote, handed
41/// [`ReleasedImage`]s.
42enum Backend<L: ?Sized, R: ?Sized> {
43    Local(Arc<L>),
44    Remote(Arc<R>),
45}
46
47impl<L: ?Sized, R: ?Sized> Clone for Backend<L, R> {
48    fn clone(&self) -> Self {
49        match self {
50            Self::Local(b) => Self::Local(Arc::clone(b)),
51            Self::Remote(b) => Self::Remote(Arc::clone(b)),
52        }
53    }
54}
55
56impl<L: ?Sized, R: ?Sized> Backend<L, R> {
57    fn is_remote(&self) -> bool {
58        matches!(self, Self::Remote(_))
59    }
60}
61
62/// The backends of one trait, in registration order.
63struct Registry<L: ?Sized, R: ?Sized> {
64    entries: Vec<(BackendDescriptor, Backend<L, R>)>,
65}
66
67impl<L: ?Sized, R: ?Sized> Default for Registry<L, R> {
68    fn default() -> Self {
69        Self { entries: Vec::new() }
70    }
71}
72
73impl<L: ?Sized, R: ?Sized> Registry<L, R> {
74    fn add(
75        &mut self,
76        task: VisionTask,
77        descriptor: BackendDescriptor,
78        backend: Backend<L, R>,
79    ) -> Result<()> {
80        let remote = descriptor.locality.is_remote();
81        if remote != backend.is_remote() {
82            return Err(VisionError::InvalidInput(format!(
83                "backend `{}` declares {} locality but was registered as {}; register remote \
84                 backends with the `remote_` builder methods, which hand them only released images",
85                descriptor.id,
86                if remote { "remote" } else { "on-device" },
87                if backend.is_remote() { "remote" } else { "on-device" },
88            )));
89        }
90        if self.entries.iter().any(|(d, _)| d.id == descriptor.id) {
91            return Err(VisionError::InvalidInput(format!(
92                "a {task:?} backend `{}` is already registered",
93                descriptor.id
94            )));
95        }
96        self.entries.push((descriptor, backend));
97        Ok(())
98    }
99
100    fn get(&self, id: &BackendId) -> Result<(&BackendDescriptor, &Backend<L, R>)> {
101        self.entries
102            .iter()
103            .find(|(d, _)| &d.id == id)
104            .map(|(d, b)| (d, b))
105            .ok_or_else(|| VisionError::BackendNotFound(id.to_string()))
106    }
107
108    /// The first on-device backend, else the first remote one: registration order decides,
109    /// no backend is privileged.
110    fn default_id(&self) -> Option<&BackendId> {
111        self.entries
112            .iter()
113            .find(|(d, _)| !d.locality.is_remote())
114            .or_else(|| self.entries.first())
115            .map(|(d, _)| &d.id)
116    }
117
118    fn contains(&self, id: &BackendId) -> bool {
119        self.entries.iter().any(|(d, _)| &d.id == id)
120    }
121}
122
123type Detectors = Registry<dyn Detector, dyn Detector<ReleasedImage>>;
124type Segmenters = Registry<dyn Segmenter, dyn Segmenter<ReleasedImage>>;
125type Readers = Registry<dyn DocumentReader, dyn DocumentReader<ReleasedImage>>;
126type Embedders = Registry<dyn Embedder, dyn Embedder<ReleasedImage>>;
127type Describers = Registry<dyn Describer, dyn Describer<ReleasedImage>>;
128type Editors = Registry<dyn Editor, dyn Editor<ReleasedImage>>;
129type Videos = Registry<dyn VideoAnalyzer, dyn VideoAnalyzer<ReleasedImage>>;
130
131/// The image a backend is handed for one call.
132enum Prepared {
133    Local(SentImage),
134    Remote(Box<ReleasedImage>),
135}
136
137impl Prepared {
138    fn image(&self) -> &SentImage {
139        match self {
140            Self::Local(image) => image,
141            Self::Remote(released) => released.image(),
142        }
143    }
144
145    fn egress(&self) -> Option<Digest> {
146        match self {
147            Self::Local(_) => None,
148            Self::Remote(released) => Some(released.receipt().egress),
149        }
150    }
151}
152
153/// The images of one call, for its record.
154#[derive(Default)]
155struct Inputs {
156    sources: Vec<Digest>,
157    egress: Vec<Digest>,
158}
159
160impl Inputs {
161    fn of(prepared: &[Prepared]) -> Self {
162        Self {
163            sources: prepared.iter().map(|p| p.image().source()).collect(),
164            egress: prepared.iter().filter_map(Prepared::egress).collect(),
165        }
166    }
167}
168
169/// The budget hold of one call, opened before its images are prepared (V-I6).
170struct Preflight {
171    hold: Option<UsageHold>,
172    units: UsageVector,
173    /// The cost committed on success: zero for local, the unit price for per-unit, `None`
174    /// for token-billed backends, whose model call commits its own cost.
175    cost: Option<u64>,
176}
177
178/// The size a backend is sent for an image of `size`: its crop, fitted to the backend's
179/// limits, as [`VisionRuntime::prepare`] and the egress gate make it.
180fn planned_size(size: (u32, u32), crop: Option<BBox>, limits: &InputLimits) -> (u32, u32) {
181    let base = match crop {
182        Some(crop) => {
183            let (_, _, width, height) = crop.pixel_bounds(size.0, size.1);
184            (width, height)
185        }
186        None => size,
187    };
188    limits.fit(base).unwrap_or(base)
189}
190
191/// Routes vision calls to backends, prepares and releases their images, meters them, maps
192/// their answers to source pixels and escalates.
193///
194/// # Example
195///
196/// ```
197/// use std::sync::Arc;
198/// use adk_vision::{DeterministicEditor, VisionRuntime};
199///
200/// let runtime = VisionRuntime::builder()
201///     .editor(Arc::new(DeterministicEditor::new()))
202///     .build()
203///     .unwrap();
204/// assert!(runtime.backends().iter().any(|id| id.as_str() == "deterministic-editor"));
205/// ```
206pub struct VisionRuntime {
207    detectors: Detectors,
208    segmenters: Segmenters,
209    readers: Readers,
210    embedders: Embedders,
211    describers: Describers,
212    editors: Editors,
213    videos: Videos,
214    routes: BTreeMap<VisionTask, Route>,
215    gate: Option<Arc<EgressGate>>,
216    store: Option<MediaStore>,
217}
218
219impl std::fmt::Debug for VisionRuntime {
220    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
221        f.debug_struct("VisionRuntime")
222            .field("backends", &self.backends())
223            .field("routes", &self.routes)
224            .field("egress_gate", &self.gate.is_some())
225            .finish_non_exhaustive()
226    }
227}
228
229/// Builds a [`VisionRuntime`].
230#[must_use]
231pub struct VisionRuntimeBuilder {
232    runtime: VisionRuntime,
233    error: Option<VisionError>,
234}
235
236macro_rules! register {
237    ($local:ident, $remote:ident, $field:ident, $task:expr, $trait:ident) => {
238        #[doc = concat!("Registers an on-device `", stringify!($trait), "`.")]
239        pub fn $local(mut self, backend: Arc<dyn $trait>) -> Self {
240            let descriptor = backend.descriptor().clone();
241            self.record(|rt| rt.$field.add($task, descriptor, Backend::Local(backend)));
242            self
243        }
244
245        #[doc = concat!("Registers a remote `", stringify!($trait), "`, handed only images the egress gate released.")]
246        pub fn $remote(mut self, backend: Arc<dyn $trait<ReleasedImage>>) -> Self {
247            let descriptor = backend.descriptor().clone();
248            self.record(|rt| rt.$field.add($task, descriptor, Backend::Remote(backend)));
249            self
250        }
251    };
252}
253
254impl VisionRuntimeBuilder {
255    fn record(&mut self, f: impl FnOnce(&mut VisionRuntime) -> Result<()>) {
256        if self.error.is_none()
257            && let Err(err) = f(&mut self.runtime)
258        {
259            self.error = Some(err);
260        }
261    }
262
263    register!(detector, remote_detector, detectors, VisionTask::Detect, Detector);
264    register!(segmenter, remote_segmenter, segmenters, VisionTask::Segment, Segmenter);
265    register!(reader, remote_reader, readers, VisionTask::Read, DocumentReader);
266    register!(embedder, remote_embedder, embedders, VisionTask::Embed, Embedder);
267    register!(describer, remote_describer, describers, VisionTask::Describe, Describer);
268    register!(editor, remote_editor, editors, VisionTask::Edit, Editor);
269    register!(
270        video_analyzer,
271        remote_video_analyzer,
272        videos,
273        VisionTask::AnalyzeVideo,
274        VideoAnalyzer
275    );
276
277    /// Sets a task's route.
278    pub fn route(mut self, task: VisionTask, route: Route) -> Self {
279        self.runtime.routes.insert(task, route);
280        self
281    }
282
283    /// Installs the egress gate; without one, every remote call is refused.
284    pub fn egress_gate(mut self, gate: EgressGate) -> Self {
285        self.runtime.gate = Some(Arc::new(gate));
286        self
287    }
288
289    /// Installs an egress gate shared with other parts of the application, such as the
290    /// `ImagePrivacyGuardrail` (feature `guardrail`), so every path releases through one gate.
291    pub fn shared_egress_gate(mut self, gate: Arc<EgressGate>) -> Self {
292        self.runtime.gate = Some(gate);
293        self
294    }
295
296    /// Stores edited images in `store`.
297    pub fn media_store(mut self, store: MediaStore) -> Self {
298        self.runtime.store = Some(store);
299        self
300    }
301
302    /// Builds the runtime.
303    ///
304    /// # Errors
305    ///
306    /// [`VisionError::InvalidInput`] for a backend whose locality does not match how it was
307    /// registered, a duplicate backend, or a route that names an unknown backend or a
308    /// trigger its task does not support.
309    pub fn build(self) -> Result<VisionRuntime> {
310        if let Some(err) = self.error {
311            return Err(err);
312        }
313        let runtime = self.runtime;
314        for (task, route) in &runtime.routes {
315            runtime.check_route(*task, route)?;
316        }
317        Ok(runtime)
318    }
319}
320
321impl VisionRuntime {
322    /// A builder with no backend.
323    pub fn builder() -> VisionRuntimeBuilder {
324        VisionRuntimeBuilder {
325            runtime: VisionRuntime {
326                detectors: Registry::default(),
327                segmenters: Registry::default(),
328                readers: Registry::default(),
329                embedders: Registry::default(),
330                describers: Registry::default(),
331                editors: Registry::default(),
332                videos: Registry::default(),
333                routes: BTreeMap::new(),
334                gate: None,
335                store: None,
336            },
337            error: None,
338        }
339    }
340
341    /// The embedding space a call with `options` embeds into: the space of its embedding
342    /// route's backend. A visual memory collection records the space it was built in and
343    /// refuses vectors of any other.
344    ///
345    /// # Errors
346    ///
347    /// [`VisionError::BackendNotFound`] when no embedder serves the call.
348    pub fn embedding_space(&self, options: &CallOptions) -> Result<EmbeddingSpace> {
349        let route = self.route_for(VisionTask::Embed, options, self.embedders.default_id())?;
350        let (_, backend) = self.embedders.get(&route.primary)?;
351        Ok(match backend {
352            Backend::Local(b) => b.space().clone(),
353            Backend::Remote(b) => b.space().clone(),
354        })
355    }
356
357    /// Every registered backend's id.
358    pub fn backends(&self) -> Vec<BackendId> {
359        let mut all = Vec::new();
360        all.extend(self.detectors.entries.iter().map(|(d, _)| d.id.clone()));
361        all.extend(self.segmenters.entries.iter().map(|(d, _)| d.id.clone()));
362        all.extend(self.readers.entries.iter().map(|(d, _)| d.id.clone()));
363        all.extend(self.embedders.entries.iter().map(|(d, _)| d.id.clone()));
364        all.extend(self.describers.entries.iter().map(|(d, _)| d.id.clone()));
365        all.extend(self.editors.entries.iter().map(|(d, _)| d.id.clone()));
366        all.extend(self.videos.entries.iter().map(|(d, _)| d.id.clone()));
367        all
368    }
369
370    /// The descriptor of a backend registered for `task`.
371    pub fn descriptor(&self, task: VisionTask, id: &BackendId) -> Option<&BackendDescriptor> {
372        match task {
373            VisionTask::Detect => self.detectors.get(id).ok().map(|(d, _)| d),
374            VisionTask::Segment => self.segmenters.get(id).ok().map(|(d, _)| d),
375            VisionTask::Read => self.readers.get(id).ok().map(|(d, _)| d),
376            VisionTask::Embed => self.embedders.get(id).ok().map(|(d, _)| d),
377            VisionTask::Describe => self.describers.get(id).ok().map(|(d, _)| d),
378            VisionTask::Edit => self.editors.get(id).ok().map(|(d, _)| d),
379            VisionTask::AnalyzeVideo => self.videos.get(id).ok().map(|(d, _)| d),
380        }
381    }
382
383    /// The route a call of `task` with `options` takes: the call's own route, the task's
384    /// configured route, or the task's default backend (the first on-device one registered,
385    /// else the first remote one).
386    ///
387    /// # Errors
388    ///
389    /// [`VisionError::BackendNotFound`] when no backend serves the task, and
390    /// [`VisionError::InvalidInput`] for a call route that names an unknown backend.
391    pub fn route(&self, task: VisionTask, options: &CallOptions) -> Result<Route> {
392        let default = match task {
393            VisionTask::Detect => self.detectors.default_id(),
394            VisionTask::Segment => self.segmenters.default_id(),
395            VisionTask::Read => self.readers.default_id(),
396            VisionTask::Embed => self.embedders.default_id(),
397            VisionTask::Describe => self.describers.default_id(),
398            VisionTask::Edit => self.editors.default_id(),
399            VisionTask::AnalyzeVideo => self.videos.default_id(),
400        };
401        self.route_for(task, options, default)
402    }
403
404    /// The egress gate, if one is installed.
405    pub fn egress_gate(&self) -> Option<&EgressGate> {
406        self.gate.as_deref()
407    }
408
409    /// The egress gate as a shared handle, for an `ImagePrivacyGuardrail` that releases
410    /// through the same gate.
411    pub fn shared_egress_gate(&self) -> Option<Arc<EgressGate>> {
412        self.gate.clone()
413    }
414
415    /// The media store, if one is installed.
416    pub fn media_store(&self) -> Option<&MediaStore> {
417        self.store.as_ref()
418    }
419
420    fn has(&self, task: VisionTask, id: &BackendId) -> bool {
421        match task {
422            VisionTask::Detect => self.detectors.contains(id),
423            VisionTask::Segment => self.segmenters.contains(id),
424            VisionTask::Read => self.readers.contains(id),
425            VisionTask::Embed => self.embedders.contains(id),
426            VisionTask::Describe => self.describers.contains(id),
427            VisionTask::Edit => self.editors.contains(id),
428            VisionTask::AnalyzeVideo => self.videos.contains(id),
429        }
430    }
431
432    fn check_route(&self, task: VisionTask, route: &Route) -> Result<()> {
433        if !self.has(task, &route.primary) {
434            return Err(VisionError::InvalidInput(format!(
435                "the {task:?} route names `{}`, which is not a registered {task:?} backend",
436                route.primary
437            )));
438        }
439        let Some(escalation) = &route.escalation else {
440            return Ok(());
441        };
442        if matches!(task, VisionTask::Embed | VisionTask::Edit | VisionTask::AnalyzeVideo) {
443            return Err(VisionError::InvalidInput(format!("{task:?} routes do not escalate")));
444        }
445        if !self.has(task, &escalation.backend) {
446            return Err(VisionError::InvalidInput(format!(
447                "the {task:?} route escalates to `{}`, which is not a registered {task:?} backend",
448                escalation.backend
449            )));
450        }
451        for trigger in &escalation.triggers {
452            if let Trigger::Disagreement { with, .. } = trigger {
453                if !matches!(task, VisionTask::Detect | VisionTask::Segment) {
454                    return Err(VisionError::InvalidInput(
455                        "a disagreement trigger applies to detection and segmentation only".into(),
456                    ));
457                }
458                let local = self.descriptor(task, with).is_some_and(|d| !d.locality.is_remote());
459                if !local {
460                    return Err(VisionError::InvalidInput(format!(
461                        "the disagreement trigger's second backend `{with}` must be a registered \
462                         on-device {task:?} backend, so the whole image never leaves for a second opinion"
463                    )));
464                }
465            }
466        }
467        Ok(())
468    }
469
470    /// The route for a call: the call's own, else the task's, else the default backend.
471    fn route_for(
472        &self,
473        task: VisionTask,
474        options: &CallOptions,
475        default: Option<&BackendId>,
476    ) -> Result<Route> {
477        let route = match (&options.route, self.routes.get(&task)) {
478            (Some(route), _) => {
479                self.check_route(task, route)?;
480                route.clone()
481            }
482            (None, Some(route)) => route.clone(),
483            (None, None) => Route {
484                primary: default
485                    .cloned()
486                    .ok_or_else(|| VisionError::BackendNotFound(format!("any {task:?} backend")))?,
487                escalation: None,
488            },
489        };
490        Ok(route)
491    }
492
493    /// Prepares the image a backend is handed: released through the gate for a remote
494    /// backend, downscaled to its limit for an on-device one.
495    async fn prepare(
496        &self,
497        cx: &VisionCx,
498        descriptor: &BackendDescriptor,
499        remote: bool,
500        source: &SourceImage,
501        crop: Option<BBox>,
502        options: &CallOptions,
503    ) -> Result<Prepared> {
504        cx.check()?;
505        if remote {
506            let gate = self
507                .gate
508                .as_ref()
509                .ok_or_else(|| VisionError::NotReleased { backend: descriptor.id.to_string() })?;
510            let mut request = ReleaseRequest::new(source, descriptor, options.data_class())
511                .with_marked(options.marked.clone());
512            if let Some(crop) = crop {
513                request = request.with_crop(crop);
514            }
515            for digest in &options.approved {
516                request = request.approved(*digest);
517            }
518            return Ok(Prepared::Remote(Box::new(gate.release(cx, request).await?)));
519        }
520        let (w, h) = source.size();
521        let mut chain = TransformChain::new(w, h);
522        let mut pixels = source.shared_pixels();
523        if let Some(crop) = crop {
524            let (x, y, cw, ch) = crop.pixel_bounds(w, h);
525            if cw == 0 || ch == 0 {
526                return Err(VisionError::InvalidInput(format!(
527                    "crop {crop:?} leaves no pixels of the {w}x{h} image"
528                )));
529            }
530            chain.push(Transform::Crop { x, y, width: cw, height: ch })?;
531            pixels = Arc::new(ops::crop(&pixels, x, y, cw, ch));
532        }
533        let limits = descriptor.limits;
534        if let Some((fw, fh)) = limits.fit(pixels.size()) {
535            if limits.oversize == Oversize::Refuse {
536                let (pw, ph) = pixels.size();
537                return Err(VisionError::InputTooLarge {
538                    backend: descriptor.id.to_string(),
539                    limit: limits.describe(),
540                    actual: format!("{pw}x{ph}"),
541                });
542            }
543            chain.push(Transform::Resize { width: fw, height: fh })?;
544            pixels = Arc::new(ops::resize(&pixels, fw, fh));
545        }
546        Ok(Prepared::Local(SentImage::new(source.digest(), pixels, chain)))
547    }
548
549    /// Opens the budget hold of one call before any image is prepared or released (V-I6):
550    /// the call's images (and pages, for reading) as units, and its cost bound — zero for an
551    /// on-device backend, the unit price for a per-unit one, the [`TokenEstimate`] of a
552    /// token-billed one. A hold the budget or spend ledger cannot cover refuses the call
553    /// here, so nothing is sent and no egress is recorded.
554    ///
555    /// `sizes` are the sizes the backend will be sent, `prompt_chars` the length of any
556    /// prompt, and `max_output_tokens` the call's output cap. `unit` is what each image
557    /// counts as: [`UsageUnit::Images`], or [`UsageUnit::Frames`] for a stream's frames
558    /// ([`CallOptions::as_frames`], spec 3.7 X3).
559    ///
560    /// [`TokenEstimate`]: crate::TokenEstimate
561    #[allow(clippy::too_many_arguments)] // One call's metering inputs; a struct would only rename them.
562    async fn preflight(
563        &self,
564        cx: &VisionCx,
565        task: VisionTask,
566        descriptor: &BackendDescriptor,
567        sizes: &[(u32, u32)],
568        prompt_chars: usize,
569        max_output_tokens: Option<u32>,
570        unit: UsageUnit,
571    ) -> Result<Preflight> {
572        cx.check()?;
573        let images = sizes.len() as u64;
574        let mut units = UsageVector::new().with(unit, images);
575        if task == VisionTask::Read {
576            units = units.with(UsageUnit::Pages, images);
577        }
578        let (vendor, model, cost, bound) = match &descriptor.price {
579            // A remote backend with no published price (NVIDIA's hosted NIMs) is capped by
580            // units, and its ledger entries name its host rather than `local`.
581            None => {
582                let vendor = match &descriptor.locality {
583                    Locality::Remote { hosts } => hosts.first().cloned(),
584                    Locality::InProcess | Locality::Loopback => None,
585                };
586                (vendor.unwrap_or_else(|| "local".into()), descriptor.id.to_string(), Some(0), 0)
587            }
588            Some(price) => match price.unit() {
589                Some(priced) => {
590                    let amount = if priced == UsageUnit::Requests { 1 } else { images };
591                    let cost = price.request_cost(amount);
592                    (price.vendor().to_string(), price.model().to_string(), cost, cost.unwrap_or(0))
593                }
594                // The model call meters its own tokens; the hold only has to fit the estimate.
595                None => {
596                    let estimate = descriptor.token_estimate.map_or(0, |estimate| {
597                        estimate.estimate_micro_usd(sizes, prompt_chars, max_output_tokens)
598                    });
599                    (price.vendor().to_string(), price.model().to_string(), None, estimate)
600                }
601            },
602        };
603        let scope = cx.scope();
604        if scope.is_unmetered() {
605            return Ok(Preflight { hold: None, units, cost });
606        }
607        let call =
608            UsageCall::new(vendor, model).with_max_cost_micro_usd(bound).with_units(units.clone());
609        let hold = scope.begin_usage(&call).await?;
610        Ok(Preflight { hold: Some(hold), units, cost })
611    }
612
613    /// Runs one backend call under the hold [`preflight`](Self::preflight) opened.
614    ///
615    /// On success the call's units are committed, at the per-unit price for a priced
616    /// backend and at zero cost for a local or token-billed one; on failure the hold is
617    /// released. The context's scope is current while the call runs, so a token-billed
618    /// backend's model call meters itself against the same run. Cancellation ends the call
619    /// at once.
620    async fn metered<T, F>(
621        &self,
622        cx: &VisionCx,
623        task: VisionTask,
624        descriptor: &BackendDescriptor,
625        inputs: Inputs,
626        preflight: Preflight,
627        work: F,
628    ) -> Result<(T, CallRecord)>
629    where
630        F: Future<Output = Result<T>> + Send,
631    {
632        let Preflight { hold, units, cost } = preflight;
633        if let Err(err) = cx.check() {
634            if let Some(hold) = hold {
635                hold.release().await;
636            }
637            return Err(err);
638        }
639        let cancel = cx.cancellation().clone();
640        let started = Instant::now();
641        let run = async move {
642            tokio::select! {
643                biased;
644                () = cancel.cancelled() => Err(VisionError::Cancelled),
645                result = work => result,
646            }
647        };
648        let scope = cx.scope().clone();
649        // An unmetered context leaves the enclosing run's scope current for the model calls a
650        // token-billed backend makes.
651        let outcome = if scope.is_unmetered() { run.await } else { scope.within(run).await };
652        let value = match outcome {
653            Ok(value) => {
654                if let Some(hold) = hold {
655                    let usage =
656                        MeteredUsage::new(units.clone()).with_cost_micro_usd(cost.unwrap_or(0));
657                    hold.commit(usage).await;
658                }
659                value
660            }
661            Err(err) => {
662                if let Some(hold) = hold {
663                    hold.release().await;
664                }
665                return Err(err);
666            }
667        };
668        let record = CallRecord {
669            task,
670            backend: descriptor.id.clone(),
671            locality: descriptor.locality.clone(),
672            images: inputs.sources,
673            egress: inputs.egress,
674            units,
675            cost_micro_usd: cost,
676            regions: 0,
677            duration_ms: u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX),
678            escalation: None,
679        };
680        tracing::debug!(
681            vision.task = ?task,
682            vision.backend = %descriptor.id,
683            vision.duration_ms = record.duration_ms,
684            "vision call finished"
685        );
686        Ok((value, record))
687    }
688
689    fn normalizer(descriptor: &BackendDescriptor, prepared: &Prepared) -> RegionNormalizer {
690        let image = prepared.image();
691        RegionNormalizer::new(
692            image.source(),
693            image.chain().clone(),
694            descriptor.frame,
695            descriptor.id.clone(),
696        )
697        .with_manifest(descriptor.manifest.clone())
698    }
699}
700
701fn mismatch(descriptor: &BackendDescriptor) -> VisionError {
702    VisionError::Backend {
703        backend: descriptor.id.to_string(),
704        message: "the prepared image does not match the backend's locality".into(),
705    }
706}