car-scheduler 0.25.0

Task scheduling and background execution for Common Agent Runtime
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
//! Task executor — runs tasks using the AgentRunner callback.
//!
//! Handles trigger types: once, interval, file watch, cron.
//! Each execution creates a TaskExecution record.

use crate::task::{parse_interval, Task, TaskExecution, TaskStatus, TaskTrigger};
use car_multi::{AgentRunner, AgentSpec, Mailbox, SharedInfra};
use chrono::{DateTime, Utc};
use std::sync::Arc;
use tokio::sync::watch;
use tracing::{info, warn};

/// Runs tasks through the AgentRunner.
pub struct Executor {
    runner: Arc<dyn AgentRunner>,
    infra: SharedInfra,
}

impl Executor {
    pub fn new(runner: Arc<dyn AgentRunner>) -> Self {
        Self {
            runner,
            infra: SharedInfra::new(),
        }
    }

    pub fn with_shared_infra(runner: Arc<dyn AgentRunner>, infra: SharedInfra) -> Self {
        Self { runner, infra }
    }

    /// Execute a task once and return the execution record.
    pub async fn run_once(&self, task: &mut Task) -> TaskExecution {
        self.run_occurrence(task, None).await
    }

    /// Run one occurrence of a task. `file_hash` is the triggering content
    /// hash for `FileWatch` tasks and `None` otherwise.
    ///
    /// Idempotent per occurrence: the run is identified by a deterministic
    /// `occurrence_id` derived from `(task, trigger, slot)`. If that occurrence
    /// has already completed (or is running), the prior record is returned
    /// without re-invoking the runner — so a restart-replayed slot, an
    /// overlapping loop, or a re-fired `Once` task does not run twice. A
    /// *failed* occurrence is not deduped, so it can be retried, and `Manual`
    /// runs are never deduped (an intentional repeat keeps a fresh id).
    async fn run_occurrence(&self, task: &mut Task, file_hash: Option<u64>) -> TaskExecution {
        let started_at = Utc::now();
        let occurrence = occurrence_id(task, file_hash, started_at);

        if let Some(ref id) = occurrence {
            if let Some(existing) = task.executions.iter().find(|e| {
                &e.execution_id == id
                    && matches!(e.status, TaskStatus::Completed | TaskStatus::Running)
            }) {
                info!(
                    task_id = %task.id,
                    occurrence = %id,
                    "occurrence already serviced; skipping"
                );
                return existing.clone();
            }
        }

        let execution_id =
            occurrence.unwrap_or_else(|| uuid::Uuid::new_v4().to_string()[..10].to_string());

        task.status = TaskStatus::Running;

        let spec = AgentSpec {
            name: task.name.clone(),
            system_prompt: task.system_prompt.clone(),
            tools: Vec::new(),
            max_turns: task.max_turns,
            metadata: task.agent_metadata.clone(),
            cache_control: false,
        };

        let rt = self.infra.make_runtime();
        let mailbox = Mailbox::default();
        let start = std::time::Instant::now();

        let execution = match self.runner.run(&spec, &task.prompt, &rt, &mailbox).await {
            Ok(output) => {
                let duration_ms = start.elapsed().as_secs_f64() * 1000.0;
                info!(
                    task_id = %task.id,
                    task_name = %task.name,
                    duration_ms = duration_ms,
                    "task completed"
                );
                TaskExecution {
                    execution_id,
                    started_at,
                    finished_at: Some(Utc::now()),
                    status: TaskStatus::Completed,
                    answer: output.answer,
                    error: output.error,
                    duration_ms: Some(duration_ms),
                }
            }
            Err(e) => {
                let duration_ms = start.elapsed().as_secs_f64() * 1000.0;
                warn!(
                    task_id = %task.id,
                    task_name = %task.name,
                    error = %e,
                    "task failed"
                );
                TaskExecution {
                    execution_id,
                    started_at,
                    finished_at: Some(Utc::now()),
                    status: TaskStatus::Failed,
                    answer: String::new(),
                    error: Some(e.to_string()),
                    duration_ms: Some(duration_ms),
                }
            }
        };

        task.last_run_at = Some(execution.started_at);
        task.run_count += 1;
        task.status = execution.status;
        task.executions.push(execution.clone());

        execution
    }

