Skip to main content

subspace_core/copilot_agent_tasks/
submission.rs

1//! One cloud-task attempt: a shared deadline and atomic dispatch admission.
2
3use std::sync::{Arc, Mutex};
4use std::time::{Duration, Instant};
5
6pub const SUBMISSION_TIMEOUT: Duration = Duration::from_secs(60);
7
8#[derive(Clone, Debug)]
9pub struct Submission {
10    deadline: Instant,
11    stage: Arc<Mutex<Stage>>,
12}
13
14#[derive(Clone, Copy, Debug)]
15enum Stage {
16    Preflight,
17    Dispatched,
18    Expired(SubmissionTimeout),
19}
20
21#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
22pub enum SubmissionTimeout {
23    #[error("The submission expired before task creation dispatch")]
24    NotSent,
25    #[error("The submission timed out after task creation dispatch began")]
26    Unknown,
27}
28
29impl Default for Submission {
30    fn default() -> Self {
31        Self::new(default_deadline())
32    }
33}
34
35fn default_deadline() -> Instant {
36    Instant::now() + SUBMISSION_TIMEOUT
37}
38
39impl Submission {
40    pub fn new(deadline: Instant) -> Self {
41        Self {
42            deadline,
43            stage: Arc::new(Mutex::new(Stage::Preflight)),
44        }
45    }
46
47    pub fn deadline(&self) -> Instant {
48        self.deadline
49    }
50
51    pub fn remaining(&self) -> Result<Duration, SubmissionTimeout> {
52        budget(
53            self.deadline,
54            &mut self.stage.lock().unwrap_or_else(|p| p.into_inner()),
55        )
56    }
57
58    /// Serialize the last dispatch gate with expiration. Once admitted, a
59    /// request may have reached GitHub; expiration must then report unknown.
60    /// Explicit API-version rejection may use the gate again, never a blind retry.
61    pub fn begin_dispatch(&self) -> Result<Duration, SubmissionTimeout> {
62        let mut stage = self.stage.lock().unwrap_or_else(|p| p.into_inner());
63        let remaining = budget(self.deadline, &mut stage)?;
64        *stage = Stage::Dispatched;
65        Ok(remaining)
66    }
67
68    pub fn expire(&self) -> SubmissionTimeout {
69        expire(&mut self.stage.lock().unwrap_or_else(|p| p.into_inner()))
70    }
71}
72
73fn budget(deadline: Instant, stage: &mut Stage) -> Result<Duration, SubmissionTimeout> {
74    if let Stage::Expired(outcome) = stage {
75        return Err(*outcome);
76    }
77    deadline
78        .checked_duration_since(Instant::now())
79        .filter(|remaining| !remaining.is_zero())
80        .ok_or_else(|| expire(stage))
81}
82
83fn expire(stage: &mut Stage) -> SubmissionTimeout {
84    let outcome = match *stage {
85        Stage::Preflight => SubmissionTimeout::NotSent,
86        Stage::Dispatched => SubmissionTimeout::Unknown,
87        Stage::Expired(outcome) => outcome,
88    };
89    *stage = Stage::Expired(outcome);
90    outcome
91}
92
93#[cfg(test)]
94mod tests {
95    use super::{Submission, SubmissionTimeout};
96    use std::time::{Duration, Instant};
97
98    #[test]
99    fn expiry_blocks_late_dispatch_and_preserves_an_already_admitted_outcome() {
100        let before = Submission::default();
101        let copy = before.clone();
102        assert_eq!(before.expire(), SubmissionTimeout::NotSent);
103        assert_eq!(copy.begin_dispatch(), Err(SubmissionTimeout::NotSent));
104        let after = Submission::default();
105        assert!(after.begin_dispatch().is_ok());
106        assert_eq!(after.expire(), SubmissionTimeout::Unknown);
107        assert_eq!(after.begin_dispatch(), Err(SubmissionTimeout::Unknown));
108    }
109
110    #[test]
111    fn the_absolute_deadline_also_blocks_dispatch_without_a_ui_timer() {
112        let submission = Submission::new(Instant::now() - Duration::from_secs(1));
113        assert_eq!(submission.begin_dispatch(), Err(SubmissionTimeout::NotSent));
114        assert!(submission.remaining().is_err());
115        let fresh = Submission::default();
116        assert!(fresh.deadline() > Instant::now());
117        assert!(fresh.remaining().is_ok());
118    }
119}