gflow 0.4.14

A lightweight, single-node job scheduler written in Rust.
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
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
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
//! Integration tests for the gflow job scheduler
//!
//! These tests verify end-to-end functionality using a test Scheduler instance
//! with a MockExecutor and temporary state file.

#![allow(deprecated)]

use gflow::core::executor::Executor;
use gflow::core::job::{DependencyIds, Job, JobBuilder, JobState};
use gflow::core::scheduler::{Scheduler, SchedulerBuilder};
use gflow::core::GPUSlot;
use smallvec::smallvec;
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
use std::time::Duration;
use uuid::Uuid;

/// Mock executor for testing that records executed jobs
#[derive(Clone)]
struct MockExecutor {
    executions: Arc<Mutex<Vec<Job>>>,
    should_fail: bool,
}

impl MockExecutor {
    fn new() -> Self {
        Self {
            executions: Arc::new(Mutex::new(Vec::new())),
            should_fail: false,
        }
    }

    #[allow(dead_code)]
    fn with_failure(should_fail: bool) -> Self {
        Self {
            executions: Arc::new(Mutex::new(Vec::new())),
            should_fail,
        }
    }

    fn get_executions(&self) -> Vec<Job> {
        self.executions.lock().unwrap().clone()
    }

    fn execution_count(&self) -> usize {
        self.executions.lock().unwrap().len()
    }

    fn clear(&self) {
        self.executions.lock().unwrap().clear();
    }
}

impl Executor for MockExecutor {
    fn execute(&self, job: &Job) -> anyhow::Result<()> {
        if self.should_fail {
            anyhow::bail!("Mock execution failed")
        } else {
            self.executions.lock().unwrap().push(job.clone());
            Ok(())
        }
    }
}

/// Helper function to create a test scheduler with mock executor
fn create_test_scheduler() -> (Scheduler, MockExecutor) {
    let executor = MockExecutor::new();
    let executor_clone = executor.clone();

    // Create GPU slots
    let mut gpu_slots = HashMap::new();
    gpu_slots.insert(
        "GPU-0".to_string(),
        GPUSlot {
            index: 0,
            available: true,
            total_memory_mb: None,
            reason: None,
        },
    );
    gpu_slots.insert(
        "GPU-1".to_string(),
        GPUSlot {
            index: 1,
            available: true,
            total_memory_mb: None,
            reason: None,
        },
    );

    let scheduler = SchedulerBuilder::new()
        .with_executor(Box::new(executor))
        .with_state_path(PathBuf::from("/tmp/test_scheduler.json"))
        .with_total_memory_mb(8192) // 8GB
        .with_gpu_slots(gpu_slots)
        .build();

    (scheduler, executor_clone)
}

/// Helper function to create a basic test job
fn create_test_job(username: &str) -> Job {
    JobBuilder::new()
        .submitted_by(username.to_string())
        .run_dir("/tmp")
        .command("echo test")
        .build()
}

// ============================================================================
// Job Submission and Queuing Tests
// ============================================================================

#[test]
fn test_job_submission_and_queuing() {
    let (mut scheduler, _) = create_test_scheduler();

    // Submit first job
    let job1 = create_test_job("alice");
    let (job_id1, run_name1) = scheduler.submit_job(job1);
    assert_eq!(job_id1, 1);
    assert_eq!(run_name1, "gjob-1");
    assert!(scheduler.job_exists(1));
    assert_eq!(scheduler.get_job(1).unwrap().state, JobState::Queued);

    // Submit second job
    let job2 = create_test_job("bob");
    let (job_id2, run_name2) = scheduler.submit_job(job2);
    assert_eq!(job_id2, 2);
    assert_eq!(run_name2, "gjob-2");
    assert!(scheduler.job_exists(2));
    assert_eq!(scheduler.get_job(2).unwrap().state, JobState::Queued);

    // Verify queue state
    assert_eq!(scheduler.jobs_len(), 2);
}

#[test]
fn test_job_execution_from_queue() {
    let (mut scheduler, executor) = create_test_scheduler();

    // Submit a job
    let job = create_test_job("alice");
    let (job_id, _) = scheduler.submit_job(job);

    // Schedule jobs - should execute the job
    let results = scheduler.schedule_jobs();
    assert_eq!(results.len(), 1);
    assert!(results[0].1.is_ok());

    // Verify job is running
    assert_eq!(scheduler.get_job(job_id).unwrap().state, JobState::Running);

    // Verify executor was called
    assert_eq!(executor.execution_count(), 1);
    let executed_jobs = executor.get_executions();
    assert_eq!(executed_jobs[0].id, job_id);
}

