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
//! Model fixtures for integration testing.
//!
//! Provides utilities for locating test models in a consistent way across
//! different environments (local development, CI, standalone repo builds).
//!
//! ## Resolution Order
//!
//! Model paths are resolved in the following order:
//! 1. `$XYBRID_TEST_MODELS/<model>` - Environment variable (highest priority)
//! 2. `$CARGO_MANIFEST_DIR/../integration-tests/fixtures/models/<model>` - Relative to crate
//! 3. `$CARGO_MANIFEST_DIR/../../integration-tests/fixtures/models/<model>` - Workspace layout
//!
//! ## Usage
//!
//! ```no_run
//! use xybrid_core::testing::model_fixtures;
//!
//! // Get model path (panics if not found)
//! let model_dir = model_fixtures::require_model("kokoro-82m");
//!
//! // Get model path (returns Option)
//! if let Some(model_dir) = model_fixtures::model_path("kokoro-82m") {
//!     // Use model
//! }
//!
//! // Check if model is available
//! if model_fixtures::model_available("kokoro-82m") {
//!     // Run model-dependent test
//! }
//! ```
//!
//! ## Environment Variables
//!
//! - `XYBRID_TEST_MODELS`: Override the default model search path

use std::path::{Path, PathBuf};
use std::sync::OnceLock;

/// Environment variable name for custom test models path.
pub const ENV_TEST_MODELS: &str = "XYBRID_TEST_MODELS";

/// Cached models directory path.
static MODELS_DIR: OnceLock<Option<PathBuf>> = OnceLock::new();

/// Find the integration-tests fixtures/models directory.
///
/// Searches in order:
/// 1. `$XYBRID_TEST_MODELS` environment variable
/// 2. Relative to CARGO_MANIFEST_DIR (for core crate)
/// 3. Common workspace layouts
fn find_models_dir() -> Option<PathBuf> {
    // Check environment variable first
    if let Ok(env_path) = std::env::var(ENV_TEST_MODELS) {
        let path = PathBuf::from(env_path);
        if path.exists() {
            return Some(path);
        }
    }

    // Try relative paths from CARGO_MANIFEST_DIR
    // This works when running from xybrid-core crate
    let manifest_dir = std::env::var("CARGO_MANIFEST_DIR").ok()?;
    let manifest_path = PathBuf::from(&manifest_dir);

    // Try relative paths from CARGO_MANIFEST_DIR
    // 1. crates/xybrid-core/ -> ../../integration-tests/fixtures/models (workspace layout)
    // 2. core/ -> ../integration-tests/fixtures/models (flat layout)
    let candidates = [
        manifest_path.join("../../integration-tests/fixtures/models"),
        manifest_path.join("../integration-tests/fixtures/models"),
    ];

    for fixtures_path in &candidates {
        if fixtures_path.exists() && fixtures_path.is_dir() {
            if let Ok(canonical) = fixtures_path.canonicalize() {
                return Some(canonical);
            }
            return Some(fixtures_path.clone());
        }
    }

    None
}

/// Get the models directory path.
///
/// Returns the cached models directory, finding it on first call.
pub fn models_dir() -> Option<&'static PathBuf> {
    MODELS_DIR.get_or_init(find_models_dir).as_ref()
}

/// Get the path to a specific model directory.
///
/// Returns `None` if the models directory is not found or the model doesn't exist.
///
/// # Example
///
/// ```no_run
/// # fn _example() {
/// use xybrid_core::testing::model_fixtures;
/// if let Some(path) = model_fixtures::model_path("kokoro-82m") {
///     let metadata = path.join("model_metadata.json");
/// }
/// # }
/// ```
pub fn model_path(model_name: &str) -> Option<PathBuf> {
    let models = models_dir()?;
    let path = models.join(model_name);
    if path.exists() && path.is_dir() {
        Some(path)
    } else {
        None
    }
}

