Skip to main content

adk_guardrail/
executor.rs

1use crate::{
2    Guardrail, GuardrailError, GuardrailFailure, GuardrailPhase, GuardrailResult, OutputEvidence,
3    Result, Severity,
4};
5use adk_core::Content;
6use futures::future::join_all;
7use std::sync::Arc;
8
9/// A collection of guardrails to execute together.
10///
11/// Use the builder-style [`with`](Self::with) method to add guardrails.
12pub struct GuardrailSet {
13    guardrails: Vec<Arc<dyn Guardrail>>,
14}
15
16impl GuardrailSet {
17    /// Create an empty guardrail set.
18    pub fn new() -> Self {
19        Self { guardrails: Vec::new() }
20    }
21
22    /// Add a guardrail (by value, automatically wrapped in `Arc`).
23    pub fn with(mut self, guardrail: impl Guardrail + 'static) -> Self {
24        self.guardrails.push(Arc::new(guardrail));
25        self
26    }
27
28    /// Add a pre-wrapped guardrail.
29    pub fn with_arc(mut self, guardrail: Arc<dyn Guardrail>) -> Self {
30        self.guardrails.push(guardrail);
31        self
32    }
33
34    /// Get a reference to the registered guardrails.
35    pub fn guardrails(&self) -> &[Arc<dyn Guardrail>] {
36        &self.guardrails
37    }
38
39    /// Returns `true` if no guardrails have been added.
40    pub fn is_empty(&self) -> bool {
41        self.guardrails.is_empty()
42    }
43}
44
45impl Default for GuardrailSet {
46    fn default() -> Self {
47        Self::new()
48    }
49}
50
51/// Result of running a [`GuardrailSet`].
52#[derive(Debug)]
53pub struct ExecutionResult {
54    /// `true` if all guardrails passed (no critical failures).
55    pub passed: bool,
56    /// Content after guardrail transformations, or `None` if unchanged.
57    pub transformed_content: Option<Content>,
58    /// List of failures as `(guardrail_name, reason, severity)`.
59    pub failures: Vec<(String, String, Severity)>,
60}
61
62/// What [`GuardrailExecutor::enforce`] lets through.
63#[derive(Debug, Clone)]
64pub struct Screening {
65    /// The content to continue with, after any transformation.
66    pub content: Content,
67    /// The [`Severity::Low`] failures, which pass the content.
68    pub warnings: Vec<GuardrailFailure>,
69}
70
71/// Which [`Guardrail`] method a run calls.
72#[derive(Clone, Copy)]
73enum Check<'a> {
74    Validate,
75    Preamble,
76    Output(&'a OutputEvidence<'a>),
77}
78
79/// Executor for running guardrails in parallel
80pub struct GuardrailExecutor;
81
82impl GuardrailExecutor {
83    /// Run all guardrails in parallel, with early exit on critical failures
84    pub async fn run(guardrails: &GuardrailSet, content: &Content) -> Result<ExecutionResult> {
85        Self::run_with(guardrails, content, Check::Validate).await
86    }
87
88    /// Runs every guardrail's [`validate_preamble`](Guardrail::validate_preamble) over the text
89    /// of a model turn that also calls tools, as [`run`](Self::run) runs `validate`.
90    pub async fn run_preamble(
91        guardrails: &GuardrailSet,
92        content: &Content,
93    ) -> Result<ExecutionResult> {
94        Self::run_with(guardrails, content, Check::Preamble).await
95    }
96
97    /// Runs `guardrails` over `content` and turns a failing verdict into a block.
98    ///
99    /// Content passes when no failure is above [`Severity::Low`]; it continues transformed if a
100    /// guardrail transformed it, and the low-severity failures are returned as
101    /// [`Screening::warnings`] and logged at `warn` with the guardrail's name and severity (not
102    /// its reason, which can quote the content). `preamble` selects
103    /// [`validate_preamble`](Guardrail::validate_preamble) over
104    /// [`validate`](Guardrail::validate).
105    ///
106    /// # Errors
107    ///
108    /// Returns [`GuardrailError::Blocked`] with every failure when a failure is above `Low`,
109    /// including a critical failure that stopped the run early.
110    ///
111    /// # Example
112    ///
113    /// ```rust
114    /// use adk_core::Content;
115    /// use adk_guardrail::{GuardrailExecutor, GuardrailPhase, GuardrailSet, PiiRedactor};
116    ///
117    /// # futures::executor::block_on(async {
118    /// let set = GuardrailSet::new().with(PiiRedactor::new());
119    /// let content = Content::new("model").with_text("Mail ana@example.com");
120    /// let screened = GuardrailExecutor::enforce(&set, &content, GuardrailPhase::Output, false)
121    ///     .await
122    ///     .unwrap();
123    /// assert_eq!(screened.content.parts[0].text(), Some("Mail [EMAIL REDACTED]"));
124    /// # });
125    /// ```
126    pub async fn enforce(
127        guardrails: &GuardrailSet,
128        content: &Content,
129        phase: GuardrailPhase,
130        preamble: bool,
131    ) -> Result<Screening> {
132        let check = if preamble { Check::Preamble } else { Check::Validate };
133        Self::enforce_with(guardrails, content, phase, check).await
134    }
135
136    /// Screens an agent's final answer as [`enforce`](Self::enforce) does in the output
137    /// phase, through every guardrail's [`validate_output`](Guardrail::validate_output) with
138    /// `evidence`.
139    ///
140    /// # Errors
141    ///
142    /// Returns [`GuardrailError::Blocked`] with every failure when a failure is above `Low`.
143    ///
144    /// # Example
145    ///
146    /// ```rust
147    /// use adk_core::{Content, GroundingSource};
148    /// use adk_guardrail::{CitationRequired, GuardrailExecutor, GuardrailSet, OutputEvidence};
149    ///
150    /// # futures::executor::block_on(async {
151    /// let set = GuardrailSet::new().with(CitationRequired::new());
152    /// let answer = Content::new("model").with_text("Refunds take 30 days.");
153    /// let sources = [GroundingSource::new("rag_search", "https://example.com/refunds")];
154    /// let blocked =
155    ///     GuardrailExecutor::enforce_output(&set, &answer, &OutputEvidence::new(&sources, None))
156    ///         .await;
157    /// assert!(blocked.is_err(), "the answer cites none of the retrieved sources");
158    /// # });
159    /// ```
160    pub async fn enforce_output(
161        guardrails: &GuardrailSet,
162        content: &Content,
163        evidence: &OutputEvidence<'_>,
164    ) -> Result<Screening> {
165        Self::enforce_with(guardrails, content, GuardrailPhase::Output, Check::Output(evidence))
166            .await
167    }
168
169    async fn enforce_with(
170        guardrails: &GuardrailSet,
171        content: &Content,
172        phase: GuardrailPhase,
173        check: Check<'_>,
174    ) -> Result<Screening> {
175        let result = match Self::run_with(guardrails, content, check).await {
176            Ok(result) => result,
177            Err(GuardrailError::ValidationFailed { name, reason, severity }) => {
178                return Err(GuardrailError::Blocked {
179                    phase,
180                    failures: vec![GuardrailFailure { guardrail: name, reason, severity }],
181                });
182            }
183            Err(error) => return Err(error),
184        };
185        let failures: Vec<GuardrailFailure> = result
186            .failures
187            .into_iter()
188            .map(|(guardrail, reason, severity)| GuardrailFailure { guardrail, reason, severity })
189            .collect();
190        if !result.passed {
191            return Err(GuardrailError::Blocked { phase, failures });
192        }
193        for warning in &failures {
194            tracing::warn!(
195                guardrail.name = %warning.guardrail,
196                guardrail.severity = ?warning.severity,
197                guardrail.phase = %phase,
198                "guardrail flagged content at low severity; the content passes"
199            );
200        }
201        Ok(Screening {
202            content: result.transformed_content.unwrap_or_else(|| content.clone()),
203            warnings: failures,
204        })
205    }
206
207    async fn run_with(
208        guardrails: &GuardrailSet,
209        content: &Content,
210        check: Check<'_>,
211    ) -> Result<ExecutionResult> {
212        if guardrails.is_empty() {
213            return Ok(ExecutionResult {
214                passed: true,
215                transformed_content: None,
216                failures: vec![],
217            });
218        }
219
220        // Separate parallel and sequential guardrails
221        let (parallel, sequential): (Vec<_>, Vec<_>) =
222            guardrails.guardrails().iter().partition(|g| g.run_parallel());
223
224        let mut current_content = content.clone();
225        let mut all_failures = Vec::new();
226
227        // Run parallel guardrails
228        if !parallel.is_empty() {
229            let futures: Vec<_> = parallel
230                .iter()
231                .map(|g| Self::run_single(Arc::clone(g), &current_content, check))
232                .collect();
233
234            let results = join_all(futures).await;
235
236            for (guardrail, result) in parallel.iter().zip(results) {
237                match result {
238                    GuardrailResult::Pass => {}
239                    GuardrailResult::Fail { reason, severity } => {
240                        all_failures.push((guardrail.name().to_string(), reason.clone(), severity));
241                        // Early exit on critical
242                        if severity == Severity::Critical && guardrail.fail_fast() {
243                            return Err(GuardrailError::ValidationFailed {
244                                name: guardrail.name().to_string(),
245                                reason,
246                                severity,
247                            });
248                        }
249                    }
250                    // A transform reason can quote the content it replaced, so it is not logged.
251                    GuardrailResult::Transform { new_content, reason: _ } => {
252                        tracing::debug!(guardrail = guardrail.name(), "content transformed");
253                        current_content = new_content;
254                    }
255                }
256            }
257        }
258
259        // Run sequential guardrails
260        for guardrail in sequential {
261            let result = Self::run_single(Arc::clone(guardrail), &current_content, check).await;
262            match result {
263                GuardrailResult::Pass => {}
264                GuardrailResult::Fail { reason, severity } => {
265                    all_failures.push((guardrail.name().to_string(), reason.clone(), severity));
266                    if severity == Severity::Critical && guardrail.fail_fast() {
267                        return Err(GuardrailError::ValidationFailed {
268                            name: guardrail.name().to_string(),
269                            reason,
270                            severity,
271                        });
272                    }
273                }
274                GuardrailResult::Transform { new_content, reason: _ } => {
275                    tracing::debug!(guardrail = guardrail.name(), "content transformed");
276                    current_content = new_content;
277                }
278            }
279        }
280
281        let passed =
282            all_failures.is_empty() || all_failures.iter().all(|(_, _, s)| *s == Severity::Low);
283
284        // Check if content was transformed by comparing serialized forms
285        let was_transformed =
286            serde_json::to_string(&current_content).ok() != serde_json::to_string(content).ok();
287        let transformed = if was_transformed { Some(current_content) } else { None };
288
289        Ok(ExecutionResult { passed, transformed_content: transformed, failures: all_failures })
290    }
291
292    async fn run_single(
293        guardrail: Arc<dyn Guardrail>,
294        content: &Content,
295        check: Check<'_>,
296    ) -> GuardrailResult {
297        match check {
298            Check::Validate => guardrail.validate(content).await,
299            Check::Preamble => guardrail.validate_preamble(content).await,
300            Check::Output(evidence) => guardrail.validate_output(content, evidence).await,
301        }
302    }
303}
304
305#[cfg(test)]
306mod tests {
307    use super::*;
308
309    struct PassGuardrail;
310
311    #[async_trait::async_trait]
312    impl Guardrail for PassGuardrail {
313        fn name(&self) -> &str {
314            "pass"
315        }
316        async fn validate(&self, _: &Content) -> GuardrailResult {
317            GuardrailResult::Pass
318        }
319    }
320
321    struct FailGuardrail {
322        severity: Severity,
323    }
324
325    #[async_trait::async_trait]
326    impl Guardrail for FailGuardrail {
327        fn name(&self) -> &str {
328            "fail"
329        }
330        async fn validate(&self, _: &Content) -> GuardrailResult {
331            GuardrailResult::Fail { reason: "test failure".into(), severity: self.severity }
332        }
333    }
334
335    #[tokio::test]
336    async fn test_empty_guardrails_pass() {
337        let set = GuardrailSet::new();
338        let content = Content::new("user").with_text("hello");
339        let result = GuardrailExecutor::run(&set, &content).await.unwrap();
340        assert!(result.passed);
341    }
342
343    #[tokio::test]
344    async fn test_pass_guardrail() {
345        let set = GuardrailSet::new().with(PassGuardrail);
346        let content = Content::new("user").with_text("hello");
347        let result = GuardrailExecutor::run(&set, &content).await.unwrap();
348        assert!(result.passed);
349    }
350
351    #[tokio::test]
352    async fn test_fail_guardrail_low_severity() {
353        let set = GuardrailSet::new().with(FailGuardrail { severity: Severity::Low });
354        let content = Content::new("user").with_text("hello");
355        let result = GuardrailExecutor::run(&set, &content).await.unwrap();
356        assert!(result.passed); // Low severity doesn't fail
357        assert_eq!(result.failures.len(), 1);
358    }
359
360    #[tokio::test]
361    async fn test_fail_guardrail_high_severity() {
362        let set = GuardrailSet::new().with(FailGuardrail { severity: Severity::High });
363        let content = Content::new("user").with_text("hello");
364        let result = GuardrailExecutor::run(&set, &content).await.unwrap();
365        assert!(!result.passed);
366    }
367
368    #[tokio::test]
369    async fn enforce_passes_low_severity_failures_as_warnings() {
370        let set = GuardrailSet::new().with(FailGuardrail { severity: Severity::Low });
371        let content = Content::new("model").with_text("hello");
372        let screened = GuardrailExecutor::enforce(&set, &content, GuardrailPhase::Output, false)
373            .await
374            .unwrap();
375        assert_eq!(screened.content.parts, content.parts);
376        assert_eq!(
377            screened.warnings,
378            vec![GuardrailFailure {
379                guardrail: "fail".into(),
380                reason: "test failure".into(),
381                severity: Severity::Low,
382            }]
383        );
384    }
385
386    #[tokio::test]
387    async fn enforce_blocks_a_critical_failure_with_its_phase() {
388        let set = GuardrailSet::new().with(FailGuardrail { severity: Severity::Critical });
389        let content = Content::new("user").with_text("hello");
390        let error = GuardrailExecutor::enforce(&set, &content, GuardrailPhase::Input, false)
391            .await
392            .unwrap_err();
393        assert!(matches!(
394            error,
395            GuardrailError::Blocked { phase: GuardrailPhase::Input, ref failures }
396                if failures.len() == 1 && failures[0].severity == Severity::Critical
397        ));
398    }
399
400    #[tokio::test]
401    async fn test_critical_early_exit() {
402        let set = GuardrailSet::new().with(FailGuardrail { severity: Severity::Critical });
403        let content = Content::new("user").with_text("hello");
404        let result = GuardrailExecutor::run(&set, &content).await;
405        assert!(result.is_err());
406    }
407}