#[test]
fn test_multiple_jobs_execution() {
    let (mut scheduler, executor) = create_test_scheduler();

    // Submit 3 jobs
    for i in 0..3 {
        let job = JobBuilder::new()
            .submitted_by("alice")
            .run_dir("/tmp")
            .command(format!("echo job{}", i))
            .build();
        scheduler.submit_job(job);
    }

    // Schedule jobs - should execute all jobs (we have 2 GPUs, jobs don't require GPUs)
    let results = scheduler.schedule_jobs();
    assert_eq!(results.len(), 3);

    // All jobs should have been executed
    assert_eq!(executor.execution_count(), 3);

    // Verify all jobs are running
    for job_id in 1..=3 {
        assert_eq!(scheduler.get_job(job_id).unwrap().state, JobState::Running);
    }
}

// ============================================================================
// Dependency Resolution Tests
// ============================================================================

#[test]
fn test_dependency_resolution_basic() {
    let (mut scheduler, executor) = create_test_scheduler();

    // Submit job A
    let job_a = create_test_job("alice");
    let (job_a_id, _) = scheduler.submit_job(job_a);

    // Submit job B that depends on A
    let job_b = JobBuilder::new()
        .submitted_by("alice")
        .run_dir("/tmp")
        .command("echo job_b")
        .depends_on(Some(job_a_id))
        .build();
    let (job_b_id, _) = scheduler.submit_job(job_b);

    // First schedule - only job A should run
    let results = scheduler.schedule_jobs();
    assert_eq!(results.len(), 1);
    assert_eq!(results[0].0, job_a_id);
    assert_eq!(
        scheduler.get_job(job_a_id).unwrap().state,
        JobState::Running
    );
    assert_eq!(scheduler.get_job(job_b_id).unwrap().state, JobState::Queued);

    // Try scheduling again - job B should still be waiting
    executor.clear();
    let results = scheduler.schedule_jobs();
    assert_eq!(results.len(), 0);
    assert_eq!(scheduler.get_job(job_b_id).unwrap().state, JobState::Queued);

    // Finish job A
    scheduler.finish_job(job_a_id);
    assert_eq!(
        scheduler.get_job(job_a_id).unwrap().state,
        JobState::Finished
    );

    // Now job B should run
    let results = scheduler.schedule_jobs();
    assert_eq!(results.len(), 1);
    assert_eq!(results[0].0, job_b_id);
    assert_eq!(
        scheduler.get_job(job_b_id).unwrap().state,
        JobState::Running
    );
}

#[test]
fn test_dependency_chain() {
    let (mut scheduler, _executor) = create_test_scheduler();

    // Create a chain: A -> B -> C
    let job_a = create_test_job("alice");
    let (job_a_id, _) = scheduler.submit_job(job_a);

    let job_b = JobBuilder::new()
        .submitted_by("alice")
        .run_dir("/tmp")
        .depends_on(Some(job_a_id))
        .build();
    let (job_b_id, _) = scheduler.submit_job(job_b);

    let job_c = JobBuilder::new()
        .submitted_by("alice")
        .run_dir("/tmp")
        .depends_on(Some(job_b_id))
        .build();
    let (job_c_id, _) = scheduler.submit_job(job_c);

    // First schedule - only A runs
    scheduler.schedule_jobs();
    assert_eq!(
        scheduler.get_job(job_a_id).unwrap().state,
        JobState::Running
    );
    assert_eq!(scheduler.get_job(job_b_id).unwrap().state, JobState::Queued);
    assert_eq!(scheduler.get_job(job_c_id).unwrap().state, JobState::Queued);

    // Finish A, schedule - B runs
    scheduler.finish_job(job_a_id);
    scheduler.schedule_jobs();
    assert_eq!(
        scheduler.get_job(job_a_id).unwrap().state,
        JobState::Finished
    );
    assert_eq!(
        scheduler.get_job(job_b_id).unwrap().state,
        JobState::Running
    );
    assert_eq!(scheduler.get_job(job_c_id).unwrap().state, JobState::Queued);

    // Finish B, schedule - C runs
    scheduler.finish_job(job_b_id);
    scheduler.schedule_jobs();
    assert_eq!(
        scheduler.get_job(job_b_id).unwrap().state,
        JobState::Finished
    );
    assert_eq!(
        scheduler.get_job(job_c_id).unwrap().state,
        JobState::Running
    );
}