/// Check if a model directory has actual model binary files downloaded.
///
/// A model is only considered ready if it has at least one binary file
/// (`.onnx`, `.safetensors`, or `.gguf`). Having only `model_metadata.json`
/// is not sufficient since metadata is checked into git but binaries are not.
fn has_model_binaries(dir: &Path) -> bool {
    const MODEL_EXTENSIONS: &[&str] = &["onnx", "safetensors", "gguf"];
    if let Ok(entries) = std::fs::read_dir(dir) {
        for entry in entries.flatten() {
            if let Some(ext) = entry.path().extension() {
                if MODEL_EXTENSIONS.iter().any(|e| ext == *e) {
                    return true;
                }
            }
        }
    }
    false
}

/// Check if a model is available (directory exists with downloaded model binaries).
///
/// # Example
///
/// ```no_run
/// # fn _example() {
/// use xybrid_core::testing::model_fixtures;
/// if model_fixtures::model_available("kokoro-82m") {
///     // Run integration test
/// } else {
///     eprintln!("Skipping: kokoro-82m not downloaded");
/// }
/// # }
/// ```
pub fn model_available(model_name: &str) -> bool {
    model_path(model_name)
        .map(|p| has_model_binaries(&p))
        .unwrap_or(false)
}

/// Get the path to a model, panicking with a helpful message if not found.
///
/// Use this in examples and tests where the model is required.
///
/// # Panics
///
/// Panics if the model directory doesn't exist or models directory is not found.
///
/// # Example
///
/// ```no_run
/// # fn _example() {
/// use xybrid_core::testing::model_fixtures;
/// let model_dir = model_fixtures::require_model("kokoro-82m");
/// let metadata_path = model_dir.join("model_metadata.json");
/// # let _ = metadata_path;
/// # }
/// ```
pub fn require_model(model_name: &str) -> PathBuf {
    if let Some(path) = model_path(model_name) {
        if has_model_binaries(&path) {
            return path;
        }
    }

    let models_dir_info = models_dir()
        .map(|p| format!("Models directory: {}", p.display()))
        .unwrap_or_else(|| "Models directory: NOT FOUND".to_string());

    panic!(
        r#"
Model '{}' not found!

{}

To download test models, run:
  ./integration-tests/download.sh {}

Or download all models:
  ./integration-tests/download.sh --all

You can also set XYBRID_TEST_MODELS environment variable to a custom path.
"#,
        model_name, models_dir_info, model_name
    );
}

/// Get model path or skip the test with a message.
///
/// Returns `None` and prints a skip message if the model is not available.
/// Useful for tests that should be skipped rather than fail when models are missing.
///
/// # Example
///
/// ```no_run
/// #[test]
/// fn test_tts_inference() {
///     let Some(model_dir) = model_fixtures::model_or_skip("kokoro-82m") else {
///         return; // Test skipped
///     };
///     // ... run test with model_dir
/// }
/// ```
pub fn model_or_skip(model_name: &str) -> Option<PathBuf> {
    if let Some(path) = model_path(model_name) {
        if has_model_binaries(&path) {
            return Some(path);
        }
    }

    eprintln!(
        "Skipping test: model '{}' not downloaded. Run: ./integration-tests/download.sh {}",
        model_name, model_name
    );
    None
}

/// Get the integration-tests fixtures directory (parent of models directory).
///
/// Returns the fixtures directory which contains `models/` and `input/` subdirectories.
///
/// # Example
///
/// ```no_run
/// # fn _example() {
/// use xybrid_core::testing::model_fixtures;
/// if let Some(fixtures) = model_fixtures::fixtures_dir() {
///     let test_audio = fixtures.join("input/test_audio.wav");
/// }
/// # }
/// ```
pub fn fixtures_dir() -> Option<PathBuf> {
    models_dir().and_then(|m| m.parent().map(|p| p.to_path_buf()))
}

/// List all available models in the models directory.
pub fn list_available_models() -> Vec<String> {
    let Some(models) = models_dir() else {
        return vec![];
    };

    let Ok(entries) = std::fs::read_dir(models) else {
        return vec![];
    };

    entries
        .filter_map(|e| e.ok())
        .filter(|e| e.path().is_dir())
        .filter(|e| has_model_binaries(&e.path()))
        .filter_map(|e| e.file_name().into_string().ok())
        .collect()
}

