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
use compact_str::CompactString;
use serde::{Deserialize, Serialize};
use std::time::{Duration, SystemTime};

/// Status of a GPU reservation
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum ReservationStatus {
    /// Scheduled but not yet active
    Pending,
    /// Currently active
    Active,
    /// Ended naturally
    Completed,
    /// Cancelled by user
    Cancelled,
}

/// GPU specification for a reservation
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum GpuSpec {
    /// Reserve a specific number of GPUs (scheduler will allocate dynamically)
    Count(u32),
    /// Reserve specific GPU indices (e.g., [0, 2, 3])
    Indices(Vec<u32>),
}

impl GpuSpec {
    /// Get the number of GPUs in this specification
    pub fn count(&self) -> u32 {
        match self {
            GpuSpec::Count(n) => *n,
            GpuSpec::Indices(indices) => indices.len() as u32,
        }
    }

    /// Get the GPU indices if this is an Indices spec, None otherwise
    pub fn indices(&self) -> Option<&[u32]> {
        match self {
            GpuSpec::Indices(indices) => Some(indices),
            GpuSpec::Count(_) => None,
        }
    }
}

/// A GPU reservation for a specific user
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GpuReservation {
    /// Unique reservation ID
    pub id: u32,
    /// Username who created the reservation
    pub user: CompactString,
    /// GPU specification (count or specific indices)
    pub gpu_spec: GpuSpec,
    /// When reservation starts
    pub start_time: SystemTime,
    /// How long reservation lasts
    pub duration: Duration,
    /// Current status
    pub status: ReservationStatus,
    /// Creation timestamp
    pub created_at: SystemTime,
    /// Cancellation timestamp
    pub cancelled_at: Option<SystemTime>,
}

impl GpuReservation {
    /// Check if reservation is currently active based on current time
    pub fn is_active(&self, now: SystemTime) -> bool {
        if self.status == ReservationStatus::Cancelled {
            return false;
        }

        now >= self.start_time && now < self.end_time()
    }

    /// Calculate the end time of the reservation
    pub fn end_time(&self) -> SystemTime {
        self.start_time + self.duration
    }

    /// Check if this reservation overlaps with a given time range
    pub fn overlaps_with(&self, start: SystemTime, end: SystemTime) -> bool {
        // Two ranges overlap if: start1 < end2 AND start2 < end1
        self.start_time < end && start < self.end_time()
    }

    /// Update status based on current time
    pub fn update_status(&mut self, now: SystemTime) {
        match self.status {
            ReservationStatus::Pending => {
                if now >= self.start_time && now < self.end_time() {
                    self.status = ReservationStatus::Active;
                } else if now >= self.end_time() {
                    self.status = ReservationStatus::Completed;
                }
            }
            ReservationStatus::Active => {
                if now >= self.end_time() {
                    self.status = ReservationStatus::Completed;
                }
            }
            ReservationStatus::Completed | ReservationStatus::Cancelled => {
                // Terminal states, no change
            }
        }
    }

