Skip to main content

adk_vision/runtime/
route.rs

1//! Routes, escalation triggers, call options and call records.
2
3use adk_core::{UsageUnit, UsageVector};
4use serde::{Deserialize, Serialize};
5
6use crate::backend::{BackendId, Locality};
7use crate::digest::Digest;
8use crate::egress::DataClass;
9use crate::geometry::{BBox, EscalationReason};
10use crate::manifest::VisionTask;
11
12/// When the runtime escalates from the primary backend.
13#[non_exhaustive]
14#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
15#[serde(rename_all = "camelCase", rename_all_fields = "camelCase", tag = "kind")]
16pub enum Trigger {
17    /// A region, block or description scored below `threshold`.
18    LowConfidence {
19        /// The threshold, in `[0, 1]`.
20        threshold: f32,
21    },
22    /// The primary found nothing. The only trigger that sends a whole image, since no
23    /// region exists to crop.
24    NoResult,
25    /// A second backend, run on the same image, found a region the primary did not, or the
26    /// primary found one it did not: no match at `min_iou` or better. Detection and
27    /// segmentation only.
28    Disagreement {
29        /// The second backend; it must run on the device.
30        with: BackendId,
31        /// The overlap two regions need to agree.
32        min_iou: f32,
33    },
34}
35
36/// Where a route escalates, on which triggers, and how much margin a crop keeps.
37///
38/// An escalation the egress gate refuses — a deny rule, an unlisted host, the on-device
39/// profile — leaves the primary backend's answer standing, and the gate records the refusal
40/// with its reason. An escalation the gate holds for approval stops the call, as any held
41/// release does.
42///
43/// # Example
44///
45/// ```
46/// use adk_vision::{Escalation, Trigger};
47///
48/// let to_cloud = Escalation::to("sam-3.1")
49///     .on(Trigger::LowConfidence { threshold: 0.5 })
50///     .with_margin(16.0)
51///     .with_data_class("document_crop");
52/// assert_eq!(to_cloud.triggers.len(), 1);
53/// ```
54#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
55#[serde(rename_all = "camelCase")]
56#[non_exhaustive]
57pub struct Escalation {
58    /// The backend escalated to.
59    pub backend: BackendId,
60    /// The triggers, checked in order.
61    pub triggers: Vec<Trigger>,
62    /// Pixels of context kept around an escalated region's crop.
63    pub margin: f32,
64    /// The data class escalated crops are released as, when the escalation backend is
65    /// remote; the call's own class otherwise.
66    #[serde(default, skip_serializing_if = "Option::is_none")]
67    pub data_class: Option<DataClass>,
68}
69
70impl Escalation {
71    /// Escalates to `backend`, with a 16-pixel margin and no trigger yet.
72    pub fn to(backend: impl Into<String>) -> Self {
73        Self {
74            backend: BackendId::new(backend),
75            triggers: Vec::new(),
76            margin: 16.0,
77            data_class: None,
78        }
79    }
80
81    /// Adds a trigger.
82    pub fn on(mut self, trigger: Trigger) -> Self {
83        self.triggers.push(trigger);
84        self
85    }
86
87    /// Sets the crop margin.
88    pub fn with_margin(mut self, margin: f32) -> Self {
89        self.margin = margin.max(0.0);
90        self
91    }
92
93    /// Sets the data class of escalated crops.
94    pub fn with_data_class(mut self, class: impl Into<String>) -> Self {
95        self.data_class = Some(DataClass::new(class));
96        self
97    }
98}
99
100/// A primary backend and an optional escalation.
101///
102/// # Example
103///
104/// ```
105/// use adk_vision::{Escalation, Route, Trigger};
106///
107/// let route = Route::to("rf-detr-m")
108///     .escalate(Escalation::to("sam-3.1").on(Trigger::LowConfidence { threshold: 0.4 }));
109/// assert_eq!(route.primary.as_str(), "rf-detr-m");
110/// ```
111#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
112#[serde(rename_all = "camelCase")]
113#[non_exhaustive]
114pub struct Route {
115    /// The backend every call goes to first.
116    pub primary: BackendId,
117    /// Where the runtime escalates, if anywhere.
118    #[serde(default, skip_serializing_if = "Option::is_none")]
119    pub escalation: Option<Escalation>,
120}
121
122impl Route {
123    /// A route to `backend`, with no escalation.
124    pub fn to(backend: impl Into<String>) -> Self {
125        Self { primary: BackendId::new(backend), escalation: None }
126    }
127
128    /// Adds an escalation.
129    pub fn escalate(mut self, escalation: Escalation) -> Self {
130        self.escalation = Some(escalation);
131        self
132    }
133}
134
135/// Per-call options.
136///
137/// # Example
138///
139/// ```
140/// use adk_vision::{CallOptions, Route};
141///
142/// let options = CallOptions::new().with_route(Route::to("gemini")).with_data_class("photo");
143/// assert_eq!(options.data_class.unwrap().as_str(), "photo");
144/// ```
145#[derive(Clone, Debug, Default, PartialEq)]
146#[non_exhaustive]
147pub struct CallOptions {
148    /// The route for this call, instead of the task's configured one.
149    pub route: Option<Route>,
150    /// The data class of images released to a remote backend; `image` when unset.
151    pub data_class: Option<DataClass>,
152    /// Egress digests a person approved, for rules that ask.
153    pub approved: Vec<Digest>,
154    /// Regions to fill before any release, in source pixels.
155    pub marked: Vec<BBox>,
156    /// Only this region of each image, in source pixels: the backend is sent its crop, and
157    /// answers come back in source pixels with the crop in their transform chain.
158    pub region: Option<BBox>,
159    /// Meters each image as a frame of a stream ([`UsageUnit::Frames`]) instead of an image
160    /// ([`UsageUnit::Images`]), so a stream's frames count against frame caps and quotas
161    /// (spec 3.7 X3, §7.9). The stream pipeline sets it on every detector call.
162    pub frames: bool,
163}
164
165impl CallOptions {
166    /// No options.
167    pub fn new() -> Self {
168        Self::default()
169    }
170
171    /// Routes this call.
172    pub fn with_route(mut self, route: Route) -> Self {
173        self.route = Some(route);
174        self
175    }
176
177    /// Sets the data class.
178    pub fn with_data_class(mut self, class: impl Into<String>) -> Self {
179        self.data_class = Some(DataClass::new(class));
180        self
181    }
182
183    /// Adds an approved egress digest.
184    pub fn approving(mut self, digest: Digest) -> Self {
185        self.approved.push(digest);
186        self
187    }
188
189    /// Marks regions for redaction.
190    pub fn with_marked(mut self, regions: Vec<BBox>) -> Self {
191        self.marked = regions;
192        self
193    }
194
195    /// Works on `region` of each image only; a remote backend is sent nothing else.
196    pub fn with_region(mut self, region: BBox) -> Self {
197        self.region = Some(region);
198        self
199    }
200
201    /// Meters each image as a stream frame: units go to [`UsageUnit::Frames`], and a backend
202    /// priced per image is billed one unit per frame.
203    ///
204    /// # Example
205    ///
206    /// ```
207    /// use adk_core::UsageUnit;
208    /// use adk_vision::CallOptions;
209    ///
210    /// assert_eq!(CallOptions::new().image_unit(), UsageUnit::Images);
211    /// assert_eq!(CallOptions::new().as_frames().image_unit(), UsageUnit::Frames);
212    /// ```
213    pub fn as_frames(mut self) -> Self {
214        self.frames = true;
215        self
216    }
217
218    /// The unit each image of the call is metered in: [`UsageUnit::Frames`] for a stream's
219    /// frames ([`as_frames`](Self::as_frames)), [`UsageUnit::Images`] otherwise.
220    pub fn image_unit(&self) -> UsageUnit {
221        if self.frames { UsageUnit::Frames } else { UsageUnit::Images }
222    }
223
224    pub(crate) fn data_class(&self) -> DataClass {
225        self.data_class.clone().unwrap_or_else(|| DataClass::new("image"))
226    }
227}
228
229/// One backend call, for the `vision.call` audit record: backend, locality, image digests,
230/// units, cost, region count and duration.
231#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
232#[serde(rename_all = "camelCase")]
233pub struct CallRecord {
234    /// The task.
235    pub task: VisionTask,
236    /// The backend.
237    pub backend: BackendId,
238    /// Where it ran.
239    pub locality: Locality,
240    /// The source images' digests.
241    pub images: Vec<Digest>,
242    /// The digests released through the egress gate, for a remote backend.
243    #[serde(default, skip_serializing_if = "Vec::is_empty")]
244    pub egress: Vec<Digest>,
245    /// Units recorded.
246    pub units: UsageVector,
247    /// Cost recorded in micro-USD: zero for local backends, the unit price for per-unit
248    /// ones, `None` for token-billed ones, whose model call meters its own tokens.
249    #[serde(default, skip_serializing_if = "Option::is_none")]
250    pub cost_micro_usd: Option<u64>,
251    /// Regions returned.
252    pub regions: usize,
253    /// Wall time in milliseconds.
254    pub duration_ms: u64,
255    /// Why this call was an escalation, if it was one.
256    #[serde(default, skip_serializing_if = "Option::is_none")]
257    pub escalation: Option<EscalationReason>,
258}
259
260/// A runtime result and the backend calls that produced it.
261#[derive(Clone, Debug, PartialEq)]
262pub struct VisionOutput<T> {
263    /// The result.
264    pub value: T,
265    /// Every backend call, in order.
266    pub calls: Vec<CallRecord>,
267}