// ============================================================================
// Input Fixtures (test audio, text files)
// ============================================================================

/// Get the input fixtures directory.
///
/// Returns the directory containing test input files (audio, text).
///
/// # Example
///
/// ```no_run
/// # fn _example() {
/// use xybrid_core::testing::model_fixtures;
/// if let Some(input_dir) = model_fixtures::input_dir() {
///     let test_audio = input_dir.join("test_audio.wav");
/// }
/// # }
/// ```
pub fn input_dir() -> Option<PathBuf> {
    fixtures_dir().map(|f| f.join("input"))
}

/// Get path to a test audio file.
///
/// # Example
///
/// ```no_run
/// # fn _example() -> Result<(), Box<dyn std::error::Error>> {
/// use xybrid_core::testing::model_fixtures;
/// if let Some(audio_path) = model_fixtures::test_audio("test_audio.wav") {
///     let audio_bytes = std::fs::read(&audio_path)?;
///     let _ = audio_bytes;
/// }
/// # Ok(())
/// # }
/// ```
pub fn test_audio(filename: &str) -> Option<PathBuf> {
    input_dir().map(|d| d.join(filename)).filter(|p| p.exists())
}

/// Get path to the default test audio file (test_audio.wav).
///
/// # Example
///
/// ```no_run
/// # fn _example() {
/// use xybrid_core::testing::model_fixtures;
/// let audio_path = model_fixtures::default_test_audio()
///     .expect("test_audio.wav should exist");
/// # let _ = audio_path;
/// # }
/// ```
pub fn default_test_audio() -> Option<PathBuf> {
    test_audio("test_audio.wav")
}

/// Get path to a test text file.
///
/// # Example
///
/// ```no_run
/// # fn _example() -> Result<(), Box<dyn std::error::Error>> {
/// use xybrid_core::testing::model_fixtures;
/// if let Some(text_path) = model_fixtures::test_text("sample.txt") {
///     let text = std::fs::read_to_string(&text_path)?;
///     let _ = text;
/// }
/// # Ok(())
/// # }
/// ```
pub fn test_text(filename: &str) -> Option<PathBuf> {
    input_dir().map(|d| d.join(filename)).filter(|p| p.exists())
}

/// Get the pipeline configurations directory.
///
/// Returns the directory containing pipeline YAML files.
pub fn pipelines_dir() -> Option<PathBuf> {
    fixtures_dir().map(|f| f.join("pipelines"))
}

/// Get path to a pipeline configuration file.
///
/// # Example
///
/// ```no_run
/// # fn _example() -> Result<(), Box<dyn std::error::Error>> {
/// use xybrid_core::testing::model_fixtures;
/// if let Some(pipeline_path) = model_fixtures::pipeline("tts_pipeline.yaml") {
///     let yaml = std::fs::read_to_string(&pipeline_path)?;
///     let _ = yaml;
/// }
/// # Ok(())
/// # }
/// ```
pub fn pipeline(filename: &str) -> Option<PathBuf> {
    pipelines_dir()
        .map(|d| d.join(filename))
        .filter(|p| p.exists())
}

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

    #[test]
    fn test_models_dir_found() {
        // This test may fail if run outside the xybrid workspace
        // That's expected - it validates the resolution logic works in-workspace
        if let Some(dir) = models_dir() {
            assert!(dir.exists(), "Models directory should exist: {:?}", dir);
            assert!(dir.is_dir(), "Models path should be a directory");
        }
    }

    #[test]
    fn test_model_available_returns_false_for_nonexistent() {
        assert!(!model_available("nonexistent-model-xyz"));
    }

    #[test]
    fn test_model_path_returns_none_for_nonexistent() {
        assert!(model_path("nonexistent-model-xyz").is_none());
    }

    #[test]
    fn test_list_available_models() {
        let models = list_available_models();
        // Just verify it doesn't panic and returns a vec
        // The actual count depends on which models are downloaded
        drop(models);
    }

    #[test]
    fn test_model_or_skip_returns_none_for_missing() {
        let result = model_or_skip("definitely-not-a-real-model");
        assert!(result.is_none());
    }
}