#[test]
fn test_dependency_not_started_if_parent_failed() {
    let (mut scheduler, _executor) = create_test_scheduler();

    // Submit job A
    let job_a = create_test_job("alice");
    let (job_a_id, _) = scheduler.submit_job(job_a);

    // Submit job B that depends on A
    let job_b = JobBuilder::new()
        .submitted_by("alice")
        .run_dir("/tmp")
        .depends_on(Some(job_a_id))
        .build();
    let (job_b_id, _) = scheduler.submit_job(job_b);

    // Schedule and run job A
    scheduler.schedule_jobs();
    assert_eq!(
        scheduler.get_job(job_a_id).unwrap().state,
        JobState::Running
    );

    // Fail job A
    scheduler.fail_job(job_a_id);
    assert_eq!(scheduler.get_job(job_a_id).unwrap().state, JobState::Failed);

    // Job B should not run because A failed
    let results = scheduler.schedule_jobs();
    assert_eq!(results.len(), 0);
    assert_eq!(scheduler.get_job(job_b_id).unwrap().state, JobState::Queued);
}

// ============================================================================
// Priority Scheduling Tests
// ============================================================================

#[test]
fn test_priority_scheduling_high_priority_first() {
    let (mut scheduler, executor) = create_test_scheduler();

    // Submit low priority job
    let low_priority_job = JobBuilder::new()
        .submitted_by("alice")
        .run_dir("/tmp")
        .priority(5)
        .gpus(1) // Requires GPU so only one runs at a time
        .build();
    let (low_id, _) = scheduler.submit_job(low_priority_job);

    // Submit high priority job
    let high_priority_job = JobBuilder::new()
        .submitted_by("alice")
        .run_dir("/tmp")
        .priority(20)
        .gpus(1) // Requires GPU
        .build();
    let (high_id, _) = scheduler.submit_job(high_priority_job);

    // Schedule - high priority should run first
    let results = scheduler.schedule_jobs();
    assert_eq!(results.len(), 2); // Both can run (2 GPUs available)

    let executions = executor.get_executions();
    // High priority should be executed first
    assert_eq!(executions[0].id, high_id);
    assert_eq!(executions[0].priority, 20);
    assert_eq!(executions[1].id, low_id);
    assert_eq!(executions[1].priority, 5);
}

#[test]
fn test_priority_with_time_bonus() {
    let (mut scheduler, executor) = create_test_scheduler();

    // Job with same priority but shorter time limit gets higher effective priority
    let long_job = JobBuilder::new()
        .submitted_by("alice")
        .run_dir("/tmp")
        .priority(10)
        .time_limit(Some(Duration::from_secs(3600 * 24))) // 24 hours
        .build();
    scheduler.submit_job(long_job);

    let short_job = JobBuilder::new()
        .submitted_by("alice")
        .run_dir("/tmp")
        .priority(10)
        .time_limit(Some(Duration::from_secs(60))) // 1 minute
        .build();
    let (short_id, _) = scheduler.submit_job(short_job);

    // Schedule - short job should run first due to time bonus
    scheduler.schedule_jobs();

    let executions = executor.get_executions();
    // Short job should be executed first (time bonus gives it higher effective priority)
    assert_eq!(executions[0].id, short_id);
}

#[test]
fn test_priority_tiebreaker_with_job_id() {
    let (mut scheduler, executor) = create_test_scheduler();

    // Submit 3 jobs with same priority
    for _ in 0..3 {
        let job = JobBuilder::new()
            .submitted_by("alice")
            .run_dir("/tmp")
            .priority(10)
            .build();
        scheduler.submit_job(job);
    }

    // Schedule all jobs
    scheduler.schedule_jobs();

    let executions = executor.get_executions();
    // Should execute in order of submission (job ID)
    assert_eq!(executions[0].id, 1);
    assert_eq!(executions[1].id, 2);
    assert_eq!(executions[2].id, 3);
}

// ============================================================================
// Resource Constraint Tests
// ============================================================================

