xybrid-core 0.1.0

Core runtime for hybrid cloud-edge AI inference: model execution, pipeline orchestration, and routing primitives.
Documentation
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
//! Policy Engine module - Enforces data-handling and routing rules before inference stages run.
//!
//! The Policy Engine ensures that privacy, latency, and cost constraints are respected at runtime
//! by evaluating allow/deny conditions per stage and optionally applying redaction transforms.

use crate::context::DeviceMetrics;
use crate::ir::{Envelope, EnvelopeKind};

/// Result of a policy evaluation.
#[derive(Debug, Clone)]
pub struct PolicyResult {
    pub allowed: bool,
    pub reason: Option<String>,
    pub transforms_applied: Vec<String>,
}

impl PolicyResult {
    /// Create a new PolicyResult.
    pub fn new(allowed: bool, reason: Option<String>) -> Self {
        Self {
            allowed,
            reason,
            transforms_applied: Vec::new(),
        }
    }

    /// Create an allowed result.
    pub fn allow(reason: Option<String>) -> Self {
        Self::new(true, reason)
    }

    /// Create a denied result.
    pub fn deny(reason: String) -> Self {
        Self::new(false, Some(reason))
    }
}

/// Policy bundle containing rules and metadata.
#[derive(Debug, Clone)]
pub struct PolicyBundle {
    pub version: String,
    pub rules: Vec<PolicyRule>,
    pub signature: String,
}

/// Individual policy rule.
#[derive(Debug, Clone)]
pub struct PolicyRule {
    pub id: String,
    pub expression: String, // CEL or mini-DSL
    pub action: String,     // "allow" | "deny" | "redact"
}

/// Policy Engine trait for evaluating policies.
pub trait PolicyEngine {
    /// Load and cache signed policy files.
    fn load_policies(&mut self, bundle_bytes: Vec<u8>) -> Result<(), String>;

    /// Evaluate policy conditions for a stage.
    fn evaluate(&self, stage: &str, envelope: &Envelope, metrics: &DeviceMetrics) -> PolicyResult;

    /// Apply redaction transforms to an envelope.
    fn redact(&self, envelope: &mut Envelope) -> bool;
}

/// Default implementation of PolicyEngine for MVP.
///
/// Currently supports a single expression form: `input.kind == "<value>"`.
/// The legacy `metrics.network_rtt`/`metrics.battery` comparisons were
/// dropped together with the speculative routing scalars; if device-state
/// rules are needed in the future they should target real signals on
/// `metrics.capabilities` / `metrics.resource`.
pub struct DefaultPolicyEngine {
    bundle: Option<PolicyBundle>,
}

impl DefaultPolicyEngine {
    /// Create a new DefaultPolicyEngine instance.
    pub fn new() -> Self {
        Self { bundle: None }
    }

    /// Create a new instance with the default policy bundle.
    ///
    /// The default bundle is currently empty (allow-all). Callers wanting
    /// stricter behaviour should `load_policies` an explicit bundle.
    pub fn with_default_policy() -> Self {
        let mut engine = Self::new();
        let default_bundle = PolicyBundle {
            version: "0.1.0".to_string(),
            rules: vec![],
            signature: "default_mvp".to_string(),
        };
        engine.bundle = Some(default_bundle);
        engine
    }

    /// Evaluate a single expression against the context.
    fn evaluate_expression(
        &self,
        expression: &str,
        envelope: &Envelope,
        _metrics: &DeviceMetrics,
    ) -> bool {
        // MVP: Simple expression evaluation
        // Supports:
        // - input.kind == "value"

        let expr = expression.trim();

        // Check for equality comparisons: input.kind == "value"
        if expr.contains("input.kind ==") {
            let parts: Vec<&str> = expr.split("==").collect();
            if parts.len() == 2 {
                let value = parts[1].trim().trim_matches('"').trim();

                // Direct comparison against metadata label if provided.
                if let Some(label) = envelope.get_metadata("kind_label") {
                    if label == value {
                        return true;
                    }
                }

                // Compare against the textual payload for text envelopes.
                if let EnvelopeKind::Text(text) = &envelope.kind {
                    if text == value {
                        return true;
                    }
                }

                // Compare against the high-level variant name (Audio/Text/Embedding).
                if envelope.kind_str() == value {
                    return true;
                }

                // Backwards compatibility: treat legacy labels as variant aliases.
                match &envelope.kind {
                    EnvelopeKind::Audio(_) => {
                        if value.eq_ignore_ascii_case("audioraw")
                            || value.eq_ignore_ascii_case("audio")
                        {
                            return true;
                        }
                    }
                    EnvelopeKind::Text(_) => {
                        if value.eq_ignore_ascii_case("text") {
                            return true;
                        }
                    }
                    EnvelopeKind::Embedding(_) => {
                        if value.eq_ignore_ascii_case("embedding") {
                            return true;
                        }
                    }
                }
            }
        }

        // If we can't parse it, default to false (no match → no deny).
        false
    }
}

