Skip to main content

lean_ctx_cloud/
scheduler.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Background Cloud work, started once at MCP startup.
3//!
4//! The scheduler never runs inside a tool call and never blocks one: it is a
5//! low-priority thread that renews the lease when due (and, with later
6//! packages, drains the outbox and pulls knowledge). Offline or a lapsed
7//! lease only pauses Cloud traffic; local tools are unaffected.
8
9use std::sync::{Condvar, Mutex, MutexGuard, PoisonError};
10use std::time::{Duration, Instant};
11
12use lean_ctx_time::UtcDateTime;
13
14use super::CloudError;
15use super::auth::Session;
16use super::config::CloudConfig;
17use super::state::CloudStore;
18use lean_ctx_protocol::cloud::lease::LeaseState;
19
20/// Time between passes: `[cloud] pull_interval_minutes` (SPEC-ENGINE §3.16).
21fn tick_every(config: &CloudConfig) -> Duration {
22    Duration::from_secs(u64::from(config.pull_interval()) * 60)
23}
24
25/// What one scheduler pass did.
26#[derive(Debug, Clone, PartialEq, Eq)]
27pub enum TickOutcome {
28    Idle,
29    Renewed,
30    /// Nothing to do any more (not connected, disabled, lapsed): stop.
31    Stop(String),
32    /// A failure that may pass (Cloud offline, a lease renewal refused);
33    /// try again next tick.
34    Retry(String),
35}
36
37/// One pass at local time `now`. A pass that stops (disabled, not
38/// connected, revoked, lapsed, …) also stops every local recording for
39/// Cloud (K2 review 2, N1): nothing is collected while no pass runs.
40pub fn tick(store: &CloudStore, config: &CloudConfig) -> TickOutcome {
41    let outcome = tick_once(store, config);
42    if matches!(outcome, TickOutcome::Stop(_)) {
43        super::receipts::stop_local_recording(store.data_dir());
44    }
45    outcome
46}
47
48fn tick_once(store: &CloudStore, config: &CloudConfig) -> TickOutcome {
49    if config.enabled == Some(false) {
50        return TickOutcome::Stop("disabled by [cloud] enabled = false".into());
51    }
52    let Ok(Some(instance)) = store.instance() else {
53        return TickOutcome::Stop("not connected".into());
54    };
55    // A disconnect Cloud has not confirmed yet: finish it, sync nothing.
56    match super::disconnect::retry_pending(store, config, &instance) {
57        None => {}
58        Some(Ok(done)) => return TickOutcome::Stop(done),
59        Some(Err(error)) if error.is_transient() => {
60            return TickOutcome::Retry(format!("pending disconnect: {error}"));
61        }
62        Some(Err(error)) => {
63            store.record_error(&format!("pending disconnect: {error}"));
64            return TickOutcome::Stop(format!("pending disconnect: {error}"));
65        }
66    }
67    // Upgrade duties of the first 3.12 start (local, once; §3.16).
68    if let Err(error) = super::migrate::run(store, config) {
69        store.record_error(&format!("upgrade: {error}"));
70    }
71    let session = super::root_cert::trust_root(store, config, &instance.url)
72        .and_then(|root| Session::load(store.clone(), root));
73    let mut session = match session {
74        Ok(session) => session,
75        Err(error) => {
76            store.record_error(&error.to_string());
77            return TickOutcome::Stop(error.to_string());
78        }
79    };
80    let now = UtcDateTime::now();
81    if session.lease.state_at(now) == LeaseState::Lapsed {
82        store.record_error(&CloudError::LeaseLapsed.to_string());
83        return TickOutcome::Stop(CloudError::LeaseLapsed.to_string());
84    }
85    let mut outcome = TickOutcome::Idle;
86    if session.lease.renew_due(now) {
87        match session.renew() {
88            Ok(_) => {
89                outcome = TickOutcome::Renewed;
90                // A self-hosted Cloud' root certificate is refreshed with the lease.
91                if let Ok(client) = session.client() {
92                    super::root_cert::refresh(store, &client, &instance.url);
93                }
94            }
95            // A revoked instance or a lapsed lease ends the scheduler. Any
96            // other refusal (a key this engine does not hold yet, a damaged
97            // answer, Cloud offline) is tried again next pass, one
98            // `pull_interval` later, and the pass goes on under the lease
99            // still in force: a scheduler that stopped here also stopped the
100            // pulls, metrics and receipts until the next restart. The reason
101            // stays in `cloud status` until a renewal succeeds.
102            Err(error @ (CloudError::Revoked(_) | CloudError::LeaseLapsed)) => {
103                store.record_error(&error.to_string());
104                return TickOutcome::Stop(error.to_string());
105            }
106            Err(error) => {
107                store.record_error(&error.to_string());
108                store.record_renew_error(Some(&error.to_string()));
109                outcome = TickOutcome::Retry(error.to_string());
110            }
111        }
112    }
113    // A vault a checkout left (pulled link file, identity change) leaves
114    // projects.json first, whatever pauses below: metrics and receipts
115    // read the map too and are never filed under it.
116    if let Err(error) = crate::resolution::load_current(store.data_dir()) {
117        store.record_error(&format!("vault map: {error}"));
118    }
119    // A local screening rule that does not compile pauses every content
120    // channel (fails closed) and says so each pass; the policy pull that
121    // may bring fixed rules goes on.
122    let screen_problem = super::knowledge::screening::Screen::for_installation().problem();
123    if let Some(problem) = &screen_problem {
124        store.record_error(problem);
125    } else {
126        if due(store, config, "knowledge", now) {
127            crate::knowledge::pull::sync(&session, config, None);
128        }
129        for problem in crate::tasks::propose::drain(&session).problems {
130            store.record_error(&format!("tasks: {problem}"));
131        }
132    }
133    if due(store, config, "policy", now)
134        && session
135            .lease
136            .lease
137            .grants(lean_ctx_protocol::cloud::lease::CloudRight::PolicyPull)
138    {
139        match crate::policy::pull(&session) {
140            Ok(_) => crate::policy::note_pull(store.data_dir(), crate::policy::PulledVia::Poll),
141            Err(error) => store.record_error(&format!("policy: {error}")),
142        }
143    }
144    // Engine metrics v2 (hourly, per vault); held back until released.
145    use crate::metrics_v2::upload::{self as hours, MetricsV2Run};
146    match hours::run(&session, config, now, false) {
147        Ok(MetricsV2Run::Sent { .. } | MetricsV2Run::Empty) => store.record_success(
148            "metrics_v2",
149            &now.to_rfc3339_opts(lean_ctx_time::SecondsFormat::Secs, true),
150        ),
151        Ok(_) => {}
152        Err(error) => store.record_error(&format!("instance metrics: {error}")),
153    }
154    match crate::receipts::run(&session, config, now) {
155        Ok(crate::receipts::ReceiptsRun::Sent { accepted, .. }) if accepted > 0 => {
156            store.record_success(
157                "receipts",
158                &now.to_rfc3339_opts(lean_ctx_time::SecondsFormat::Secs, true),
159            );
160        }
161        Ok(_) => {}
162        Err(error) => store.record_error(&format!("receipts: {error}")),
163    }
164    // The team stop for `cloud status`, which reads only this cache; a
165    // failed read keeps the last answer, which status then shows as stale.
166    let _ = crate::team_stop::refresh_with(store, &session);
167    outcome
168}
169
170/// Whether the last success on `channel` is older than `pull_interval_minutes`.
171fn due(
172    store: &CloudStore,
173    config: &CloudConfig,
174    channel: &str,
175    now: lean_ctx_time::UtcDateTime,
176) -> bool {
177    let interval = lean_ctx_time::Duration::minutes(i64::from(config.pull_interval()));
178    store
179        .activity()
180        .last_success
181        .get(channel)
182        .and_then(|t| lean_ctx_time::OffsetDateTime::parse_from_rfc3339(t).ok())
183        .is_none_or(|last| now - last.to_utc() >= interval)
184}
185
186/// One pending policy nudge.
187#[derive(Debug, Clone, Copy, PartialEq, Eq)]
188struct Nudge {
189    /// The version the hint named; `None` (a reconnect): pull regardless.
190    version: Option<u64>,
191}
192
193impl Nudge {
194    /// Two nudges as one: a pull regardless wins, else the newer version.
195    fn merge(self, other: Self) -> Self {
196        Self {
197            version: self.version.zip(other.version).map(|(a, b)| a.max(b)),
198        }
199    }
200}
201
202/// The pending policy nudge, and when the last nudged pull ran.
203struct Nudges {
204    policy: Option<Nudge>,
205    last_run: Option<Instant>,
206}
207
208static NUDGES: Mutex<Nudges> = Mutex::new(Nudges {
209    policy: None,
210    last_run: None,
211});
212static NUDGE_WAKE: Condvar = Condvar::new();
213/// At most one nudged policy pull per this interval (a burst of frames is
214/// one pull).
215const NUDGE_SPACING: Duration = Duration::from_secs(10);
216
217fn nudges() -> MutexGuard<'static, Nudges> {
218    NUDGES.lock().unwrap_or_else(PoisonError::into_inner)
219}
220
221/// Ask the scheduler to pull the policy now: Cloud announced `version`
222/// (`policy.advanced`), or the bus reconnected (`None`). A hint only: the
223/// pull verifies the signed bundle before anything applies, and acks it.
224pub fn nudge_policy(version: Option<u64>) {
225    {
226        let mut pending = nudges();
227        let nudge = Nudge { version };
228        pending.policy = Some(pending.policy.map_or(nudge, |held| held.merge(nudge)));
229    }
230    NUDGE_WAKE.notify_all();
231}
232
233/// Wait until `deadline` or a policy nudge that may run (spaced by
234/// [`NUDGE_SPACING`]). The nudge when nudged, `None` at `deadline`.
235fn wait_nudge(deadline: Instant) -> Option<Nudge> {
236    let mut pending = nudges();
237    loop {
238        let now = Instant::now();
239        let until = match pending.policy {
240            Some(nudge) => {
241                let ready = pending.last_run.map_or(now, |last| last + NUDGE_SPACING);
242                if ready <= now {
243                    pending.policy = None;
244                    pending.last_run = Some(now);
245                    return Some(nudge);
246                }
247                ready.min(deadline)
248            }
249            None => deadline,
250        };
251        if until <= now {
252            return None;
253        }
254        pending = NUDGE_WAKE
255            .wait_timeout(pending, until - now)
256            .unwrap_or_else(PoisonError::into_inner)
257            .0;
258    }
259}
260
261/// Whether a nudge for `requested` needs a pull with `installed` in force.
262fn nudge_needed(requested: Option<u64>, installed: Option<u64>) -> bool {
263    match requested {
264        None => true,
265        Some(version) => installed.is_none_or(|have| have < version),
266    }
267}
268
269/// The Cloud session of this connected machine under a lease still in
270/// force, for work off the tick (nudged pulls, background sync). The tick
271/// alone renews the lease and finishes a pending disconnect.
272pub(crate) fn connected_session(
273    store: &CloudStore,
274    config: &CloudConfig,
275) -> Result<Session, CloudError> {
276    if config.enabled == Some(false) {
277        return Err(CloudError::NotConnected);
278    }
279    let instance = store.instance()?.ok_or(CloudError::NotConnected)?;
280    let root = super::root_cert::trust_root(store, config, &instance.url)?;
281    let session = Session::load(store.clone(), root)?;
282    if session.lease.state_at(UtcDateTime::now()) == LeaseState::Lapsed {
283        return Err(CloudError::LeaseLapsed);
284    }
285    Ok(session)
286}
287
288/// The nudged pull: verify, apply and ack the policy now (the same
289/// [`crate::policy::pull`] the tick runs), outside the tick.
290fn policy_now(store: &CloudStore, config: &CloudConfig, requested: Option<u64>) {
291    let installed = crate::policy::load_state(store.data_dir())
292        .effective
293        .map(|effective| effective.version);
294    if config.enabled == Some(false) || !nudge_needed(requested, installed) {
295        return;
296    }
297    let session = match connected_session(store, config) {
298        Ok(session) => session,
299        Err(error) => {
300            store.record_error(&format!("policy nudge: {error}"));
301            return;
302        }
303    };
304    if !session
305        .lease
306        .lease
307        .grants(lean_ctx_protocol::cloud::lease::CloudRight::PolicyPull)
308    {
309        return;
310    }
311    match crate::policy::pull(&session) {
312        Ok(_) => crate::policy::note_pull(store.data_dir(), crate::policy::PulledVia::Nudge),
313        Err(error) => store.record_error(&format!("policy: {error}")),
314    }
315}
316
317/// Start the scheduler thread when this machine is connected and Cloud is
318/// not disabled. Returns `None` when there is nothing to schedule.
319pub fn spawn(config: CloudConfig) -> Option<std::thread::JoinHandle<()>> {
320    let store = CloudStore::open().ok()?;
321    if config.enabled == Some(false) || !matches!(store.instance(), Ok(Some(_))) {
322        // Disabled or not connected: nothing records for Cloud (N1).
323        super::receipts::stop_local_recording(store.data_dir());
324        return None;
325    }
326    // Vault sync in the background, beside the scheduler (gap 2 A).
327    super::sync::auto::spawn(store.clone(), config.clone());
328    std::thread::Builder::new()
329        .name("cloud-scheduler".into())
330        .spawn(move || {
331            let mut config = config;
332            loop {
333                if let TickOutcome::Stop(_) = tick(&store, &config) {
334                    super::sync::auto::stop();
335                    return;
336                }
337                // Sleep until the next tick; a policy nudge (bus frame
338                // `policy.advanced`, a reconnect) pulls the policy at once.
339                let next = Instant::now() + tick_every(&config);
340                while let Some(nudge) = wait_nudge(next) {
341                    policy_now(&store, &config, nudge.version);
342                }
343                // K2 review 3 (NEW-2): `config set cloud.metrics_upload false`
344                // or `cloud.enabled false` applies on the next tick, not only
345                // after a restart of this long-lived process.
346                config = lean_ctx::core::config::Config::load().cloud.clone();
347            }
348        })
349        .ok()
350}
351
352#[cfg(test)]
353mod tests {
354    use super::*;
355
356    #[test]
357    fn a_nudge_pulls_only_a_newer_version_or_after_a_reconnect() {
358        assert!(nudge_needed(None, Some(9)));
359        assert!(nudge_needed(Some(3), None));
360        assert!(nudge_needed(Some(4), Some(3)));
361        assert!(!nudge_needed(Some(3), Some(3)));
362        assert!(!nudge_needed(Some(2), Some(3)));
363    }
364
365    /// One test owns the process-wide nudge state (nextest runs each test
366    /// in its own process).
367    #[test]
368    fn nudges_coalesce_and_are_spaced() {
369        let soon = || Instant::now() + Duration::from_millis(50);
370        assert_eq!(wait_nudge(soon()), None, "no nudge: the deadline");
371        nudge_policy(Some(4));
372        nudge_policy(None);
373        nudge_policy(Some(6));
374        assert_eq!(
375            wait_nudge(soon()),
376            Some(Nudge { version: None }),
377            "one pull for the burst; the reconnect pulls regardless"
378        );
379        // The next nudge within the spacing waits past a short deadline.
380        nudge_policy(Some(7));
381        assert_eq!(wait_nudge(soon()), None);
382        nudges().last_run = Instant::now().checked_sub(NUDGE_SPACING);
383        assert_eq!(wait_nudge(soon()), Some(Nudge { version: Some(7) }));
384    }
385}