    /// Run a task according to its trigger. Respects the cancellation token.
    ///
    /// - Once/Manual: runs once.
    /// - Interval: runs every N seconds until cancelled or max_iterations.
    /// - FileWatch: polls file for changes, runs on change.
    /// - Cron: treated as interval (full cron parsing is out of scope).
    pub async fn run_loop(
        &self,
        task: &mut Task,
        max_iterations: Option<u32>,
        cancel: watch::Receiver<bool>,
    ) -> Vec<TaskExecution> {
        match task.trigger {
            TaskTrigger::Once | TaskTrigger::Manual => {
                vec![self.run_once(task).await]
            }
            TaskTrigger::Interval | TaskTrigger::Cron => {
                self.run_interval(task, max_iterations, cancel).await
            }
            TaskTrigger::FileWatch => self.run_file_watch(task, max_iterations, cancel).await,
        }
    }

    async fn run_interval(
        &self,
        task: &mut Task,
        max_iterations: Option<u32>,
        mut cancel: watch::Receiver<bool>,
    ) -> Vec<TaskExecution> {
        let interval_secs = parse_interval(&task.schedule);
        let interval = tokio::time::Duration::from_secs_f64(interval_secs);
        let mut executions: Vec<TaskExecution> = Vec::new();
        let mut iterations: u32 = 0;

        task.status = TaskStatus::Scheduled;

        loop {
            if !task.enabled {
                break;
            }
            if let Some(max) = max_iterations {
                if iterations >= max {
                    break;
                }
            }

            let exec = self.run_once(task).await;
            if !executions.iter().any(|e| e.execution_id == exec.execution_id) {
                executions.push(exec);
            }
            iterations += 1;

            if let Some(max) = max_iterations {
                if iterations >= max {
                    break;
                }
            }

            // Wait for interval or cancellation
            tokio::select! {
                _ = tokio::time::sleep(interval) => {}
                _ = cancel.changed() => {
                    if *cancel.borrow() {
                        info!(task_id = %task.id, "task cancelled");
                        break;
                    }
                }
            }
        }

        task.status = if task.enabled {
            TaskStatus::Scheduled
        } else {
            TaskStatus::Completed
        };

        executions
    }

    async fn run_file_watch(
        &self,
        task: &mut Task,
        max_iterations: Option<u32>,
        mut cancel: watch::Receiver<bool>,
    ) -> Vec<TaskExecution> {
        let poll_interval = tokio::time::Duration::from_secs(2);
        let mut executions: Vec<TaskExecution> = Vec::new();
        let mut iterations: u32 = 0;
        let mut last_hash = file_hash(&task.watch_path);

        task.status = TaskStatus::Scheduled;

        loop {
            if !task.enabled {
                break;
            }
            if let Some(max) = max_iterations {
                if iterations >= max {
                    break;
                }
            }

            // Wait for poll interval or cancellation
            tokio::select! {
                _ = tokio::time::sleep(poll_interval) => {}
                _ = cancel.changed() => {
                    if *cancel.borrow() {
                        info!(task_id = %task.id, "file watch cancelled");
                        break;
                    }
                }
            }

            let current_hash = file_hash(&task.watch_path);
            if current_hash != last_hash {
                last_hash = current_hash;
                let exec = self.run_occurrence(task, current_hash).await;
                if !executions.iter().any(|e| e.execution_id == exec.execution_id) {
                    executions.push(exec);
                }
                iterations += 1;
            }
        }

        task.status = TaskStatus::Completed;
        executions
    }
}

/// Short tag for a trigger kind, used in the occurrence id.
fn trigger_tag(trigger: TaskTrigger) -> &'static str {
    match trigger {
        TaskTrigger::Once => "once",
        TaskTrigger::Cron => "cron",
        TaskTrigger::Interval => "int",
        TaskTrigger::FileWatch => "file",
        TaskTrigger::Manual => "manual",
    }
}

