agnosai 1.1.0

Provider-agnostic AI orchestration framework
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
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
//! Crew fan-out, result aggregation, and failover.

use std::collections::HashMap;

use uuid::Uuid;

use super::registry::NodeId;
use super::state::{CrewRunId, CrewStateManager};

/// A task managed by the fleet coordinator.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct FleetTask {
    pub task_id: Uuid,
    pub description: String,
    pub assigned_node: Option<NodeId>,
    pub status: FleetTaskStatus,
}

/// Status of a fleet task.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum FleetTaskStatus {
    Pending,
    Assigned,
    Running,
    Completed,
    Failed,
    /// Failed on one node and eligible for reassignment.
    Reassigned,
}

/// Action to take after a task failure.
#[derive(Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum FailoverAction {
    /// Task can be retried on another node.
    Retry,
    /// Maximum retries exhausted.
    Exhausted,
    /// Task ID not found.
    UnknownTask,
}

/// Maximum number of completed tasks retained in the coordinator.
const MAX_RETAINED_TASKS: usize = 10_000;

/// Coordinates fan-out, tracking, and failover for fleet tasks.
pub struct FleetCoordinator {
    state_manager: CrewStateManager,
    tasks: HashMap<Uuid, FleetTask>,
    max_retries: usize,
    retry_counts: HashMap<Uuid, usize>,
}

impl FleetCoordinator {
    pub fn new() -> Self {
        Self {
            state_manager: CrewStateManager::new(),
            tasks: HashMap::new(),
            max_retries: 3,
            retry_counts: HashMap::new(),
        }
    }

    pub fn with_max_retries(max_retries: usize) -> Self {
        Self {
            state_manager: CrewStateManager::new(),
            tasks: HashMap::new(),
            max_retries,
            retry_counts: HashMap::new(),
        }
    }

    /// Fan out tasks to nodes based on pre-computed placement assignments.
    ///
    /// Creates a crew run in the state manager and registers all tasks with their
    /// assigned nodes. Returns the run ID.
    /// Evict completed/failed tasks when at capacity.
    fn evict_completed_tasks(&mut self) {
        if self.tasks.len() >= MAX_RETAINED_TASKS {
            let to_remove: Vec<Uuid> = self
                .tasks
                .iter()
                .filter(|(_, t)| {
                    matches!(
                        t.status,
                        FleetTaskStatus::Completed | FleetTaskStatus::Failed
                    )
                })
                .map(|(&id, _)| id)
                .collect();
            for id in to_remove {
                self.tasks.remove(&id);
                self.retry_counts.remove(&id);
            }
        }
    }

    /// Fan out tasks to nodes based on pre-computed placement assignments.
    ///
    /// Creates a crew run in the state manager and registers all tasks with their
    /// assigned nodes. Returns the run ID.
    pub fn fan_out(
        &mut self,
        tasks: Vec<(Uuid, String)>,
        assignments: Vec<(Uuid, NodeId)>,
    ) -> CrewRunId {
        self.evict_completed_tasks();
        // Build lookup from task_id -> node_id.
        let assignment_map: HashMap<Uuid, NodeId> = assignments.into_iter().collect();

        // Collect unique nodes and count tasks per node for the state manager.
        let mut nodes = std::collections::HashSet::new();
        let mut tasks_per_node: HashMap<NodeId, usize> = HashMap::new();

        for (task_id, description) in &tasks {
            let node = assignment_map.get(task_id).cloned();
            if let Some(ref n) = node {
                nodes.insert(n.clone());
                *tasks_per_node.entry(n.clone()).or_insert(0) += 1;
            }

            self.tasks.insert(
                *task_id,
                FleetTask {
                    task_id: *task_id,
                    description: description.clone(),
                    assigned_node: node,
                    status: if assignment_map.contains_key(task_id) {
                        FleetTaskStatus::Assigned
                    } else {
                        FleetTaskStatus::Pending
                    },
                },
            );
        }

        // Use the max tasks-per-node value so every node gets a slot in the state
        // manager (the state manager uses a uniform count).
        let max_tasks = tasks_per_node.values().copied().max().unwrap_or(0);
        self.state_manager.create_run(nodes, max_tasks)
    }

    /// Report a task as completed. Returns `true` if the task was found and updated.
    pub fn task_completed(&mut self, task_id: Uuid) -> bool {
        let Some(task) = self.tasks.get_mut(&task_id) else {
            return false;
        };
        task.status = FleetTaskStatus::Completed;
        true
    }

