righvalor 0.1.0

RighValor: AI Infrastructure and Applications Framework for the Far Edge
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
use std::{collections::HashMap, sync::Arc};

use tokio::sync::RwLock;
use tracing::{info, warn};

use crate::{
    common::task::{
        ValorMasterTask, ValorTaskError, ValorTaskId, ValorTaskOutput, ValorTaskStatus,
    },
    types::ValorID,
};

/// Task manager for Valor Master
///
/// Manages the lifecycle of computational tasks, including creation,
/// assignment, status tracking, and completion.
pub struct ValorTaskManager {
    /// All tasks indexed by task_id
    tasks: RwLock<HashMap<ValorTaskId, ValorMasterTask>>,
    /// Tasks by status for efficient querying
    tasks_by_status: RwLock<HashMap<ValorTaskStatus, Vec<ValorTaskId>>>,
    /// Tasks assigned to workers
    tasks_by_worker: RwLock<HashMap<ValorID, Vec<ValorTaskId>>>,
    /// Optional result aggregator for terminal notifications
    result_aggregator: RwLock<Option<Arc<crate::master::ValorResultAggregator>>>,
    /// Watchdog tasks for timeouts
    timeout_watchdogs: RwLock<HashMap<ValorTaskId, tokio::task::JoinHandle<()>>>,
}

impl ValorTaskManager {
    /// Create a new task manager
    pub fn new() -> Self {
        Self {
            tasks: RwLock::new(HashMap::new()),
            tasks_by_status: RwLock::new(HashMap::new()),
            tasks_by_worker: RwLock::new(HashMap::new()),
            result_aggregator: RwLock::new(None),
            timeout_watchdogs: RwLock::new(HashMap::new()),
        }
    }

    /// Inject a result aggregator
    pub async fn set_result_aggregator(
        &self,
        aggregator: Arc<crate::master::ValorResultAggregator>,
    ) {
        let mut slot = self.result_aggregator.write().await;
        *slot = Some(aggregator);
    }

    /// Add a new task to the manager
    pub async fn create_task(&self, mut task: ValorMasterTask) -> Result<ValorTaskId, String> {
        let task_id = task.task_id.clone();

        // Ensure task starts in pending state
        task.status = ValorTaskStatus::Pending;
        task.created_at = current_timestamp_ms();
        task.attempt = 0;

        let mut tasks = self.tasks.write().await;
        if tasks.contains_key(&task_id) {
            return Err(format!("Task {task_id} already exists"));
        }

        tasks.insert(task_id.clone(), task.clone());
        drop(tasks);

        // Observability: task creation
        let svc_id = match &task.task_type {
            crate::common::task::ValorTaskType::ExecuteService { service_id, .. } => service_id,
        };
        tracing::info!(
            task_id = %task_id,
            service_id = %svc_id,
            priority = ?task.priority,
            "Task created (pending)"
        );

        // Update status index
        let mut by_status = self.tasks_by_status.write().await;
        by_status
            .entry(ValorTaskStatus::Pending)
            .or_insert_with(Vec::new)
            .push(task_id.clone());
        drop(by_status);

        Ok(task_id)
    }

    /// Spawn timeout watchdog for a task if it has timeout. Requires Arc<Self> receiver.
    pub async fn maybe_spawn_watchdog(self: &Arc<Self>, task_id: &ValorTaskId) {
        let timeout_ms = if let Some(task) = self.get_task(task_id).await {
            task.timeout_ms
        } else {
            None
        };
        if let Some(ms) = timeout_ms {
            // Deduplicate existing watchdog
            if self.timeout_watchdogs.read().await.contains_key(task_id) {
                return;
            }
            let id = task_id.clone();
            let mgr = Arc::clone(self);
            let handle = tokio::spawn(async move {
                let dur = std::time::Duration::from_millis(ms);
                tokio::time::sleep(dur).await;
                // After sleep, if task is still non-terminal, mark timeout
                if let Some(task) = mgr.get_task(&id).await {
                    use crate::common::task::ValorTaskStatus::*;
                    if !matches!(task.status, Completed | Failed | Cancelled) {
                        let _ = mgr.fail_task_timeout(&id, ms).await;
                    }
                }
            });
            self.timeout_watchdogs
                .write()
                .await
                .insert(task_id.clone(), handle);
        }
    }

