Skip to main content

lean_ctx_cloud/sync/
on_write.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Push a knowledge write to Cloud from the process that made it (#270).
3//!
4//! `ctx_knowledge` runs in the MCP server of the agent, the background
5//! sync ([`super::auto`]) in the daemon: the daemon only saw a remembered
6//! fact on its next poll, after its debounce and spacing. Here the writing
7//! process syncs the vault of the checkout itself, about `COALESCE` after
8//! the write and off the tool call, on its own thread — the `cloud-calls`
9//! thread of task claims never waits behind it.
10//!
11//! Bounded: requests of one checkout coalesce (a burst of writes is one
12//! push), one push per `SPACING` per checkout in this process, and every
13//! push takes its turn from the vault's budget that all processes of the
14//! machine share (`super::budget`: a burst of `BURST_MAX` attempts, then
15//! one per `BURST_EVERY`, none while a failure or Cloud's `Retry-After` holds the
16//! vault back). A vault another sync holds is tried again at most
17//! `LOCK_RETRIES` times. Whatever does not go out here, the daemon's sync
18//! takes along.
19
20use std::collections::BTreeMap;
21use std::path::Path;
22use std::sync::atomic::{AtomicBool, Ordering};
23use std::sync::{Condvar, Mutex, OnceLock};
24use std::time::{Duration, Instant};
25
26use crate::state::CloudStore;
27use crate::vault::VaultRecord;
28
29/// Wait after the first request of a burst before the push.
30pub(crate) const COALESCE: Duration = Duration::from_millis(300);
31/// Least time between two pushes of one checkout.
32pub(crate) const SPACING: Duration = Duration::from_secs(2);
33/// How often a push the vault lock turned away is tried again.
34pub(crate) const LOCK_RETRIES: u8 = 3;
35
36/// What one push attempt came to.
37#[derive(Debug, Clone, Copy, PartialEq, Eq)]
38pub(crate) enum Outcome {
39    /// Synced (or failed and noted in the status: the backoff holds it).
40    Done,
41    /// Another sync of the vault holds its lock: try again.
42    Busy,
43    /// Nothing to push from here (not connected, not shared, backing off).
44    Skipped,
45}
46
47/// The checkouts waiting for a push.
48#[derive(Debug, Default)]
49pub(crate) struct Queue {
50    /// Checkout → its earliest request not pushed yet.
51    wants: BTreeMap<String, Instant>,
52    /// Checkout → when its last push started.
53    last: BTreeMap<String, Instant>,
54    /// Checkout → lock retries so far.
55    retries: BTreeMap<String, u8>,
56}
57
58impl Queue {
59    /// Ask for a push of `root`; a request already waiting keeps its time.
60    pub(crate) fn request(&mut self, root: &str, now: Instant) {
61        self.wants.entry(root.to_string()).or_insert(now);
62    }
63
64    fn ready_at(&self, root: &str, requested: Instant) -> Instant {
65        let coalesced = requested + COALESCE;
66        match self.last.get(root) {
67            Some(last) => coalesced.max(*last + SPACING),
68            None => coalesced,
69        }
70    }
71
72    /// The checkouts to push at `now`, and when the next one is due.
73    pub(crate) fn due(&self, now: Instant) -> (Vec<String>, Option<Instant>) {
74        let mut ready = Vec::new();
75        let mut next: Option<Instant> = None;
76        for (root, requested) in &self.wants {
77            let at = self.ready_at(root, *requested);
78            if at <= now {
79                ready.push(root.clone());
80            } else {
81                next = Some(next.map_or(at, |n| n.min(at)));
82            }
83        }
84        (ready, next)
85    }
86
87    /// `root` is pushed from `now` on.
88    pub(crate) fn take(&mut self, root: &str, now: Instant) {
89        self.wants.remove(root);
90        self.last
91            .retain(|_, at| now.saturating_duration_since(*at) < SPACING);
92        self.last.insert(root.to_string(), now);
93    }
94
95    /// Record how the push of `root` ended.
96    pub(crate) fn finished(&mut self, root: &str, outcome: Outcome, now: Instant) {
97        if outcome != Outcome::Busy {
98            self.retries.remove(root);
99            return;
100        }
101        let tries = self.retries.entry(root.to_string()).or_insert(0);
102        *tries += 1;
103        if *tries > LOCK_RETRIES {
104            // The sync holding the lock or the daemon's next one takes it.
105            self.retries.remove(root);
106        } else {
107            self.request(root, now);
108        }
109    }
110}
111
112/// Push every checkout due at `now` with `push`; the time the next one is
113/// due. The queue is not locked while a push runs.
114pub(crate) fn step(
115    queue: &Mutex<Queue>,
116    now: Instant,
117    push: &mut impl FnMut(&str) -> Outcome,
118) -> Option<Instant> {
119    let ready = {
120        let mut queue = queue
121            .lock()
122            .unwrap_or_else(std::sync::PoisonError::into_inner);
123        let (ready, _) = queue.due(now);
124        for root in &ready {
125            queue.take(root, now);
126        }
127        ready
128    };
129    let ended: Vec<(String, Outcome)> = ready
130        .into_iter()
131        .map(|root| {
132            let outcome = push(&root);
133            (root, outcome)
134        })
135        .collect();
136    let mut queue = queue
137        .lock()
138        .unwrap_or_else(std::sync::PoisonError::into_inner);
139    for (root, outcome) in ended {
140        queue.finished(&root, outcome, now);
141    }
142    queue.due(now).1
143}
144
145fn state() -> &'static (Mutex<Queue>, Condvar) {
146    static STATE: OnceLock<(Mutex<Queue>, Condvar)> = OnceLock::new();
147    STATE.get_or_init(|| (Mutex::new(Queue::default()), Condvar::new()))
148}
149
150static STARTED: AtomicBool = AtomicBool::new(false);
151
152/// Push the vault of the checkout `project_root` to Cloud soon: call after
153/// a knowledge write. Returns at once without touching the disk; whether
154/// this machine is connected is looked at on the `cloud-push` thread.
155pub fn push_soon(project_root: &str) {
156    #[cfg(any(test, feature = "test-support"))]
157    record_request(project_root);
158    let (queue, wake) = state();
159    queue
160        .lock()
161        .unwrap_or_else(std::sync::PoisonError::into_inner)
162        .request(project_root, Instant::now());
163    wake.notify_all();
164    if STARTED.swap(true, Ordering::SeqCst) {
165        return;
166    }
167    let started = std::thread::Builder::new()
168        .name("cloud-push".into())
169        .spawn(worker);
170    if started.is_err() {
171        // The daemon's sync takes the write along.
172        STARTED.store(false, Ordering::SeqCst);
173    }
174}
175
176/// Requests per checkout `push_soon` took (tests across crates observe
177/// that a tool asks for a push).
178#[cfg(any(test, feature = "test-support"))]
179fn requests() -> &'static Mutex<BTreeMap<String, usize>> {
180    static REQUESTS: OnceLock<Mutex<BTreeMap<String, usize>>> = OnceLock::new();
181    REQUESTS.get_or_init(Mutex::default)
182}
183
184#[cfg(any(test, feature = "test-support"))]
185fn record_request(root: &str) {
186    *requests()
187        .lock()
188        .unwrap_or_else(std::sync::PoisonError::into_inner)
189        .entry(root.to_string())
190        .or_default() += 1;
191}
192
193/// How many pushes of the checkout `root` were asked for in this process.
194#[cfg(any(test, feature = "test-support"))]
195pub fn requested(root: &str) -> usize {
196    requests()
197        .lock()
198        .unwrap_or_else(std::sync::PoisonError::into_inner)
199        .get(root)
200        .copied()
201        .unwrap_or(0)
202}
203
204/// Clears `STARTED` when the worker ends in any way (a panic included), so
205/// the next write starts a new one instead of switching push on write off.
206struct Running;
207
208impl Drop for Running {
209    fn drop(&mut self) {
210        STARTED.store(false, Ordering::SeqCst);
211    }
212}
213
214fn worker() {
215    let _running = Running;
216    let (queue, wake) = state();
217    // A push that panics ends as done (the daemon takes it along); the
218    // thread goes on with the next one.
219    let mut push = |root: &str| {
220        std::panic::catch_unwind(|| push_now(root)).unwrap_or_else(|_| {
221            tracing::debug!("cloud: push on write of {root} panicked");
222            Outcome::Done
223        })
224    };
225    loop {
226        let now = Instant::now();
227        let next = step(queue, now, &mut push);
228        let guard = queue
229            .lock()
230            .unwrap_or_else(std::sync::PoisonError::into_inner);
231        // A request that came in during the push is due on the next step.
232        let next = match guard.due(Instant::now()) {
233            (ready, _) if !ready.is_empty() => continue,
234            (_, later) => later.or(next),
235        };
236        match next {
237            Some(at) => {
238                let wait = at.saturating_duration_since(Instant::now());
239                drop(wake.wait_timeout(guard, wait));
240            }
241            // Idle: sleep until the next request.
242            None => drop(wake.wait(guard)),
243        }
244    }
245}
246
247/// The vault bound to the checkout `root`, as this machine recorded it.
248fn bound_record(store: &CloudStore, root: &Path) -> Option<VaultRecord> {
249    let stable =
250        lean_ctx_protocol::cloud::vault::stable_identity(&crate::vault::project_identity(root)?);
251    crate::vault::VaultMap::load(store.data_dir())
252        .vaults
253        .get(&stable)
254        .cloned()
255}
256
257/// Sync the vault of `root` now, as the daemon's pass does.
258fn push_now(root: &str) -> Outcome {
259    let Ok(store) = CloudStore::open() else {
260        return Outcome::Skipped;
261    };
262    // Not connected to Cloud: nothing to push.
263    if !matches!(store.instance(), Ok(Some(_))) {
264        return Outcome::Skipped;
265    }
266    let config = lean_ctx::core::config::Config::load().cloud.clone();
267    if config.enabled == Some(false) || !crate::bus::relay_v2::speaks_v2(&store) {
268        return Outcome::Skipped;
269    }
270    let path = Path::new(root);
271    let Some(record) = bound_record(&store, path) else {
272        return Outcome::Skipped;
273    };
274    // Storage full, a plan that does not allow it, repeated `404`s or a
275    // link that needs a login: the vault is held until a person syncs (or
276    // the daemon's recheck succeeds); a write does not resend the batch. A
277    // login or new lease since then ends the hold first.
278    super::auto::release_holds(&store, &config);
279    if super::auto::is_parked(store.data_dir(), &record.vault_id) {
280        return Outcome::Skipped;
281    }
282    let mut screen = crate::knowledge::screening::Screen::for_installation();
283    if screen.problem().is_some() {
284        return Outcome::Skipped;
285    }
286    let lock = match super::auto::lock_vault(store.data_dir(), &record.vault_id, false) {
287        Ok(Some(lock)) => lock,
288        Ok(None) => return Outcome::Busy,
289        Err(_) => return Outcome::Skipped,
290    };
291    // The vault's budget, shared with the daemon and every other process:
292    // held back or used up, the daemon's sync takes the write along later.
293    if super::budget::admit_sync(
294        store.data_dir(),
295        &record.vault_id,
296        false,
297        lean_ctx_time::UtcDateTime::now(),
298    ) != super::budget::Admit::Go
299    {
300        return Outcome::Skipped;
301    }
302    // Offline or lapsed: the daemon's sync backs off and retries.
303    let Ok(session) = crate::scheduler::connected_session(&store, &config) else {
304        return Outcome::Skipped;
305    };
306    let synced = super::place::sync_vault(&session, &record, path, &mut screen);
307    if let Err(error) = &synced {
308        tracing::debug!(
309            "cloud: push on write of {} failed: {error}",
310            record.vault_id
311        );
312    }
313    let wait = super::auto::note_outside(
314        &session.store,
315        &record,
316        super::auto::Trigger::Local,
317        synced.as_ref(),
318    );
319    super::budget::settle(
320        store.data_dir(),
321        &record.vault_id,
322        wait,
323        lean_ctx_time::UtcDateTime::now(),
324    );
325    drop(lock);
326    Outcome::Done
327}
328
329#[cfg(test)]
330#[path = "on_write_tests.rs"]
331mod tests;