xybrid-core 0.1.0-rc4

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
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
//! Orchestrator Bootstrap module - Initializes the orchestration runtime environment.
//!
//! The bootstrap module provides a unified API for initializing an orchestrator
//! with all required components: adapters, executor, policy engine, routing engine,
//! event bus, and telemetry.
//!
//! # Example
//!
//! ```rust,ignore
//! use xybrid_core::orchestrator::Orchestrator;
//!
//! let orchestrator = Orchestrator::bootstrap(None)?;
//! // orchestrator is ready to execute pipelines
//! ```

use crate::context::DeviceMetrics;
use crate::control_sync::{
    ControlSync, ControlSyncConfig, ControlSyncHandler, ControlSyncProvider,
    NoopControlSyncHandler, NoopControlSyncProvider,
};
use crate::device::ResourceMonitor;
use crate::event_bus::{EventBus, OrchestratorEvent};
use crate::executor::Executor;
use crate::orchestrator::policy_engine::DefaultPolicyEngine;
use crate::orchestrator::routing_engine::DefaultRoutingEngine;
use crate::orchestrator::{
    ExecutionMode, LocalAuthority, OrchestrationAuthority, Orchestrator, OrchestratorError,
};
#[cfg(any(target_os = "macos", target_os = "ios"))]
use crate::runtime_adapter::CoreMLRuntimeAdapter;
#[cfg(target_os = "android")]
use crate::runtime_adapter::ONNXMobileRuntimeAdapter;
use crate::runtime_adapter::{OnnxRuntimeAdapter, RuntimeAdapter};
use crate::streaming::manager::StreamManager;
use crate::telemetry::{Severity, Telemetry};
use serde_json::json;
use std::path::Path;
use std::sync::Arc;

/// Bootstrap configuration loaded from file.
#[derive(Debug, Clone, serde::Deserialize)]
struct BootstrapConfig {
    /// Execution mode (batch or streaming)
    #[serde(default)]
    execution_mode: Option<String>,
    /// Adapter configuration
    #[serde(default)]
    adapters: Option<AdapterConfig>,
}

/// Adapter configuration.
#[derive(Debug, Clone, serde::Deserialize)]
struct AdapterConfig {
    /// Enable local adapter
    #[serde(default = "default_true")]
    local: bool,
    /// Enable cloud adapter
    #[serde(default = "default_true")]
    cloud: bool,
    /// Enable mock adapter
    #[serde(default = "default_false")]
    mock: bool,
}

fn default_true() -> bool {
    true
}

fn default_false() -> bool {
    false
}