    /// Mark task as failed due to timeout, regardless of current assignment.
    pub async fn fail_task_timeout(
        &self,
        task_id: &ValorTaskId,
        timeout_ms: u64,
    ) -> Result<(), String> {
        let mut tasks = self.tasks.write().await;
        let task = tasks
            .get_mut(task_id)
            .ok_or_else(|| format!("Task {task_id} not found"))?;
        if matches!(
            task.status,
            ValorTaskStatus::Completed | ValorTaskStatus::Failed | ValorTaskStatus::Cancelled
        ) {
            return Ok(());
        }
        let old_status = task.status;
        task.status = ValorTaskStatus::Failed;
        task.completed_at = Some(current_timestamp_ms());
        task.error = Some(ValorTaskError::Timeout { timeout_ms });
        let snapshot = task.clone();
        drop(tasks);

        self.update_status_index(task_id, old_status, ValorTaskStatus::Failed)
            .await;

        // Cancel watchdog handle
        if let Some(handle) = self.timeout_watchdogs.write().await.remove(task_id) {
            handle.abort();
        }

        if let Some(agg) = self.result_aggregator.read().await.as_ref().cloned() {
            agg.notify_if_terminal(&snapshot).await;
        }
        info!(task_id = %task_id, timeout_ms, "Task timed out and marked as Failed");
        Ok(())
    }

    /// Get a task by ID
    pub async fn get_task(&self, task_id: &ValorTaskId) -> Option<ValorMasterTask> {
        self.tasks.read().await.get(task_id).cloned()
    }

    /// List all tasks
    pub async fn list_tasks(&self) -> Vec<ValorMasterTask> {
        self.tasks.read().await.values().cloned().collect()
    }

    /// List tasks by status
    pub async fn list_tasks_by_status(&self, status: ValorTaskStatus) -> Vec<ValorMasterTask> {
        let by_status = self.tasks_by_status.read().await;
        if let Some(task_ids) = by_status.get(&status) {
            let tasks = self.tasks.read().await;
            task_ids
                .iter()
                .filter_map(|id| tasks.get(id).cloned())
                .collect()
        } else {
            Vec::new()
        }
    }

    /// Assign a task to a worker
    pub async fn assign_task(
        &self,
        task_id: &ValorTaskId,
        worker_id: &ValorID,
    ) -> Result<(), String> {
        // Update under lock, capture data needed for logging outside the lock
        let (svc_id, attempt_count) = {
            let mut tasks = self.tasks.write().await;
            let task = tasks
                .get_mut(task_id)
                .ok_or_else(|| format!("Task {task_id} not found"))?;

            if task.status != ValorTaskStatus::Pending {
                return Err(format!("Task {task_id} is not pending"));
            }

            // Update task
            let service_id = match &task.task_type {
                crate::common::task::ValorTaskType::ExecuteService { service_id, .. } => {
                    service_id.clone()
                }
            };
            task.status = ValorTaskStatus::Assigned;
            task.assigned_worker = Some(worker_id.to_string());
            task.assigned_at = Some(current_timestamp_ms());
            task.attempt = task.attempt.saturating_add(1);
            (service_id, task.attempt)
        };

        // Update indices
        self.update_status_index(task_id, ValorTaskStatus::Pending, ValorTaskStatus::Assigned)
            .await;

        {
            let mut by_worker = self.tasks_by_worker.write().await;
            by_worker
                .entry(worker_id.clone())
                .or_insert_with(Vec::new)
                .push(task_id.clone());
        }

        info!(worker_id = %worker_id, service_id = %svc_id, attempt = attempt_count, "Task assigned");

        Ok(())
    }