#[test]
fn test_gpu_constraints() {
    let (mut scheduler, executor) = create_test_scheduler();

    // Submit 3 jobs, each requiring 1 GPU (we only have 2 GPUs)
    for _ in 0..3 {
        let job = JobBuilder::new()
            .submitted_by("alice")
            .run_dir("/tmp")
            .gpus(1)
            .build();
        scheduler.submit_job(job);
    }

    // First schedule - only 2 jobs should run
    let results = scheduler.schedule_jobs();
    assert_eq!(results.len(), 2);
    assert_eq!(executor.execution_count(), 2);

    // Jobs 1 and 2 should be running, job 3 should be queued
    assert_eq!(scheduler.get_job(1).unwrap().state, JobState::Running);
    assert_eq!(scheduler.get_job(2).unwrap().state, JobState::Running);
    assert_eq!(scheduler.get_job(3).unwrap().state, JobState::Queued);

    // Verify GPU allocation
    assert_eq!(scheduler.get_job(1).unwrap().gpu_ids, Some(smallvec![0]));
    assert_eq!(scheduler.get_job(2).unwrap().gpu_ids, Some(smallvec![1]));

    // Mark GPUs as unavailable (simulating what gflowd would do)
    scheduler
        .gpu_slots_mut()
        .get_mut("GPU-0")
        .unwrap()
        .available = false;
    scheduler
        .gpu_slots_mut()
        .get_mut("GPU-1")
        .unwrap()
        .available = false;

    // Second schedule - job 3 should still be waiting (no GPUs available)
    executor.clear();
    let results = scheduler.schedule_jobs();
    assert_eq!(results.len(), 0);
    assert_eq!(scheduler.get_job(3).unwrap().state, JobState::Queued);
}

#[test]
fn test_multi_gpu_job() {
    let (mut scheduler, executor) = create_test_scheduler();

    // Submit a job requiring 2 GPUs
    let job = JobBuilder::new()
        .submitted_by("alice")
        .run_dir("/tmp")
        .gpus(2)
        .build();
    let (job_id, _) = scheduler.submit_job(job);

    // Schedule - job should run and get both GPUs
    let results = scheduler.schedule_jobs();
    assert_eq!(results.len(), 1);
    assert_eq!(scheduler.get_job(job_id).unwrap().state, JobState::Running);
    assert_eq!(
        scheduler.get_job(job_id).unwrap().gpu_ids,
        Some(smallvec![0, 1])
    );

    // Verify execution
    assert_eq!(executor.execution_count(), 1);
}

#[test]
fn test_insufficient_gpus() {
    let (mut scheduler, executor) = create_test_scheduler();

    // Submit a job requiring 3 GPUs (we only have 2)
    let job = JobBuilder::new()
        .submitted_by("alice")
        .run_dir("/tmp")
        .gpus(3)
        .build();
    let (job_id, _) = scheduler.submit_job(job);

    // Schedule - job should not run
    let results = scheduler.schedule_jobs();
    assert_eq!(results.len(), 0);
    assert_eq!(scheduler.get_job(job_id).unwrap().state, JobState::Queued);
    assert_eq!(executor.execution_count(), 0);
}

#[test]
fn test_memory_constraints() {
    let (mut scheduler, _executor) = create_test_scheduler();

    // Submit a job requiring 4GB
    let job1 = JobBuilder::new()
        .submitted_by("alice")
        .run_dir("/tmp")
        .memory_limit_mb(Some(4096))
        .build();
    let (job1_id, _) = scheduler.submit_job(job1);

    // Submit a job requiring 3GB
    let job2 = JobBuilder::new()
        .submitted_by("alice")
        .run_dir("/tmp")
        .memory_limit_mb(Some(3072))
        .build();
    let (job2_id, _) = scheduler.submit_job(job2);

    // Submit a job requiring 2GB
    let job3 = JobBuilder::new()
        .submitted_by("alice")
        .run_dir("/tmp")
        .memory_limit_mb(Some(2048))
        .build();
    let (job3_id, _) = scheduler.submit_job(job3);

    // Schedule - only 2 jobs should start (4GB + 3GB = 7GB < 8GB)
    // The third job (2GB) would exceed the limit (7GB + 2GB = 9GB > 8GB)
    // Note: Fixed memory accounting now tracks available memory correctly
    let results = scheduler.schedule_jobs();
    assert_eq!(results.len(), 2);

    assert_eq!(scheduler.get_job(job1_id).unwrap().state, JobState::Running);
    assert_eq!(scheduler.get_job(job2_id).unwrap().state, JobState::Running);
    assert_eq!(scheduler.get_job(job3_id).unwrap().state, JobState::Queued); // Waiting for memory

    // Verify memory is tracked correctly
    scheduler.refresh_available_memory();
    // After 2 jobs running: 8192 - 4096 - 3072 = 1024 MB available

    // Finish job1 and refresh memory
    scheduler.finish_job(job1_id);
    scheduler.refresh_available_memory();
    // After job1 finishes: 8192 - 3072 = 5120 MB available

    // Now job3 should be able to start
    let results2 = scheduler.schedule_jobs();
    assert_eq!(results2.len(), 1);
    assert_eq!(scheduler.get_job(job3_id).unwrap().state, JobState::Running);
}

