Skip to main content

dynamo_protocols/
validation.rs

1// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Opt-in, partial validation of parsed protocol values.
5//!
6//! Select one contract namespace: [`openai`], [`vllm`], or [`sglang`]. Each
7//! namespace exposes field helpers and a request trait for the covered request
8//! types. The engine namespaces reuse the OpenAI operation where the engine
9//! matches it and define an override where it differs. Engine contracts are not
10//! supersets of OpenAI, so do not run the OpenAI checks before an engine's checks.
11//!
12//! All operations in this module follow the same contract:
13//!
14//! - They are read-only. They never mutate, normalize, insert defaults, or dispatch.
15//! - Field helpers are named `validate_<field>` and take the request field's
16//!   parsed type. `None` (omitted or null at the typed boundary) always succeeds.
17//! - Float helpers reject NaN and infinities. They check parsed `f32` values and do
18//!   not reproduce JSON coercion, null admission, or backend HTTP diagnostics.
19//! - Request traits run their covered checks in a documented order and return the
20//!   first failure. Success does not establish complete endpoint admission.
21//!
22//! Coverage and known gaps are tracked in the temporary
23//! [coverage tracker](https://github.com/ai-dynamo/frontend-crates/blob/main/protocols/src/validation/coverage.md).
24//!
25//! ```rust
26//! use dynamo_protocols::{
27//!     normalization,
28//!     types::CreateCompletionRequest,
29//!     validation::{openai::OpenAIValidation, vllm::VllmValidation},
30//! };
31//!
32//! let mut request = CreateCompletionRequest {
33//!     logprobs: Some(10),
34//!     ..Default::default()
35//! };
36//! normalization::vllm::normalize_completion_logprobs(&mut request.logprobs);
37//! // vLLM accepts 10 completion logprobs; the OpenAI baseline allows at most 5.
38//! assert!(VllmValidation::validate(&request).is_ok());
39//! assert!(OpenAIValidation::validate(&request).is_err());
40//! assert_eq!(request.logprobs, Some(10));
41//! ```
42//!
43//! A server still owns prompt, model, runtime, and other admission checks.
44
45pub mod openai;
46pub mod sglang;
47pub mod vllm;
48
49// Operations that vLLM and SGLang implement equivalently outside the OpenAI
50// contract. Private: consumers reach them through an engine namespace.
51mod shared;
52
53/// A library diagnostic for the first failed covered check.
54///
55/// `Display` renders `"{message}, got {value}"`. The error carries no HTTP status
56/// or backend exception metadata; consumers select their own transport mapping.
57#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
58#[error("{message}, got {value}")]
59pub struct ValidationError {
60    /// The request field whose check failed.
61    pub field: &'static str,
62    /// Field label and constraint, without the rejected value.
63    pub message: String,
64    /// Rust `Display` of the rejected value, for example `NaN` or `-0`.
65    /// This is not the original JSON text.
66    pub value: String,
67}
68
69/// Accepts `None` or a value for which `accepted` returns true.
70/// Builds the diagnostic only on failure.
71fn check<T: Copy + std::fmt::Display>(
72    value: Option<T>,
73    accepted: impl FnOnce(T) -> bool,
74    field: &'static str,
75    message: impl FnOnce() -> String,
76) -> Result<(), ValidationError> {
77    match value {
78        Some(value) if !accepted(value) => Err(ValidationError {
79            field,
80            message: message(),
81            value: value.to_string(),
82        }),
83        _ => Ok(()),
84    }
85}