impl Default for DefaultPolicyEngine {
    fn default() -> Self {
        Self::new()
    }
}

impl PolicyEngine for DefaultPolicyEngine {
    fn load_policies(&mut self, bundle_bytes: Vec<u8>) -> Result<(), String> {
        // Try to parse as YAML first
        let yaml_result: Result<serde_yaml::Value, _> = serde_yaml::from_slice(&bundle_bytes);

        if let Ok(yaml_value) = yaml_result {
            self.parse_yaml_policy(yaml_value)?;
            return Ok(());
        }

        // Try to parse as JSON
        let json_result: Result<serde_json::Value, _> = serde_json::from_slice(&bundle_bytes);

        if let Ok(json_value) = json_result {
            self.parse_json_policy(json_value)?;
            return Ok(());
        }

        Err("Failed to parse policy bundle as YAML or JSON".to_string())
    }

    fn evaluate(&self, _stage: &str, envelope: &Envelope, metrics: &DeviceMetrics) -> PolicyResult {
        // If no policy bundle is loaded, default to allow
        let Some(ref bundle) = self.bundle else {
            return PolicyResult::allow(Some("no policy loaded".to_string()));
        };

        // Evaluate each rule
        for rule in &bundle.rules {
            let matches = self.evaluate_expression(&rule.expression, envelope, metrics);

            if matches {
                match rule.action.as_str() {
                    "deny" => {
                        let reason =
                            format!("Policy rule '{}' matched: {}", rule.id, rule.expression);
                        return PolicyResult::deny(reason);
                    }
                    "redact" => {
                        // For redact, we'll mark it in the result but still allow
                        // The actual redaction is applied by the redact() method
                        let mut result = PolicyResult::allow(Some(format!(
                            "Rule '{}' requires redaction",
                            rule.id
                        )));
                        result.transforms_applied.push(rule.id.clone());
                        return result;
                    }
                    _ => {
                        // "allow" or unknown action - continue to next rule
                    }
                }
            }
        }

        // No denying rules matched, allow
        PolicyResult::allow(Some("all policy checks passed".to_string()))
    }

    fn redact(&self, _envelope: &mut Envelope) -> bool {
        // MVP: Simple redaction - just log for now
        // TODO: Implement actual redaction transforms (text filtering, truncation, etc.)
        // For now, this is a no-op but returns false to indicate no changes
        false
    }
}

impl DefaultPolicyEngine {
    /// Parse a YAML policy structure.
    fn parse_yaml_policy(&mut self, value: serde_yaml::Value) -> Result<(), String> {
        let mut rules = Vec::new();
        let mut version = "1.0.0".to_string();
        let mut signature = "unsigned".to_string();

        // Parse version if present
        if let Some(v) = value.get("version").and_then(|v| v.as_str()) {
            version = v.to_string();
        }

        // Parse signature if present
        if let Some(s) = value.get("signature").and_then(|s| s.as_str()) {
            signature = s.to_string();
        }

        // Parse deny_cloud_if rules (MVP format)
        if let Some(deny_rules) = value.get("deny_cloud_if").and_then(|v| v.as_sequence()) {
            for (idx, rule_value) in deny_rules.iter().enumerate() {
                if let Some(expr) = rule_value.as_str() {
                    rules.push(PolicyRule {
                        id: format!("deny_rule_{}", idx),
                        expression: expr.to_string(),
                        action: "deny".to_string(),
                    });
                }
            }
        }

        // Parse rules array if present (more structured format)
        if let Some(rules_array) = value.get("rules").and_then(|v| v.as_sequence()) {
            for rule_value in rules_array {
                if let Some(id) = rule_value.get("id").and_then(|v| v.as_str()) {
                    let expression = rule_value
                        .get("expression")
                        .and_then(|v| v.as_str())
                        .unwrap_or("")
                        .to_string();
                    let action = rule_value
                        .get("action")
                        .and_then(|v| v.as_str())
                        .unwrap_or("deny")
                        .to_string();

                    rules.push(PolicyRule {
                        id: id.to_string(),
                        expression,
                        action,
                    });
                }
            }
        }

        if rules.is_empty() {
            return Err("No valid rules found in policy bundle".to_string());
        }

        self.bundle = Some(PolicyBundle {
            version,
            rules,
            signature,
        });

        Ok(())
    }

