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
9pub struct GuardrailSet {
13 guardrails: Vec<Arc<dyn Guardrail>>,
14}
15
16impl GuardrailSet {
17 pub fn new() -> Self {
19 Self { guardrails: Vec::new() }
20 }
21
22 pub fn with(mut self, guardrail: impl Guardrail + 'static) -> Self {
24 self.guardrails.push(Arc::new(guardrail));
25 self
26 }
27
28 pub fn with_arc(mut self, guardrail: Arc<dyn Guardrail>) -> Self {
30 self.guardrails.push(guardrail);
31 self
32 }
33
34 pub fn guardrails(&self) -> &[Arc<dyn Guardrail>] {
36 &self.guardrails
37 }
38
39 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#[derive(Debug)]
53pub struct ExecutionResult {
54 pub passed: bool,
56 pub transformed_content: Option<Content>,
58 pub failures: Vec<(String, String, Severity)>,
60}
61
62#[derive(Debug, Clone)]
64pub struct Screening {
65 pub content: Content,
67 pub warnings: Vec<GuardrailFailure>,
69}
70
71#[derive(Clone, Copy)]
73enum Check<'a> {
74 Validate,
75 Preamble,
76 Output(&'a OutputEvidence<'a>),
77}
78
79pub struct GuardrailExecutor;
81
82impl GuardrailExecutor {
83 pub async fn run(guardrails: &GuardrailSet, content: &Content) -> Result<ExecutionResult> {
85 Self::run_with(guardrails, content, Check::Validate).await
86 }
87
88 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 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 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 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 if !parallel.is_empty() {
229 let futures: Vec<_> = parallel
230 .iter()
231 .map(|g| Self::run_single(Arc::clone(g), ¤t_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 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 GuardrailResult::Transform { new_content, reason: _ } => {
252 tracing::debug!(guardrail = guardrail.name(), "content transformed");
253 current_content = new_content;
254 }
255 }
256 }
257 }
258
259 for guardrail in sequential {
261 let result = Self::run_single(Arc::clone(guardrail), ¤t_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 let was_transformed =
286 serde_json::to_string(¤t_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); 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}