    /// Report a task as failed. If retries remain, marks the task as `Reassigned`
    /// and returns `Retry`. Otherwise returns `Exhausted`.
    pub fn task_failed(&mut self, task_id: Uuid) -> FailoverAction {
        let Some(task) = self.tasks.get_mut(&task_id) else {
            return FailoverAction::UnknownTask;
        };

        let count = self.retry_counts.entry(task_id).or_insert(0);
        *count += 1;

        if *count < self.max_retries {
            task.status = FleetTaskStatus::Reassigned;
            FailoverAction::Retry
        } else {
            task.status = FleetTaskStatus::Failed;
            FailoverAction::Exhausted
        }
    }

    /// Get all tasks assigned to a specific node.
    #[must_use]
    pub fn tasks_for_node(&self, node_id: NodeId) -> Vec<&FleetTask> {
        self.tasks
            .values()
            .filter(|t| t.assigned_node.as_ref() == Some(&node_id))
            .collect()
    }

    /// Returns `true` when every task is either `Completed` or terminally `Failed`.
    #[must_use]
    pub fn is_complete(&self) -> bool {
        if self.tasks.is_empty() {
            return true;
        }
        self.tasks.values().all(|t| {
            matches!(
                t.status,
                FleetTaskStatus::Completed | FleetTaskStatus::Failed
            )
        })
    }

    /// Fraction of tasks that are completed (0.0–1.0).
    #[must_use]
    pub fn completion_pct(&self) -> f64 {
        if self.tasks.is_empty() {
            return 1.0;
        }
        let completed = self
            .tasks
            .values()
            .filter(|t| t.status == FleetTaskStatus::Completed)
            .count();
        completed as f64 / self.tasks.len() as f64
    }

    /// List tasks that have been marked `Reassigned` (failed but retriable).
    #[must_use]
    pub fn pending_reassignment(&self) -> Vec<&FleetTask> {
        self.tasks
            .values()
            .filter(|t| t.status == FleetTaskStatus::Reassigned)
            .collect()
    }

    /// Reassign a task to a new node. Returns `true` if the task was found
    /// and successfully reassigned.
    pub fn reassign(&mut self, task_id: Uuid, new_node: NodeId) -> bool {
        let Some(task) = self.tasks.get_mut(&task_id) else {
            return false;
        };
        task.assigned_node = Some(new_node);
        task.status = FleetTaskStatus::Assigned;
        true
    }

    /// Read-only access to the underlying state manager.
    #[must_use]
    pub fn state_manager(&self) -> &CrewStateManager {
        &self.state_manager
    }

