-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathpolicy.rs
More file actions
1171 lines (1024 loc) · 43.6 KB
/
policy.rs
File metadata and controls
1171 lines (1024 loc) · 43.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Policy evaluation engine for routing decisions
use std::collections::HashMap;
use super::config::{RoutingPolicyConfig, RouteAction, ModelPreference};
use super::decision::{RouteDecision, RoutingContext, LLMProvider};
use super::error::{RoutingError, TaskType};
use super::classifier::{TaskClassifier, ClassificationResult};
use crate::models::ModelCatalog;
use crate::config::{ResourceConstraints, ModelCapability};
/// Policy evaluation engine for making routing decisions
#[derive(Debug)]
pub struct PolicyEvaluator {
/// Policy configuration
config: RoutingPolicyConfig,
/// Task classifier for automatic task type detection
classifier: TaskClassifier,
/// Model catalog for finding suitable models
model_catalog: ModelCatalog,
/// Evaluation cache for performance
evaluation_cache: std::sync::RwLock<HashMap<String, CachedEvaluation>>,
}
/// Cached evaluation result
#[derive(Debug, Clone)]
struct CachedEvaluation {
decision: RouteDecision,
timestamp: std::time::Instant,
#[allow(dead_code)]
context_hash: u64,
}
/// Policy evaluation result
#[derive(Debug, Clone)]
pub struct PolicyEvaluationResult {
/// The routing decision
pub decision: RouteDecision,
/// Rule that matched (if any)
pub matched_rule: Option<String>,
/// Task classification result
pub task_classification: ClassificationResult,
/// Evaluation metadata
pub metadata: HashMap<String, String>,
}
/// Policy context for evaluation
#[derive(Debug, Clone)]
pub struct PolicyContext {
/// Routing context
pub routing_context: RoutingContext,
/// Available resource constraints
pub available_resources: Option<ResourceConstraints>,
/// Current system load
pub system_load: Option<f64>,
/// Additional evaluation hints
pub hints: HashMap<String, String>,
}
impl PolicyEvaluator {
/// Create a new policy evaluator
pub fn new(
config: RoutingPolicyConfig,
classifier: TaskClassifier,
model_catalog: ModelCatalog,
) -> Result<Self, RoutingError> {
// Validate the policy configuration
config.validate()?;
Ok(Self {
config,
classifier,
model_catalog,
evaluation_cache: std::sync::RwLock::new(HashMap::new()),
})
}
/// Evaluate routing policies and make a decision
pub async fn evaluate_policies(
&self,
context: &RoutingContext,
) -> Result<PolicyEvaluationResult, RoutingError> {
let policy_context = PolicyContext {
routing_context: context.clone(),
available_resources: None,
system_load: None,
hints: HashMap::new(),
};
self.evaluate_policies_with_context(&policy_context).await
}
/// Evaluate routing policies with additional context
pub async fn evaluate_policies_with_context(
&self,
context: &PolicyContext,
) -> Result<PolicyEvaluationResult, RoutingError> {
// Check if SLM routing is globally enabled
if !self.config.global_settings.slm_routing_enabled {
return Ok(PolicyEvaluationResult {
decision: self.apply_default_action()?,
matched_rule: None,
task_classification: ClassificationResult {
task_type: context.routing_context.task_type.clone(),
confidence: 1.0,
matched_patterns: vec!["slm_routing_disabled".to_string()],
keyword_matches: Vec::new(),
},
metadata: {
let mut meta = HashMap::new();
meta.insert("reason".to_string(), "SLM routing globally disabled".to_string());
meta
},
});
}
// Check cache first
let cache_key = self.generate_cache_key(context);
if let Some(cached) = self.check_cache(&cache_key) {
return Ok(PolicyEvaluationResult {
decision: cached.decision,
matched_rule: Some("cached".to_string()),
task_classification: ClassificationResult {
task_type: context.routing_context.task_type.clone(),
confidence: 1.0,
matched_patterns: vec!["cached_result".to_string()],
keyword_matches: Vec::new(),
},
metadata: {
let mut meta = HashMap::new();
meta.insert("source".to_string(), "cache".to_string());
meta
},
});
}
// Classify the task if not already classified
let task_classification = if matches!(context.routing_context.task_type, TaskType::Custom(ref name) if name == "unknown") {
self.classifier.classify_task(&context.routing_context.prompt, &context.routing_context)?
} else {
ClassificationResult {
task_type: context.routing_context.task_type.clone(),
confidence: 1.0,
matched_patterns: vec!["pre_classified".to_string()],
keyword_matches: Vec::new(),
}
};
let mut evaluation_context = context.clone();
evaluation_context.routing_context.task_type = task_classification.task_type.clone();
// Evaluate rules in priority order
for rule in &self.config.rules {
if rule.matches(&evaluation_context.routing_context) {
let decision = self.apply_rule_action(&rule.action, &evaluation_context).await?;
// Cache the result
self.cache_evaluation(&cache_key, &decision);
return Ok(PolicyEvaluationResult {
decision,
matched_rule: Some(rule.name.clone()),
task_classification,
metadata: {
let mut meta = HashMap::new();
meta.insert("rule_priority".to_string(), rule.priority.to_string());
meta.insert("rule_name".to_string(), rule.name.clone());
meta
},
});
}
}
// No rules matched, apply default action
let decision = self.apply_default_action()?;
self.cache_evaluation(&cache_key, &decision);
Ok(PolicyEvaluationResult {
decision,
matched_rule: None,
task_classification,
metadata: {
let mut meta = HashMap::new();
meta.insert("source".to_string(), "default_action".to_string());
meta
},
})
}
/// Apply a rule action to generate a routing decision
async fn apply_rule_action(
&self,
action: &RouteAction,
context: &PolicyContext,
) -> Result<RouteDecision, RoutingError> {
match action {
RouteAction::UseSLM {
model_preference,
monitoring_level,
fallback_on_low_confidence,
confidence_threshold: _,
} => {
let model = self.find_suitable_slm(
model_preference,
&context.routing_context.task_type,
context.routing_context.resource_limits.as_ref(),
Some(&context.routing_context.agent_id.to_string()),
)?;
Ok(RouteDecision::UseSLM {
model_id: model.id.clone(),
monitoring: monitoring_level.clone(),
fallback_on_failure: *fallback_on_low_confidence,
})
}
RouteAction::UseLLM { provider, model: _ } => {
Ok(RouteDecision::UseLLM {
provider: provider.clone(),
reason: "Policy rule matched".to_string(),
})
}
RouteAction::Deny { reason } => {
Ok(RouteDecision::Deny {
reason: reason.clone(),
policy_violated: "Explicit deny rule".to_string(),
})
}
}
}
/// Apply the default action when no rules match
fn apply_default_action(&self) -> Result<RouteDecision, RoutingError> {
match &self.config.default_action {
RouteAction::UseSLM { .. } => {
// For default SLM action, use a simple fallback
Ok(RouteDecision::UseLLM {
provider: LLMProvider::OpenAI { model: None },
reason: "Default action - no SLM available".to_string(),
})
}
RouteAction::UseLLM { provider, .. } => {
Ok(RouteDecision::UseLLM {
provider: provider.clone(),
reason: "Default action".to_string(),
})
}
RouteAction::Deny { reason } => {
Ok(RouteDecision::Deny {
reason: reason.clone(),
policy_violated: "Default deny policy".to_string(),
})
}
}
}
/// Find a suitable SLM based on preferences and constraints
fn find_suitable_slm(
&self,
preference: &ModelPreference,
task_type: &TaskType,
resource_constraints: Option<&ResourceConstraints>,
agent_id: Option<&str>,
) -> Result<&crate::config::Model, RoutingError> {
let required_capabilities = task_type.to_capabilities();
let max_memory = resource_constraints.map(|rc| rc.max_memory_mb);
let model = match preference {
ModelPreference::Specialist => {
self.find_specialist_model(task_type, &required_capabilities, max_memory, agent_id)?
}
ModelPreference::Generalist => {
self.find_generalist_model(&required_capabilities, max_memory, agent_id)?
}
ModelPreference::Specific { model_id } => {
self.model_catalog.get_model(model_id)
.ok_or_else(|| RoutingError::NoSuitableModel {
task_type: task_type.clone()
})?
}
ModelPreference::BestAvailable => {
self.model_catalog.find_best_model_for_requirements(
&required_capabilities,
max_memory,
agent_id,
).ok_or_else(|| RoutingError::NoSuitableModel {
task_type: task_type.clone()
})?
}
};
// Validate the model meets our requirements
self.validate_model_for_task(model, task_type, resource_constraints)?;
Ok(model)
}
/// Find a specialist model for the given task type
fn find_specialist_model(
&self,
task_type: &TaskType,
required_capabilities: &[ModelCapability],
max_memory: Option<u64>,
agent_id: Option<&str>,
) -> Result<&crate::config::Model, RoutingError> {
let candidate_models = if let Some(agent_id) = agent_id {
self.model_catalog.get_models_for_agent(agent_id)
} else {
self.model_catalog.list_models()
};
// Filter for models with required capabilities
let suitable_models: Vec<_> = candidate_models
.into_iter()
.filter(|model| {
required_capabilities.iter().all(|cap| model.capabilities.contains(cap))
})
.filter(|model| {
if let Some(max_mem) = max_memory {
model.resource_requirements.min_memory_mb <= max_mem
} else {
true
}
})
.collect();
// Prefer models that are specifically good for this task type
let specialist = suitable_models.iter().find(|model| {
match task_type {
TaskType::CodeGeneration | TaskType::BoilerplateCode => {
model.capabilities.contains(&ModelCapability::CodeGeneration)
}
TaskType::Reasoning | TaskType::Analysis => {
model.capabilities.contains(&ModelCapability::Reasoning)
}
_ => false,
}
});
specialist.or_else(|| suitable_models.first())
.copied()
.ok_or_else(|| RoutingError::NoSuitableModel {
task_type: task_type.clone()
})
}
/// Find a generalist model
fn find_generalist_model(
&self,
required_capabilities: &[ModelCapability],
max_memory: Option<u64>,
agent_id: Option<&str>,
) -> Result<&crate::config::Model, RoutingError> {
self.model_catalog.find_best_model_for_requirements(
required_capabilities,
max_memory,
agent_id,
).ok_or_else(|| RoutingError::NoSuitableModel {
task_type: TaskType::Custom("generalist".to_string())
})
}
/// Validate that a model is suitable for the given task and constraints
fn validate_model_for_task(
&self,
model: &crate::config::Model,
task_type: &TaskType,
resource_constraints: Option<&ResourceConstraints>,
) -> Result<(), RoutingError> {
// Check capabilities
let required_capabilities = task_type.to_capabilities();
for capability in &required_capabilities {
if !model.capabilities.contains(capability) {
return Err(RoutingError::NoSuitableModel {
task_type: task_type.clone()
});
}
}
// Check resource constraints
if let Some(constraints) = resource_constraints {
if model.resource_requirements.min_memory_mb > constraints.max_memory_mb {
return Err(RoutingError::ResourceConstraintViolation {
constraint: format!(
"Model requires {}MB memory but only {}MB available",
model.resource_requirements.min_memory_mb,
constraints.max_memory_mb
),
});
}
}
Ok(())
}
/// Generate cache key for evaluation context
fn generate_cache_key(&self, context: &PolicyContext) -> String {
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
let mut hasher = DefaultHasher::new();
context.routing_context.agent_id.hash(&mut hasher);
context.routing_context.task_type.hash(&mut hasher);
context.routing_context.prompt.hash(&mut hasher);
if let Some(ref constraints) = context.routing_context.resource_limits {
constraints.max_memory_mb.hash(&mut hasher);
constraints.max_cpu_cores.to_bits().hash(&mut hasher);
}
format!("policy_eval_{:x}", hasher.finish())
}
/// Check evaluation cache
fn check_cache(&self, key: &str) -> Option<CachedEvaluation> {
let cache = self.evaluation_cache.read().ok()?;
let cached = cache.get(key)?;
// Check if cache entry is still fresh (5 minutes)
if cached.timestamp.elapsed() < std::time::Duration::from_secs(300) {
Some(cached.clone())
} else {
None
}
}
/// Cache evaluation result
fn cache_evaluation(&self, key: &str, decision: &RouteDecision) {
if let Ok(mut cache) = self.evaluation_cache.write() {
// Limit cache size
if cache.len() > 1000 {
cache.clear();
}
cache.insert(key.to_string(), CachedEvaluation {
decision: decision.clone(),
timestamp: std::time::Instant::now(),
context_hash: 0, // Could be used for more sophisticated caching
});
}
}
/// Update policy configuration
pub fn update_config(&mut self, config: RoutingPolicyConfig) -> Result<(), RoutingError> {
config.validate()?;
self.config = config;
// Clear cache when config changes
if let Ok(mut cache) = self.evaluation_cache.write() {
cache.clear();
}
Ok(())
}
/// Get policy evaluation statistics
pub fn get_statistics(&self) -> PolicyStatistics {
let cache_size = self.evaluation_cache.read()
.map(|cache| cache.len())
.unwrap_or(0);
PolicyStatistics {
total_rules: self.config.rules.len(),
cache_size,
slm_routing_enabled: self.config.global_settings.slm_routing_enabled,
global_confidence_threshold: self.config.global_settings.global_confidence_threshold,
max_slm_retries: self.config.global_settings.max_slm_retries,
}
}
}
/// Statistics about policy evaluation
#[derive(Debug, Clone)]
pub struct PolicyStatistics {
pub total_rules: usize,
pub cache_size: usize,
pub slm_routing_enabled: bool,
pub global_confidence_threshold: f64,
pub max_slm_retries: u32,
}
#[cfg(test)]
mod tests {
use super::*;
use crate::types::AgentId;
use crate::config::{Slm, Model, ModelProvider, ModelResourceRequirements, ModelAllowListConfig, SandboxProfile, ResourceConstraints};
use crate::routing::config::{RoutingRule, RoutingConditions};
use crate::routing::decision::MonitoringLevel;
use std::path::PathBuf;
use std::collections::HashMap;
fn create_test_model_catalog() -> ModelCatalog {
let mut global_models = Vec::new();
global_models.push(Model {
id: "test-slm-1".to_string(),
name: "Test SLM 1".to_string(),
provider: ModelProvider::LocalFile { file_path: PathBuf::from("/tmp/test.gguf") },
capabilities: vec![ModelCapability::TextGeneration, ModelCapability::CodeGeneration],
resource_requirements: ModelResourceRequirements {
min_memory_mb: 1024,
preferred_cpu_cores: 2.0,
gpu_requirements: None,
},
});
global_models.push(Model {
id: "test-slm-2".to_string(),
name: "Test SLM 2".to_string(),
provider: ModelProvider::LocalFile { file_path: PathBuf::from("/tmp/test2.gguf") },
capabilities: vec![ModelCapability::TextGeneration, ModelCapability::Reasoning],
resource_requirements: ModelResourceRequirements {
min_memory_mb: 2048,
preferred_cpu_cores: 4.0,
gpu_requirements: None,
},
});
global_models.push(Model {
id: "specialist-code".to_string(),
name: "Code Specialist".to_string(),
provider: ModelProvider::LocalFile { file_path: PathBuf::from("/tmp/code.gguf") },
capabilities: vec![ModelCapability::CodeGeneration],
resource_requirements: ModelResourceRequirements {
min_memory_mb: 1536,
preferred_cpu_cores: 3.0,
gpu_requirements: None,
},
});
// Add agent model mappings for testing
let mut agent_model_maps = HashMap::new();
agent_model_maps.insert("restricted-agent".to_string(), vec!["test-slm-1".to_string()]);
agent_model_maps.insert("code-agent".to_string(), vec!["specialist-code".to_string(), "test-slm-1".to_string()]);
let mut sandbox_profiles = HashMap::new();
sandbox_profiles.insert("default".to_string(), SandboxProfile::secure_default());
let slm_config = Slm {
enabled: true,
model_allow_lists: ModelAllowListConfig {
global_models,
agent_model_maps,
allow_runtime_overrides: false,
},
sandbox_profiles,
default_sandbox_profile: "default".to_string(),
};
ModelCatalog::new(slm_config).unwrap()
}
fn create_test_classifier() -> TaskClassifier {
let config = super::super::config::TaskClassificationConfig::default();
TaskClassifier::new(config).unwrap()
}
fn create_routing_context_with_resource_limits(
agent_id: AgentId,
task_type: TaskType,
prompt: String,
max_memory_mb: u64,
) -> RoutingContext {
let mut context = RoutingContext::new(agent_id, task_type, prompt);
context.resource_limits = Some(ResourceConstraints {
max_memory_mb,
max_cpu_cores: 2.0,
max_disk_mb: 1000,
gpu_access: crate::config::GpuAccess::None,
max_io_bandwidth_mbps: Some(100),
});
context
}
#[tokio::test]
async fn test_policy_evaluation_with_slm_action() {
let model_catalog = create_test_model_catalog();
let classifier = create_test_classifier();
let mut config = RoutingPolicyConfig::default();
config.rules.push(RoutingRule {
name: "test_rule".to_string(),
priority: 100,
conditions: super::super::config::RoutingConditions {
task_types: Some(vec![TaskType::CodeGeneration]),
agent_ids: None,
resource_constraints: None,
security_level: None,
custom_conditions: None,
},
action: RouteAction::UseSLM {
model_preference: ModelPreference::BestAvailable,
monitoring_level: MonitoringLevel::Basic,
fallback_on_low_confidence: true,
confidence_threshold: Some(0.8),
},
override_allowed: true,
});
let evaluator = PolicyEvaluator::new(config, classifier, model_catalog).unwrap();
let context = RoutingContext::new(
AgentId::new(),
TaskType::CodeGeneration,
"Write a function to sort an array".to_string(),
);
let result = evaluator.evaluate_policies(&context).await.unwrap();
match result.decision {
RouteDecision::UseSLM { model_id, .. } => {
assert_eq!(model_id, "test-slm-1"); // Should pick the first available model
}
_ => panic!("Expected UseSLM decision"),
}
assert_eq!(result.matched_rule, Some("test_rule".to_string()));
}
#[tokio::test]
async fn test_policy_evaluation_with_specialist_preference() {
let model_catalog = create_test_model_catalog();
let classifier = create_test_classifier();
let mut config = RoutingPolicyConfig::default();
config.rules.push(RoutingRule {
name: "specialist_rule".to_string(),
priority: 100,
conditions: super::super::config::RoutingConditions {
task_types: Some(vec![TaskType::CodeGeneration]),
agent_ids: None,
resource_constraints: None,
security_level: None,
custom_conditions: None,
},
action: RouteAction::UseSLM {
model_preference: ModelPreference::Specialist,
monitoring_level: MonitoringLevel::Enhanced { confidence_threshold: 0.9 },
fallback_on_low_confidence: true,
confidence_threshold: Some(0.9),
},
override_allowed: true,
});
let evaluator = PolicyEvaluator::new(config, classifier, model_catalog).unwrap();
let context = RoutingContext::new(
AgentId::new(),
TaskType::CodeGeneration,
"Generate complex algorithm".to_string(),
);
let result = evaluator.evaluate_policies(&context).await.unwrap();
match result.decision {
RouteDecision::UseSLM { model_id, .. } => {
assert_eq!(model_id, "specialist-code"); // Should pick the specialist model
}
_ => panic!("Expected UseSLM decision with specialist model"),
}
}
#[tokio::test]
async fn test_policy_evaluation_with_specific_model() {
let model_catalog = create_test_model_catalog();
let classifier = create_test_classifier();
let mut config = RoutingPolicyConfig::default();
config.rules.push(RoutingRule {
name: "specific_model_rule".to_string(),
priority: 100,
conditions: super::super::config::RoutingConditions {
task_types: Some(vec![TaskType::CodeGeneration]),
agent_ids: None,
resource_constraints: None,
security_level: None,
custom_conditions: None,
},
action: RouteAction::UseSLM {
model_preference: ModelPreference::Specific { model_id: "test-slm-2".to_string() },
monitoring_level: MonitoringLevel::None,
fallback_on_low_confidence: false,
confidence_threshold: None,
},
override_allowed: false,
});
let evaluator = PolicyEvaluator::new(config, classifier, model_catalog).unwrap();
let context = RoutingContext::new(
AgentId::new(),
TaskType::CodeGeneration,
"Generate some text".to_string(),
);
let result = evaluator.evaluate_policies(&context).await.unwrap();
match result.decision {
RouteDecision::UseSLM { model_id, .. } => {
assert_eq!(model_id, "test-slm-2");
}
_ => panic!("Expected UseSLM decision with specific model"),
}
}
#[tokio::test]
async fn test_policy_evaluation_with_agent_restrictions() {
let model_catalog = create_test_model_catalog();
let classifier = create_test_classifier();
let mut config = RoutingPolicyConfig::default();
config.rules.push(RoutingRule {
name: "agent_restricted_rule".to_string(),
priority: 100,
conditions: super::super::config::RoutingConditions {
task_types: Some(vec![TaskType::CodeGeneration]),
agent_ids: Some(vec!["code-agent".to_string()]),
resource_constraints: None,
security_level: None,
custom_conditions: None,
},
action: RouteAction::UseSLM {
model_preference: ModelPreference::Specialist,
monitoring_level: MonitoringLevel::Basic,
fallback_on_low_confidence: true,
confidence_threshold: Some(0.8),
},
override_allowed: true,
});
let evaluator = PolicyEvaluator::new(config, classifier, model_catalog).unwrap();
// Test with matching agent
let code_agent_id = AgentId::new();
let context = RoutingContext::new(
code_agent_id,
TaskType::CodeGeneration,
"Write optimized code".to_string(),
);
let result = evaluator.evaluate_policies(&context).await.unwrap();
match result.decision {
RouteDecision::UseSLM { model_id, .. } => {
assert_eq!(model_id, "specialist-code"); // Should get specialist from agent's allowed models
}
_ => panic!("Expected UseSLM decision for code agent"),
}
// Test with non-matching agent - should fall back to default action
let other_agent_id = AgentId::new();
let other_context = RoutingContext::new(
other_agent_id,
TaskType::CodeGeneration,
"Write code".to_string(),
);
let other_result = evaluator.evaluate_policies(&other_context).await.unwrap();
// Should fall back to default action since agent doesn't match
match other_result.decision {
RouteDecision::UseLLM { .. } => {
// Expected default fallback
}
_ => panic!("Expected default LLM fallback for non-matching agent"),
}
}
#[tokio::test]
async fn test_policy_evaluation_with_resource_constraints() {
let model_catalog = create_test_model_catalog();
let classifier = create_test_classifier();
let mut config = RoutingPolicyConfig::default();
config.rules.push(RoutingRule {
name: "resource_constrained_rule".to_string(),
priority: 100,
conditions: super::super::config::RoutingConditions {
task_types: Some(vec![TaskType::CodeGeneration]),
agent_ids: None,
resource_constraints: Some(ResourceConstraints {
max_memory_mb: 1500, // Only test-slm-1 fits
max_cpu_cores: 3.0,
max_disk_mb: 1000,
gpu_access: crate::config::GpuAccess::None,
max_io_bandwidth_mbps: Some(100),
}),
security_level: None,
custom_conditions: None,
},
action: RouteAction::UseSLM {
model_preference: ModelPreference::BestAvailable,
monitoring_level: MonitoringLevel::Basic,
fallback_on_low_confidence: false,
confidence_threshold: None,
},
override_allowed: true,
});
let evaluator = PolicyEvaluator::new(config, classifier, model_catalog).unwrap();
let context = create_routing_context_with_resource_limits(
AgentId::new(),
TaskType::CodeGeneration,
"Generate text with constraints".to_string(),
1500,
);
let result = evaluator.evaluate_policies(&context).await.unwrap();
match result.decision {
RouteDecision::UseSLM { model_id, .. } => {
assert_eq!(model_id, "test-slm-1"); // Only model that fits the constraints
}
_ => panic!("Expected UseSLM decision with resource constraints"),
}
}
#[tokio::test]
async fn test_policy_evaluation_with_llm_action() {
let model_catalog = create_test_model_catalog();
let classifier = create_test_classifier();
let mut config = RoutingPolicyConfig::default();
config.rules.push(RoutingRule {
name: "llm_rule".to_string(),
priority: 100,
conditions: super::super::config::RoutingConditions {
task_types: Some(vec![TaskType::Reasoning]),
agent_ids: None,
resource_constraints: None,
security_level: None,
custom_conditions: None,
},
action: RouteAction::UseLLM {
provider: LLMProvider::OpenAI { model: Some("gpt-4".to_string()) },
model: Some("gpt-4".to_string()),
},
override_allowed: false,
});
let evaluator = PolicyEvaluator::new(config, classifier, model_catalog).unwrap();
let context = RoutingContext::new(
AgentId::new(),
TaskType::Reasoning,
"Solve complex reasoning problem".to_string(),
);
let result = evaluator.evaluate_policies(&context).await.unwrap();
match result.decision {
RouteDecision::UseLLM { provider, reason } => {
assert!(matches!(provider, LLMProvider::OpenAI { .. }));
assert!(reason.contains("Policy rule matched"));
}
_ => panic!("Expected UseLLM decision"),
}
}
#[tokio::test]
async fn test_policy_evaluation_with_deny_action() {
let model_catalog = create_test_model_catalog();
let classifier = create_test_classifier();
let mut config = RoutingPolicyConfig::default();
config.rules.push(RoutingRule {
name: "deny_rule".to_string(),
priority: 100,
conditions: super::super::config::RoutingConditions {
task_types: Some(vec![TaskType::Custom("forbidden".to_string())]),
agent_ids: None,
resource_constraints: None,
security_level: None,
custom_conditions: None,
},
action: RouteAction::Deny {
reason: "Forbidden task type".to_string(),
},
override_allowed: false,
});
let evaluator = PolicyEvaluator::new(config, classifier, model_catalog).unwrap();
let context = RoutingContext::new(
AgentId::new(),
TaskType::Custom("forbidden".to_string()),
"Forbidden operation".to_string(),
);
let result = evaluator.evaluate_policies(&context).await.unwrap();
match result.decision {
RouteDecision::Deny { reason, policy_violated } => {
assert_eq!(reason, "Forbidden task type");
assert_eq!(policy_violated, "Explicit deny rule");
}
_ => panic!("Expected Deny decision"),
}
}
#[tokio::test]
async fn test_default_action_fallback() {
let model_catalog = create_test_model_catalog();
let classifier = create_test_classifier();
let config = RoutingPolicyConfig::default(); // No rules, will use default action
let evaluator = PolicyEvaluator::new(config, classifier, model_catalog).unwrap();
let context = RoutingContext::new(
AgentId::new(),
TaskType::Analysis,
"Analyze this data".to_string(),
);
let result = evaluator.evaluate_policies(&context).await.unwrap();
match result.decision {
RouteDecision::UseLLM { .. } => {
// Expected default action
}
_ => panic!("Expected UseLLM decision from default action"),
}
assert!(result.matched_rule.is_none());
}
#[tokio::test]
async fn test_policy_rule_priority_ordering() {
let model_catalog = create_test_model_catalog();
let classifier = create_test_classifier();
let mut config = RoutingPolicyConfig::default();
// Add lower priority rule first
config.rules.push(RoutingRule {
name: "low_priority".to_string(),
priority: 50,
conditions: super::super::config::RoutingConditions {
task_types: Some(vec![TaskType::CodeGeneration]),
agent_ids: None,
resource_constraints: None,
security_level: None,
custom_conditions: None,
},
action: RouteAction::UseLLM {
provider: LLMProvider::OpenAI { model: None },
model: None,
},
override_allowed: true,
});
// Add higher priority rule second
config.rules.push(RoutingRule {
name: "high_priority".to_string(),
priority: 100,
conditions: super::super::config::RoutingConditions {
task_types: Some(vec![TaskType::CodeGeneration]),
agent_ids: None,
resource_constraints: None,
security_level: None,
custom_conditions: None,
},
action: RouteAction::UseSLM {
model_preference: ModelPreference::BestAvailable,
monitoring_level: MonitoringLevel::Basic,
fallback_on_low_confidence: false,
confidence_threshold: None,
},
override_allowed: true,
});
// Sort rules by priority (should be done automatically)
config.rules.sort_by(|a, b| b.priority.cmp(&a.priority));
let evaluator = PolicyEvaluator::new(config, classifier, model_catalog).unwrap();
let context = RoutingContext::new(
AgentId::new(),
TaskType::CodeGeneration,
"Generate text".to_string(),
);
let result = evaluator.evaluate_policies(&context).await.unwrap();
// Should match the higher priority rule
assert_eq!(result.matched_rule, Some("high_priority".to_string()));
assert!(matches!(result.decision, RouteDecision::UseSLM { .. }));
}
#[tokio::test]
async fn test_slm_routing_globally_disabled() {
let model_catalog = create_test_model_catalog();
let classifier = create_test_classifier();
let mut config = RoutingPolicyConfig::default();
config.global_settings.slm_routing_enabled = false; // Disable SLM routing globally
config.rules.push(RoutingRule {
name: "slm_rule".to_string(),
priority: 100,
conditions: super::super::config::RoutingConditions {