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(), None) {
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/// How often a daemon that started before `cloud connect` looks for the
318/// connection (#1314): one file read.
319pub(crate) const CONNECT_POLL: Duration = Duration::from_secs(15);
320
321/// The longest wait after a connection whose first pass stopped at once.
322const STOPPED_BACKOFF_MAX: Duration = Duration::from_secs(3600);
323
324/// Whether this machine is enrolled with a Cloud (an instance record).
325pub(crate) fn is_connected(store: &CloudStore) -> bool {
326    matches!(store.instance(), Ok(Some(_)))
327}
328
329/// Block until this machine is enrolled, looking every `poll` (#1314).
330pub(crate) fn wait_until_connected(store: &CloudStore, poll: Duration) {
331    wait_until(poll, || is_connected(store).then_some(()));
332}
333
334/// Block until `ready` gives a value, asking every `poll`.
335fn wait_until<T>(poll: Duration, mut ready: impl FnMut() -> Option<T>) -> T {
336    loop {
337        if let Some(value) = ready() {
338            return value;
339        }
340        std::thread::sleep(poll);
341    }
342}
343
344/// Start the scheduler thread unless Cloud is disabled. The thread runs the
345/// passes while this machine has a usable session and waits for one (a
346/// `cloud connect`) before and after (#1314). Returns `None` when Cloud is
347/// disabled at start.
348pub fn spawn(config: &CloudConfig) -> Option<std::thread::JoinHandle<()>> {
349    let store = CloudStore::open().ok()?;
350    if config.enabled == Some(false) {
351        // Disabled: nothing records for Cloud (N1).
352        super::receipts::stop_local_recording(store.data_dir());
353        return None;
354    }
355    if connected_session(&store, config).is_err() {
356        // Not connected (or not usable) yet: nothing records for Cloud (N1)
357        // until the first pass after `cloud connect` turns it on again.
358        super::receipts::stop_local_recording(store.data_dir());
359    }
360    std::thread::Builder::new()
361        .name("cloud-scheduler".into())
362        .spawn(move || {
363            // #1314: a daemon running before `cloud connect` is not always
364            // restarted by it (the app supervises its own daemon), and a
365            // pass that stopped (a disconnect, a lapsed lease) may see a new
366            // connection later: wait for a session that loads, so a connect
367            // half written (instance before lease) is not a final Stop.
368            serve(
369                CONNECT_POLL,
370                STOPPED_BACKOFF_MAX,
371                || {
372                    let config = lean_ctx::core::config::Config::load().cloud.clone();
373                    connected_session(&store, &config).is_ok().then_some(config)
374                },
375                |config| run_passes(&store, config),
376                std::thread::sleep,
377                usize::MAX,
378            );
379        })
380        .ok()
381}
382
383/// The scheduler's life over connections: wait (every `poll`) until `ready`
384/// gives a config, `run` the passes until a Stop, and again, `rounds`
385/// times. A connection whose first pass stops at once (a pending
386/// disconnect the Cloud refuses, a state the session check does not see)
387/// waits longer each time, doubling from `poll` to `max`, so it never
388/// spins or floods the Cloud; one that ran waits `poll` again.
389fn serve<C>(
390    poll: Duration,
391    max: Duration,
392    mut ready: impl FnMut() -> Option<C>,
393    mut run: impl FnMut(C) -> bool,
394    mut sleep: impl FnMut(Duration),
395    rounds: usize,
396) {
397    let mut backoff = poll;
398    for _ in 0..rounds {
399        let config = loop {
400            if let Some(config) = ready() {
401                break config;
402            }
403            sleep(poll);
404        };
405        if run(config) {
406            backoff = poll;
407            sleep(poll);
408        } else {
409            sleep(backoff);
410            backoff = backoff.saturating_mul(2).min(max);
411        }
412    }
413}
414
415/// The passes of one connection, until a pass stops (disconnected,
416/// disabled, revoked, lapsed). Vault sync runs beside them (gap 2 A).
417/// Whether a pass ran before the Stop.
418fn run_passes(store: &CloudStore, mut config: CloudConfig) -> bool {
419    super::sync::auto::spawn(store.clone(), config.clone());
420    let mut ran = false;
421    loop {
422        if let TickOutcome::Stop(_) = tick(store, &config) {
423            super::sync::auto::stop();
424            return ran;
425        }
426        ran = true;
427        // Sleep until the next tick; a policy nudge (bus frame
428        // `policy.advanced`, a reconnect) pulls the policy at once.
429        let next = Instant::now() + tick_every(&config);
430        while let Some(nudge) = wait_nudge(next) {
431            policy_now(store, &config, nudge.version);
432        }
433        // K2 review 3 (NEW-2): `config set cloud.metrics_upload false`
434        // or `cloud.enabled false` applies on the next tick, not only
435        // after a restart of this long-lived process.
436        config = lean_ctx::core::config::Config::load().cloud.clone();
437    }
438}
439
440#[cfg(test)]
441mod tests {
442    use super::*;
443
444    #[test]
445    fn a_nudge_pulls_only_a_newer_version_or_after_a_reconnect() {
446        assert!(nudge_needed(None, Some(9)));
447        assert!(nudge_needed(Some(3), None));
448        assert!(nudge_needed(Some(4), Some(3)));
449        assert!(!nudge_needed(Some(3), Some(3)));
450        assert!(!nudge_needed(Some(2), Some(3)));
451    }
452
453    /// #1314 (bd 41427): a connection whose pass stops at once (revoked,
454    /// a refused pending disconnect) is asked again only after a wait that
455    /// doubles up to the maximum, never in a hot loop; one that ran waits
456    /// the poll again; an unready one is asked every poll.
457    #[test]
458    fn a_pass_that_stops_at_once_backs_off() {
459        let poll = Duration::from_secs(15);
460        let max = Duration::from_secs(60);
461        let mut asked = 0;
462        let mut runs = 0;
463        let mut slept = Vec::new();
464        serve(
465            poll,
466            max,
467            || {
468                asked += 1;
469                (asked != 2).then_some(())
470            },
471            |()| {
472                runs += 1;
473                runs == 4
474            },
475            |d| slept.push(d.as_secs()),
476            6,
477        );
478        assert_eq!(runs, 6);
479        // Stopped at once: 15; not ready: 15; stopped: 30, 60 (the
480        // maximum); ran: 15 (reset); stopped: 15, 30.
481        assert_eq!(slept, [15, 15, 30, 60, 15, 15, 30]);
482    }
483
484    /// #1314: the wait for `cloud connect` ends as soon as the instance
485    /// record is there.
486    #[test]
487    fn the_wait_ends_once_the_machine_is_connected() {
488        let tmp = tempfile::tempdir().unwrap();
489        let store = CloudStore::at(tmp.path().join("config"), tmp.path().join("data"));
490        assert!(!is_connected(&store));
491        let waiting = {
492            let store = store.clone();
493            std::thread::spawn(move || wait_until_connected(&store, Duration::from_millis(5)))
494        };
495        std::thread::sleep(Duration::from_millis(30));
496        assert!(!waiting.is_finished(), "no instance record: still waiting");
497        let record = crate::state::InstanceRecord {
498            instance_id: "inst_8e3c0d5f2b4e4f609b8c1d2e3f4a5b6c".into(),
499            org_id: "org_ada".into(),
500            org_name: "ada".into(),
501            label: "laptop".into(),
502            url: "https://cloud.example".into(),
503            org_salt_id: "s".into(),
504            enrolled_at: "2026-11-26T10:00:00Z".into(),
505            web_url: None,
506            org_kind: None,
507            company_name: None,
508        };
509        store
510            .write_config(crate::state::INSTANCE_FILE, &record)
511            .unwrap();
512        waiting.join().unwrap();
513        assert!(is_connected(&store));
514    }
515
516    /// One test owns the process-wide nudge state (nextest runs each test
517    /// in its own process).
518    #[test]
519    fn nudges_coalesce_and_are_spaced() {
520        let soon = || Instant::now() + Duration::from_millis(50);
521        assert_eq!(wait_nudge(soon()), None, "no nudge: the deadline");
522        nudge_policy(Some(4));
523        nudge_policy(None);
524        nudge_policy(Some(6));
525        assert_eq!(
526            wait_nudge(soon()),
527            Some(Nudge { version: None }),
528            "one pull for the burst; the reconnect pulls regardless"
529        );
530        // The next nudge within the spacing waits past a short deadline.
531        nudge_policy(Some(7));
532        assert_eq!(wait_nudge(soon()), None);
533        nudges().last_run = Instant::now().checked_sub(NUDGE_SPACING);
534        assert_eq!(wait_nudge(soon()), Some(Nudge { version: Some(7) }));
535    }
536}