Skip to main content

adk_vision/
error.rs

1//! [`VisionError`], the crate's error type, and its mapping to [`AdkError`].
2
3use std::path::PathBuf;
4use std::time::Duration;
5
6use adk_core::{AdkError, ErrorCategory, ErrorComponent, RetryHint};
7
8use crate::digest::Digest;
9
10/// What went wrong in a vision operation.
11///
12/// Every variant maps to an [`AdkError`] category at the boundary (`From<VisionError>`):
13/// an unreleased image or a refused egress to `Forbidden`, a licence gate to `Unauthorized`
14/// with the acceptance command in the message, a provider's rate limit to `RateLimited`
15/// with its retry hint.
16///
17/// # Example
18///
19/// ```
20/// use adk_core::{AdkError, ErrorCategory};
21/// use adk_vision::VisionError;
22///
23/// let err = VisionError::TooManyPixels { limit: 40_000_000, actual: 64_000_000 };
24/// let adk: AdkError = err.into();
25/// assert_eq!(adk.category, ErrorCategory::InvalidInput);
26/// assert!(adk.message.contains("40000000"));
27/// ```
28#[derive(Debug, thiserror::Error)]
29#[non_exhaustive]
30pub enum VisionError {
31    /// The bytes are not one of the accepted image formats.
32    #[error(
33        "unsupported image format {detected}; accepted formats are PNG, JPEG, WebP and the first frame of a GIF"
34    )]
35    UnsupportedFormat {
36        /// The format the header named, or `unknown`.
37        detected: String,
38    },
39
40    /// The encoded image is larger than the byte cap.
41    #[error(
42        "the image is {actual} bytes, over the {limit}-byte cap; downscale or recompress it before handing it over"
43    )]
44    TooManyBytes {
45        /// The cap in bytes.
46        limit: u64,
47        /// The image's size in bytes.
48        actual: u64,
49    },
50
51    /// The image has more pixels than the cap, read from its header before decoding.
52    #[error(
53        "the image has {actual} pixels, over the {limit}-pixel cap; downscale it before handing it over"
54    )]
55    TooManyPixels {
56        /// The cap in pixels.
57        limit: u64,
58        /// The image's pixel count.
59        actual: u64,
60    },
61
62    /// The image could not be decoded.
63    #[error("the image could not be decoded: {0}")]
64    Decode(String),
65
66    /// The image exceeds what a backend accepts and the backend refuses to have it resized.
67    #[error(
68        "backend `{backend}` accepts at most {limit}; the image is {actual}. Crop or downscale it first"
69    )]
70    InputTooLarge {
71        /// The backend that refused the input.
72        backend: String,
73        /// The limit, in words (`2576 px on the long edge`).
74        limit: String,
75        /// The input's size, in the same words.
76        actual: String,
77    },
78
79    /// An image was routed to a remote backend without passing the egress gate.
80    #[error(
81        "backend `{backend}` is remote and only takes images released by the egress gate; configure an `EgressGate` on the runtime"
82    )]
83    NotReleased {
84        /// The remote backend.
85        backend: String,
86    },
87
88    /// The egress gate refused to release an image.
89    #[error("the image was not released to {host}: {reason}")]
90    EgressRefused {
91        /// The destination host.
92        host: String,
93        /// Why, in words a person can act on.
94        reason: String,
95    },
96
97    /// The egress rule for this destination and data class asks a person first.
98    #[error(
99        "sending image {egress} to {host} as `{data_class}` needs a person's approval; approve that digest and retry"
100    )]
101    EgressHeld {
102        /// The destination host.
103        host: String,
104        /// The data class of the image.
105        data_class: String,
106        /// The digest of the exact redacted image that would be sent.
107        egress: Digest,
108    },
109
110    /// The policy requires a redaction class for which no redactor is installed.
111    #[error(
112        "the egress policy requires `{class}` redaction and no redactor for it is installed; add one to the egress gate or remove the class from the policy"
113    )]
114    RedactionUnavailable {
115        /// The redaction class with no redactor.
116        class: String,
117    },
118
119    /// A use-restricted model was requested before a person accepted its licence.
120    #[error(
121        "licence acceptance required for model `{model}`: read {licence_url}, then run `adk-rust vision models accept {model}`"
122    )]
123    LicenceAcceptanceRequired {
124        /// The model manifest id.
125        model: String,
126        /// The licence, or the gated repository page, a person must read.
127        licence_url: String,
128    },
129
130    /// A non-commercial or copyleft model that the configuration does not name.
131    #[error(
132        "model `{model}` is licensed {class} ({licence_url}); name it in the licence policy to allow it"
133    )]
134    LicenceNotAllowed {
135        /// The model manifest id.
136        model: String,
137        /// The licence class.
138        class: String,
139        /// The licence URL.
140        licence_url: String,
141    },
142
143    /// A model file's SHA-256 differs from its manifest; the file is never loaded.
144    #[error(
145        "model file {path} does not match its manifest: expected {expected}, found {actual}; delete it and fetch again"
146    )]
147    DigestMismatch {
148        /// The file on disk.
149        path: PathBuf,
150        /// The digest the manifest pins.
151        expected: Digest,
152        /// The digest of the file on disk.
153        actual: Digest,
154    },
155
156    /// A model file's size differs from its manifest; the file is never loaded.
157    #[error(
158        "model file {path} is {actual} bytes, but its manifest pins {expected}; delete it and fetch again"
159    )]
160    SizeMismatch {
161        /// The file on disk.
162        path: PathBuf,
163        /// The size the manifest pins.
164        expected: u64,
165        /// The size on disk.
166        actual: u64,
167    },
168
169    /// Offline mode is on and a file is not in the cache.
170    #[error(
171        "`{file}` of model `{model}` is not in the cache and HF_HUB_OFFLINE is set; fetch it once with network access"
172    )]
173    Offline {
174        /// The model manifest id.
175        model: String,
176        /// The missing file.
177        file: String,
178    },
179
180    /// A download failed.
181    #[error("fetching `{file}` of model `{model}` failed: {message}")]
182    Fetch {
183        /// The model manifest id.
184        model: String,
185        /// The file being fetched.
186        file: String,
187        /// What failed.
188        message: String,
189    },
190
191    /// A manifest is invalid.
192    #[error("model manifest `{id}` is invalid: {reason}")]
193    Manifest {
194        /// The manifest id.
195        id: String,
196        /// Why.
197        reason: String,
198    },
199
200    /// A provider refused for rate limiting.
201    #[error("backend `{backend}` is rate limited; retry later")]
202    RateLimited {
203        /// The backend.
204        backend: String,
205        /// The provider's retry hint.
206        retry_after: Option<Duration>,
207    },
208
209    /// A backend call ran out of time.
210    #[error("backend `{backend}` timed out")]
211    Timeout {
212        /// The backend.
213        backend: String,
214    },
215
216    /// The call was cancelled.
217    #[error("the vision call was cancelled")]
218    Cancelled,
219
220    /// A backend is temporarily unavailable.
221    #[error("backend `{backend}` is unavailable: {message}")]
222    Unavailable {
223        /// The backend.
224        backend: String,
225        /// What failed.
226        message: String,
227    },
228
229    /// A capability a backend or the runtime does not have.
230    #[error("unsupported: {0}")]
231    Unsupported(String),
232
233    /// The caller's input is invalid.
234    #[error("invalid input: {0}")]
235    InvalidInput(String),
236
237    /// No backend with this id is registered, or none serves the task.
238    #[error("no vision backend `{0}` is registered for this task")]
239    BackendNotFound(String),
240
241    /// A backend's output could not be parsed; nothing is guessed.
242    #[error("backend `{backend}` returned output that could not be parsed: {message}")]
243    Parse {
244        /// The backend.
245        backend: String,
246        /// What was wrong.
247        message: String,
248    },
249
250    /// A backend failed.
251    #[error("backend `{backend}` failed: {message}")]
252    Backend {
253        /// The backend.
254        backend: String,
255        /// What failed.
256        message: String,
257    },
258
259    /// A file operation failed.
260    #[error("{action} {path}: {source}")]
261    Io {
262        /// What was being done.
263        action: &'static str,
264        /// The path.
265        path: PathBuf,
266        /// The I/O error.
267        #[source]
268        source: std::io::Error,
269    },
270
271    /// A visual memory collection holds vectors of another embedding space; vectors of two
272    /// spaces never share a collection.
273    #[error(
274        "collection `{collection}` holds vectors of embedding space {recorded}, not {offered}; \
275         re-index into a new collection with this embedder, or use the embedder the collection \
276         was built with"
277    )]
278    SpaceMismatch {
279        /// The collection.
280        collection: String,
281        /// The space the collection recorded, or a note that its record could not be read.
282        recorded: String,
283        /// The space of the embedder that was offered.
284        offered: String,
285    },
286
287    /// An error from the platform: a budget or spend refusal, a frozen kill switch, storage.
288    #[error(transparent)]
289    Core(#[from] AdkError),
290}
291
292impl VisionError {
293    /// The stable error code, `vision.<kind>`.
294    pub fn code(&self) -> &'static str {
295        match self {
296            Self::UnsupportedFormat { .. } => "vision.unsupported_format",
297            Self::TooManyBytes { .. } => "vision.too_many_bytes",
298            Self::TooManyPixels { .. } => "vision.too_many_pixels",
299            Self::Decode(_) => "vision.decode",
300            Self::InputTooLarge { .. } => "vision.input_too_large",
301            Self::NotReleased { .. } => "vision.not_released",
302            Self::EgressRefused { .. } => "vision.egress.refused",
303            Self::EgressHeld { .. } => "vision.egress.held",
304            Self::RedactionUnavailable { .. } => "vision.egress.redaction_unavailable",
305            Self::LicenceAcceptanceRequired { .. } => "vision.model.licence_acceptance_required",
306            Self::LicenceNotAllowed { .. } => "vision.model.licence_not_allowed",
307            Self::DigestMismatch { .. } => "vision.model.digest_mismatch",
308            Self::SizeMismatch { .. } => "vision.model.size_mismatch",
309            Self::Offline { .. } => "vision.model.offline",
310            Self::Fetch { .. } => "vision.model.fetch",
311            Self::Manifest { .. } => "vision.model.manifest",
312            Self::RateLimited { .. } => "vision.rate_limited",
313            Self::Timeout { .. } => "vision.timeout",
314            Self::Cancelled => "vision.cancelled",
315            Self::Unavailable { .. } => "vision.unavailable",
316            Self::Unsupported(_) => "vision.unsupported",
317            Self::InvalidInput(_) => "vision.invalid_input",
318            Self::BackendNotFound(_) => "vision.backend_not_found",
319            Self::Parse { .. } => "vision.parse",
320            Self::Backend { .. } => "vision.backend",
321            Self::Io { .. } => "vision.io",
322            Self::SpaceMismatch { .. } => "vision.memory.space_mismatch",
323            Self::Core(_) => "vision.core",
324        }
325    }
326
327    /// The [`ErrorCategory`] this error maps to.
328    pub fn category(&self) -> ErrorCategory {
329        match self {
330            Self::UnsupportedFormat { .. }
331            | Self::TooManyBytes { .. }
332            | Self::TooManyPixels { .. }
333            | Self::Decode(_)
334            | Self::InputTooLarge { .. }
335            | Self::Manifest { .. }
336            | Self::SpaceMismatch { .. }
337            | Self::InvalidInput(_) => ErrorCategory::InvalidInput,
338            Self::NotReleased { .. }
339            | Self::EgressRefused { .. }
340            | Self::EgressHeld { .. }
341            | Self::RedactionUnavailable { .. }
342            | Self::LicenceNotAllowed { .. }
343            | Self::DigestMismatch { .. }
344            | Self::SizeMismatch { .. } => ErrorCategory::Forbidden,
345            Self::LicenceAcceptanceRequired { .. } => ErrorCategory::Unauthorized,
346            Self::Offline { .. } | Self::BackendNotFound(_) => ErrorCategory::NotFound,
347            Self::Fetch { .. } | Self::Unavailable { .. } => ErrorCategory::Unavailable,
348            Self::RateLimited { .. } => ErrorCategory::RateLimited,
349            Self::Timeout { .. } => ErrorCategory::Timeout,
350            Self::Cancelled => ErrorCategory::Cancelled,
351            Self::Unsupported(_) => ErrorCategory::Unsupported,
352            Self::Parse { .. } | Self::Backend { .. } | Self::Io { .. } => ErrorCategory::Internal,
353            Self::Core(err) => err.category,
354        }
355    }
356
357    pub(crate) fn io(
358        action: &'static str,
359        path: impl Into<PathBuf>,
360        source: std::io::Error,
361    ) -> Self {
362        Self::Io { action, path: path.into(), source }
363    }
364}
365
366impl From<VisionError> for AdkError {
367    fn from(err: VisionError) -> Self {
368        let code = err.code();
369        let category = err.category();
370        match err {
371            VisionError::Core(inner) => inner,
372            VisionError::RateLimited { ref backend, retry_after } => {
373                let mut retry = RetryHint::for_category(category);
374                if let Some(after) = retry_after {
375                    retry = retry.with_retry_after(after);
376                }
377                let provider = backend.clone();
378                AdkError::new(ErrorComponent::Tool, category, code, err.to_string())
379                    .with_retry(retry)
380                    .with_provider(provider)
381            }
382            other => AdkError::new(ErrorComponent::Tool, category, code, other.to_string()),
383        }
384    }
385}
386
387/// `Result` with [`VisionError`].
388pub type Result<T, E = VisionError> = std::result::Result<T, E>;
389
390#[cfg(test)]
391mod tests {
392    use super::*;
393
394    #[test]
395    fn rate_limits_carry_the_retry_hint() {
396        let err: AdkError = VisionError::RateLimited {
397            backend: "sam-3.1".into(),
398            retry_after: Some(Duration::from_secs(3)),
399        }
400        .into();
401        assert_eq!(err.category, ErrorCategory::RateLimited);
402        assert_eq!(err.code, "vision.rate_limited");
403        assert_eq!(err.retry.retry_after(), Some(Duration::from_secs(3)));
404        assert!(err.retry.should_retry);
405    }
406
407    #[test]
408    fn licence_gate_names_the_url_and_the_command() {
409        let err: AdkError = VisionError::LicenceAcceptanceRequired {
410            model: "sam3-local".into(),
411            licence_url: "https://example.org/sam-license".into(),
412        }
413        .into();
414        assert_eq!(err.category, ErrorCategory::Unauthorized);
415        assert!(err.message.contains("licence acceptance required"));
416        assert!(err.message.contains("https://example.org/sam-license"));
417        assert!(err.message.contains("adk-rust vision models accept sam3-local"));
418    }
419
420    #[test]
421    fn unreleased_images_are_forbidden() {
422        let err: AdkError = VisionError::NotReleased { backend: "gemini".into() }.into();
423        assert_eq!(err.category, ErrorCategory::Forbidden);
424    }
425
426    #[test]
427    fn platform_errors_pass_through_unchanged() {
428        let inner = AdkError::new(
429            ErrorComponent::Model,
430            ErrorCategory::ResourceExhausted,
431            "budget.exceeded",
432            "over budget",
433        );
434        let err: AdkError = VisionError::Core(inner).into();
435        assert_eq!(err.code, "budget.exceeded");
436        assert_eq!(err.category, ErrorCategory::ResourceExhausted);
437    }
438}