inferno-ai 0.10.3

Enterprise AI/ML model runner with automatic updates, real-time monitoring, and multi-interface support
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
#![allow(dead_code, unused_imports, unused_variables)]
pub mod queue;
pub mod scheduler;

use crate::{
    backends::{Backend, InferenceParams},
    metrics::{InferenceEvent, MetricsCollector},
};
use anyhow::Result;
// Futures support for parallel processing (if needed in future)
use serde::{Deserialize, Serialize};
use std::{
    path::Path,
    sync::{Arc, atomic::AtomicUsize},
    time::{Duration, Instant},
};
// use tokio::sync::Semaphore; // Reserved for future concurrent processing
use tracing::{info, warn};

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BatchConfig {
    pub concurrency: usize,
    pub timeout_seconds: u64,
    pub retry_attempts: u32,
    pub checkpoint_interval: u32,
    pub output_format: BatchOutputFormat,
    pub continue_on_error: bool,
    pub shuffle_inputs: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum BatchOutputFormat {
    JsonLines,
    Json,
    Csv,
    Tsv,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BatchInput {
    pub id: String,
    pub content: String,
    pub metadata: Option<serde_json::Value>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BatchResult {
    pub id: String,
    pub input: String,
    pub output: Option<String>,
    pub error: Option<String>,
    pub duration_ms: u64,
    pub tokens_generated: Option<u32>,
    pub timestamp: chrono::DateTime<chrono::Utc>,
    pub metadata: Option<serde_json::Value>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BatchProgress {
    pub total_items: usize,
    pub completed_items: usize,
    pub failed_items: usize,
    pub skipped_items: usize,
    pub start_time: chrono::DateTime<chrono::Utc>,
    pub estimated_completion: Option<chrono::DateTime<chrono::Utc>>,
    pub current_rate: f64, // items per second
}

#[derive(Debug)]
pub struct BatchProcessor {
    config: BatchConfig,
    metrics: Option<Arc<MetricsCollector>>,
    progress: Arc<AtomicUsize>,
    total: usize,
    start_time: Instant,
}

impl Default for BatchConfig {
    fn default() -> Self {
        Self {
            concurrency: 4,
            timeout_seconds: 300,
            retry_attempts: 3,
            checkpoint_interval: 100,
            output_format: BatchOutputFormat::JsonLines,
            continue_on_error: true,
            shuffle_inputs: false,
        }
    }
}

impl BatchProcessor {
    pub fn new(config: BatchConfig, total_items: usize) -> Self {
        Self {
            config,
            metrics: None,
            progress: Arc::new(AtomicUsize::new(0)),
            total: total_items,
            start_time: Instant::now(),
        }
    }

    pub fn with_metrics(mut self, metrics: Arc<MetricsCollector>) -> Self {
        self.metrics = Some(metrics);
        self
    }

    pub async fn process_file(
        &self,
        backend: &mut Backend,
        input_path: &Path,
        output_path: Option<&Path>,
        inference_params: &InferenceParams,
    ) -> Result<BatchProgress> {
        let inputs = self.load_inputs(input_path).await?;
        self.process_inputs(backend, inputs, output_path, inference_params)
            .await
    }

    pub async fn process_inputs(
        &self,
        backend: &mut Backend,
        mut inputs: Vec<BatchInput>,
        output_path: Option<&Path>,
        inference_params: &InferenceParams,
    ) -> Result<BatchProgress> {
        if self.config.shuffle_inputs {
            use rand::seq::SliceRandom;
            inputs.shuffle(&mut rand::thread_rng());
        }

        let total_items = inputs.len();
        info!(
            "Starting batch processing of {} items (sequential mode)",
            total_items
        );

        let mut results = Vec::new();
        let start_time = chrono::Utc::now();
        let mut completed = 0;
        let mut failed = 0;

        for (i, input) in inputs.into_iter().enumerate() {
            if (i + 1) % 10 == 0 || i == 0 {
                info!("Processing item {}/{}", i + 1, total_items);
            }

            let result = Self::process_single_input_simple(
                backend,
                input,
                inference_params,
                self.metrics.clone(),
                "batch_model".to_string(),
                self.config.timeout_seconds,
                self.config.retry_attempts,
            )
            .await;

            if result.error.is_none() {
                completed += 1;
            } else {
                failed += 1;
                if !self.config.continue_on_error {
                    warn!("Stopping batch processing due to error (continue_on_error=false)");
                    break;
                }
            }

            results.push(result);

            // Checkpoint save
            if results.len() % self.config.checkpoint_interval as usize == 0 {
                if let Some(output_path) = output_path {
                    self.save_checkpoint(output_path, &results).await?;
                }
            }
        }

        // Final save
        if let Some(output_path) = output_path {
            self.save_results(output_path, &results).await?;
        }

        let elapsed = chrono::Utc::now() - start_time;
        let elapsed_seconds = elapsed.num_seconds().max(1);

        info!(
            "Batch processing completed: {}/{} items processed ({} failed) in {}",
            completed,
            total_items,
            failed,
            humantime::format_duration(elapsed.to_std().unwrap_or(Duration::ZERO))
        );

        Ok(BatchProgress {
            total_items,
            completed_items: completed,
            failed_items: failed,
            skipped_items: 0,
            start_time,
            estimated_completion: Some(chrono::Utc::now()),
            current_rate: completed as f64 / elapsed_seconds as f64,
        })
    }

    async fn process_single_input_simple(
        backend: &mut Backend,
        input: BatchInput,
        params: &InferenceParams,
        metrics: Option<Arc<MetricsCollector>>,
        model_name: String,
        timeout_seconds: u64,
        retry_attempts: u32,
    ) -> BatchResult {
        let start_time = Instant::now();
        let timestamp = chrono::Utc::now();

        for attempt in 0..=retry_attempts {
            match tokio::time::timeout(
                Duration::from_secs(timeout_seconds),
                backend.infer(&input.content, params),
            )
            .await
            {
                Ok(Ok(output)) => {
                    let duration = start_time.elapsed();

                    // Record metrics
                    if let Some(metrics) = &metrics {
                        let event = InferenceEvent {
                            model_name: model_name.clone(),
                            input_length: input.content.len() as u32,
                            output_length: output.len() as u32, // Rough estimate
                            duration,
                            success: true,
                        };
                        metrics.record_inference(event);
                    }

                    return BatchResult {
                        id: input.id,
                        input: input.content,
                        output: Some(output.clone()),
                        error: None,
                        duration_ms: duration.as_millis() as u64,
                        tokens_generated: Some((output.len() / 4) as u32), // Rough token estimate
                        timestamp,
                        metadata: input.metadata,
                    };
                }
                Ok(Err(e)) => {
                    warn!(
                        "Inference failed for item {}: {} (attempt {}/{})",
                        input.id,
                        e,
                        attempt + 1,
                        retry_attempts + 1
                    );
                    if attempt == retry_attempts {
                        // Record failed metrics
                        if let Some(metrics) = &metrics {
                            let event = InferenceEvent {
                                model_name: model_name.clone(),
                                input_length: input.content.len() as u32,
                                output_length: 0,
                                duration: start_time.elapsed(),
                                success: false,
                            };
                            metrics.record_inference(event);
                        }

                        return BatchResult {
                            id: input.id,
                            input: input.content,
                            output: None,
                            error: Some(e.to_string()),
                            duration_ms: start_time.elapsed().as_millis() as u64,
                            tokens_generated: None,
                            timestamp,
                            metadata: input.metadata,
                        };
                    }
                    tokio::time::sleep(Duration::from_millis(1000 * (attempt + 1) as u64)).await;
                }
                Err(_) => {
                    warn!(
                        "Timeout for item {} (attempt {}/{})",
                        input.id,
                        attempt + 1,
                        retry_attempts + 1
                    );
                    if attempt == retry_attempts {
                        return BatchResult {
                            id: input.id,
                            input: input.content,
                            output: None,
                            error: Some("Timeout".to_string()),
                            duration_ms: start_time.elapsed().as_millis() as u64,
                            tokens_generated: None,
                            timestamp,
                            metadata: input.metadata,
                        };
                    }
                }
            }
        }

        unreachable!()
    }

    pub async fn load_inputs(&self, input_path: &Path) -> Result<Vec<BatchInput>> {
        let content = tokio::fs::read_to_string(input_path).await?;
        let extension = input_path
            .extension()
            .and_then(|s| s.to_str())
            .unwrap_or("");

        match extension.to_lowercase().as_str() {
            "json" => self.load_json_inputs(&content),
            "jsonl" | "ndjson" => self.load_jsonl_inputs(&content),
            "csv" => self.load_csv_inputs(&content).await,
            "tsv" => self.load_tsv_inputs(&content).await,
            _ => self.load_text_inputs(&content),
        }
    }

    fn load_json_inputs(&self, content: &str) -> Result<Vec<BatchInput>> {
        let value: serde_json::Value = serde_json::from_str(content)?;
        match value {
            serde_json::Value::Array(items) => {
                let mut inputs = Vec::new();
                for (i, item) in items.into_iter().enumerate() {
                    match item {
                        serde_json::Value::String(text) => {
                            inputs.push(BatchInput {
                                id: format!("item_{}", i),
                                content: text,
                                metadata: None,
                            });
                        }
                        serde_json::Value::Object(obj) => {
                            let content = obj
                                .get("content")
                                .or_else(|| obj.get("text"))
                                .or_else(|| obj.get("input"))
                                .and_then(|v| v.as_str())
                                .ok_or_else(|| {
                                    anyhow::anyhow!("No content field found in JSON object")
                                })?
                                .to_string();

                            let id = obj
                                .get("id")
                                .and_then(|v| v.as_str())
                                .unwrap_or(&format!("item_{}", i))
                                .to_string();

                            inputs.push(BatchInput {
                                id,
                                content,
                                metadata: Some(serde_json::Value::Object(obj)),
                            });
                        }
                        _ => return Err(anyhow::anyhow!("Invalid JSON array item format")),
                    }
                }
                Ok(inputs)
            }
            _ => Err(anyhow::anyhow!("JSON must be an array")),
        }
    }

    fn load_jsonl_inputs(&self, content: &str) -> Result<Vec<BatchInput>> {
        let mut inputs = Vec::new();
        for (i, line) in content.lines().enumerate() {
            if line.trim().is_empty() {
                continue;
            }
            let value: serde_json::Value = serde_json::from_str(line)?;
            match value {
                serde_json::Value::String(text) => {
                    inputs.push(BatchInput {
                        id: format!("line_{}", i + 1),
                        content: text,
                        metadata: None,
                    });
                }
                serde_json::Value::Object(obj) => {
                    let content = obj
                        .get("content")
                        .or_else(|| obj.get("text"))
                        .or_else(|| obj.get("input"))
                        .and_then(|v| v.as_str())
                        .ok_or_else(|| {
                            anyhow::anyhow!(
                                "No content field found in JSONL object at line {}",
                                i + 1
                            )
                        })?
                        .to_string();

                    let id = obj
                        .get("id")
                        .and_then(|v| v.as_str())
                        .unwrap_or(&format!("line_{}", i + 1))
                        .to_string();

                    inputs.push(BatchInput {
                        id,
                        content,
                        metadata: Some(serde_json::Value::Object(obj)),
                    });
                }
                _ => return Err(anyhow::anyhow!("Invalid JSONL format at line {}", i + 1)),
            }
        }
        Ok(inputs)
    }

    async fn load_csv_inputs(&self, content: &str) -> Result<Vec<BatchInput>> {
        self.load_delimited_inputs(content, ',').await
    }

    async fn load_tsv_inputs(&self, content: &str) -> Result<Vec<BatchInput>> {
        self.load_delimited_inputs(content, '\t').await
    }

    async fn load_delimited_inputs(
        &self,
        content: &str,
        delimiter: char,
    ) -> Result<Vec<BatchInput>> {
        let mut rdr = csv::ReaderBuilder::new()
            .delimiter(delimiter as u8)
            .from_reader(content.as_bytes());

        let headers = rdr.headers()?.clone();
        let mut inputs = Vec::new();

        for (i, result) in rdr.records().enumerate() {
            let record = result?;

            // Look for content in common column names
            let content = record
                .get(0)
                .or_else(|| {
                    headers
                        .iter()
                        .enumerate()
                        .find(|(_, h)| {
                            matches!(
                                h.to_lowercase().as_str(),
                                "content" | "text" | "input" | "prompt"
                            )
                        })
                        .and_then(|(idx, _)| record.get(idx))
                })
                .ok_or_else(|| anyhow::anyhow!("No content column found in CSV row {}", i + 1))?
                .to_string();

            // Create metadata from all columns
            let mut metadata = serde_json::Map::new();
            for (idx, value) in record.iter().enumerate() {
                if let Some(header) = headers.get(idx) {
                    metadata.insert(
                        header.to_string(),
                        serde_json::Value::String(value.to_string()),
                    );
                }
            }

            let id = metadata
                .get("id")
                .and_then(|v| v.as_str())
                .unwrap_or(&format!("row_{}", i + 1))
                .to_string();

            inputs.push(BatchInput {
                id,
                content,
                metadata: Some(serde_json::Value::Object(metadata)),
            });
        }

        Ok(inputs)
    }

    fn load_text_inputs(&self, content: &str) -> Result<Vec<BatchInput>> {
        let inputs = content
            .lines()
            .enumerate()
            .filter_map(|(i, line)| {
                let trimmed = line.trim();
                if trimmed.is_empty() {
                    None
                } else {
                    Some(BatchInput {
                        id: format!("line_{}", i + 1),
                        content: trimmed.to_string(),
                        metadata: None,
                    })
                }
            })
            .collect();
        Ok(inputs)
    }

    async fn save_checkpoint(&self, output_path: &Path, results: &[BatchResult]) -> Result<()> {
        let checkpoint_path = output_path.with_extension(format!(
            "checkpoint.{}",
            output_path
                .extension()
                .and_then(|s| s.to_str())
                .unwrap_or("json")
        ));
        self.save_results(&checkpoint_path, results).await
    }

    async fn save_results(&self, output_path: &Path, results: &[BatchResult]) -> Result<()> {
        let content = match self.config.output_format {
            BatchOutputFormat::Json => serde_json::to_string_pretty(results)?,
            BatchOutputFormat::JsonLines => results
                .iter()
                .map(serde_json::to_string)
                .collect::<Result<Vec<_>, _>>()?
                .join("\n"),
            BatchOutputFormat::Csv => self.results_to_csv(results)?,
            BatchOutputFormat::Tsv => self.results_to_tsv(results)?,
        };

        tokio::fs::write(output_path, content).await?;
        Ok(())
    }

    fn results_to_csv(&self, results: &[BatchResult]) -> Result<String> {
        let mut wtr = csv::Writer::from_writer(vec![]);

        // Write header
        wtr.write_record([
            "id",
            "input",
            "output",
            "error",
            "duration_ms",
            "tokens_generated",
            "timestamp",
        ])?;

        // Write data
        for result in results {
            wtr.write_record([
                &result.id,
                &result.input,
                result.output.as_deref().unwrap_or(""),
                result.error.as_deref().unwrap_or(""),
                &result.duration_ms.to_string(),
                &result
                    .tokens_generated
                    .map(|t| t.to_string())
                    .unwrap_or_default(),
                &result.timestamp.to_rfc3339(),
            ])?;
        }

        let data = String::from_utf8(wtr.into_inner()?)?;
        Ok(data)
    }

    fn results_to_tsv(&self, results: &[BatchResult]) -> Result<String> {
        let mut wtr = csv::WriterBuilder::new()
            .delimiter(b'\t')
            .from_writer(vec![]);

        // Write header
        wtr.write_record([
            "id",
            "input",
            "output",
            "error",
            "duration_ms",
            "tokens_generated",
            "timestamp",
        ])?;

        // Write data
        for result in results {
            wtr.write_record([
                &result.id,
                &result.input,
                result.output.as_deref().unwrap_or(""),
                result.error.as_deref().unwrap_or(""),
                &result.duration_ms.to_string(),
                &result
                    .tokens_generated
                    .map(|t| t.to_string())
                    .unwrap_or_default(),
                &result.timestamp.to_rfc3339(),
            ])?;
        }

        let data = String::from_utf8(wtr.into_inner()?)?;
        Ok(data)
    }
}