    /// Update task status
    pub async fn update_task_status(
        &self,
        task_id: &ValorTaskId,
        worker_id: &ValorID,
        status: ValorTaskStatus,
        output: Option<ValorTaskOutput>,
        error: Option<ValorTaskError>,
    ) -> Result<(), String> {
        let mut tasks = self.tasks.write().await;
        let task = tasks
            .get_mut(task_id)
            .ok_or_else(|| format!("Task {task_id} not found"))?;

        // Verify worker assignment
        if task.assigned_worker.as_ref() != Some(&worker_id.to_string()) {
            return Err(format!(
                "Task {task_id} is not assigned to worker {worker_id}"
            ));
        }

        let old_status = task.status;
        task.status = status;

        // Update completion info
        match status {
            ValorTaskStatus::Completed => {
                task.completed_at = Some(current_timestamp_ms());
                task.output = output;
            }
            ValorTaskStatus::Failed => {
                task.completed_at = Some(current_timestamp_ms());
                task.error = error;
            }
            _ => {}
        }

        // Clone final snapshot before releasing lock for notifications
        let task_snapshot = task.clone();
        drop(tasks);

        // Update status index
        self.update_status_index(task_id, old_status, status).await;

        // Notify waiters if terminal
        if matches!(
            status,
            ValorTaskStatus::Completed | ValorTaskStatus::Failed | ValorTaskStatus::Cancelled
        ) {
            // Cancel and remove timeout watchdog if any
            if let Some(handle) = self.timeout_watchdogs.write().await.remove(task_id) {
                handle.abort();
            }
            if let Some(agg) = self.result_aggregator.read().await.as_ref().cloned() {
                agg.notify_if_terminal(&task_snapshot).await;
            }
        }

        // Observability: status transition
        let _svc_id = match &task_snapshot.task_type {
            crate::common::task::ValorTaskType::ExecuteService { service_id, .. } => service_id,
        };
        let worker_label = task_snapshot
            .assigned_worker
            .as_deref()
            .unwrap_or("<unassigned>");
        info!(worker = worker_label, from = ?old_status, to = ?status, "Task status updated");

        Ok(())
    }

    /// Cancel a task
    pub async fn cancel_task(&self, task_id: &ValorTaskId) -> Result<(), String> {
        let mut tasks = self.tasks.write().await;
        let task = tasks
            .get_mut(task_id)
            .ok_or_else(|| format!("Task {task_id} not found"))?;

        if matches!(
            task.status,
            ValorTaskStatus::Completed | ValorTaskStatus::Failed | ValorTaskStatus::Cancelled
        ) {
            return Err(format!("Task {task_id} is already finished"));
        }

        let old_status = task.status;
        task.status = ValorTaskStatus::Cancelled;
        task.completed_at = Some(current_timestamp_ms());

        let task_snapshot = task.clone();
        drop(tasks);

        // Update status index
        self.update_status_index(task_id, old_status, ValorTaskStatus::Cancelled)
            .await;

        // Cancel and remove timeout watchdog if any
        if let Some(handle) = self.timeout_watchdogs.write().await.remove(task_id) {
            handle.abort();
        }
        // Notify waiters
        if let Some(agg) = self.result_aggregator.read().await.as_ref().cloned() {
            agg.notify_if_terminal(&task_snapshot).await;
        }

        // Observability: cancellation
        let _svc_id = match &task_snapshot.task_type {
            crate::common::task::ValorTaskType::ExecuteService { service_id, .. } => service_id,
        };
        let worker_label = task_snapshot
            .assigned_worker
            .as_deref()
            .unwrap_or("<unassigned>");
        warn!(worker = worker_label, "Task cancelled");

        Ok(())
    }

