Skip to main content

vitrify_cli/run/
lease.rs

1//! Orchestrator-side leases: renewal when remaining lease <
2//! `renew_fraction` × `lease_minutes`, and the hard worker wall-clock
3//! budget. The renewal decision is pure over an injected clock; expiry is
4//! advisory — the fencing token protects integration.
5
6use std::process::Child;
7use std::time::Duration;
8
9use vitrify_core::model::UtcTime;
10
11use super::worker::kill_group;
12
13/// Pure renewal decision: remaining lease < fraction × lease.
14pub fn should_renew(
15    now: UtcTime,
16    expires: UtcTime,
17    lease_minutes: i64,
18    renew_fraction: f64,
19) -> bool {
20    let remaining = expires.0 - now.0;
21    (remaining as f64) < renew_fraction * (lease_minutes as f64) * 60.0
22}
23
24/// Injected clock (unit-testable without real time).
25pub trait Clock: Send + Sync {
26    fn now(&self) -> UtcTime;
27}
28
29pub struct RealClock;
30
31impl Clock for RealClock {
32    fn now(&self) -> UtcTime {
33        UtcTime::now()
34    }
35}
36
37#[derive(Debug, Clone)]
38pub enum RenewResult {
39    Renewed {
40        expires: UtcTime,
41    },
42    /// exit 6: lease already expired — stop renewing, kill, leave reclaim
43    /// to the loop's derive step.
44    LeaseExpired,
45    /// transient failure (lost race, git hiccup): keep the worker running,
46    /// retry on the next tick.
47    Failed(String),
48}
49
50/// Injected lease operations (the U-011 transaction in production; scripted
51/// in tests).
52pub trait LeaseBackend: Send + Sync {
53    fn renew(&self, unit: &str, holder: &str) -> RenewResult;
54}
55
56#[derive(Debug, Clone, PartialEq, Eq)]
57pub enum MonitorVerdict {
58    /// The worker exited on its own (exit success recorded by the caller).
59    Exited,
60    /// Hard budget exceeded: process group killed; the caller releases the
61    /// claim and counts the unit failed for the wave.
62    TimedOut,
63    /// Renewal returned exit 6: group killed; reclaim is the loop's job.
64    LeaseLost,
65}
66
67#[derive(Debug, Clone)]
68pub struct MonitorParams {
69    pub lease_minutes: i64,
70    pub renew_fraction: f64,
71    pub worker_timeout_minutes: i64,
72    pub tick: Duration,
73}
74
75/// One worker under monitoring.
76pub struct MonitorTarget<'a> {
77    pub child: &'a mut Child,
78    pub pid: u32,
79    pub unit: &'a str,
80    pub holder: &'a str,
81    pub expires: UtcTime,
82}
83
84/// Monitor one worker until it exits, times out, or loses its lease.
85/// One monitor thread per worker (std threads); 1 s tick in
86/// production.
87pub fn monitor_worker(
88    target: MonitorTarget<'_>,
89    params: &MonitorParams,
90    clock: &dyn Clock,
91    backend: &dyn LeaseBackend,
92) -> MonitorVerdict {
93    monitor_worker_tracked(target, params, clock, backend).0
94}
95
96/// [`monitor_worker`], also returning the lease expiry as last renewed —
97/// the orchestrator keeps the lease alive after the worker has exited, until
98/// its work is integrated.
99pub fn monitor_worker_tracked(
100    target: MonitorTarget<'_>,
101    params: &MonitorParams,
102    clock: &dyn Clock,
103    backend: &dyn LeaseBackend,
104) -> (MonitorVerdict, UtcTime) {
105    let MonitorTarget {
106        child,
107        pid,
108        unit,
109        holder,
110        mut expires,
111    } = target;
112    let start = clock.now();
113    loop {
114        match child.try_wait() {
115            Ok(Some(_)) => return (MonitorVerdict::Exited, expires),
116            Ok(None) => {}
117            Err(_) => return (MonitorVerdict::Exited, expires),
118        }
119        let now = clock.now();
120        if now.0 - start.0 > params.worker_timeout_minutes * 60 {
121            kill_group(pid);
122            let _ = child.wait();
123            return (MonitorVerdict::TimedOut, expires);
124        }
125        if should_renew(now, expires, params.lease_minutes, params.renew_fraction) {
126            match backend.renew(unit, holder) {
127                RenewResult::Renewed { expires: e } => expires = e,
128                RenewResult::LeaseExpired => {
129                    kill_group(pid);
130                    let _ = child.wait();
131                    return (MonitorVerdict::LeaseLost, expires);
132                }
133                RenewResult::Failed(_) => {
134                    // advisory: retry next tick; the fencing token protects
135                    // integration either way
136                }
137            }
138        }
139        std::thread::sleep(params.tick);
140    }
141}
142
143/// Leases the orchestrator holds for work that is waiting to be integrated:
144/// the worker has exited, so nothing else renews them, and a lease that
145/// lapsed in the queue would send finished work back to the pool.
146#[derive(Default)]
147pub struct Keeper {
148    held: std::sync::Mutex<Vec<Held>>,
149    stop: std::sync::atomic::AtomicBool,
150}
151
152struct Held {
153    unit: String,
154    holder: String,
155    expires: UtcTime,
156}
157
158impl Keeper {
159    /// Keep `unit`'s lease alive from now on.
160    pub fn hold(&self, unit: &str, holder: &str, expires: UtcTime) {
161        let mut held = self.held.lock().unwrap_or_else(|e| e.into_inner());
162        held.retain(|h| h.unit != unit);
163        held.push(Held {
164            unit: unit.to_string(),
165            holder: holder.to_string(),
166            expires,
167        });
168    }
169
170    /// Stop renewing `unit`'s lease.
171    pub fn drop_unit(&self, unit: &str) {
172        self.held
173            .lock()
174            .unwrap_or_else(|e| e.into_inner())
175            .retain(|h| h.unit != unit);
176    }
177
178    pub fn stop(&self) {
179        self.stop.store(true, std::sync::atomic::Ordering::SeqCst);
180    }
181
182    /// One pass: renew every held lease that is due. Returns the units whose
183    /// lease turned out to be gone.
184    pub fn renew_due(
185        &self,
186        params: &MonitorParams,
187        clock: &dyn Clock,
188        backend: &dyn LeaseBackend,
189    ) -> Vec<String> {
190        let due: Vec<(String, String)> = {
191            let held = self.held.lock().unwrap_or_else(|e| e.into_inner());
192            let now = clock.now();
193            held.iter()
194                .filter(|h| {
195                    should_renew(now, h.expires, params.lease_minutes, params.renew_fraction)
196                })
197                .map(|h| (h.unit.clone(), h.holder.clone()))
198                .collect()
199        };
200        let mut lost = Vec::new();
201        for (unit, holder) in due {
202            let result = backend.renew(&unit, &holder);
203            let mut held = self.held.lock().unwrap_or_else(|e| e.into_inner());
204            match result {
205                RenewResult::Renewed { expires } => {
206                    if let Some(h) = held.iter_mut().find(|h| h.unit == unit) {
207                        h.expires = expires;
208                    }
209                }
210                RenewResult::LeaseExpired => {
211                    held.retain(|h| h.unit != unit);
212                    lost.push(unit);
213                }
214                // advisory: retried at the next pass; the fencing token
215                // protects integration either way
216                RenewResult::Failed(_) => {}
217            }
218        }
219        lost
220    }
221
222    /// Renew until [`Keeper::stop`], one pass per `params.tick`.
223    pub fn run(&self, params: &MonitorParams, clock: &dyn Clock, backend: &dyn LeaseBackend) {
224        while !self.stop.load(std::sync::atomic::Ordering::SeqCst) {
225            self.renew_due(params, clock, backend);
226            std::thread::sleep(params.tick);
227        }
228    }
229}