1use std::collections::HashMap;
3
4use serde::{Deserialize, Serialize};
5
6pub type RequestId = String;
7
8#[derive(Debug, Clone, PartialEq, Eq)]
10pub enum SecurityRequestState {
11 Running,
13 Finished(SecurityRequestCompletion),
15}
16
17#[derive(Debug, Clone, PartialEq, Eq)]
19pub enum SecurityRequestCompletion {
20 Complete,
22 Degraded { failures: Vec<SecurityFailure> },
24 Failed { failures: Vec<SecurityFailure> },
26}
27
28#[derive(Debug, Clone, PartialEq, Eq)]
30pub struct SecurityFailure {
31 pub stage: SecurityFailureStage,
32 pub level: Option<SecurityLevel>,
33 pub detector_id: Option<String>,
34 pub kind: SecurityFailureKind,
35 pub retryable: bool,
36 pub message: String,
37}
38
39#[derive(Debug, Clone, Copy, PartialEq, Eq)]
41pub enum SecurityFailureStage {
42 Warmup,
43 Asset,
44 Scanner,
45 Inference,
46 Queue,
47 Worker,
48}
49
50#[derive(Debug, Clone, Copy, PartialEq, Eq)]
52pub enum SecurityFailureKind {
53 NotReady,
54 MissingAsset,
55 IntegrityFailure,
56 InitializationFailure,
57 InferenceFailure,
58 Timeout,
59 QueueFull,
60 WorkerUnavailable,
61 Internal,
62}
63
64#[derive(Debug, Clone, PartialEq, Eq)]
66pub struct SecurityRuntimeReadiness {
67 pub l1: SecurityLevelReadiness,
68 pub l2: SecurityLevelReadiness,
69 pub l3: SecurityLevelReadiness,
70}
71
72#[derive(Debug, Clone, PartialEq, Eq)]
78pub struct SecurityAssetReadiness {
79 pub l1: SecurityLevelReadiness,
80 pub l2: SecurityLevelReadiness,
81 pub l3: SecurityLevelReadiness,
82}
83
84#[derive(Debug, Clone, PartialEq, Eq)]
86pub struct SecurityAssetProgress {
87 pub category: SecurityCategory,
89 pub model: String,
91 pub completed_files: usize,
93 pub total_files: usize,
95}
96
97pub type SecurityAssetProgressCallback =
99 std::sync::Arc<dyn Fn(SecurityAssetProgress) + Send + Sync>;
100
101#[derive(Debug, Clone, PartialEq, Eq)]
103pub enum SecurityLevelReadiness {
104 Ready,
105 NotConfigured,
106 NotReady { failures: Vec<SecurityFailure> },
107}
108
109impl std::fmt::Display for SecurityFailure {
110 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
111 write!(formatter, "{}", self.message)
112 }
113}
114
115impl std::error::Error for SecurityFailure {}
116
117impl SecurityFailureStage {
118 pub fn as_str(self) -> &'static str {
119 match self {
120 Self::Warmup => "warmup",
121 Self::Asset => "asset",
122 Self::Scanner => "scanner",
123 Self::Inference => "inference",
124 Self::Queue => "queue",
125 Self::Worker => "worker",
126 }
127 }
128}
129
130impl SecurityFailureKind {
131 pub fn as_str(self) -> &'static str {
132 match self {
133 Self::NotReady => "not_ready",
134 Self::MissingAsset => "missing_asset",
135 Self::IntegrityFailure => "integrity_failure",
136 Self::InitializationFailure => "initialization_failure",
137 Self::InferenceFailure => "inference_failure",
138 Self::Timeout => "timeout",
139 Self::QueueFull => "queue_full",
140 Self::WorkerUnavailable => "worker_unavailable",
141 Self::Internal => "internal",
142 }
143 }
144}
145
146#[derive(Debug, Clone)]
148pub enum QueuedSecurityEvent {
149 Result(QueuedSecurityScanResult),
151 Progress(QueuedSecurityProgress),
153 Provisional(QueuedSecurityScanResult),
155 Finished {
157 request_id: RequestId,
158 completion: SecurityRequestCompletion,
159 },
160}
161
162impl QueuedSecurityEvent {
163 pub fn request_id(&self) -> &str {
165 match self {
166 Self::Result(queued) => &queued.request_id,
167 Self::Progress(progress) => &progress.request_id,
168 Self::Provisional(queued) => &queued.request_id,
169 Self::Finished { request_id, .. } => request_id,
170 }
171 }
172}
173
174#[derive(Debug, Clone, Serialize, Deserialize)]
175pub struct QueuedSecurityProgress {
177 pub request_id: RequestId,
178 pub category: String,
179 pub model: String,
180 pub stage: String,
181 pub completed_chunks: usize,
182 pub total_chunks: usize,
183 pub inferred_chunks: usize,
184 pub propagated_chunks: usize,
185 pub cache_hits: usize,
186 pub early_exit: bool,
187 pub coverage: f64,
188 pub details: HashMap<String, serde_json::Value>,
189}
190
191#[derive(Debug, Clone)]
192pub struct QueuedSecurityScanResult {
194 pub request_id: RequestId,
196 pub result: SecurityScanResult,
198}
199
200#[derive(Debug, Clone)]
201pub struct SecurityScanResult {
203 pub category: String,
205 pub class_name: String,
207 pub confidence: f64,
209 pub level: String,
211 pub model: String,
213 pub duration_ms: f64,
215 pub layers: Vec<LayerResult>,
217 #[doc(hidden)]
220 pub internal_l2_chunk_outputs: Vec<crate::ml::ntdb_executor::L2ChunkOutput>,
221 pub evidence_spans: Vec<crate::dynamic_pii::EvidenceSpan>,
223 pub label_scores: Vec<LabelScore>,
225 pub decision: Option<DecisionEnvelope>,
227}
228
229#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
230pub enum SecurityLevel {
232 L1 = 1,
234 L2 = 2,
236 L3 = 3,
238}
239
240impl SecurityLevel {
241 pub fn as_str(self) -> &'static str {
243 match self {
244 SecurityLevel::L1 => "L1",
245 SecurityLevel::L2 => "L2",
246 SecurityLevel::L3 => "L3",
247 }
248 }
249}
250
251impl Serialize for SecurityLevel {
253 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
254 serializer.serialize_str(self.as_str())
255 }
256}
257
258impl<'de> Deserialize<'de> for SecurityLevel {
260 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
261 String::deserialize(deserializer)?
262 .parse()
263 .map_err(serde::de::Error::custom)
264 }
265}
266
267impl std::str::FromStr for SecurityLevel {
268 type Err = String;
269
270 fn from_str(s: &str) -> Result<Self, Self::Err> {
271 match s.to_lowercase().as_str() {
272 "1" | "l1" => Ok(SecurityLevel::L1),
273 "2" | "l2" => Ok(SecurityLevel::L2),
274 "3" | "l3" => Ok(SecurityLevel::L3),
275 _ => Err(format!("Unknown security level: {}", s)),
276 }
277 }
278}
279
280#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
281pub enum OnnxBatchMode {
283 #[default]
285 LazyBatches,
286 TensorBatch,
288}
289
290impl OnnxBatchMode {
291 pub fn as_str(self) -> &'static str {
293 match self {
294 OnnxBatchMode::LazyBatches => "lazy_batches",
295 OnnxBatchMode::TensorBatch => "tensor_batch",
296 }
297 }
298}
299
300impl std::str::FromStr for OnnxBatchMode {
301 type Err = String;
302
303 fn from_str(s: &str) -> Result<Self, Self::Err> {
304 match s.to_lowercase().replace('-', "_").as_str() {
305 "lazy" | "lazy_batches" | "lazybatches" => Ok(OnnxBatchMode::LazyBatches),
306 "tensor" | "tensor_batch" | "tensorbatch" => Ok(OnnxBatchMode::TensorBatch),
307 _ => Err(format!("Unknown ONNX batch mode: {}", s)),
308 }
309 }
310}
311
312#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
313pub enum NtdbOperatingPoint {
315 BestF1,
316 #[default]
317 BestPromote,
318 ArkApiShortInjectionUtility,
321 BestFprInF1,
322 BestFnrInF1,
323 BestLatencyInF1,
324}
325
326impl NtdbOperatingPoint {
327 pub fn as_str(self) -> &'static str {
329 match self {
330 Self::BestF1 => "best_f1",
331 Self::BestPromote => "best_promote",
332 Self::ArkApiShortInjectionUtility => "ark_api_short_injection_utility",
333 Self::BestFprInF1 => "best_fpr_in_f1",
334 Self::BestFnrInF1 => "best_fnr_in_f1",
335 Self::BestLatencyInF1 => "best_latency_in_f1",
336 }
337 }
338}
339
340impl std::str::FromStr for NtdbOperatingPoint {
341 type Err = String;
342
343 fn from_str(s: &str) -> Result<Self, Self::Err> {
344 match s.to_lowercase().replace('-', "_").as_str() {
345 "best_f1" => Ok(Self::BestF1),
346 "best_promote" => Ok(Self::BestPromote),
347 "ark_api_short_injection_utility" => Ok(Self::ArkApiShortInjectionUtility),
348 "best_fpr_in_f1" => Ok(Self::BestFprInF1),
349 "best_fnr_in_f1" => Ok(Self::BestFnrInF1),
350 "best_latency_in_f1" => Ok(Self::BestLatencyInF1),
351 _ => Err(format!("Unknown NTDB operating point: {s}")),
352 }
353 }
354}
355
356#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
357pub enum L3Strategy {
359 #[default]
361 Dedicated,
362 Multi,
364}
365
366impl L3Strategy {
367 pub fn as_str(self) -> &'static str {
368 match self {
369 Self::Dedicated => "dedicated",
370 Self::Multi => "multi",
371 }
372 }
373}
374
375impl std::str::FromStr for L3Strategy {
376 type Err = String;
377
378 fn from_str(value: &str) -> Result<Self, Self::Err> {
379 match value.trim().to_lowercase().replace('-', "_").as_str() {
380 "dedicated" | "single" | "single_model" => Ok(Self::Dedicated),
381 "multi" | "multitask" | "multi_task" => Ok(Self::Multi),
382 _ => Err(format!("Unknown L3 strategy: {value}")),
383 }
384 }
385}
386
387#[derive(Debug, Clone, Default, Deserialize)]
388#[serde(try_from = "GateConfig")]
389pub struct ScanGateMatrix {
402 pub native: crate::NativeGates,
404 pub l1: Option<bool>,
406 pub l2: Option<bool>,
408 pub l3: Option<bool>,
410 pub conditional: Vec<ConditionalPipelineGate>,
412 pub l3_policy: L3SchedulerPolicy,
414}
415
416#[derive(Debug, Clone)]
417pub struct L3SchedulerPolicy {
419 pub enabled: bool,
421 pub priority: Vec<String>,
423 pub ttl_ms: HashMap<String, u64>,
425 pub estimated_cost_ms: HashMap<String, u64>,
428 pub fairness_quantum_ms: u64,
430 pub max_wait_ms: u64,
432 pub degraded_factor: f64,
434 pub early_exit: L3EarlyExitMode,
436 pub progress: L3ProgressMode,
438 pub clustering: L3ClusteringStrategy,
440 pub representatives_per_cluster: usize,
443 pub verify_representatives_per_cluster: usize,
446 pub min_cluster_similarity: f64,
449 pub max_cluster_size: usize,
451 pub pipelines: HashMap<String, L3PipelinePolicy>,
454}
455
456#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
457#[serde(deny_unknown_fields)]
458pub struct L3PipelinePolicy {
460 #[serde(default)]
462 pub clustering: Option<L3ClusteringStrategy>,
463 #[serde(default)]
465 pub representatives_per_cluster: Option<usize>,
466 #[serde(default)]
468 pub verify_representatives_per_cluster: Option<usize>,
469 #[serde(default)]
471 pub min_cluster_similarity: Option<f64>,
472 #[serde(default)]
474 pub max_cluster_size: Option<usize>,
475 #[serde(default)]
477 pub aggregation: Option<L3AggregationStrategy>,
478 #[serde(default)]
480 pub early_exit: Option<L3PipelineEarlyExit>,
481}
482
483#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
484#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
485pub enum L3AggregationStrategy {
487 AnyPositiveOrHighest {
488 positive_class: String,
489 threshold: f64,
490 },
491 HighestRiskAboveThresholdOrConfidence {
492 threshold: f64,
493 },
494 MajorityVoteOrHighest,
495}
496
497#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
498#[serde(rename_all = "snake_case")]
499pub enum L3PipelineEarlyExit {
501 Disabled,
502 HeadStable,
503 RequestWidePositive,
504}
505
506#[derive(Debug, Clone, PartialEq)]
507pub struct EffectiveL3PipelinePolicy {
509 pub clustering: L3ClusteringStrategy,
510 pub representatives_per_cluster: usize,
511 pub verify_representatives_per_cluster: usize,
512 pub min_cluster_similarity: f64,
513 pub max_cluster_size: usize,
514 pub aggregation: Option<L3AggregationStrategy>,
515 pub early_exit: L3PipelineEarlyExit,
516}
517
518#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
519#[serde(rename_all = "snake_case")]
520pub enum L3EarlyExitMode {
521 Disabled,
522 ClassStable,
523}
524
525#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
526#[serde(rename_all = "snake_case")]
527pub enum L3ProgressMode {
528 Disabled,
529 Progress,
530 Provisional,
531}
532
533#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
534#[serde(rename_all = "snake_case")]
535pub enum L3ClusteringStrategy {
536 Disabled,
537 RankOnly,
538 Representative,
539 VerifyRepresentative,
540}
541
542#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
543#[serde(deny_unknown_fields)]
544pub struct ConditionalPipelineGate {
546 pub level: SecurityLevel,
548 #[serde(default)]
550 pub pipeline: Option<String>,
551 pub when: GateExpression,
553 #[serde(default)]
556 pub l3_policy: Option<L3PipelinePolicy>,
557}
558
559#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
560#[serde(rename_all = "snake_case")]
561pub enum GateExpression {
563 All(Vec<GateExpression>),
564 Any(Vec<GateExpression>),
565 Not(Box<GateExpression>),
566 Metadata(MetadataCondition),
567 Result(ResultCondition),
568}
569
570#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
571#[serde(deny_unknown_fields)]
572pub struct MetadataCondition {
574 pub path: String,
575 #[serde(default)]
576 pub equals: Option<serde_json::Value>,
577 #[serde(default, rename = "in")]
578 pub in_values: Option<Vec<serde_json::Value>>,
579 #[serde(default)]
580 pub exists: Option<bool>,
581}
582
583#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
584#[serde(deny_unknown_fields)]
585pub struct ResultCondition {
587 pub pipeline: String,
588 #[serde(default)]
589 pub classes: Vec<String>,
590 #[serde(default)]
591 pub min_confidence: Option<f64>,
592}
593
594#[derive(Debug, Clone, PartialEq)]
595pub struct GateResult {
597 pub pipeline: String,
598 pub class_name: String,
599 pub confidence: f64,
600 pub level: SecurityLevel,
601}
602
603impl Default for L3SchedulerPolicy {
604 fn default() -> Self {
605 let mut ttl_ms = HashMap::new();
606 ttl_ms.insert("injection".to_string(), 15_000);
607 ttl_ms.insert("wolf-defender-small".to_string(), 15_000);
608 ttl_ms.insert("dynamic-pii".to_string(), 12_000);
609 ttl_ms.insert("gliner_small-v2.5-edge".to_string(), 12_000);
610 ttl_ms.insert("sensitive_document".to_string(), 12_000);
611 ttl_ms.insert("orca-sonar-document-classifier".to_string(), 12_000);
612 for name in [
613 "tool_class",
614 "tool_action",
615 "tool_tags",
616 "routing",
617 "threat",
618 "unified-v3-tool-class",
619 "unified-v3-tool-action",
620 "unified-v3-tool-tags",
621 "unified-v3-routing",
622 "unified-v3-threat",
623 ] {
624 ttl_ms.insert(name.to_string(), 10_500);
625 }
626 ttl_ms.insert("unified-multitask-model-augmented-v3".to_string(), 15_000);
627 let mut estimated_cost_ms = HashMap::new();
628 estimated_cost_ms.insert("injection".to_string(), 200);
629 estimated_cost_ms.insert("wolf-defender-small".to_string(), 200);
630 estimated_cost_ms.insert("dynamic-pii".to_string(), 240);
631 estimated_cost_ms.insert("gliner_small-v2.5-edge".to_string(), 240);
632 estimated_cost_ms.insert("sensitive_document".to_string(), 150);
633 estimated_cost_ms.insert("orca-sonar-document-classifier".to_string(), 150);
634 for name in [
635 "tool_class",
636 "tool_action",
637 "tool_tags",
638 "routing",
639 "threat",
640 "unified-v3-tool-class",
641 "unified-v3-tool-action",
642 "unified-v3-tool-tags",
643 "unified-v3-routing",
644 "unified-v3-threat",
645 ] {
646 estimated_cost_ms.insert(name.to_string(), 150);
647 }
648 estimated_cost_ms.insert("unified-multitask-model-augmented-v3".to_string(), 200);
649 Self {
650 enabled: true,
651 priority: vec![
652 "injection".to_string(),
653 "wolf-defender-small".to_string(),
654 "threat".to_string(),
655 "unified-v3-threat".to_string(),
656 "dynamic-pii".to_string(),
657 "gliner_small-v2.5-edge".to_string(),
658 "sensitive_document".to_string(),
659 "orca-sonar-document-classifier".to_string(),
660 "tool_class".to_string(),
661 "tool_action".to_string(),
662 "tool_tags".to_string(),
663 "routing".to_string(),
664 "unified-multitask-model-augmented-v3".to_string(),
665 ],
666 ttl_ms,
667 estimated_cost_ms,
668 fairness_quantum_ms: 50,
669 max_wait_ms: 2_000,
670 degraded_factor: 0.75,
671 early_exit: L3EarlyExitMode::ClassStable,
672 progress: L3ProgressMode::Disabled,
673 clustering: L3ClusteringStrategy::RankOnly,
674 representatives_per_cluster: 1,
675 verify_representatives_per_cluster: 1,
676 min_cluster_similarity: 0.90,
677 max_cluster_size: 8,
678 pipelines: HashMap::new(),
679 }
680 }
681}
682
683impl L3SchedulerPolicy {
684 pub fn pipeline_policy(&self, category: &str, model: &str) -> EffectiveL3PipelinePolicy {
686 let pipeline = self
687 .pipelines
688 .get(category)
689 .or_else(|| self.pipelines.get(model));
690 let inherited_early_exit = match self.early_exit {
691 L3EarlyExitMode::Disabled => L3PipelineEarlyExit::Disabled,
692 L3EarlyExitMode::ClassStable
693 if category == "injection"
694 || category == "threat"
695 || model == "wolf-defender-small"
696 || model == "unified-v3-threat" =>
697 {
698 L3PipelineEarlyExit::RequestWidePositive
699 }
700 L3EarlyExitMode::ClassStable => L3PipelineEarlyExit::HeadStable,
701 };
702 EffectiveL3PipelinePolicy {
703 clustering: pipeline
704 .and_then(|policy| policy.clustering)
705 .unwrap_or(self.clustering),
706 representatives_per_cluster: pipeline
707 .and_then(|policy| policy.representatives_per_cluster)
708 .unwrap_or(self.representatives_per_cluster)
709 .max(1),
710 verify_representatives_per_cluster: pipeline
711 .and_then(|policy| policy.verify_representatives_per_cluster)
712 .unwrap_or(self.verify_representatives_per_cluster)
713 .max(1),
714 min_cluster_similarity: pipeline
715 .and_then(|policy| policy.min_cluster_similarity)
716 .unwrap_or(self.min_cluster_similarity)
717 .clamp(0.0, 1.0),
718 max_cluster_size: pipeline
719 .and_then(|policy| policy.max_cluster_size)
720 .unwrap_or(self.max_cluster_size)
721 .max(1),
722 aggregation: pipeline.and_then(|policy| policy.aggregation.clone()),
723 early_exit: pipeline
724 .and_then(|policy| policy.early_exit)
725 .unwrap_or(inherited_early_exit),
726 }
727 }
728}
729
730impl ScanGateMatrix {
731 pub fn all_enabled() -> Self {
733 Self {
734 native: crate::NativeGates::all_enabled(),
735 ..Self::default()
736 }
737 }
738
739 pub fn levels(l1: bool, l2: bool, l3: bool) -> Self {
741 Self {
742 l1: Some(l1),
743 l2: Some(l2),
744 l3: Some(l3),
745 ..Self::default()
746 }
747 }
748
749 pub fn set_level(&mut self, level: SecurityLevel, enabled: bool) {
751 match level {
752 SecurityLevel::L1 => self.l1 = Some(enabled),
753 SecurityLevel::L2 => self.l2 = Some(enabled),
754 SecurityLevel::L3 => self.l3 = Some(enabled),
755 }
756 }
757
758 pub fn set_model(&mut self, model: impl Into<String>, enabled: bool) {
760 self.native.models.insert(model.into(), enabled);
761 }
762
763 pub fn with_model(mut self, model: impl Into<String>, enabled: bool) -> Self {
765 self.set_model(model, enabled);
766 self
767 }
768
769 pub fn set_rule(&mut self, rule_id: impl Into<String>, enabled: bool) {
771 self.native.rules.insert(rule_id.into(), enabled);
772 }
773
774 pub fn with_rule(mut self, rule_id: impl Into<String>, enabled: bool) -> Self {
776 self.set_rule(rule_id, enabled);
777 self
778 }
779
780 pub fn set_conditional(&mut self, gates: Vec<ConditionalPipelineGate>) -> Result<(), String> {
782 for gate in &gates {
783 gate.validate()?;
784 }
785 self.conditional = gates;
786 Ok(())
787 }
788
789 pub fn allows_level(&self, level: SecurityLevel) -> bool {
792 match level {
793 SecurityLevel::L1 => self.l1.unwrap_or(true),
794 SecurityLevel::L2 => self.l2.unwrap_or(true),
795 SecurityLevel::L3 => self.l3.unwrap_or(true),
796 }
797 }
798
799 pub fn set_l3_policy(&mut self, policy: L3SchedulerPolicy) {
801 self.l3_policy = policy;
802 }
803}
804
805#[derive(Default, Deserialize)]
807#[serde(default, deny_unknown_fields)]
808struct GateConfig {
809 #[serde(flatten)]
810 native: crate::NativeGates,
811 l1: Option<bool>,
812 l2: Option<bool>,
813 l3: Option<bool>,
814 conditional: Vec<ConditionalPipelineGate>,
815 l3_policy: L3PolicyConfig,
816}
817
818#[derive(Default, Deserialize)]
821#[serde(default, deny_unknown_fields)]
822struct L3PolicyConfig {
823 enabled: Option<bool>,
824 priority: Option<Vec<String>>,
825 ttl_ms: HashMap<String, u64>,
826 estimated_cost_ms: HashMap<String, u64>,
827 fairness_quantum_ms: Option<u64>,
828 max_wait_ms: Option<u64>,
829 degraded_factor: Option<f64>,
830 early_exit: Option<L3EarlyExitMode>,
831 progress: Option<L3ProgressMode>,
832 clustering: Option<L3ClusteringStrategy>,
833 representatives_per_cluster: Option<usize>,
834 verify_representatives_per_cluster: Option<usize>,
835 min_cluster_similarity: Option<f64>,
836 max_cluster_size: Option<usize>,
837 pipelines: HashMap<String, L3PipelinePolicy>,
838}
839
840impl TryFrom<GateConfig> for ScanGateMatrix {
841 type Error = String;
842
843 fn try_from(config: GateConfig) -> Result<Self, String> {
844 let raw = config.l3_policy;
845 let mut policy = L3SchedulerPolicy::default();
846 macro_rules! set {
847 ($($field:ident),*) => {$(
848 if let Some(value) = raw.$field {
849 policy.$field = value;
850 }
851 )*};
852 }
853 set!(
854 enabled,
855 priority,
856 fairness_quantum_ms,
857 max_wait_ms,
858 degraded_factor,
859 early_exit,
860 progress,
861 clustering,
862 representatives_per_cluster,
863 verify_representatives_per_cluster,
864 min_cluster_similarity,
865 max_cluster_size
866 );
867 policy.ttl_ms.extend(raw.ttl_ms);
868 policy.estimated_cost_ms.extend(raw.estimated_cost_ms);
869 policy.pipelines = raw.pipelines;
870 policy.validate()?;
871 let mut gates = Self {
872 native: config.native,
873 l1: config.l1,
874 l2: config.l2,
875 l3: config.l3,
876 l3_policy: policy,
877 ..Self::default()
878 };
879 gates.set_conditional(config.conditional)?;
880 Ok(gates)
881 }
882}
883
884fn check_fraction(value: f64, field: &str) -> Result<(), String> {
885 if (0.0..=1.0).contains(&value) {
886 Ok(())
887 } else {
888 Err(format!("{field} must be between 0.0 and 1.0"))
889 }
890}
891
892fn check_count(value: usize, field: &str) -> Result<(), String> {
893 if value == 0 {
894 Err(format!("{field} must be >= 1"))
895 } else {
896 Ok(())
897 }
898}
899
900impl L3SchedulerPolicy {
901 pub fn validate(&self) -> Result<(), String> {
904 check_count(
905 usize::try_from(self.fairness_quantum_ms).unwrap_or(usize::MAX),
906 "l3_policy.fairness_quantum_ms",
907 )?;
908 check_count(
909 self.representatives_per_cluster,
910 "l3_policy.representatives_per_cluster",
911 )?;
912 check_count(
913 self.verify_representatives_per_cluster,
914 "l3_policy.verify_representatives_per_cluster",
915 )?;
916 check_count(self.max_cluster_size, "l3_policy.max_cluster_size")?;
917 check_fraction(self.degraded_factor, "l3_policy.degraded_factor")?;
918 check_fraction(
919 self.min_cluster_similarity,
920 "l3_policy.min_cluster_similarity",
921 )?;
922 if let Some(name) = self.estimated_cost_ms.iter().find(|(_, &cost)| cost == 0) {
923 return Err(format!(
924 "l3_policy.estimated_cost_ms.{} must be >= 1",
925 name.0
926 ));
927 }
928 for (name, pipeline) in &self.pipelines {
929 if name.trim().is_empty() {
930 return Err("l3_policy.pipelines keys must not be empty".to_string());
931 }
932 pipeline
933 .validate()
934 .map_err(|error| format!("l3_policy.pipelines.{name}.{error}"))?;
935 }
936 Ok(())
937 }
938}
939
940impl L3PipelinePolicy {
941 pub fn validate(&self) -> Result<(), String> {
943 for (field, value) in [
944 (
945 "representatives_per_cluster",
946 self.representatives_per_cluster,
947 ),
948 (
949 "verify_representatives_per_cluster",
950 self.verify_representatives_per_cluster,
951 ),
952 ("max_cluster_size", self.max_cluster_size),
953 ] {
954 value.map_or(Ok(()), |value| check_count(value, field))?;
955 }
956 if let Some(value) = self.min_cluster_similarity {
957 check_fraction(value, "min_cluster_similarity")?;
958 }
959 match &self.aggregation {
960 Some(L3AggregationStrategy::AnyPositiveOrHighest {
961 positive_class,
962 threshold,
963 }) => {
964 if positive_class.trim().is_empty() {
965 return Err("aggregation.positive_class must not be empty".to_string());
966 }
967 check_fraction(*threshold, "aggregation.threshold")
968 }
969 Some(L3AggregationStrategy::HighestRiskAboveThresholdOrConfidence { threshold }) => {
970 check_fraction(*threshold, "aggregation.threshold")
971 }
972 Some(L3AggregationStrategy::MajorityVoteOrHighest) | None => Ok(()),
973 }
974 }
975}
976
977impl ConditionalPipelineGate {
978 pub fn validate(&self) -> Result<(), String> {
979 if self.level == SecurityLevel::L1 {
980 return Err("conditional gates may only target L2 or L3".to_string());
981 }
982 if self
983 .pipeline
984 .as_ref()
985 .is_some_and(|value| value.trim().is_empty())
986 {
987 return Err("conditional gate pipeline must not be empty".to_string());
988 }
989 if self.l3_policy.is_some() && (self.level != SecurityLevel::L3 || self.pipeline.is_none())
990 {
991 return Err(
992 "conditional l3_policy overrides require level l3 and a pipeline".to_string(),
993 );
994 }
995 if let Some(policy) = &self.l3_policy {
996 policy
997 .validate()
998 .map_err(|error| format!("conditional l3_policy.{error}"))?;
999 }
1000 self.when.validate()
1001 }
1002}
1003
1004impl L3PipelinePolicy {
1005 pub(crate) fn apply_override(&mut self, override_policy: &Self) {
1006 if override_policy.clustering.is_some() {
1007 self.clustering = override_policy.clustering;
1008 }
1009 if override_policy.representatives_per_cluster.is_some() {
1010 self.representatives_per_cluster = override_policy.representatives_per_cluster;
1011 }
1012 if override_policy.verify_representatives_per_cluster.is_some() {
1013 self.verify_representatives_per_cluster =
1014 override_policy.verify_representatives_per_cluster;
1015 }
1016 if override_policy.min_cluster_similarity.is_some() {
1017 self.min_cluster_similarity = override_policy.min_cluster_similarity;
1018 }
1019 if override_policy.max_cluster_size.is_some() {
1020 self.max_cluster_size = override_policy.max_cluster_size;
1021 }
1022 if override_policy.aggregation.is_some() {
1023 self.aggregation = override_policy.aggregation.clone();
1024 }
1025 if override_policy.early_exit.is_some() {
1026 self.early_exit = override_policy.early_exit;
1027 }
1028 }
1029}
1030
1031impl GateExpression {
1032 fn validate(&self) -> Result<(), String> {
1033 match self {
1034 Self::All(items) | Self::Any(items) => {
1035 if items.is_empty() {
1036 return Err("conditional gate all/any must not be empty".to_string());
1037 }
1038 for item in items {
1039 item.validate()?;
1040 }
1041 Ok(())
1042 }
1043 Self::Not(item) => item.validate(),
1044 Self::Metadata(condition) => condition.validate(),
1045 Self::Result(condition) => condition.validate(),
1046 }
1047 }
1048}
1049
1050impl MetadataCondition {
1051 fn validate(&self) -> Result<(), String> {
1052 if self.path.trim().is_empty() {
1053 return Err("metadata gate path must not be empty".to_string());
1054 }
1055 let predicates = usize::from(self.equals.is_some())
1056 + usize::from(self.in_values.is_some())
1057 + usize::from(self.exists.is_some());
1058 if predicates != 1 {
1059 return Err(
1060 "metadata gate must configure exactly one of equals, in, or exists".to_string(),
1061 );
1062 }
1063 if self.in_values.as_ref().is_some_and(Vec::is_empty) {
1064 return Err("metadata gate in list must not be empty".to_string());
1065 }
1066 Ok(())
1067 }
1068}
1069
1070impl ResultCondition {
1071 fn validate(&self) -> Result<(), String> {
1072 if self.pipeline.trim().is_empty() {
1073 return Err("result gate pipeline must not be empty".to_string());
1074 }
1075 if self
1076 .min_confidence
1077 .is_some_and(|value| !(0.0..=1.0).contains(&value))
1078 {
1079 return Err("result gate min_confidence must be between 0.0 and 1.0".to_string());
1080 }
1081 Ok(())
1082 }
1083}
1084
1085#[derive(Debug, Clone)]
1086pub struct ScanExecution {
1088 max_level: SecurityLevel,
1089 gates: ScanGateMatrix,
1090 backend: ExecutionBackend,
1091 onnx_runtime_options: OnnxRuntimeOptions,
1092 onnx_batch_mode: OnnxBatchMode,
1093 ntdb_operating_point: NtdbOperatingPoint,
1094 ntdb_decision_threshold_point: NtdbOperatingPoint,
1095 l3_strategy: L3Strategy,
1096 defer_l3: bool,
1097 chunk_overlap_tokens: usize,
1098 wolf_execution_options: crate::WolfExecutionOptions,
1099 wolf_selection: WolfSelection,
1100}
1101
1102#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
1104#[serde(default, deny_unknown_fields)]
1105pub struct WolfSelection {
1106 pub model: crate::WolfModel,
1107 pub precision: crate::WolfPrecision,
1108}
1109
1110impl ScanExecution {
1111 pub fn new(max_level: SecurityLevel) -> Self {
1113 Self {
1114 max_level,
1115 gates: ScanGateMatrix::default(),
1116 backend: ExecutionBackend::default(),
1117 onnx_runtime_options: OnnxRuntimeOptions::default(),
1118 onnx_batch_mode: OnnxBatchMode::LazyBatches,
1119 ntdb_operating_point: NtdbOperatingPoint::default(),
1120 ntdb_decision_threshold_point: NtdbOperatingPoint::BestF1,
1121 l3_strategy: L3Strategy::default(),
1122 defer_l3: false,
1123 chunk_overlap_tokens: 0,
1124 wolf_execution_options: crate::WolfExecutionOptions::default(),
1125 wolf_selection: WolfSelection::default(),
1126 }
1127 }
1128
1129 pub fn with_gates(max_level: SecurityLevel, gates: ScanGateMatrix) -> Self {
1131 Self {
1132 max_level,
1133 gates,
1134 backend: ExecutionBackend::default(),
1135 onnx_runtime_options: OnnxRuntimeOptions::default(),
1136 onnx_batch_mode: OnnxBatchMode::LazyBatches,
1137 ntdb_operating_point: NtdbOperatingPoint::default(),
1138 ntdb_decision_threshold_point: NtdbOperatingPoint::BestF1,
1139 l3_strategy: L3Strategy::default(),
1140 defer_l3: false,
1141 chunk_overlap_tokens: 0,
1142 wolf_execution_options: crate::WolfExecutionOptions::default(),
1143 wolf_selection: WolfSelection::default(),
1144 }
1145 }
1146
1147 pub fn set_wolf_selection(&mut self, selection: WolfSelection) -> Result<(), String> {
1149 selection.precision.resolve().map_err(|e| e.to_string())?;
1150 self.wolf_selection = selection;
1151 Ok(())
1152 }
1153
1154 pub fn wolf_selection(&self) -> WolfSelection {
1155 self.wolf_selection
1156 }
1157
1158 pub fn set_wolf_execution_options(
1160 &mut self,
1161 options: crate::WolfExecutionOptions,
1162 ) -> Result<(), String> {
1163 options.validate().map_err(|e| e.to_string())?;
1164 self.wolf_execution_options = options;
1165 Ok(())
1166 }
1167
1168 pub fn wolf_execution_options(&self) -> crate::WolfExecutionOptions {
1169 self.wolf_execution_options
1170 }
1171
1172 pub fn set_gates(&mut self, gates: ScanGateMatrix) {
1174 self.gates = gates;
1175 }
1176
1177 pub fn set_onnx_batch_mode(&mut self, mode: OnnxBatchMode) {
1179 self.onnx_batch_mode = mode;
1180 }
1181
1182 pub fn set_backend(&mut self, backend: ExecutionBackend) {
1184 self.backend = backend;
1185 self.onnx_batch_mode = match backend {
1186 ExecutionBackend::Auto | ExecutionBackend::Cpu => OnnxBatchMode::LazyBatches,
1187 ExecutionBackend::Gpu
1188 | ExecutionBackend::CoreMl
1189 | ExecutionBackend::Cuda
1190 | ExecutionBackend::DirectMl
1191 | ExecutionBackend::TensorRt => OnnxBatchMode::TensorBatch,
1192 };
1193 }
1194
1195 pub fn set_onnx_runtime_options(&mut self, options: OnnxRuntimeOptions) {
1197 self.onnx_runtime_options = options.normalized();
1198 }
1199
1200 pub fn set_ntdb_operating_point(&mut self, point: NtdbOperatingPoint) {
1202 self.ntdb_operating_point = point;
1203 }
1204
1205 pub fn set_ntdb_decision_threshold_point(&mut self, point: NtdbOperatingPoint) {
1207 self.ntdb_decision_threshold_point = point;
1208 }
1209
1210 pub fn set_l3_strategy(&mut self, strategy: L3Strategy) {
1212 self.l3_strategy = strategy;
1213 }
1214
1215 pub fn set_defer_l3(&mut self, defer_l3: bool) {
1217 self.defer_l3 = defer_l3;
1218 }
1219
1220 pub fn set_chunk_overlap_tokens(&mut self, overlap: usize) -> Result<(), String> {
1222 self.set_validated_chunk_overlap_tokens(crate::ChunkOverlapTokens::try_from(overlap)?);
1223 Ok(())
1224 }
1225
1226 pub(crate) fn set_validated_chunk_overlap_tokens(
1227 &mut self,
1228 overlap: crate::ChunkOverlapTokens,
1229 ) {
1230 self.chunk_overlap_tokens = overlap.get();
1231 }
1232
1233 pub fn with_max_level(mut self, max_level: SecurityLevel) -> Self {
1235 self.max_level = max_level;
1236 self
1237 }
1238
1239 pub fn allows_level(&self, level: SecurityLevel) -> bool {
1242 level <= self.max_level && self.gates.allows_level(level)
1243 }
1244
1245 pub fn gates(&self) -> &ScanGateMatrix {
1247 &self.gates
1248 }
1249
1250 pub fn onnx_batch_mode(&self) -> OnnxBatchMode {
1252 self.onnx_batch_mode
1253 }
1254
1255 pub fn backend(&self) -> ExecutionBackend {
1257 self.backend
1258 }
1259
1260 pub fn onnx_runtime_options(&self) -> OnnxRuntimeOptions {
1262 self.onnx_runtime_options
1263 }
1264
1265 pub fn ntdb_operating_point(&self) -> NtdbOperatingPoint {
1267 self.ntdb_operating_point
1268 }
1269
1270 pub fn ntdb_decision_threshold_point(&self) -> NtdbOperatingPoint {
1272 self.ntdb_decision_threshold_point
1273 }
1274
1275 pub fn l3_strategy(&self) -> L3Strategy {
1277 self.l3_strategy
1278 }
1279
1280 pub fn defer_l3(&self) -> bool {
1282 self.defer_l3
1283 }
1284
1285 pub fn chunk_overlap_tokens(&self) -> usize {
1287 self.chunk_overlap_tokens
1288 }
1289
1290 pub fn l3_policy(&self) -> &L3SchedulerPolicy {
1292 &self.gates.l3_policy
1293 }
1294
1295 pub fn max_level(&self) -> SecurityLevel {
1297 self.max_level
1298 }
1299}
1300
1301impl Default for ScanExecution {
1302 fn default() -> Self {
1303 Self::new(SecurityLevel::L3)
1304 }
1305}
1306
1307pub use patronus_ark_core::{
1308 DecisionCandidate, DecisionEnvelope, DecisionProvenance, DecisionRecommendation,
1309 DecisionResult, DecisionTerminality, EvaluationResult, LabelScore, LayerResult,
1310 SecurityCategory,
1311};
1312
1313impl From<patronus_ark_core::NativeResult> for SecurityScanResult {
1314 fn from(value: patronus_ark_core::NativeResult) -> Self {
1315 Self {
1316 category: value.category,
1317 class_name: value.class_name,
1318 confidence: value.confidence,
1319 level: value.level,
1320 model: value.model,
1321 duration_ms: value.duration_ms,
1322 layers: value.layers,
1323 evidence_spans: value.evidence_spans,
1324 label_scores: value.label_scores,
1325 decision: value.decision,
1326 internal_l2_chunk_outputs: Vec::new(),
1327 }
1328 }
1329}
1330
1331impl From<SecurityScanResult> for patronus_ark_core::NativeResult {
1332 fn from(value: SecurityScanResult) -> Self {
1333 Self {
1334 category: value.category,
1335 class_name: value.class_name,
1336 confidence: value.confidence,
1337 level: value.level,
1338 model: value.model,
1339 duration_ms: value.duration_ms,
1340 layers: value.layers,
1341 evidence_spans: value.evidence_spans,
1342 label_scores: value.label_scores,
1343 decision: value.decision,
1344 }
1345 }
1346}
1347
1348pub use patronus_ark_core::{ExecutionBackend, OnnxRuntimeOptions};
1349
1350#[cfg(test)]
1351mod gate_schema_tests {
1352 use super::*;
1353
1354 fn gates(value: serde_json::Value) -> Result<ScanGateMatrix, String> {
1355 serde_json::from_value(value).map_err(|error| error.to_string())
1356 }
1357
1358 #[test]
1359 fn one_gate_schema_reads_every_key() {
1360 let gates = gates(serde_json::json!({
1361 "rules": {"pii_email": false, "cat.core.remote_to_exec": false},
1362 "models": {"native:pii": false},
1363 "pii_mode": "recall",
1364 "dlp_mode": "balanced",
1365 "explain": true,
1366 "l1": true,
1367 "l2": false,
1368 "l3": false,
1369 "conditional": [{
1370 "level": "l3",
1371 "pipeline": "injection",
1372 "when": {"metadata": {"path": "tenant", "equals": "a"}},
1373 "l3_policy": {"clustering": "representative"}
1374 }],
1375 "l3_policy": {
1376 "enabled": false,
1377 "priority": ["tool_class"],
1378 "ttl_ms": {"tool_class": 1234},
1379 "estimated_cost_ms": {"tool_class": 30},
1380 "fairness_quantum_ms": 10,
1381 "max_wait_ms": 100,
1382 "degraded_factor": 0.5,
1383 "early_exit": "disabled",
1384 "progress": "provisional",
1385 "clustering": "verify_representative",
1386 "representatives_per_cluster": 2,
1387 "verify_representatives_per_cluster": 2,
1388 "min_cluster_similarity": 0.8,
1389 "max_cluster_size": 4,
1390 "pipelines": {"injection": {
1391 "clustering": "representative",
1392 "aggregation": {"type": "any_positive_or_highest", "positive_class": "attack", "threshold": 0.93},
1393 "early_exit": "request_wide_positive"
1394 }}
1395 }
1396 }))
1397 .unwrap();
1398 assert!(!gates.native.allows_rule("cat.core.remote_to_exec"));
1399 assert!(!gates.native.allows_model("native:pii"));
1400 assert_eq!(gates.native.pii_mode, crate::ScoreMode::Recall);
1401 assert!(gates.native.explain);
1402 assert_eq!(
1403 (gates.l1, gates.l2, gates.l3),
1404 (Some(true), Some(false), Some(false))
1405 );
1406 assert_eq!(gates.conditional.len(), 1);
1407 let policy = &gates.l3_policy;
1408 assert!(!policy.enabled);
1409 assert_eq!(policy.ttl_ms["tool_class"], 1234);
1410 assert_eq!(policy.ttl_ms["injection"], 15_000);
1412 assert_eq!(
1413 policy.clustering,
1414 L3ClusteringStrategy::VerifyRepresentative
1415 );
1416 assert_eq!(policy.max_cluster_size, 4);
1417 assert_eq!(
1418 policy.pipelines["injection"].clustering,
1419 Some(L3ClusteringStrategy::Representative)
1420 );
1421 let default = self::gates(serde_json::json!({})).unwrap();
1422 assert_eq!(
1423 default.l3_policy.priority,
1424 L3SchedulerPolicy::default().priority
1425 );
1426 assert!(default.native.allows_rule("pii_email"));
1427 }
1428
1429 #[test]
1430 fn gate_schema_refuses_old_keys_and_bad_values() {
1431 for invalid in [
1432 serde_json::json!({"levels": {"l1": true}}),
1433 serde_json::json!({"model_areas": {"native:pii": false}}),
1434 serde_json::json!({"policy": {"enabled": true}}),
1435 serde_json::json!({"l3": {"enabled": true}}),
1436 serde_json::json!({"l3_policy": {"execution": "rank_only"}}),
1437 serde_json::json!({"l3_policy": {"min_similarity": 0.9}}),
1438 serde_json::json!({"l3_policy": {"pipelines": {"injection": {"execution": "representative"}}}}),
1439 serde_json::json!({"rules": {"pii_email": "no"}}),
1440 serde_json::json!({"l1": "yes"}),
1441 serde_json::json!({"pii_mode": "fast"}),
1442 serde_json::json!({"l3_policy": {"priority": "injection"}}),
1443 serde_json::json!({"l3_policy": {"ttl_ms": {"injection": "soon"}}}),
1444 serde_json::json!({"l3_policy": {"estimated_cost_ms": {"dynamic-pii": 0}}}),
1445 serde_json::json!({"l3_policy": {"fairness_quantum_ms": 0}}),
1446 serde_json::json!({"l3_policy": {"max_wait_ms": -1}}),
1447 serde_json::json!({"l3_policy": {"degraded_factor": 2.0}}),
1448 serde_json::json!({"l3_policy": {"min_cluster_similarity": 1.5}}),
1449 serde_json::json!({"l3_policy": {"early_exit": "sometimes"}}),
1450 serde_json::json!({"l3_policy": {"progress": "verbose"}}),
1451 serde_json::json!({"l3_policy": {"clustering": "aggressive"}}),
1452 serde_json::json!({"l3_policy": {"representatives_per_cluster": 0}}),
1453 serde_json::json!({"l3_policy": {"max_cluster_size": 0}}),
1454 serde_json::json!({"l3_policy": {"pipelines": {"": {}}}}),
1455 serde_json::json!({"l3_policy": {"pipelines": {"injection": {"max_cluster_size": 0}}}}),
1456 serde_json::json!({"l3_policy": {"pipelines": {"injection": {"min_cluster_similarity": 1.5}}}}),
1457 serde_json::json!({"l3_policy": {"pipelines": {"injection": {"aggregation": {"type": "any_positive_or_highest", "positive_class": " ", "threshold": 0.5}}}}}),
1458 serde_json::json!({"conditional": [{"level": "l1", "when": {"metadata": {"path": "a", "exists": true}}}]}),
1459 serde_json::json!({"conditional": [{"level": "l3", "pipeline": "injection", "when": {"metadata": {"path": "a", "exists": true}}, "l3_policy": {"max_cluster_size": 0}}]}),
1460 ] {
1461 assert!(gates(invalid.clone()).is_err(), "{invalid} must be refused");
1462 }
1463 }
1464}
1465
1466#[cfg(test)]
1467mod tests {
1468 use super::*;
1469
1470 #[test]
1471 fn l3_pipeline_policy_overrides_request_defaults_by_category() {
1472 let mut policy = L3SchedulerPolicy {
1473 clustering: L3ClusteringStrategy::RankOnly,
1474 ..L3SchedulerPolicy::default()
1475 };
1476 policy.pipelines.insert(
1477 "injection".to_string(),
1478 L3PipelinePolicy {
1479 clustering: Some(L3ClusteringStrategy::VerifyRepresentative),
1480 representatives_per_cluster: Some(2),
1481 verify_representatives_per_cluster: Some(1),
1482 min_cluster_similarity: Some(0.96),
1483 max_cluster_size: Some(4),
1484 aggregation: Some(L3AggregationStrategy::AnyPositiveOrHighest {
1485 positive_class: "attack".to_string(),
1486 threshold: 0.9,
1487 }),
1488 early_exit: Some(L3PipelineEarlyExit::RequestWidePositive),
1489 },
1490 );
1491
1492 let resolved = policy.pipeline_policy("injection", "wolf-defender-small");
1493
1494 assert_eq!(
1495 resolved.clustering,
1496 L3ClusteringStrategy::VerifyRepresentative
1497 );
1498 assert_eq!(resolved.representatives_per_cluster, 2);
1499 assert_eq!(resolved.min_cluster_similarity, 0.96);
1500 assert_eq!(resolved.max_cluster_size, 4);
1501 assert_eq!(
1502 resolved.early_exit,
1503 L3PipelineEarlyExit::RequestWidePositive
1504 );
1505 }
1506
1507 #[test]
1508 fn l3_pipeline_policy_uses_model_override_when_category_is_absent() {
1509 let mut policy = L3SchedulerPolicy::default();
1510 policy.pipelines.insert(
1511 "unified-v3-tool-class".to_string(),
1512 L3PipelinePolicy {
1513 clustering: Some(L3ClusteringStrategy::Representative),
1514 ..L3PipelinePolicy::default()
1515 },
1516 );
1517
1518 assert_eq!(
1519 policy
1520 .pipeline_policy("tool_class", "unified-v3-tool-class")
1521 .clustering,
1522 L3ClusteringStrategy::Representative
1523 );
1524 }
1525
1526 #[test]
1527 fn l3_default_early_exit_scope_matches_pipeline_semantics() {
1528 let policy = L3SchedulerPolicy::default();
1529
1530 assert_eq!(
1531 policy
1532 .pipeline_policy("threat", "unified-v3-threat")
1533 .early_exit,
1534 L3PipelineEarlyExit::RequestWidePositive
1535 );
1536 assert_eq!(
1537 policy
1538 .pipeline_policy("tool_class", "unified-v3-tool-class")
1539 .early_exit,
1540 L3PipelineEarlyExit::HeadStable
1541 );
1542 }
1543
1544 #[test]
1545 fn security_level_serde_accepts_from_str_names_and_writes_canonical_names() {
1546 for (name, level) in [
1547 ("L1", SecurityLevel::L1),
1548 ("l2", SecurityLevel::L2),
1549 ("3", SecurityLevel::L3),
1550 ] {
1551 let parsed: SecurityLevel = serde_json::from_value(serde_json::json!(name)).unwrap();
1552 assert_eq!(parsed, level);
1553 assert_eq!(serde_json::to_value(level).unwrap(), level.as_str());
1554 }
1555 assert!(serde_json::from_value::<SecurityLevel>(serde_json::json!("L4")).is_err());
1556 }
1557}