    /// Requeue tasks assigned to an unreachable worker back to Pending.
    /// Returns number of tasks requeued.
    pub async fn requeue_tasks_for_unreachable_worker(&self, worker_id: &ValorID) -> usize {
        let mut changed = 0usize;
        // Snapshot list of tasks assigned to worker
        let assigned_ids = {
            let by_worker = self.tasks_by_worker.read().await;
            by_worker.get(worker_id).cloned().unwrap_or_default()
        };
        if assigned_ids.is_empty() {
            return 0;
        }
        // For each task, if status is Assigned/Running and still assigned to this worker, move to Pending
        for task_id in &assigned_ids {
            let mut tasks = self.tasks.write().await;
            if let Some(task) = tasks.get_mut(task_id) {
                let still_mine = task
                    .assigned_worker
                    .as_ref()
                    .map(|w| w == &worker_id.to_string())
                    .unwrap_or(false);
                if still_mine
                    && matches!(
                        task.status,
                        ValorTaskStatus::Assigned | ValorTaskStatus::Running
                    )
                {
                    let old_status = task.status;
                    task.status = ValorTaskStatus::Pending;
                    task.assigned_worker = None;
                    task.assigned_at = None;
                    changed += 1;
                    let tid = task.task_id.clone();
                    drop(tasks);
                    self.update_status_index(&tid, old_status, ValorTaskStatus::Pending)
                        .await;
                } else {
                    drop(tasks);
                }
            }
        }
        // Remove these tasks from worker mapping
        let mut by_worker = self.tasks_by_worker.write().await;
        by_worker.remove(worker_id);
        changed
    }

    /// Wait for terminal result of a task. If already terminal, returns immediately.
    pub async fn wait_for_terminal(
        &self,
        task_id: &ValorTaskId,
        timeout_ms: Option<u64>,
    ) -> Result<ValorMasterTask, String> {
        // Fast path: already terminal
        if let Some(current) = self.get_task(task_id).await {
            if matches!(
                current.status,
                ValorTaskStatus::Completed | ValorTaskStatus::Failed | ValorTaskStatus::Cancelled
            ) {
                return Ok(current);
            }
        }

        let agg = self
            .result_aggregator
            .read()
            .await
            .as_ref()
            .cloned()
            .ok_or_else(|| "Result aggregator not configured".to_string())?;

        let rx = agg.register_waiter(task_id).await;
        if let Some(ms) = timeout_ms {
            let dur = std::time::Duration::from_millis(ms);
            match tokio::time::timeout(dur, rx).await {
                Ok(Ok(task)) => Ok(task),
                Ok(Err(_canceled)) => Err("Waiter cancelled".to_string()),
                Err(_elapsed) => Err("Wait timeout".to_string()),
            }
        } else {
            rx.await.map_err(|_| "Waiter cancelled".to_string())
        }
    }

    /// Update status index when task status changes
    async fn update_status_index(
        &self,
        task_id: &ValorTaskId,
        old_status: ValorTaskStatus,
        new_status: ValorTaskStatus,
    ) {
        let mut by_status = self.tasks_by_status.write().await;

        // Remove from old status
        if let Some(ids) = by_status.get_mut(&old_status) {
            ids.retain(|id| id != task_id);
        }

        // Add to new status
        by_status
            .entry(new_status)
            .or_insert_with(Vec::new)
            .push(task_id.clone());
    }

    /// Get task statistics
    pub async fn get_stats(&self) -> TaskStats {
        let by_status = self.tasks_by_status.read().await;

        TaskStats {
            pending: by_status
                .get(&ValorTaskStatus::Pending)
                .map(|v| v.len())
                .unwrap_or(0),
            assigned: by_status
                .get(&ValorTaskStatus::Assigned)
                .map(|v| v.len())
                .unwrap_or(0),
            running: by_status
                .get(&ValorTaskStatus::Running)
                .map(|v| v.len())
                .unwrap_or(0),
            completed: by_status
                .get(&ValorTaskStatus::Completed)
                .map(|v| v.len())
                .unwrap_or(0),
            failed: by_status
                .get(&ValorTaskStatus::Failed)
                .map(|v| v.len())
                .unwrap_or(0),
            cancelled: by_status
                .get(&ValorTaskStatus::Cancelled)
                .map(|v| v.len())
                .unwrap_or(0),
        }
    }
}

/// Task statistics
#[derive(Debug, Clone, Copy)]
pub struct TaskStats {
    pub pending: usize,
    pub assigned: usize,
    pub running: usize,
    pub completed: usize,
    pub failed: usize,
    pub cancelled: usize,
}

impl TaskStats {
    pub fn total(&self) -> usize {
        self.pending + self.assigned + self.running + self.completed + self.failed + self.cancelled
    }
}

fn current_timestamp_ms() -> u64 {
    use std::time::{SystemTime, UNIX_EPOCH};
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap()
        .as_millis() as u64
}