impl Orchestrator {
    /// Bootstrap a new orchestrator instance with registered adapters and telemetry.
    ///
    /// This function initializes all orchestrator components:
    /// - Policy engine with default policies
    /// - Routing engine
    /// - Executor with registered runtime adapters
    /// - Event bus with subscription enabled
    /// - Telemetry for logging
    /// - Device metrics collection
    ///
    /// # Arguments
    ///
    /// * `config_path` - Optional path to configuration file (YAML format)
    ///
    /// # Returns
    ///
    /// A fully initialized `Orchestrator` ready to execute pipelines, or an error
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use xybrid_core::orchestrator::Orchestrator;
    ///
    /// // Bootstrap with defaults
    /// let orchestrator = Orchestrator::bootstrap(None)?;
    ///
    /// // Bootstrap with configuration file
    /// let orchestrator = Orchestrator::bootstrap(Some("config/hiiipe.yml"))?;
    /// ```
    pub fn bootstrap(config_path: Option<&Path>) -> Result<Self, OrchestratorError> {
        // Emit bootstrap start event
        let event_bus = EventBus::new();
        event_bus.publish(OrchestratorEvent::BootstrapStart {
            context: Default::default(),
        });

        // Load configuration if provided
        let config = if let Some(path) = config_path {
            load_config(path)?
        } else {
            None
        };

        // Initialize telemetry
        let telemetry = Arc::new(Telemetry::new());
        telemetry.log_bootstrap_start();

        // Initialize policy engine
        let policy_engine = Box::new(DefaultPolicyEngine::with_default_policy());
        event_bus.publish(OrchestratorEvent::ComponentInitialized {
            component: "policy_engine".to_string(),
            context: Default::default(),
        });

        // Initialize routing engine
        let routing_engine = Box::new(DefaultRoutingEngine::new());
        event_bus.publish(OrchestratorEvent::ComponentInitialized {
            component: "routing_engine".to_string(),
            context: Default::default(),
        });

        // Initialize executor
        // Note: Model downloading is handled by the SDK's RegistryClient.
        // The executor works with already-downloaded models via bundle_path.
        let mut executor = Executor::new();

        event_bus.publish(OrchestratorEvent::ComponentInitialized {
            component: "executor".to_string(),
            context: Default::default(),
        });

        // Register adapters based on configuration
        let adapter_config = config
            .as_ref()
            .and_then(|c| c.adapters.as_ref())
            .cloned()
            .unwrap_or(AdapterConfig {
                local: true,
                cloud: true,
                mock: false,
            });

        // Register local adapters
        if adapter_config.local {
            // Prefer CoreML on macOS/iOS, fallback to ONNX
            #[cfg(any(target_os = "macos", target_os = "ios"))]
            {
                let adapter = Arc::new(CoreMLRuntimeAdapter::new());
                executor.register_adapter(adapter);
                event_bus.publish(OrchestratorEvent::AdapterRegistered {
                    name: "coreml".to_string(),
                    context: Default::default(),
                });
            }

            // Prefer ONNX Mobile on Android
            #[cfg(target_os = "android")]
            {
                let adapter = Arc::new(ONNXMobileRuntimeAdapter::new());
                executor.register_adapter(adapter);
                event_bus.publish(OrchestratorEvent::AdapterRegistered {
                    name: "onnx-mobile".to_string(),
                    context: Default::default(),
                });
            }

            // Register ONNX adapter (desktop/fallback)
            #[cfg(not(any(target_os = "macos", target_os = "ios", target_os = "android")))]
            {
                let adapter = Arc::new(OnnxRuntimeAdapter::new());
                executor.register_adapter(adapter);
                event_bus.publish(OrchestratorEvent::AdapterRegistered {
                    name: "onnx".to_string(),
                    context: Default::default(),
                });
            }

            // On macOS/iOS, also register ONNX as fallback
            #[cfg(any(target_os = "macos", target_os = "ios"))]
            {
                let adapter = Arc::new(OnnxRuntimeAdapter::new());
                executor.register_adapter(adapter);
                event_bus.publish(OrchestratorEvent::AdapterRegistered {
                    name: "onnx".to_string(),
                    context: Default::default(),
                });
            }

            // On Android, also register regular ONNX as fallback
            #[cfg(target_os = "android")]
            {
                let adapter = Arc::new(OnnxRuntimeAdapter::new());
                executor.register_adapter(adapter);
                event_bus.publish(OrchestratorEvent::AdapterRegistered {
                    name: "onnx".to_string(),
                    context: Default::default(),
                });
            }
        }

        // Register cloud adapter (mock for now)
        if adapter_config.cloud {
            let adapter = Arc::new(CloudRuntimeAdapter::new());
            executor.register_adapter(adapter);
            event_bus.publish(OrchestratorEvent::AdapterRegistered {
                name: "cloud".to_string(),
                context: Default::default(),
            });
        }

        // Register mock adapter
        if adapter_config.mock {
            let adapter = Arc::new(MockRuntimeAdapter::new());
            executor.register_adapter(adapter);
            event_bus.publish(OrchestratorEvent::AdapterRegistered {
                name: "mock".to_string(),
                context: Default::default(),
            });
        }

        // Initialize stream manager
        let stream_manager = StreamManager::new();
        let resource_monitor = ResourceMonitor::global();

        // Determine execution mode
        let execution_mode = config
            .as_ref()
            .and_then(|c| c.execution_mode.as_ref())
            .map(|m| match m.as_str() {
                "streaming" => ExecutionMode::Streaming,
                _ => ExecutionMode::Batch,
            })
            .unwrap_or(ExecutionMode::Batch);

        // Device metrics: capabilities are detected statically; live resource
        // signals are sampled on demand via the ResourceMonitor at routing time.
        let _device_metrics = DeviceMetrics::default();

        // Initialize control sync manager (noop defaults for now)
        let control_sync = {
            let provider: Arc<dyn ControlSyncProvider> = Arc::new(NoopControlSyncProvider);
            let handler: Arc<dyn ControlSyncHandler> = Arc::new(NoopControlSyncHandler);
            match ControlSync::new(
                ControlSyncConfig::default(),
                provider,
                handler,
                telemetry.clone(),
            ) {
                Ok(manager) => Some(manager),
                Err(err) => {
                    telemetry.log_control_sync_event(
                        Severity::Error,
                        "spawn_failed",
                        json!({ "error": err.to_string() }),
                    );
                    None
                }
            }
        };

        // Initialize authority (local by default - fully offline, no phone-home)
        let authority: Box<dyn OrchestrationAuthority> = Box::new(LocalAuthority::new());
        event_bus.publish(OrchestratorEvent::ComponentInitialized {
            component: "authority".to_string(),
            context: Default::default(),
        });

        event_bus.publish(OrchestratorEvent::ExecutorReady {
            context: Default::default(),
        });
        event_bus.publish(OrchestratorEvent::OrchestratorReady {
            context: Default::default(),
        });

        // Create orchestrator instance
        let orchestrator = Orchestrator::with_all(
            authority,
            policy_engine,
            routing_engine,
            executor,
            stream_manager,
            event_bus,
            telemetry.clone(),
            resource_monitor,
            control_sync,
            execution_mode,
        );

        if orchestrator.control_sync.is_some() {
            orchestrator.telemetry.log_control_sync_event(
                Severity::Debug,
                "worker_ready",
                json!({}),
            );
        }

        // Log bootstrap completion
        orchestrator.telemetry.log_bootstrap_complete();

        Ok(orchestrator)
    }
}