    /// Parse a JSON policy structure.
    fn parse_json_policy(&mut self, value: serde_json::Value) -> Result<(), String> {
        let mut rules = Vec::new();
        let mut version = "1.0.0".to_string();
        let mut signature = "unsigned".to_string();

        // Parse version if present
        if let Some(v) = value.get("version").and_then(|v| v.as_str()) {
            version = v.to_string();
        }

        // Parse signature if present
        if let Some(s) = value.get("signature").and_then(|s| s.as_str()) {
            signature = s.to_string();
        }

        // Parse deny_cloud_if rules (MVP format)
        if let Some(deny_rules) = value.get("deny_cloud_if").and_then(|v| v.as_array()) {
            for (idx, rule_value) in deny_rules.iter().enumerate() {
                if let Some(expr) = rule_value.as_str() {
                    rules.push(PolicyRule {
                        id: format!("deny_rule_{}", idx),
                        expression: expr.to_string(),
                        action: "deny".to_string(),
                    });
                }
            }
        }

        // Parse rules array if present (more structured format)
        if let Some(rules_array) = value.get("rules").and_then(|v| v.as_array()) {
            for rule_value in rules_array {
                if let Some(id) = rule_value.get("id").and_then(|v| v.as_str()) {
                    let expression = rule_value
                        .get("expression")
                        .and_then(|v| v.as_str())
                        .unwrap_or("")
                        .to_string();
                    let action = rule_value
                        .get("action")
                        .and_then(|v| v.as_str())
                        .unwrap_or("deny")
                        .to_string();

                    rules.push(PolicyRule {
                        id: id.to_string(),
                        expression,
                        action,
                    });
                }
            }
        }

        if rules.is_empty() {
            return Err("No valid rules found in policy bundle".to_string());
        }

        self.bundle = Some(PolicyBundle {
            version,
            rules,
            signature,
        });

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ir::{Envelope, EnvelopeKind};

    fn text_envelope(value: &str) -> Envelope {
        Envelope::new(EnvelopeKind::Text(value.to_string()))
    }

    fn audio_envelope(bytes: &[u8]) -> Envelope {
        Envelope::new(EnvelopeKind::Audio(bytes.to_vec()))
    }

    #[test]
    fn test_default_policy_allows_text() {
        let engine = DefaultPolicyEngine::with_default_policy();
        let envelope = text_envelope("Text");
        let metrics = DeviceMetrics::default();

        let result = engine.evaluate("test_stage", &envelope, &metrics);
        assert!(result.allowed);
    }

    #[test]
    fn test_default_policy_allows_audio_raw() {
        let engine = DefaultPolicyEngine::with_default_policy();
        let envelope = audio_envelope(&[0, 1, 2]);
        let metrics = DeviceMetrics::default();

        let result = engine.evaluate("test_stage", &envelope, &metrics);
        assert!(result.allowed);
        assert!(result.reason.is_some());
        assert!(result.reason.unwrap().contains("all policy checks passed"));
    }

    #[test]
    fn test_load_yaml_policy_input_kind_rule() {
        let yaml_content = r#"
version: "0.1.0"
deny_cloud_if:
  - input.kind == "SensitiveData"
signature: "test"
"#;

        let mut engine = DefaultPolicyEngine::new();
        let result = engine.load_policies(yaml_content.as_bytes().to_vec());
        assert!(result.is_ok());

        let envelope = text_envelope("SensitiveData");
        let metrics = DeviceMetrics::default();

        let policy_result = engine.evaluate("test", &envelope, &metrics);
        assert!(!policy_result.allowed);
    }

    #[test]
    fn test_load_json_policy_input_kind_rule() {
        let json_content = r#"{
            "version": "0.1.0",
            "deny_cloud_if": [
                "input.kind == \"AudioRaw\""
            ],
            "signature": "test"
        }"#;

        let mut engine = DefaultPolicyEngine::new();
        let result = engine.load_policies(json_content.as_bytes().to_vec());
        assert!(result.is_ok());

        let envelope = audio_envelope(&[1, 2, 3]);
        let metrics = DeviceMetrics::default();

        let policy_result = engine.evaluate("test", &envelope, &metrics);
        assert!(!policy_result.allowed);
    }

    #[test]
    fn test_no_policy_allows() {
        let engine = DefaultPolicyEngine::new();
        let envelope = text_envelope("Text");
        let metrics = DeviceMetrics::default();

        let result = engine.evaluate("test_stage", &envelope, &metrics);
        assert!(result.allowed);
    }
}