#[test]
fn test_job_exceeds_total_memory() {
    let (mut scheduler, executor) = create_test_scheduler();

    // Submit a job requiring more memory than available
    let job = JobBuilder::new()
        .submitted_by("alice")
        .run_dir("/tmp")
        .memory_limit_mb(Some(10240)) // 10GB, but we only have 8GB
        .build();
    let (job_id, _) = scheduler.submit_job(job);

    // Schedule - job should not run
    let results = scheduler.schedule_jobs();
    assert_eq!(results.len(), 0);
    assert_eq!(scheduler.get_job(job_id).unwrap().state, JobState::Queued);
    assert_eq!(executor.execution_count(), 0);
}

// ============================================================================
// Combined Resource and Priority Tests
// ============================================================================

#[test]
fn test_priority_with_resource_constraints() {
    let (mut scheduler, executor) = create_test_scheduler();

    // Low priority job requiring 1 GPU
    let low_priority = JobBuilder::new()
        .submitted_by("alice")
        .run_dir("/tmp")
        .priority(5)
        .gpus(1)
        .build();
    scheduler.submit_job(low_priority);

    // High priority job requiring 2 GPUs
    let high_priority = JobBuilder::new()
        .submitted_by("alice")
        .run_dir("/tmp")
        .priority(20)
        .gpus(2)
        .build();
    let (high_id, _) = scheduler.submit_job(high_priority);

    // Schedule - high priority job should run first and get both GPUs
    let _results = scheduler.schedule_jobs();

    // High priority job executed first
    let executions = executor.get_executions();
    assert_eq!(executions[0].id, high_id);
    assert_eq!(executions[0].gpu_ids, Some(smallvec![0, 1]));
}

#[test]
fn test_group_concurrency_limit() {
    let (mut scheduler, _executor) = create_test_scheduler();

    let group_id = Uuid::new_v4();

    // Submit 3 jobs in the same group with max_concurrent = 2
    for _ in 0..3 {
        let job = JobBuilder::new()
            .submitted_by("alice")
            .run_dir("/tmp")
            .group_id_uuid(Some(group_id))
            .max_concurrent(Some(2))
            .build();
        scheduler.submit_job(job);
    }

    // Schedule - only 2 jobs should run (group limit)
    scheduler.schedule_jobs();

    assert_eq!(scheduler.get_job(1).unwrap().state, JobState::Running);
    assert_eq!(scheduler.get_job(2).unwrap().state, JobState::Running);
    assert_eq!(scheduler.get_job(3).unwrap().state, JobState::Queued);

    // Finish one job
    scheduler.finish_job(1);

    // Now the third job should run
    scheduler.schedule_jobs();
    assert_eq!(scheduler.get_job(3).unwrap().state, JobState::Running);
}

// ============================================================================
// Cascade Redo Tests
// ============================================================================