/// Deterministic id for the occurrence a run is about to service.
///
/// Same occurrence ⇒ same id ⇒ the admission guard in [`Executor::run_occurrence`]
/// collapses duplicates from a restart-replayed slot, an overlapping loop, or
/// (later, once runs sync) another device. A readable composite
/// `"{task_id}:{trigger}:{slot}"` rather than a hash — deterministic and easy to
/// eyeball; opacity can come later if a surface ever needs it.
///
/// `slot` is chosen per trigger so two independent computations of the *same*
/// occurrence agree:
/// - `Interval`/`Cron`: the wall-clock slot index anchored on the task's
///   (stable, persisted) `created_at` — **not** the in-process loop counter,
///   which resets on restart and differs per process/site.
/// - `FileWatch`: the triggering content hash.
/// - `Once`: a constant — a restart-replay is skipped, never re-run.
/// - `Manual`: `None` — a manual invocation is an intentional repeat and keeps
///   a fresh random id.
fn occurrence_id(task: &Task, file_hash: Option<u64>, now: DateTime<Utc>) -> Option<String> {
    let slot = match task.trigger {
        TaskTrigger::Interval | TaskTrigger::Cron => {
            let interval = parse_interval(&task.schedule).max(1.0);
            let elapsed = (now - task.created_at).num_milliseconds().max(0) as f64 / 1000.0;
            ((elapsed / interval).floor() as i64).to_string()
        }
        TaskTrigger::FileWatch => format!("{:016x}", file_hash.unwrap_or(0)),
        TaskTrigger::Once => "0".to_string(),
        TaskTrigger::Manual => return None,
    };
    Some(format!("{}:{}:{}", task.id, trigger_tag(task.trigger), slot))
}

/// Simple file hash for change detection.
fn file_hash(path: &str) -> Option<u64> {
    use std::hash::{Hash, Hasher};
    let data = std::fs::read(path).ok()?;
    let mut hasher = std::collections::hash_map::DefaultHasher::new();
    data.hash(&mut hasher);
    Some(hasher.finish())
}

/// Handle for a background task. Send `true` to cancel.
pub struct TaskHandle {
    pub task_id: String,
    pub cancel_tx: watch::Sender<bool>,
    pub join: tokio::task::JoinHandle<Vec<TaskExecution>>,
}

impl TaskHandle {
    /// Cancel the running task.
    pub fn cancel(&self) {
        let _ = self.cancel_tx.send(true);
    }
}

/// Spawn a task to run in the background. Returns a handle for cancellation.
pub fn spawn_task(
    mut task: Task,
    runner: Arc<dyn AgentRunner>,
    max_iterations: Option<u32>,
) -> TaskHandle {
    let (cancel_tx, cancel_rx) = watch::channel(false);
    let task_id = task.id.clone();

    let join = tokio::spawn(async move {
        let executor = Executor::new(runner);
        executor
            .run_loop(&mut task, max_iterations, cancel_rx)
            .await
    });

    TaskHandle {
        task_id,
        cancel_tx,
        join,
    }
}