/// Load bootstrap configuration from file.
fn load_config(path: &Path) -> Result<Option<BootstrapConfig>, OrchestratorError> {
    if !path.exists() {
        return Ok(None);
    }

    let content = std::fs::read_to_string(path).map_err(|e| {
        OrchestratorError::Other(format!(
            "Failed to read config file '{}': {}",
            path.display(),
            e
        ))
    })?;

    let config: BootstrapConfig = serde_yaml::from_str(&content).map_err(|e| {
        OrchestratorError::Other(format!(
            "Failed to parse config file '{}': {}",
            path.display(),
            e
        ))
    })?;

    Ok(Some(config))
}

/// Cloud runtime adapter (mock implementation).
///
/// This adapter simulates cloud inference execution by adding network latency
/// and returning mock outputs. Future implementations will integrate with
/// actual cloud inference services (gRPC, REST APIs, etc.).
struct CloudRuntimeAdapter {
    // Future: cloud endpoint configuration, auth tokens, etc.
}

impl CloudRuntimeAdapter {
    fn new() -> Self {
        Self {}
    }
}

impl RuntimeAdapter for CloudRuntimeAdapter {
    fn name(&self) -> &str {
        "cloud"
    }

    fn supported_formats(&self) -> Vec<&'static str> {
        vec!["onnx", "tensorflow", "pytorch"]
    }

    fn load_model(&mut self, _path: &str) -> crate::runtime_adapter::AdapterResult<()> {
        // Cloud models are loaded remotely, not from local files
        Ok(())
    }

    fn execute(
        &self,
        input: &crate::ir::Envelope,
    ) -> crate::runtime_adapter::AdapterResult<crate::ir::Envelope> {
        // Simulate cloud execution with network latency
        use crate::ir::EnvelopeKind;
        use std::thread;

        // Simulate network delay
        thread::sleep(std::time::Duration::from_millis(50));

        // Mock cloud inference
        let output = match &input.kind {
            EnvelopeKind::Audio(_) => EnvelopeKind::Text("cloud-output-transcribed".to_string()),
            EnvelopeKind::Text(t) => EnvelopeKind::Text(format!("cloud-output-{}", t)),
            EnvelopeKind::Embedding(_) => EnvelopeKind::Text("cloud-output".to_string()),
        };

        Ok(crate::ir::Envelope::new(output))
    }
}

/// Mock runtime adapter for testing.
///
/// This adapter always returns mock outputs without any real inference.
/// Useful for testing and development when models are not available.
struct MockRuntimeAdapter {
    // Future: mock response configuration
}

impl MockRuntimeAdapter {
    fn new() -> Self {
        Self {}
    }
}

impl RuntimeAdapter for MockRuntimeAdapter {
    fn name(&self) -> &str {
        "mock"
    }

    fn supported_formats(&self) -> Vec<&'static str> {
        vec!["*"] // Mock supports all formats
    }

    fn load_model(&mut self, _path: &str) -> crate::runtime_adapter::AdapterResult<()> {
        // Mock adapter doesn't need to load models
        Ok(())
    }

    fn execute(
        &self,
        input: &crate::ir::Envelope,
    ) -> crate::runtime_adapter::AdapterResult<crate::ir::Envelope> {
        // Return mock output
        use crate::ir::EnvelopeKind;

        let output = match &input.kind {
            EnvelopeKind::Audio(_) => EnvelopeKind::Text("mock-output-transcribed".to_string()),
            EnvelopeKind::Text(t) => EnvelopeKind::Text(format!("mock-output-{}", t)),
            EnvelopeKind::Embedding(_) => EnvelopeKind::Text("mock-output".to_string()),
        };

        Ok(crate::ir::Envelope::new(output))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_bootstrap_default() {
        let orchestrator = Orchestrator::bootstrap(None);
        assert!(orchestrator.is_ok());

        let orchestrator = orchestrator.unwrap();
        assert_eq!(*orchestrator.execution_mode(), ExecutionMode::Batch);
        assert!(orchestrator
            .executor
            .list_adapters()
            .contains(&"onnx".to_string()));
    }

    #[test]
    fn test_bootstrap_with_cloud_adapter() {
        // Create a temporary config file
        use std::io::Write;
        use tempfile::NamedTempFile;

        let mut file = NamedTempFile::new().unwrap();
        writeln!(file, "adapters:\n  cloud: true").unwrap();
        let path = file.path();

        let orchestrator = Orchestrator::bootstrap(Some(path));
        assert!(orchestrator.is_ok());

        let orchestrator = orchestrator.unwrap();
        let adapters = orchestrator.executor.list_adapters();
        assert!(adapters.contains(&"cloud".to_string()));
    }

    #[test]
    fn test_bootstrap_with_mock_adapter() {
        use std::io::Write;
        use tempfile::NamedTempFile;

        let mut file = NamedTempFile::new().unwrap();
        writeln!(file, "adapters:\n  mock: true").unwrap();
        let path = file.path();

        let orchestrator = Orchestrator::bootstrap(Some(path));
        assert!(orchestrator.is_ok());

        let orchestrator = orchestrator.unwrap();
        let adapters = orchestrator.executor.list_adapters();
        assert!(adapters.contains(&"mock".to_string()));
    }
}