#[test]
fn test_cascade_redo_dependency_chain() {
    use gflow::core::job::JobStateReason;

    let (mut scheduler, _executor) = create_test_scheduler();

    // Create a dependency chain: Job 1 -> Job 2 -> Job 3
    // Job 1 (parent)
    let job1 = JobBuilder::new()
        .submitted_by("alice")
        .run_dir("/tmp")
        .command("echo job1")
        .build();
    let (job1_id, _) = scheduler.submit_job(job1);

    // Job 2 (depends on Job 1)
    let job2 = JobBuilder::new()
        .submitted_by("alice")
        .run_dir("/tmp")
        .command("echo job2")
        .depends_on_ids(vec![job1_id])
        .auto_cancel_on_dependency_failure(true)
        .build();
    let (job2_id, _) = scheduler.submit_job(job2);

    // Job 3 (depends on Job 2)
    let job3 = JobBuilder::new()
        .submitted_by("alice")
        .run_dir("/tmp")
        .command("echo job3")
        .depends_on_ids(vec![job2_id])
        .auto_cancel_on_dependency_failure(true)
        .build();
    let (job3_id, _) = scheduler.submit_job(job3);

    // Schedule and run Job 1
    scheduler.schedule_jobs();
    assert_eq!(scheduler.get_job(job1_id).unwrap().state, JobState::Running);

    // Fail Job 1 - this should cascade cancel Job 2 and Job 3
    scheduler.fail_job(job1_id);
    assert_eq!(scheduler.get_job(job1_id).unwrap().state, JobState::Failed);

    // Trigger auto-cancellation
    scheduler.auto_cancel_dependent_jobs(job1_id);

    // Verify cascade cancellation
    assert_eq!(
        scheduler.get_job(job2_id).unwrap().state,
        JobState::Cancelled
    );
    assert_eq!(
        scheduler.get_job(job2_id).unwrap().reason,
        Some(Box::new(JobStateReason::DependencyFailed(job1_id)))
    );
    assert_eq!(
        scheduler.get_job(job3_id).unwrap().state,
        JobState::Cancelled
    );
    assert_eq!(
        scheduler.get_job(job3_id).unwrap().reason,
        Some(Box::new(JobStateReason::DependencyFailed(job2_id)))
    );

    // Now simulate cascade redo:
    // 1. Redo Job 1 (creates Job 4)
    let job4 = JobBuilder::new()
        .submitted_by("alice")
        .run_dir("/tmp")
        .command("echo job1")
        .redone_from(Some(job1_id))
        .build();
    let (job4_id, _) = scheduler.submit_job(job4);

    // 2. Redo Job 2 with updated dependency (creates Job 5)
    let job5 = JobBuilder::new()
        .submitted_by("alice")
        .run_dir("/tmp")
        .command("echo job2")
        .depends_on_ids(vec![job4_id]) // Updated to depend on Job 4
        .auto_cancel_on_dependency_failure(true)
        .redone_from(Some(job2_id))
        .build();
    let (job5_id, _) = scheduler.submit_job(job5);

    // 3. Redo Job 3 with updated dependency (creates Job 6)
    let job6 = JobBuilder::new()
        .submitted_by("alice")
        .run_dir("/tmp")
        .command("echo job3")
        .depends_on_ids(vec![job5_id]) // Updated to depend on Job 5
        .auto_cancel_on_dependency_failure(true)
        .redone_from(Some(job3_id))
        .build();
    let (job6_id, _) = scheduler.submit_job(job6);

    // Verify the new jobs are queued
    assert_eq!(scheduler.get_job(job4_id).unwrap().state, JobState::Queued);
    assert_eq!(scheduler.get_job(job5_id).unwrap().state, JobState::Queued);
    assert_eq!(scheduler.get_job(job6_id).unwrap().state, JobState::Queued);

    // Schedule and run Job 4
    scheduler.schedule_jobs();
    assert_eq!(scheduler.get_job(job4_id).unwrap().state, JobState::Running);
    assert_eq!(scheduler.get_job(job5_id).unwrap().state, JobState::Queued); // Still waiting

    // Finish Job 4 - Job 5 should now run
    scheduler.finish_job(job4_id);
    scheduler.schedule_jobs();
    assert_eq!(
        scheduler.get_job(job4_id).unwrap().state,
        JobState::Finished
    );
    assert_eq!(scheduler.get_job(job5_id).unwrap().state, JobState::Running);
    assert_eq!(scheduler.get_job(job6_id).unwrap().state, JobState::Queued); // Still waiting

    // Finish Job 5 - Job 6 should now run
    scheduler.finish_job(job5_id);
    scheduler.schedule_jobs();
    assert_eq!(
        scheduler.get_job(job5_id).unwrap().state,
        JobState::Finished
    );
    assert_eq!(scheduler.get_job(job6_id).unwrap().state, JobState::Running);

    // Finish Job 6
    scheduler.finish_job(job6_id);
    assert_eq!(
        scheduler.get_job(job6_id).unwrap().state,
        JobState::Finished
    );

    // Verify the cascade redo preserved the dependency chain
    assert_eq!(
        scheduler.get_job(job5_id).unwrap().depends_on_ids,
        DependencyIds::from_slice(&[job4_id])
    );
    assert_eq!(
        scheduler.get_job(job6_id).unwrap().depends_on_ids,
        DependencyIds::from_slice(&[job5_id])
    );
}