/// Spawn a task with shared infrastructure. Returns a handle for cancellation.
pub fn spawn_task_shared(
    mut task: Task,
    runner: Arc<dyn AgentRunner>,
    infra: SharedInfra,
    max_iterations: Option<u32>,
) -> TaskHandle {
    let (cancel_tx, cancel_rx) = watch::channel(false);
    let task_id = task.id.clone();

    let join = tokio::spawn(async move {
        let executor = Executor::with_shared_infra(runner, infra);
        executor
            .run_loop(&mut task, max_iterations, cancel_rx)
            .await
    });

    TaskHandle {
        task_id,
        cancel_tx,
        join,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use car_engine::Runtime;
    use car_multi::{AgentOutput, AgentRunner, Mailbox, MultiError};

    struct MockRunner;

    #[async_trait::async_trait]
    impl AgentRunner for MockRunner {
        async fn run(
            &self,
            spec: &AgentSpec,
            task: &str,
            _runtime: &Runtime,
            _mailbox: &Mailbox,
        ) -> Result<AgentOutput, MultiError> {
            Ok(AgentOutput {
                name: spec.name.clone(),
                answer: format!("completed: {}", &task[..task.len().min(50)]),
                turns: 1,
                tool_calls: 0,
                duration_ms: 10.0,
                error: None,
                outcome: None,
                tokens: None,
                tools_used: Vec::new(),
            })
        }
    }

    struct FailRunner;

    #[async_trait::async_trait]
    impl AgentRunner for FailRunner {
        async fn run(
            &self,
            _spec: &AgentSpec,
            _task: &str,
            _runtime: &Runtime,
            _mailbox: &Mailbox,
        ) -> Result<AgentOutput, MultiError> {
            Err(MultiError::AgentFailed(
                "flaky".to_string(),
                "boom".to_string(),
            ))
        }
    }

    #[tokio::test]
    async fn test_run_once() {
        let runner: Arc<dyn AgentRunner> = Arc::new(MockRunner);
        let executor = Executor::new(runner);
        let mut task = Task::new("test", "do something");

        let execution = executor.run_once(&mut task).await;

        assert_eq!(execution.status, TaskStatus::Completed);
        assert!(execution.answer.contains("completed"));
        assert_eq!(task.run_count, 1);
        assert!(task.last_run_at.is_some());
    }

    #[tokio::test]
    async fn test_interval_same_slot_dedups() {
        let runner: Arc<dyn AgentRunner> = Arc::new(MockRunner);
        let executor = Executor::new(runner);
        // A 1h interval: two rapid runs land in the same slot 0 (elapsed since
        // created_at ≈ 0), so they share one occurrence id and the second is
        // deduped. Driven directly rather than through run_loop, which would
        // sleep the full interval between iterations.
        let mut task =
            Task::new("interval_test", "repeat this").with_trigger(TaskTrigger::Interval, "1h");

        let a = executor.run_once(&mut task).await;
        let b = executor.run_once(&mut task).await; // same slot ⇒ deduped

        assert_eq!(a.execution_id, b.execution_id);
        assert_eq!(task.run_count, 1, "same slot dedups to one execution");
        assert_eq!(task.executions.len(), 1);
    }

    #[test]
    fn test_occurrence_id_interval_slot_stable_across_now() {
        let mut task = Task::new("t", "p").with_trigger(TaskTrigger::Interval, "60");
        let anchor = task.created_at;
        // Two computations in the same 60s slot agree; the next slot differs.
        let a = occurrence_id(&task, None, anchor + chrono::Duration::seconds(10)).unwrap();
        let b = occurrence_id(&task, None, anchor + chrono::Duration::seconds(50)).unwrap();
        let c = occurrence_id(&task, None, anchor + chrono::Duration::seconds(70)).unwrap();
        assert_eq!(a, b, "same slot ⇒ same id regardless of when in the slot");
        assert_ne!(a, c, "next slot ⇒ new id");
        assert!(a.ends_with(":int:0"));
        assert!(c.ends_with(":int:1"));
        // Cron shares the interval slotting.
        task.trigger = TaskTrigger::Cron;
        assert!(occurrence_id(&task, None, anchor)
            .unwrap()
            .contains(":cron:"));
    }

    #[test]
    fn test_occurrence_id_once_is_stable() {
        let task = Task::new("t", "p").with_trigger(TaskTrigger::Once, "");
        let a = occurrence_id(&task, None, task.created_at).unwrap();
        let b = occurrence_id(&task, None, task.created_at + chrono::Duration::days(3)).unwrap();
        assert_eq!(a, b, "Once is a single occurrence regardless of wall time");
    }

    #[test]
    fn test_occurrence_id_manual_is_none() {
        let task = Task::new("t", "p"); // default trigger is Manual
        assert!(occurrence_id(&task, None, task.created_at).is_none());
    }

    #[test]
    fn test_occurrence_id_filewatch_keys_on_hash() {
        let task = Task::new("t", "p").with_file_watch("/tmp/x");
        let now = task.created_at;
        let h1 = occurrence_id(&task, Some(0xABCD), now).unwrap();
        let h1_again = occurrence_id(&task, Some(0xABCD), now).unwrap();
        let h2 = occurrence_id(&task, Some(0x1234), now).unwrap();
        assert_eq!(h1, h1_again, "same change ⇒ same id");
        assert_ne!(h1, h2, "different change ⇒ different id");
    }

    #[tokio::test]
    async fn test_once_does_not_refire() {
        let runner: Arc<dyn AgentRunner> = Arc::new(MockRunner);
        let executor = Executor::new(runner);
        let mut task = Task::new("once_task", "do it once").with_trigger(TaskTrigger::Once, "");

        let first = executor.run_once(&mut task).await;
        let second = executor.run_once(&mut task).await; // simulates a restart-replay

        assert_eq!(first.execution_id, second.execution_id);
        assert_eq!(task.run_count, 1, "the second call is deduped, not re-run");
        assert_eq!(task.executions.len(), 1);
    }

    #[tokio::test]
    async fn test_failed_occurrence_can_retry() {
        let runner: Arc<dyn AgentRunner> = Arc::new(FailRunner);
        let executor = Executor::new(runner);
        let mut task = Task::new("flaky", "try it").with_trigger(TaskTrigger::Once, "");

        executor.run_once(&mut task).await;
        executor.run_once(&mut task).await;

        // A failed occurrence is not deduped — both attempts ran.
        assert_eq!(task.run_count, 2);
        assert!(task
            .executions
            .iter()
            .all(|e| e.status == TaskStatus::Failed));
    }

    #[tokio::test]
    async fn test_manual_runs_are_not_deduped() {
        let runner: Arc<dyn AgentRunner> = Arc::new(MockRunner);
        let executor = Executor::new(runner);
        let mut task = Task::new("manual", "again and again"); // Manual

        let a = executor.run_once(&mut task).await;
        let b = executor.run_once(&mut task).await;

        assert_ne!(a.execution_id, b.execution_id, "manual repeats stay distinct");
        assert_eq!(task.run_count, 2);
    }

    #[tokio::test]
    async fn test_spawn_and_cancel() {
        let runner: Arc<dyn AgentRunner> = Arc::new(MockRunner);
        let task = Task::new("bg_task", "background work").with_trigger(TaskTrigger::Interval, "0");

        let handle = spawn_task(task, runner, None);

        // Let it run a couple iterations
        tokio::time::sleep(tokio::time::Duration::from_millis(50)).await;

        // Cancel it
        handle.cancel();
        let executions = handle.join.await.unwrap();

        assert!(!executions.is_empty());
    }

    #[tokio::test]
    async fn test_file_watch() {
        let dir = tempfile::TempDir::new().unwrap();
        let watch_file = dir.path().join("watched.txt");
        std::fs::write(&watch_file, "v1").unwrap();

        let runner: Arc<dyn AgentRunner> = Arc::new(MockRunner);
        let executor = Executor::new(runner);
        let mut task = Task::new("watcher", "process file change")
            .with_file_watch(watch_file.to_str().unwrap());

        let (cancel_tx, cancel_rx) = watch::channel(false);

        // Spawn file watch in background
        let watch_path = watch_file.clone();
        let cancel_tx_clone = cancel_tx.clone();
        tokio::spawn(async move {
            tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;
            std::fs::write(&watch_path, "v2").unwrap();
            tokio::time::sleep(tokio::time::Duration::from_millis(3000)).await;
            let _ = cancel_tx_clone.send(true);
        });

        let executions = executor.run_loop(&mut task, Some(1), cancel_rx).await;

        assert_eq!(executions.len(), 1);
        assert!(executions[0].answer.contains("completed"));
    }
}