    /// Calculate the next status transition time for this reservation
    ///
    /// Returns `None` if the reservation is in a terminal state (Completed/Cancelled)
    /// or if the transition time is in the past.
    pub fn next_transition_time(&self, now: SystemTime) -> Option<SystemTime> {
        match self.status {
            ReservationStatus::Pending => {
                // Next transition: start_time (Pending → Active)
                if self.start_time > now {
                    Some(self.start_time)
                } else {
                    // Already past start time, should transition immediately
                    None
                }
            }
            ReservationStatus::Active => {
                // Next transition: end_time (Active → Completed)
                let end = self.end_time();
                if end > now {
                    Some(end)
                } else {
                    // Already past end time, should transition immediately
                    None
                }
            }
            ReservationStatus::Completed | ReservationStatus::Cancelled => {
                // Terminal states, no future transitions
                None
            }
        }
    }
}

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

    #[test]
    fn test_is_active() {
        let start = SystemTime::UNIX_EPOCH + Duration::from_secs(1000);
        let duration = Duration::from_secs(3600); // 1 hour

        let mut reservation = GpuReservation {
            id: 1,
            user: "alice".into(),
            gpu_spec: GpuSpec::Count(2),
            start_time: start,
            duration,
            status: ReservationStatus::Pending,
            created_at: SystemTime::UNIX_EPOCH,
            cancelled_at: None,
        };

        // Before start time
        let before = start - Duration::from_secs(100);
        assert!(!reservation.is_active(before));

        // At start time
        assert!(reservation.is_active(start));

        // During reservation
        let during = start + Duration::from_secs(1800); // 30 minutes in
        assert!(reservation.is_active(during));

        // At end time
        let end = start + duration;
        assert!(!reservation.is_active(end));

        // After end time
        let after = end + Duration::from_secs(100);
        assert!(!reservation.is_active(after));

        // Cancelled reservation is never active
        reservation.status = ReservationStatus::Cancelled;
        assert!(!reservation.is_active(during));
    }

    #[test]
    fn test_end_time() {
        let start = SystemTime::UNIX_EPOCH + Duration::from_secs(1000);
        let duration = Duration::from_secs(3600);

        let reservation = GpuReservation {
            id: 1,
            user: "alice".into(),
            gpu_spec: GpuSpec::Count(2),
            start_time: start,
            duration,
            status: ReservationStatus::Pending,
            created_at: SystemTime::UNIX_EPOCH,
            cancelled_at: None,
        };

        assert_eq!(reservation.end_time(), start + duration);
    }

    #[test]
    fn test_overlaps_with() {
        let start = SystemTime::UNIX_EPOCH + Duration::from_secs(1000);
        let duration = Duration::from_secs(3600); // 1 hour

        let reservation = GpuReservation {
            id: 1,
            user: "alice".into(),
            gpu_spec: GpuSpec::Count(2),
            start_time: start,
            duration,
            status: ReservationStatus::Pending,
            created_at: SystemTime::UNIX_EPOCH,
            cancelled_at: None,
        };

        let end = start + duration;

        // Completely before
        let before_start = start - Duration::from_secs(200);
        let before_end = start - Duration::from_secs(100);
        assert!(!reservation.overlaps_with(before_start, before_end));

        // Completely after
        let after_start = end + Duration::from_secs(100);
        let after_end = end + Duration::from_secs(200);
        assert!(!reservation.overlaps_with(after_start, after_end));

        // Overlaps at start
        let overlap_start = start - Duration::from_secs(100);
        let overlap_end = start + Duration::from_secs(100);
        assert!(reservation.overlaps_with(overlap_start, overlap_end));

        // Overlaps at end
        let overlap_start = end - Duration::from_secs(100);
        let overlap_end = end + Duration::from_secs(100);
        assert!(reservation.overlaps_with(overlap_start, overlap_end));

        // Completely contains
        let contains_start = start - Duration::from_secs(100);
        let contains_end = end + Duration::from_secs(100);
        assert!(reservation.overlaps_with(contains_start, contains_end));

        // Completely contained
        let contained_start = start + Duration::from_secs(100);
        let contained_end = end - Duration::from_secs(100);
        assert!(reservation.overlaps_with(contained_start, contained_end));

        // Exact match
        assert!(reservation.overlaps_with(start, end));
    }

    #[test]
    fn test_update_status() {
        let start = SystemTime::UNIX_EPOCH + Duration::from_secs(1000);
        let duration = Duration::from_secs(3600);
        let end = start + duration;

        let mut reservation = GpuReservation {
            id: 1,
            user: "alice".into(),
            gpu_spec: GpuSpec::Count(2),
            start_time: start,
            duration,
            status: ReservationStatus::Pending,
            created_at: SystemTime::UNIX_EPOCH,
            cancelled_at: None,
        };

        // Before start: stays Pending
        let before = start - Duration::from_secs(100);
        reservation.update_status(before);
        assert_eq!(reservation.status, ReservationStatus::Pending);

        // At start: becomes Active
        reservation.update_status(start);
        assert_eq!(reservation.status, ReservationStatus::Active);

        // During: stays Active
        let during = start + Duration::from_secs(1800);
        reservation.update_status(during);
        assert_eq!(reservation.status, ReservationStatus::Active);

        // At end: becomes Completed
        reservation.update_status(end);
        assert_eq!(reservation.status, ReservationStatus::Completed);

        // After end: stays Completed
        let after = end + Duration::from_secs(100);
        reservation.update_status(after);
        assert_eq!(reservation.status, ReservationStatus::Completed);

        // Cancelled stays Cancelled
        reservation.status = ReservationStatus::Cancelled;
        reservation.update_status(during);
        assert_eq!(reservation.status, ReservationStatus::Cancelled);
    }

    #[test]
    fn test_pending_to_completed_directly() {
        let start = SystemTime::UNIX_EPOCH + Duration::from_secs(1000);
        let duration = Duration::from_secs(3600);
        let end = start + duration;

        let mut reservation = GpuReservation {
            id: 1,
            user: "alice".into(),
            gpu_spec: GpuSpec::Count(2),
            start_time: start,
            duration,
            status: ReservationStatus::Pending,
            created_at: SystemTime::UNIX_EPOCH,
            cancelled_at: None,
        };

        // If we check after end time while still Pending, it should go to Completed
        let after = end + Duration::from_secs(100);
        reservation.update_status(after);
        assert_eq!(reservation.status, ReservationStatus::Completed);
    }

    #[test]
    fn test_next_transition_time_pending() {
        let now = SystemTime::now();
        let start_time = now + Duration::from_secs(3600); // 1 hour from now

        let reservation = GpuReservation {
            id: 1,
            user: "alice".into(),
            gpu_spec: GpuSpec::Count(2),
            start_time,
            duration: Duration::from_secs(7200),
            status: ReservationStatus::Pending,
            created_at: now,
            cancelled_at: None,
        };

        // Should return start_time for pending reservation
        assert_eq!(reservation.next_transition_time(now), Some(start_time));

        // If current time is past start_time, should return None
        let future = start_time + Duration::from_secs(100);
        assert_eq!(reservation.next_transition_time(future), None);
    }

    #[test]
    fn test_next_transition_time_active() {
        let now = SystemTime::now();
        let start_time = now - Duration::from_secs(1800); // Started 30 min ago
        let duration = Duration::from_secs(3600); // 1 hour total
        let end_time = start_time + duration;

        let reservation = GpuReservation {
            id: 1,
            user: "alice".into(),
            gpu_spec: GpuSpec::Count(2),
            start_time,
            duration,
            status: ReservationStatus::Active,
            created_at: now - Duration::from_secs(2000),
            cancelled_at: None,
        };

        // Should return end_time for active reservation
        assert_eq!(reservation.next_transition_time(now), Some(end_time));

        // If current time is past end_time, should return None
        let future = end_time + Duration::from_secs(100);
        assert_eq!(reservation.next_transition_time(future), None);
    }

    #[test]
    fn test_next_transition_time_terminal_states() {
        let now = SystemTime::now();
        let start_time = now - Duration::from_secs(7200);

        let mut reservation = GpuReservation {
            id: 1,
            user: "alice".into(),
            gpu_spec: GpuSpec::Count(2),
            start_time,
            duration: Duration::from_secs(3600),
            status: ReservationStatus::Completed,
            created_at: now - Duration::from_secs(8000),
            cancelled_at: None,
        };

        // Completed reservation should return None
        assert_eq!(reservation.next_transition_time(now), None);

        // Cancelled reservation should return None
        reservation.status = ReservationStatus::Cancelled;
        reservation.cancelled_at = Some(now);
        assert_eq!(reservation.next_transition_time(now), None);
    }

    #[test]
    fn test_gpu_spec_count() {
        let spec = GpuSpec::Count(4);
        assert_eq!(spec.count(), 4);
        assert_eq!(spec.indices(), None);
    }

    #[test]
    fn test_gpu_spec_indices() {
        let spec = GpuSpec::Indices(vec![0, 2, 3]);
        assert_eq!(spec.count(), 3);
        assert_eq!(spec.indices(), Some(&[0, 2, 3][..]));
    }

    #[test]
    fn test_gpu_spec_empty_indices() {
        let spec = GpuSpec::Indices(vec![]);
        assert_eq!(spec.count(), 0);
        assert_eq!(spec.indices(), Some(&[][..]));
    }

    // Property-based tests
    mod proptests {
        use super::*;
        use proptest::prelude::*;

        // Strategy to generate valid time ranges
        fn time_range_strategy() -> impl Strategy<Value = (SystemTime, Duration)> {
            (1000u64..1_000_000_000, 1u64..86400).prop_map(|(start_secs, duration_secs)| {
                let start = SystemTime::UNIX_EPOCH + Duration::from_secs(start_secs);
                let duration = Duration::from_secs(duration_secs);
                (start, duration)
            })
        }

        proptest! {
            /// Property: Overlap detection is symmetric
            /// If reservation A overlaps with B, then B overlaps with A
            #[test]
            fn prop_overlap_is_symmetric(
                (start1, dur1) in time_range_strategy(),
                (start2, dur2) in time_range_strategy(),
            ) {
                let res1 = GpuReservation {
                    id: 1,
                    user: "alice".into(),
                    gpu_spec: GpuSpec::Count(2),
                    start_time: start1,
                    duration: dur1,
                    status: ReservationStatus::Pending,
                    created_at: SystemTime::UNIX_EPOCH,
                    cancelled_at: None,
                };

                let end2 = start2 + dur2;
                let overlap_1_with_2 = res1.overlaps_with(start2, end2);

                // Create res2 and check reverse
                let res2 = GpuReservation {
                    id: 2,
                    user: "bob".into(),
                    gpu_spec: GpuSpec::Count(2),
                    start_time: start2,
                    duration: dur2,
                    status: ReservationStatus::Pending,
                    created_at: SystemTime::UNIX_EPOCH,
                    cancelled_at: None,
                };

                let end1 = start1 + dur1;
                let overlap_2_with_1 = res2.overlaps_with(start1, end1);

                prop_assert_eq!(overlap_1_with_2, overlap_2_with_1);
            }

            /// Property: A reservation never overlaps with itself at non-overlapping times
            /// If we have a reservation [start, end), it should not overlap with [end+1, end+2)
            #[test]
            fn prop_no_overlap_after_end(
                (start, dur) in time_range_strategy(),
                gap in 1u64..1000,
            ) {
                let reservation = GpuReservation {
                    id: 1,
                    user: "alice".into(),
                    gpu_spec: GpuSpec::Count(2),
                    start_time: start,
                    duration: dur,
                    status: ReservationStatus::Pending,
                    created_at: SystemTime::UNIX_EPOCH,
                    cancelled_at: None,
                };

                let end = start + dur;
                let after_start = end + Duration::from_secs(gap);
                let after_end = after_start + Duration::from_secs(100);

                prop_assert!(!reservation.overlaps_with(after_start, after_end));
            }

            /// Property: A reservation always overlaps with any time range that contains it
            #[test]
            fn prop_overlap_when_contained(
                (start, dur) in time_range_strategy(),
                before in 1u64..1000,
                after in 1u64..1000,
            ) {
                let reservation = GpuReservation {
                    id: 1,
                    user: "alice".into(),
                    gpu_spec: GpuSpec::Count(2),
                    start_time: start,
                    duration: dur,
                    status: ReservationStatus::Pending,
                    created_at: SystemTime::UNIX_EPOCH,
                    cancelled_at: None,
                };

                let end = start + dur;
                let container_start = start - Duration::from_secs(before);
                let container_end = end + Duration::from_secs(after);

                prop_assert!(reservation.overlaps_with(container_start, container_end));
            }

            /// Property: Status transitions are monotonic (never go backwards)
            /// Pending -> Active -> Completed (or Cancelled from any state)
            #[test]
            fn prop_status_monotonic(
                (start, dur) in time_range_strategy(),
            ) {
                let mut reservation = GpuReservation {
                    id: 1,
                    user: "alice".into(),
                    gpu_spec: GpuSpec::Count(2),
                    start_time: start,
                    duration: dur,
                    status: ReservationStatus::Pending,
                    created_at: SystemTime::UNIX_EPOCH,
                    cancelled_at: None,
                };

                let end = start + dur;

                // Before start: should be Pending
                let before = start - Duration::from_secs(100);
                reservation.update_status(before);
                prop_assert_eq!(reservation.status, ReservationStatus::Pending);

                // At start: should be Active
                reservation.update_status(start);
                prop_assert_eq!(reservation.status, ReservationStatus::Active);

                // After end: should be Completed
                let after = end + Duration::from_secs(100);
                reservation.update_status(after);
                prop_assert_eq!(reservation.status, ReservationStatus::Completed);

                // Once Completed, stays Completed
                reservation.update_status(after + Duration::from_secs(1000));
                prop_assert_eq!(reservation.status, ReservationStatus::Completed);
            }

            /// Property: end_time is always start_time + duration
            #[test]
            fn prop_end_time_calculation(
                (start, dur) in time_range_strategy(),
            ) {
                let reservation = GpuReservation {
                    id: 1,
                    user: "alice".into(),
                    gpu_spec: GpuSpec::Count(2),
                    start_time: start,
                    duration: dur,
                    status: ReservationStatus::Pending,
                    created_at: SystemTime::UNIX_EPOCH,
                    cancelled_at: None,
                };

                prop_assert_eq!(reservation.end_time(), start + dur);
            }

            /// Property: GpuSpec::Count always returns the count value
            #[test]
            fn prop_gpu_spec_count(count in 1u32..100) {
                let spec = GpuSpec::Count(count);
                prop_assert_eq!(spec.count(), count);
                prop_assert_eq!(spec.indices(), None);
            }

            /// Property: GpuSpec::Indices count equals the length of indices vector
            #[test]
            fn prop_gpu_spec_indices(indices in prop::collection::vec(0u32..16, 0..10)) {
                let spec = GpuSpec::Indices(indices.clone());
                prop_assert_eq!(spec.count(), indices.len() as u32);
                prop_assert_eq!(spec.indices(), Some(indices.as_slice()));
            }

            /// Property: Cancelled reservations are never active
            #[test]
            fn prop_cancelled_never_active(
                (start, dur) in time_range_strategy(),
                check_time in 1000u64..1_000_000_000,
            ) {
                let mut reservation = GpuReservation {
                    id: 1,
                    user: "alice".into(),
                    gpu_spec: GpuSpec::Count(2),
                    start_time: start,
                    duration: dur,
                    status: ReservationStatus::Cancelled,
                    created_at: SystemTime::UNIX_EPOCH,
                    cancelled_at: Some(SystemTime::UNIX_EPOCH),
                };

                let check = SystemTime::UNIX_EPOCH + Duration::from_secs(check_time);
                prop_assert!(!reservation.is_active(check));

                // Even if we try to update status, it should stay Cancelled
                reservation.update_status(check);
                prop_assert_eq!(reservation.status, ReservationStatus::Cancelled);
            }
        }
    }
}