    /// Plan how to distribute a model across available devices.
    ///
    /// Uses `ai-hwaccel`'s sharding planner to determine the optimal strategy
    /// (pipeline parallel, tensor parallel, or no sharding) based on model size,
    /// quantization level, and available hardware.
    ///
    /// # Arguments
    /// * `model_params` — approximate parameter count (e.g. 70_000_000_000 for 70B)
    /// * `quant` — quantization level to use
    /// * `registry` — detected hardware
    ///
    /// Returns a `ShardingPlan` describing how to split the model.
    #[cfg(feature = "hwaccel")]
    pub fn plan_sharding(
        model_params: u64,
        quant: &ai_hwaccel::QuantizationLevel,
        registry: &ai_hwaccel::AcceleratorRegistry,
    ) -> ai_hwaccel::ShardingPlan {
        registry.plan_sharding(model_params, quant)
    }
}

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

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

    fn make_tasks(n: usize) -> Vec<(Uuid, String)> {
        (0..n)
            .map(|i| (Uuid::new_v4(), format!("task-{i}")))
            .collect()
    }

    #[test]
    fn fan_out_creates_tasks_with_assignments() {
        let mut coord = FleetCoordinator::new();
        let tasks = make_tasks(3);
        let assignments: Vec<(Uuid, NodeId)> = vec![
            (tasks[0].0, "node-a".into()),
            (tasks[1].0, "node-b".into()),
            (tasks[2].0, "node-a".into()),
        ];

        let _run_id = coord.fan_out(tasks.clone(), assignments);

        assert_eq!(coord.tasks.len(), 3);
        for (id, _) in &tasks {
            let t = coord.tasks.get(id).unwrap();
            assert_eq!(t.status, FleetTaskStatus::Assigned);
            assert!(t.assigned_node.is_some());
        }
    }

    #[test]
    fn task_completed_transitions() {
        let mut coord = FleetCoordinator::new();
        let tasks = make_tasks(1);
        let assignments = vec![(tasks[0].0, "n".into())];
        coord.fan_out(tasks.clone(), assignments);

        assert!(coord.task_completed(tasks[0].0));
        assert_eq!(coord.tasks[&tasks[0].0].status, FleetTaskStatus::Completed);
    }

    #[test]
    fn task_completed_unknown() {
        let mut coord = FleetCoordinator::new();
        assert!(!coord.task_completed(Uuid::new_v4()));
    }

    #[test]
    fn task_failed_with_retries_returns_retry() {
        let mut coord = FleetCoordinator::with_max_retries(3);
        let tasks = make_tasks(1);
        coord.fan_out(tasks.clone(), vec![(tasks[0].0, "n".into())]);

        assert_eq!(coord.task_failed(tasks[0].0), FailoverAction::Retry);
        assert_eq!(coord.tasks[&tasks[0].0].status, FleetTaskStatus::Reassigned);
    }

    #[test]
    fn task_failed_exhausted_after_max_retries() {
        let mut coord = FleetCoordinator::with_max_retries(2);
        let tasks = make_tasks(1);
        coord.fan_out(tasks.clone(), vec![(tasks[0].0, "n".into())]);

        assert_eq!(coord.task_failed(tasks[0].0), FailoverAction::Retry);
        assert_eq!(coord.task_failed(tasks[0].0), FailoverAction::Exhausted);
        assert_eq!(coord.tasks[&tasks[0].0].status, FleetTaskStatus::Failed);
    }

    #[test]
    fn task_failed_unknown() {
        let mut coord = FleetCoordinator::new();
        assert_eq!(
            coord.task_failed(Uuid::new_v4()),
            FailoverAction::UnknownTask
        );
    }

    #[test]
    fn tasks_for_node_filters() {
        let mut coord = FleetCoordinator::new();
        let tasks = make_tasks(3);
        let assignments = vec![
            (tasks[0].0, "a".into()),
            (tasks[1].0, "b".into()),
            (tasks[2].0, "a".into()),
        ];
        coord.fan_out(tasks.clone(), assignments);

        let a_tasks = coord.tasks_for_node("a".into());
        assert_eq!(a_tasks.len(), 2);

        let b_tasks = coord.tasks_for_node("b".into());
        assert_eq!(b_tasks.len(), 1);

        let c_tasks = coord.tasks_for_node("c".into());
        assert_eq!(c_tasks.len(), 0);
    }

    #[test]
    fn is_complete_all_done() {
        let mut coord = FleetCoordinator::new();
        let tasks = make_tasks(2);
        coord.fan_out(
            tasks.clone(),
            vec![(tasks[0].0, "n".into()), (tasks[1].0, "n".into())],
        );

        assert!(!coord.is_complete());

        coord.task_completed(tasks[0].0);
        assert!(!coord.is_complete());

        coord.task_completed(tasks[1].0);
        assert!(coord.is_complete());
    }

    #[test]
    fn is_complete_with_terminal_failure() {
        let mut coord = FleetCoordinator::with_max_retries(1);
        let tasks = make_tasks(2);
        coord.fan_out(
            tasks.clone(),
            vec![(tasks[0].0, "n".into()), (tasks[1].0, "n".into())],
        );

        coord.task_completed(tasks[0].0);
        coord.task_failed(tasks[1].0); // exhausted (max_retries=1)
        assert!(coord.is_complete());
    }

    #[test]
    fn completion_pct_calculation() {
        let mut coord = FleetCoordinator::new();
        let tasks = make_tasks(4);
        let assignments: Vec<(Uuid, NodeId)> =
            tasks.iter().map(|(id, _)| (*id, "n".into())).collect();
        coord.fan_out(tasks.clone(), assignments);

        assert!((coord.completion_pct() - 0.0).abs() < 1e-9);

        coord.task_completed(tasks[0].0);
        assert!((coord.completion_pct() - 0.25).abs() < 1e-9);

        coord.task_completed(tasks[1].0);
        coord.task_completed(tasks[2].0);
        coord.task_completed(tasks[3].0);
        assert!((coord.completion_pct() - 1.0).abs() < 1e-9);
    }

    #[test]
    fn pending_reassignment_lists_retriable() {
        let mut coord = FleetCoordinator::with_max_retries(3);
        let tasks = make_tasks(3);
        coord.fan_out(
            tasks.clone(),
            vec![
                (tasks[0].0, "n".into()),
                (tasks[1].0, "n".into()),
                (tasks[2].0, "n".into()),
            ],
        );

        coord.task_failed(tasks[0].0); // Reassigned
        coord.task_completed(tasks[1].0);
        // tasks[2] still Assigned

        let pending = coord.pending_reassignment();
        assert_eq!(pending.len(), 1);
        assert_eq!(pending[0].task_id, tasks[0].0);
    }

    #[test]
    fn reassign_moves_task() {
        let mut coord = FleetCoordinator::with_max_retries(3);
        let tasks = make_tasks(1);
        coord.fan_out(tasks.clone(), vec![(tasks[0].0, "old".into())]);

        coord.task_failed(tasks[0].0);
        assert!(coord.reassign(tasks[0].0, "new".into()));

        let t = &coord.tasks[&tasks[0].0];
        assert_eq!(t.assigned_node.as_deref(), Some("new"));
        assert_eq!(t.status, FleetTaskStatus::Assigned);
    }

    #[test]
    fn reassign_unknown_task() {
        let mut coord = FleetCoordinator::new();
        assert!(!coord.reassign(Uuid::new_v4(), "n".into()));
    }

    #[test]
    fn state_manager_accessible() {
        let coord = FleetCoordinator::new();
        // Just verify we can access it without panic.
        let _sm = coord.state_manager();
    }

    #[cfg(feature = "hwaccel")]
    mod hwaccel_tests {
        use super::super::*;
        use ai_hwaccel::{AcceleratorProfile, AcceleratorRegistry, QuantizationLevel};

        #[test]
        fn plan_sharding_single_gpu_no_shard() {
            // 7B model at FP16 (~14GB) on a single 80GB GPU — should not shard.
            let registry = AcceleratorRegistry::from_profiles(vec![
                AcceleratorProfile::cpu(64 * 1024 * 1024 * 1024),
                AcceleratorProfile::cuda(0, 80 * 1024 * 1024 * 1024),
            ]);
            let plan = FleetCoordinator::plan_sharding(
                7_000_000_000,
                &QuantizationLevel::Float16,
                &registry,
            );
            assert!(
                plan.shards().len() <= 1,
                "7B FP16 on 80GB should not need sharding, got {} shards",
                plan.shards().len()
            );
        }

        #[test]
        fn plan_sharding_multi_gpu_large_model() {
            // 70B model at FP16 (~140GB) on 2x 80GB GPUs — should shard.
            let registry = AcceleratorRegistry::from_profiles(vec![
                AcceleratorProfile::cpu(128 * 1024 * 1024 * 1024),
                AcceleratorProfile::cuda(0, 80 * 1024 * 1024 * 1024),
                AcceleratorProfile::cuda(1, 80 * 1024 * 1024 * 1024),
            ]);
            let plan = FleetCoordinator::plan_sharding(
                70_000_000_000,
                &QuantizationLevel::Float16,
                &registry,
            );
            assert!(
                plan.shards().len() >= 2,
                "70B FP16 on 2x80GB should shard across devices, got {} shards",
                plan.shards().len()
            );
            assert!(
                plan.total_memory_bytes > 0,
                "plan should report memory usage"
            );
        }

        #[test]
        fn plan_sharding_quantized_fits_single() {
            // 70B model at INT4 (~35GB) on single 80GB GPU — may fit without sharding.
            let registry = AcceleratorRegistry::from_profiles(vec![
                AcceleratorProfile::cpu(64 * 1024 * 1024 * 1024),
                AcceleratorProfile::cuda(0, 80 * 1024 * 1024 * 1024),
            ]);
            let plan = FleetCoordinator::plan_sharding(
                70_000_000_000,
                &QuantizationLevel::Int4,
                &registry,
            );
            // INT4 70B ≈ 35GB, fits in 80GB.
            assert!(
                plan.shards().len() <= 1,
                "70B INT4 on 80GB should fit without sharding, got {} shards",
                plan.shards().len()
            );
        }
    }
}