Skip to main content

weirdnet_agent/
jobs.rs

1//! Synced jobs (feature `jobs`): a typed job board over the weirdnet-sync job log, so a job one
2//! device started can be picked up by another from its last checkpoint.
3//!
4//! [`JobBoard<P>`] is a thin, typed layer over `weirdnet_sync::Jobs` and `Leases::claim_job`,
5//! not a second log: every job is signed [`JobEvent`]s in the op log, sealed and synced like
6//! any other record type, and every device folds them into the same [`JobRecord<P>`]. Apps
7//! add only their payload type `P` (for Ymir, a training job).
8//!
9//! - **Claims** are majority-vote leases (`<kind>/<job id>`) among the devices with the job's
10//!   role. Their term is the fencing token ([`Claim::term`], [`Claim::fence`]). A [`Claim`]
11//!   renews in the background; if its holder disappears, voters wait out
12//!   [`JobPolicy::takeover_after_ms`] after the lease lapsed before another device may claim,
13//!   so a network drop doesn't move a long job. The holder itself can renew back inside that
14//!   wait.
15//! - **Who may claim**: devices with [`JobPolicy::role`], narrowed by
16//!   [`JobPolicy::candidates`], plus the app's own check passed to [`JobBoard::claim`].
17//!   Claims from anyone else are ignored when folding and refused by voters.
18//! - **Checkpoints** are pointers ([`CheckpointRef`]): a content hash, its size and the devices
19//!   holding a copy. The app moves the bytes itself.
20//! - **Retries**: [`Claim::fail`] with `retry: true` reopens the job after
21//!   [`JobPolicy::retry_backoff_ms`] until [`JobPolicy::max_attempts`] claims were used
22//!   (lapsed claims count); `retry: false` is final. [`Claim::pause`] and the owner's
23//!   [`JobBoard::pause`] never count as an attempt.
24//!
25//! Voters: every device with the role runs a `weirdnet_sync::Voter` for it, with limits that
26//! allow the job's claim time ([`JobPolicy::configure_voter`]). The `jobs` feature needs
27//! weirdnet-sync 0.8.2 or newer.
28use std::collections::{BTreeMap, VecDeque};
29use std::marker::PhantomData;
30use std::sync::atomic::{AtomicBool, Ordering};
31use std::sync::{Arc, Mutex};
32use std::time::{Duration, Instant};
33
34use serde::de::DeserializeOwned;
35use serde::{Deserialize, Serialize};
36use tokio::sync::watch;
37use weirdnet_net::Node;
38use weirdnet_sync::{
39    FenceGuard, Hlc, JobEvent, JobRules, JobSpec, JobStatus, JobView, Jobs, LeaseConfig, LeaseError, LeaseHandle, LeaseName, Leases, Stale,
40    SyncState, Term, Voter, Voters, job_lease,
41};
42
43/// A device's peer id, as in the weirdnet-sync roster.
44pub type PeerId = String;
45/// Largest encoded payload.
46pub const MAX_PAYLOAD: usize = 64 * 1024;
47/// Finished and cancelled jobs older than this are left out of [`JobBoard::list`] unless
48/// [`JobFilter::include_old`] is set.
49pub const RETENTION: Duration = Duration::from_secs(30 * 24 * 3600);
50/// Checkpoints [`JobBoard::checkpoints`] returns, newest last.
51pub const KEEP_CHECKPOINTS: usize = 8;
52/// [`Claim::progress`] writes at most once per this interval.
53pub const PROGRESS_EVERY: Duration = Duration::from_secs(30);
54const NOTE_PROGRESS: &str = "progress";
55const NOTE_HOLDERS: &str = "holders";
56
57type SyncNode = Node<Vec<u8>, Vec<u8>>;
58
59/// A SHA-256 digest; shown and parsed as `sha256:<64 hex>`.
60#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default, Serialize, Deserialize)]
61pub struct ContentHash(pub [u8; 32]);
62
63impl ContentHash {
64    /// The first 16 hex digits with the `sha256:` prefix, as Ymir writes base revisions.
65    pub fn short(&self) -> String {
66        format!("sha256:{}", &hex(&self.0)[..16])
67    }
68}
69
70fn hex(b: &[u8]) -> String {
71    b.iter().map(|x| format!("{x:02x}")).collect()
72}
73
74impl std::fmt::Display for ContentHash {
75    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
76        write!(f, "sha256:{}", hex(&self.0))
77    }
78}
79
80impl std::fmt::Debug for ContentHash {
81    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
82        std::fmt::Display::fmt(self, f)
83    }
84}
85
86impl std::str::FromStr for ContentHash {
87    type Err = JobError;
88    fn from_str(s: &str) -> Result<Self, JobError> {
89        let h = s.strip_prefix("sha256:").unwrap_or(s);
90        if h.len() != 64 || !h.bytes().all(|c| c.is_ascii_hexdigit()) {
91            return Err(JobError::Codec(format!("not a sha256 digest: {s:?}")));
92        }
93        let mut out = [0u8; 32];
94        for (i, o) in out.iter_mut().enumerate() {
95            *o = u8::from_str_radix(&h[2 * i..2 * i + 2], 16).map_err(|e| JobError::Codec(e.to_string()))?;
96        }
97        Ok(Self(out))
98    }
99}
100
101/// Where a job stands.
102#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
103#[non_exhaustive]
104pub enum JobState {
105    Queued,
106    Running,
107    Paused,
108    Failed,
109    Done,
110    Cancelled,
111}
112
113impl From<JobStatus> for JobState {
114    fn from(s: JobStatus) -> Self {
115        match s {
116            JobStatus::Open => JobState::Queued,
117            JobStatus::Claimed => JobState::Running,
118            JobStatus::Paused => JobState::Paused,
119            JobStatus::Done => JobState::Done,
120            JobStatus::Cancelled => JobState::Cancelled,
121            _ => JobState::Failed,
122        }
123    }
124}
125
126/// The claim with the highest term, as recorded in the log.
127#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
128#[non_exhaustive]
129pub struct LeaseInfo {
130    pub holder: PeerId,
131    /// The fencing term.
132    pub term: u64,
133    /// The holder's newest event (its claim, a checkpoint or a note) plus the claim time, by
134    /// the writer's clock. Informational: the voters decide whether the lease is alive.
135    pub expires_ms: u64,
136}
137
138/// A pointer to a checkpoint the app stores itself.
139#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
140#[non_exhaustive]
141pub struct CheckpointRef {
142    /// Increases per checkpoint within a claim.
143    pub seq: u64,
144    /// The app's step (for training, the optimizer step).
145    pub step: u64,
146    /// Hash of the checkpoint's manifest.
147    pub root: ContentHash,
148    pub bytes: u64,
149    /// Devices holding a copy, the writer first.
150    pub holders: Vec<PeerId>,
151}
152
153impl CheckpointRef {
154    pub fn new(seq: u64, step: u64, root: ContentHash, bytes: u64, holders: Vec<PeerId>) -> Self {
155        Self { seq, step, root, bytes, holders }
156    }
157}
158
159/// How a job is claimed, renewed, taken over and retried.
160#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
161#[non_exhaustive]
162pub struct JobPolicy {
163    /// How long a claim lasts at the voters (ms).
164    pub claim_ms: u64,
165    /// How often the holder renews (ms).
166    pub renew_ms: u64,
167    /// After a claim lapses, how long voters wait before another device may claim (ms).
168    pub takeover_after_ms: u64,
169    /// Claims (lapsed ones included) before a retryable failure is final.
170    pub max_attempts: u32,
171    /// Wait after a retryable failure before the next claim (ms).
172    pub retry_backoff_ms: u64,
173    /// Devices that may claim; empty means any device with `role`.
174    pub candidates: Vec<PeerId>,
175    /// The role grant claimers need; the voters are the devices with it.
176    pub role: String,
177}
178
179impl Default for JobPolicy {
180    /// 60 s claims renewed every 20 s, a 5 min takeover wait, 3 attempts, 60 s backoff, no role.
181    fn default() -> Self {
182        Self {
183            claim_ms: 60_000,
184            renew_ms: 20_000,
185            takeover_after_ms: 300_000,
186            max_attempts: 3,
187            retry_backoff_ms: 60_000,
188            candidates: Vec::new(),
189            role: String::new(),
190        }
191    }
192}
193
194impl JobPolicy {
195    /// The defaults with claimers and voters taken from `role`.
196    pub fn for_role(role: impl Into<String>) -> Self {
197        Self { role: role.into(), ..Self::default() }
198    }
199
200    /// Sets the claim time and renews every third of it.
201    pub fn with_claim(mut self, claim: Duration) -> Self {
202        self.claim_ms = ms(claim);
203        self.renew_ms = self.claim_ms / 3;
204        self
205    }
206
207    pub fn with_renew(mut self, every: Duration) -> Self {
208        self.renew_ms = ms(every);
209        self
210    }
211
212    pub fn with_takeover_after(mut self, wait: Duration) -> Self {
213        self.takeover_after_ms = ms(wait);
214        self
215    }
216
217    pub fn with_max_attempts(mut self, n: u32) -> Self {
218        self.max_attempts = n.max(1);
219        self
220    }
221
222    pub fn with_retry_backoff(mut self, wait: Duration) -> Self {
223        self.retry_backoff_ms = ms(wait);
224        self
225    }
226
227    pub fn with_candidates<S: Into<PeerId>>(mut self, peers: impl IntoIterator<Item = S>) -> Self {
228        self.candidates = peers.into_iter().map(Into::into).collect();
229        self
230    }
231
232    pub fn claim(&self) -> Duration {
233        Duration::from_millis(self.claim_ms)
234    }
235
236    pub fn takeover_after(&self) -> Duration {
237        Duration::from_millis(self.takeover_after_ms)
238    }
239
240    fn voters(&self) -> Voters {
241        if self.role.is_empty() { Voters::Peers(self.candidates.clone()) } else { Voters::Role(self.role.clone()) }
242    }
243
244    /// `voter` with limits for `kind`'s claim leases: grants up to this policy's claim time
245    /// and the takeover wait. Voters also apply each job's own rules once they have synced it.
246    pub fn configure_voter(&self, voter: Voter, kind: &str) -> Voter {
247        voter.with_limits(format!("{kind}/"), self.claim(), self.takeover_after())
248    }
249
250    /// A fresh voter for this policy's role (or candidates) with [`configure_voter`]'s limits.
251    ///
252    /// [`configure_voter`]: Self::configure_voter
253    pub fn voter(&self, kind: &str) -> Voter {
254        self.configure_voter(Voter::new(self.voters()), kind)
255    }
256
257    fn rules(&self) -> JobRules {
258        let mut r = JobRules::new()
259            .with_takeover_after(self.takeover_after())
260            .with_retry_backoff(Duration::from_millis(self.retry_backoff_ms))
261            .with_candidates(self.candidates.clone());
262        if !self.role.is_empty() {
263            r = r.with_role(self.role.clone());
264        }
265        r
266    }
267}
268
269fn ms(d: Duration) -> u64 {
270    d.as_millis().min(u64::MAX as u128) as u64
271}
272
273/// A job folded from the log.
274#[derive(Debug, Clone, PartialEq)]
275#[non_exhaustive]
276pub struct JobRecord<P> {
277    pub id: String,
278    pub kind: String,
279    /// The device that posted it; it (or a full device of the user) may pause, resume and
280    /// cancel.
281    pub owner: PeerId,
282    pub base_revision: String,
283    pub dataset: ContentHash,
284    pub payload: P,
285    pub state: JobState,
286    /// Set while running.
287    pub lease: Option<LeaseInfo>,
288    /// The newest checkpoint of the highest term.
289    pub checkpoint: Option<CheckpointRef>,
290    pub attempts: u32,
291    pub policy: JobPolicy,
292    pub failure: Option<String>,
293    pub result: Option<Vec<u8>>,
294    /// The holder's newest [`Claim::progress`].
295    pub progress: Option<serde_json::Value>,
296    pub priority: u8,
297    pub created_ms: u64,
298    /// Not claimable before this time after a retryable failure (ms).
299    pub not_before_ms: Option<u64>,
300    /// The newest event's clock.
301    pub updated: Hlc,
302}
303
304/// A job to post.
305#[derive(Debug, Clone, PartialEq)]
306#[non_exhaustive]
307pub struct NewJob<P> {
308    pub id: String,
309    pub base_revision: String,
310    pub dataset: ContentHash,
311    pub payload: P,
312    pub policy: JobPolicy,
313    pub priority: u8,
314}
315
316impl<P> NewJob<P> {
317    /// A job with the default policy (set a role with [`with_policy`](Self::with_policy)).
318    pub fn new(id: impl Into<String>, base_revision: impl Into<String>, dataset: ContentHash, payload: P) -> Self {
319        Self { id: id.into(), base_revision: base_revision.into(), dataset, payload, policy: JobPolicy::default(), priority: 0 }
320    }
321
322    pub fn with_policy(mut self, policy: JobPolicy) -> Self {
323        self.policy = policy;
324        self
325    }
326
327    pub fn with_priority(mut self, priority: u8) -> Self {
328        self.priority = priority;
329        self
330    }
331}
332
333/// What [`JobBoard::list`] returns.
334#[derive(Debug, Clone, Default, PartialEq, Eq)]
335#[non_exhaustive]
336pub struct JobFilter {
337    pub state: Option<JobState>,
338    pub owner: Option<PeerId>,
339    /// Include finished and cancelled jobs older than [`RETENTION`].
340    pub include_old: bool,
341}
342
343impl JobFilter {
344    pub fn all() -> Self {
345        Self::default()
346    }
347
348    pub fn state(state: JobState) -> Self {
349        Self { state: Some(state), ..Self::default() }
350    }
351
352    pub fn with_owner(mut self, owner: impl Into<PeerId>) -> Self {
353        self.owner = Some(owner.into());
354        self
355    }
356
357    pub fn with_old(mut self) -> Self {
358        self.include_old = true;
359        self
360    }
361}
362
363/// A job that is new or changed, from [`JobBoard::watch`].
364#[derive(Debug, Clone, PartialEq)]
365#[non_exhaustive]
366pub struct JobChange<P> {
367    pub id: String,
368    pub record: JobRecord<P>,
369}
370
371/// Why a [`Claim`] ended without the holder finishing, failing or pausing it.
372#[derive(Debug, Clone, Copy, PartialEq, Eq)]
373#[non_exhaustive]
374pub enum Lost {
375    /// The lease ran out and could not be renewed within the takeover wait.
376    Lease,
377    /// Another device holds a higher term.
378    Superseded,
379    /// The owner paused the job; the claim paused itself (no attempt used) and let go.
380    PausedByOwner,
381    /// The job was cancelled; the claim let go.
382    Cancelled,
383    /// The holder finished, failed, paused or dropped the claim.
384    Released,
385}
386
387/// Job board and claim errors.
388#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
389#[non_exhaustive]
390pub enum JobError {
391    #[error("no job {0}")]
392    NotFound(String),
393    #[error("job is {0:?}")]
394    NotClaimable(JobState),
395    /// The app's check, the job's candidates or its role leave this device out.
396    #[error("this device may not claim the job")]
397    Ineligible,
398    /// In the retry backoff.
399    #[error("not claimable yet, retry in {retry_in:?}")]
400    NotYet { retry_in: Duration },
401    /// Another device holds it, or voters wait out a lapsed claim.
402    #[error("held by {holder}, retry in {retry_in:?}")]
403    Held { holder: PeerId, retry_in: Duration },
404    #[error("no quorum: {reached} of {needed} grants")]
405    NoQuorum { reached: usize, needed: usize },
406    /// The claim's lease is not valid now.
407    #[error("not holding the claim")]
408    NotHolding,
409    #[error("payload is {0} bytes encoded, over the limit")]
410    PayloadTooLarge(usize),
411    #[error("a job needs a role or candidates")]
412    NoVoters,
413    #[error("codec: {0}")]
414    Codec(String),
415    #[error("sync: {0}")]
416    Sync(String),
417}
418
419/// The spec's name for claim errors.
420pub type ClaimError = JobError;
421
422impl From<LeaseError> for JobError {
423    fn from(e: LeaseError) -> Self {
424        match e {
425            LeaseError::Held { holder, retry_in, .. } => JobError::Held { holder, retry_in },
426            LeaseError::NoQuorum { reached, needed } => JobError::NoQuorum { reached, needed },
427            LeaseError::NotEligible => JobError::Ineligible,
428            LeaseError::NotYet { retry_in } => JobError::NotYet { retry_in },
429            LeaseError::Lost => JobError::NotHolding,
430            other => JobError::Sync(other.to_string()),
431        }
432    }
433}
434
435impl From<weirdnet_sync::SyncError> for JobError {
436    fn from(e: weirdnet_sync::SyncError) -> Self {
437        JobError::Sync(e.to_string())
438    }
439}
440
441fn enc<T: Serialize>(v: &T) -> Result<Vec<u8>, JobError> {
442    cbor4ii::serde::to_vec(Vec::new(), v).map_err(|e| JobError::Codec(e.to_string()))
443}
444
445fn dec<T: DeserializeOwned>(b: &[u8]) -> Result<T, JobError> {
446    cbor4ii::serde::from_slice(b).map_err(|e| JobError::Codec(e.to_string()))
447}
448
449fn now_ms() -> u64 {
450    std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_millis() as u64).unwrap_or(0)
451}
452
453/// What a job's sync spec body holds beside the sync fields.
454#[derive(Serialize, Deserialize)]
455struct Body<P> {
456    base_revision: String,
457    dataset: ContentHash,
458    payload: P,
459    renew_ms: u64,
460    created_ms: u64,
461}
462
463/// The sync state and node the jobs use (the same ones the app syncs with).
464#[derive(Clone)]
465pub struct SyncHandle {
466    leases: Leases,
467}
468
469impl SyncHandle {
470    pub fn new(node: Arc<SyncNode>, state: Arc<Mutex<SyncState>>) -> Self {
471        Self { leases: Leases::new(node, state) }
472    }
473
474    /// From leases already set up (for example with an address book, `Leases::with_addrs`).
475    pub fn from_leases(leases: Leases) -> Self {
476        Self { leases }
477    }
478
479    pub fn leases(&self) -> &Leases {
480        &self.leases
481    }
482
483    pub fn state(&self) -> &Arc<Mutex<SyncState>> {
484        self.leases.state()
485    }
486}
487
488fn lock(st: &Mutex<SyncState>) -> Result<std::sync::MutexGuard<'_, SyncState>, JobError> {
489    st.lock().map_err(|_| JobError::Sync("sync state lock poisoned".into()))
490}
491
492/// The jobs of one kind (also their sync record type and lease prefix), with payload `P`.
493pub struct JobBoard<P> {
494    sync: SyncHandle,
495    kind: String,
496    _p: PhantomData<fn() -> P>,
497}
498
499impl<P> Clone for JobBoard<P> {
500    fn clone(&self) -> Self {
501        Self { sync: self.sync.clone(), kind: self.kind.clone(), _p: PhantomData }
502    }
503}
504
505impl<P: Serialize + DeserializeOwned + Clone + Send + Sync + 'static> JobBoard<P> {
506    /// The board for `kind` (for example `ymir.train`), which must be one of the state's
507    /// synced record types for jobs to reach other devices.
508    pub fn open(sync: &SyncHandle, kind: impl Into<String>) -> Result<Self, JobError> {
509        let kind = kind.into();
510        job_lease(&kind, "x")?;
511        Ok(Self { sync: sync.clone(), kind, _p: PhantomData })
512    }
513
514    pub fn kind(&self) -> &str {
515        &self.kind
516    }
517
518    /// Post a job; this device is its owner. Posting an id again keeps the first job.
519    pub fn post(&self, job: NewJob<P>) -> Result<JobRecord<P>, JobError> {
520        job_lease(&self.kind, &job.id)?;
521        if job.policy.role.is_empty() && job.policy.candidates.is_empty() {
522            return Err(JobError::NoVoters);
523        }
524        let size = enc(&job.payload)?.len();
525        if size > MAX_PAYLOAD {
526            return Err(JobError::PayloadTooLarge(size));
527        }
528        let body = Body {
529            base_revision: job.base_revision,
530            dataset: job.dataset,
531            payload: job.payload,
532            renew_ms: job.policy.renew_ms,
533            created_ms: now_ms(),
534        };
535        let spec = JobSpec::new(job.id.clone(), self.kind.clone(), enc(&body)?)
536            .with_priority(job.priority)
537            .with_max_attempts(job.policy.max_attempts)
538            .with_claim(job.policy.claim())
539            .with_rules(job.policy.rules());
540        let mut st = lock(self.sync.state())?;
541        Jobs::new(&mut st, self.kind.clone()).post(now_ms(), spec)?;
542        let view = Jobs::new(&mut st, self.kind.clone()).view(&job.id).ok_or_else(|| JobError::NotFound(job.id.clone()))?;
543        self.record(&st, view)
544    }
545
546    fn record(&self, st: &SyncState, v: JobView) -> Result<JobRecord<P>, JobError> {
547        let body: Body<P> = dec(&v.spec.body)?;
548        let rules = v.spec.rules.clone().unwrap_or_default();
549        let policy = JobPolicy {
550            claim_ms: v.spec.claim_ms,
551            renew_ms: body.renew_ms,
552            takeover_after_ms: rules.takeover_after_ms,
553            max_attempts: v.spec.max_attempts,
554            retry_backoff_ms: rules.retry_backoff_ms,
555            candidates: rules.candidates.clone(),
556            role: rules.role.clone().unwrap_or_default(),
557        };
558        let state = JobState::from(v.status);
559        let lease = v.claim.as_ref().filter(|_| state == JobState::Running).map(|(holder, term)| LeaseInfo {
560            holder: holder.clone(),
561            term: term.0,
562            expires_ms: v.last_seen_ms.unwrap_or(v.changed_ms).saturating_add(v.spec.claim_ms),
563        });
564        let mut checkpoint = latest_checkpoint(&v);
565        if let (Some(cp), Some((_, data))) = (checkpoint.as_mut(), v.notes.get(NOTE_HOLDERS))
566            && let Ok((seq, holders)) = dec::<(u64, Vec<PeerId>)>(data)
567            && seq == cp.seq
568        {
569            cp.holders = holders;
570        }
571        let progress = v.notes.get(NOTE_PROGRESS).and_then(|(_, d)| serde_json::from_slice(d).ok());
572        let updated = st
573            .log
574            .iter()
575            .filter(|e| e.typ == self.kind && e.record_id == v.spec.id)
576            .map(|e| e.hlc.clone())
577            .max_by(|a, b| a.cmp_total(b))
578            .ok_or_else(|| JobError::NotFound(v.spec.id.clone()))?;
579        Ok(JobRecord {
580            id: v.spec.id.clone(),
581            kind: v.spec.kind.clone(),
582            owner: v.owner.clone(),
583            base_revision: body.base_revision,
584            dataset: body.dataset,
585            payload: body.payload,
586            state,
587            lease,
588            checkpoint,
589            attempts: v.attempts,
590            policy,
591            failure: v.failure.clone(),
592            result: v.result.clone(),
593            progress,
594            priority: v.spec.priority,
595            created_ms: body.created_ms,
596            not_before_ms: v.not_before_ms,
597            updated,
598        })
599    }
600
601    fn view(&self, st: &mut SyncState, id: &str) -> Option<JobView> {
602        Jobs::new(st, self.kind.clone()).view(id)
603    }
604
605    pub fn get(&self, id: &str) -> Result<Option<JobRecord<P>>, JobError> {
606        let mut st = lock(self.sync.state())?;
607        match self.view(&mut st, id) {
608            Some(v) => self.record(&st, v).map(Some),
609            None => Ok(None),
610        }
611    }
612
613    /// Jobs matching `filter`, highest priority first, then by id. Jobs whose payload doesn't
614    /// decode as `P` are skipped.
615    pub fn list(&self, filter: &JobFilter) -> Result<Vec<JobRecord<P>>, JobError> {
616        let mut st = lock(self.sync.state())?;
617        let ids = Jobs::new(&mut st, self.kind.clone()).ids();
618        let cutoff = now_ms().saturating_sub(ms(RETENTION));
619        let mut out = Vec::new();
620        for id in ids {
621            let Some(v) = self.view(&mut st, &id) else { continue };
622            let old = matches!(v.status, JobStatus::Done | JobStatus::Cancelled) && v.changed_ms < cutoff;
623            if old && !filter.include_old {
624                continue;
625            }
626            let Ok(r) = self.record(&st, v) else { continue };
627            if filter.state.is_some_and(|s| s != r.state) || filter.owner.as_ref().is_some_and(|o| *o != r.owner) {
628                continue;
629            }
630            out.push(r);
631        }
632        out.sort_by(|a, b| b.priority.cmp(&a.priority).then_with(|| a.id.cmp(&b.id)));
633        Ok(out)
634    }
635
636    /// The newest [`KEEP_CHECKPOINTS`] checkpoints, oldest first, ordered by (term, seq).
637    pub fn checkpoints(&self, id: &str) -> Result<Vec<CheckpointRef>, JobError> {
638        let mut st = lock(self.sync.state())?;
639        let v = self.view(&mut st, id).ok_or_else(|| JobError::NotFound(id.to_string()))?;
640        let mut cps: Vec<(Term, u64, CheckpointRef)> =
641            v.checkpoints.iter().filter_map(|(t, s, d)| dec::<CheckpointRef>(d).ok().map(|c| (*t, *s, c))).collect();
642        cps.sort_by_key(|c| (c.0, c.1));
643        let skip = cps.len().saturating_sub(KEEP_CHECKPOINTS);
644        Ok(cps.into_iter().skip(skip).map(|c| c.2).collect())
645    }
646
647    /// New and changed jobs, polled once a second (the first poll reports every job).
648    pub fn watch(&self) -> impl futures::Stream<Item = JobChange<P>> + Send + 'static {
649        self.watch_every(Duration::from_secs(1))
650    }
651
652    /// [`watch`](Self::watch) polling every `every`.
653    pub fn watch_every(&self, every: Duration) -> impl futures::Stream<Item = JobChange<P>> + Send + 'static {
654        let seen: BTreeMap<String, (JobState, Hlc)> = BTreeMap::new();
655        futures::stream::unfold((self.clone(), seen, VecDeque::new()), move |(board, mut seen, mut queue)| async move {
656            loop {
657                if let Some(c) = queue.pop_front() {
658                    return Some((c, (board, seen, queue)));
659                }
660                if let Ok(all) = board.list(&JobFilter::all().with_old()) {
661                    for r in all {
662                        let key = (r.state, r.updated.clone());
663                        if seen.get(&r.id) != Some(&key) {
664                            seen.insert(r.id.clone(), key);
665                            queue.push_back(JobChange { id: r.id.clone(), record: r });
666                        }
667                    }
668                }
669                if queue.is_empty() {
670                    tokio::time::sleep(every).await;
671                }
672            }
673        })
674    }
675
676    /// Claim job `id`: it must be queued (or running with a lease that lapsed; the voters
677    /// decide), pass `eligible`, the job's candidates and role, and be past any retry backoff.
678    /// The returned [`Claim`] renews in the background until finished, failed, paused, lost
679    /// or dropped.
680    pub async fn claim(&self, id: &str, eligible: impl Fn(&JobRecord<P>) -> bool) -> Result<Claim<P>, JobError> {
681        let record = self.get(id)?.ok_or_else(|| JobError::NotFound(id.to_string()))?;
682        if !matches!(record.state, JobState::Queued | JobState::Running) {
683            return Err(JobError::NotClaimable(record.state));
684        }
685        if !eligible(&record) {
686            return Err(JobError::Ineligible);
687        }
688        let policy = record.policy.clone();
689        let mut cfg = LeaseConfig::new(policy.voters()).with_duration(policy.claim());
690        if policy.renew_ms > 0 {
691            cfg.renew_every = Duration::from_millis(policy.renew_ms);
692        }
693        let (leases, kind, jid, c) = (self.sync.leases.clone(), self.kind.clone(), id.to_string(), cfg.clone());
694        let handle = tokio::task::spawn_blocking(move || leases.claim_job(&kind, &jid, &c)).await.map_err(|e| JobError::Sync(e.to_string()))??;
695        let record = self.get(id)?.ok_or_else(|| JobError::NotFound(id.to_string()))?;
696        let (lost_tx, _) = watch::channel(None);
697        let inner = Arc::new(ClaimInner {
698            leases: self.sync.leases.clone(),
699            cfg,
700            kind: self.kind.clone(),
701            id: id.to_string(),
702            name: handle.name().clone(),
703            term: handle.term(),
704            handle: Mutex::new(handle),
705            stop: AtomicBool::new(false),
706            lost: lost_tx,
707            progress: Mutex::new((None, None)),
708            takeover_after: policy.takeover_after(),
709            thread: Mutex::new(None),
710        });
711        let worker = inner.clone();
712        let t = std::thread::Builder::new()
713            .name(format!("job claim {id}"))
714            .spawn(move || run_claim(worker))
715            .map_err(|e| JobError::Sync(format!("starting the renew thread: {e}")))?;
716        if let Ok(mut slot) = inner.thread.lock() {
717            *slot = Some(t);
718        }
719        Ok(Claim { inner, record })
720    }
721
722    fn owner_op(&self, id: &str, op: impl FnOnce(&mut Jobs<'_>, u64, &str) -> weirdnet_sync::Result<()>) -> Result<(), JobError> {
723        let mut st = lock(self.sync.state())?;
724        let mut jobs = Jobs::new(&mut st, self.kind.clone());
725        if jobs.view(id).is_none() {
726            return Err(JobError::NotFound(id.to_string()));
727        }
728        op(&mut jobs, now_ms(), id).map_err(Into::into)
729    }
730
731    /// Pause a job as its owner (or a full device). A running holder pauses itself and lets
732    /// go once it has synced this; no attempt is used.
733    pub fn pause(&self, id: &str) -> Result<(), JobError> {
734        self.owner_op(id, |j, now, id| j.pause(now, id))
735    }
736
737    /// Put a paused job back in the queue.
738    pub fn resume(&self, id: &str) -> Result<(), JobError> {
739        self.owner_op(id, |j, now, id| j.resume(now, id))
740    }
741
742    pub fn cancel(&self, id: &str) -> Result<(), JobError> {
743        self.owner_op(id, |j, now, id| j.cancel(now, id))
744    }
745}
746
747fn latest_checkpoint(v: &JobView) -> Option<CheckpointRef> {
748    v.checkpoints.iter().filter_map(|(t, s, d)| dec::<CheckpointRef>(d).ok().map(|c| ((*t, *s), c))).max_by(|a, b| a.0.cmp(&b.0)).map(|x| x.1)
749}
750
751struct ClaimInner {
752    leases: Leases,
753    cfg: LeaseConfig,
754    kind: String,
755    id: String,
756    name: LeaseName,
757    term: Term,
758    handle: Mutex<LeaseHandle>,
759    stop: AtomicBool,
760    lost: watch::Sender<Option<Lost>>,
761    /// When progress was last written, and progress waiting for its turn.
762    progress: Mutex<(Option<Instant>, Option<serde_json::Value>)>,
763    takeover_after: Duration,
764    thread: Mutex<Option<std::thread::JoinHandle<()>>>,
765}
766
767impl ClaimInner {
768    fn handle(&self) -> Option<LeaseHandle> {
769        self.handle.lock().ok().map(|h| h.clone())
770    }
771
772    fn write(&self, ev: JobEvent) -> Result<(), JobError> {
773        let h = self.handle().ok_or(JobError::NotHolding)?;
774        if !h.is_valid() {
775            return Err(JobError::NotHolding);
776        }
777        let mut st = lock(self.leases.state())?;
778        Jobs::new(&mut st, self.kind.clone()).record(now_ms(), &self.id, &h, ev).map_err(|e| match e {
779            weirdnet_sync::SyncError::NotPermitted(_) => JobError::NotHolding,
780            e => e.into(),
781        })
782    }
783
784    fn end(&self, why: Lost) {
785        self.lost.send_if_modified(|v| {
786            if v.is_none() {
787                *v = Some(why);
788                true
789            } else {
790                false
791            }
792        });
793    }
794
795    fn release(&self) {
796        if let Some(h) = self.handle() {
797            self.leases.release(h, &self.cfg);
798        }
799    }
800
801    fn flush_progress(&self, force: bool) {
802        let pending = {
803            let Ok(mut p) = self.progress.lock() else { return };
804            let due = force || p.0.is_none_or(|t| t.elapsed() >= PROGRESS_EVERY);
805            if !due || p.1.is_none() {
806                return;
807            }
808            p.0 = Some(Instant::now());
809            p.1.take()
810        };
811        if let Some(v) = pending
812            && let Ok(data) = serde_json::to_vec(&v)
813        {
814            let _ = self.write(JobEvent::Note { term: self.term, key: NOTE_PROGRESS.into(), data });
815        }
816    }
817
818    fn sleep(&self, d: Duration) -> bool {
819        let end = Instant::now() + d;
820        while Instant::now() < end {
821            if self.stop.load(Ordering::SeqCst) {
822                return false;
823            }
824            std::thread::sleep((end - Instant::now()).min(Duration::from_millis(25)));
825        }
826        !self.stop.load(Ordering::SeqCst)
827    }
828}
829
830fn run_claim(c: Arc<ClaimInner>) {
831    let mut lapsed: Option<Instant> = None;
832    loop {
833        let wait = match (lapsed, c.handle()) {
834            (Some(_), _) => Duration::from_millis(200).min(c.cfg.renew_every),
835            (None, Some(h)) => c.cfg.renew_every.min(h.remaining() / 2).max(Duration::from_millis(20)),
836            (None, None) => return,
837        };
838        if !c.sleep(wait) {
839            return;
840        }
841        // What the log says: a higher term, the owner's pause or a cancel ends this claim.
842        let view = c.leases.state().lock().ok().and_then(|mut st| Jobs::new(&mut st, c.kind.clone()).view(&c.id));
843        if let Some(v) = view {
844            if v.claim.as_ref().is_some_and(|(_, t)| *t > c.term) {
845                c.end(Lost::Superseded);
846                return;
847            }
848            match v.status {
849                JobStatus::Paused => {
850                    // Not an attempt either way: with weirdnet-sync 0.8.2 the owner's pause
851                    // spares the claim in progress even when this lease ran out first.
852                    let _ = c.write(JobEvent::Paused { term: Some(c.term) });
853                    c.release();
854                    c.end(Lost::PausedByOwner);
855                    return;
856                }
857                JobStatus::Cancelled => {
858                    c.release();
859                    c.end(Lost::Cancelled);
860                    return;
861                }
862                _ => {}
863            }
864        }
865        c.flush_progress(false);
866        let Some(mut h) = c.handle() else { return };
867        match c.leases.renew(&mut h, &c.cfg) {
868            Ok(()) => {
869                if let Ok(mut slot) = c.handle.lock() {
870                    *slot = h;
871                }
872                lapsed = None;
873            }
874            Err(LeaseError::Lost) => {
875                let since = *lapsed.get_or_insert_with(Instant::now);
876                if c.leases.term_seen(&c.name) > c.term {
877                    c.end(Lost::Superseded);
878                    return;
879                }
880                if since.elapsed() >= c.takeover_after {
881                    c.end(Lost::Lease);
882                    return;
883                }
884            }
885            Err(LeaseError::NotEligible) => {
886                c.end(Lost::Lease);
887                return;
888            }
889            Err(_) => {}
890        }
891    }
892}
893
894/// A held claim on a job. Carry [`term`](Self::term) (or a [`fence`](Self::fence)) into every
895/// effect that must happen once. Dropping it stops renewing and lets go of the lease (the job
896/// stays running in the log until another device claims it).
897pub struct Claim<P> {
898    inner: Arc<ClaimInner>,
899    record: JobRecord<P>,
900}
901
902/// A claim's fencing token for a resource's `FenceGuard`.
903#[derive(Debug, Clone, PartialEq, Eq)]
904pub struct Fence {
905    pub name: LeaseName,
906    pub term: Term,
907}
908
909impl Fence {
910    /// Accepts this term at `guard` unless it has seen a newer one for the same job.
911    pub fn check(&self, guard: &mut FenceGuard) -> Result<(), Stale> {
912        guard.check(&self.name, self.term)
913    }
914}
915
916impl<P: Clone + Send + 'static> Claim<P> {
917    pub fn id(&self) -> &str {
918        &self.inner.id
919    }
920
921    /// The fencing term.
922    pub fn term(&self) -> u64 {
923        self.inner.term.0
924    }
925
926    /// The job as it was when claimed (with the checkpoint to resume from).
927    pub fn record(&self) -> &JobRecord<P> {
928        &self.record
929    }
930
931    /// The checkpoint to resume from.
932    pub fn resume_from(&self) -> Option<&CheckpointRef> {
933        self.record.checkpoint.as_ref()
934    }
935
936    /// Whether the lease is valid now. Stop acting while it isn't; it may come back after a
937    /// network drop shorter than the takeover wait.
938    pub fn is_valid(&self) -> bool {
939        self.inner.handle().is_some_and(|h| h.is_valid()) && self.inner.lost.borrow().is_none()
940    }
941
942    /// Resolves once the claim has ended without the holder finishing, failing or pausing it.
943    pub async fn lost(&self) -> Lost {
944        let mut rx = self.inner.lost.subscribe();
945        loop {
946            if let Some(l) = *rx.borrow_and_update() {
947                return l;
948            }
949            if rx.changed().await.is_err() {
950                return Lost::Released;
951            }
952        }
953    }
954
955    /// Record a checkpoint the app has stored.
956    pub fn checkpoint(&self, cp: CheckpointRef) -> Result<(), JobError> {
957        let data = enc(&cp)?;
958        self.inner.write(JobEvent::Checkpoint { term: self.inner.term, seq: cp.seq, data })
959    }
960
961    /// Replace the holders of checkpoint `seq` without writing a new checkpoint.
962    pub fn set_holders(&self, seq: u64, holders: Vec<PeerId>) -> Result<(), JobError> {
963        let data = enc(&(seq, holders))?;
964        self.inner.write(JobEvent::Note { term: self.inner.term, key: NOTE_HOLDERS.into(), data })
965    }
966
967    /// Report progress (last writer wins). Written at most once per [`PROGRESS_EVERY`]; a
968    /// newer value given sooner replaces the waiting one and is written in its turn.
969    pub fn progress(&self, value: serde_json::Value) -> Result<(), JobError> {
970        if let Ok(mut p) = self.inner.progress.lock() {
971            p.1 = Some(value);
972        }
973        self.inner.flush_progress(false);
974        Ok(())
975    }
976
977    /// A fencing token for once-only effects (for Ymir, installing the trained adapter).
978    pub fn fence(&self) -> Fence {
979        Fence { name: self.inner.name.clone(), term: self.inner.term }
980    }
981
982    async fn close(&self, ev: Option<JobEvent>) -> Result<(), JobError> {
983        let inner = self.inner.clone();
984        tokio::task::spawn_blocking(move || {
985            inner.stop.store(true, Ordering::SeqCst);
986            if let Some(t) = inner.thread.lock().ok().and_then(|mut t| t.take()) {
987                let _ = t.join();
988            }
989            inner.flush_progress(true);
990            let r = ev.map(|e| inner.write(e)).unwrap_or(Ok(()));
991            inner.release();
992            inner.end(Lost::Released);
993            r
994        })
995        .await
996        .map_err(|e| JobError::Sync(e.to_string()))?
997    }
998
999    /// The job is done with `result`.
1000    pub async fn finish(self, result: Vec<u8>) -> Result<(), JobError> {
1001        self.close(Some(JobEvent::Finished { term: self.inner.term, result })).await
1002    }
1003
1004    /// The attempt failed. `retry: true` reopens the job after the backoff while attempts
1005    /// remain; `retry: false` is final.
1006    pub async fn fail(self, reason: impl Into<String>, retry: bool) -> Result<(), JobError> {
1007        self.close(Some(JobEvent::Failed { term: self.inner.term, reason: reason.into(), retry })).await
1008    }
1009
1010    /// Stop and let go without failing; the job is paused until its owner resumes it, and
1011    /// this claim is not counted as an attempt.
1012    pub async fn pause(self) -> Result<(), JobError> {
1013        self.close(Some(JobEvent::Paused { term: Some(self.inner.term) })).await
1014    }
1015}
1016
1017impl<P> Drop for Claim<P> {
1018    fn drop(&mut self) {
1019        if self.inner.stop.swap(true, Ordering::SeqCst) {
1020            return;
1021        }
1022        let inner = self.inner.clone();
1023        // Let go off the async runtime: a release waits for the voters.
1024        let _ = std::thread::Builder::new().name("job claim release".into()).spawn(move || {
1025            if let Some(t) = inner.thread.lock().ok().and_then(|mut t| t.take()) {
1026                let _ = t.join();
1027            }
1028            if inner.lost.borrow().is_none() {
1029                inner.release();
1030                inner.end(Lost::Released);
1031            }
1032        });
1033    }
1034}
1035
1036#[cfg(test)]
1037mod tests {
1038    use super::*;
1039
1040    #[test]
1041    fn content_hashes_print_and_parse() {
1042        let h = ContentHash([0xab; 32]);
1043        let s = h.to_string();
1044        assert_eq!(s.len(), 7 + 64);
1045        assert_eq!(s.parse::<ContentHash>().unwrap(), h);
1046        assert_eq!(s[7..].parse::<ContentHash>().unwrap(), h);
1047        assert_eq!(h.short(), "sha256:abababababababab");
1048        assert!("sha256:xyz".parse::<ContentHash>().is_err());
1049    }
1050
1051    #[test]
1052    fn the_default_policy_matches_training_jobs() {
1053        let p = JobPolicy::for_role("ymir.model");
1054        assert_eq!((p.claim_ms, p.renew_ms, p.takeover_after_ms, p.max_attempts, p.retry_backoff_ms), (60_000, 20_000, 300_000, 3, 60_000));
1055        let v = p.voter("ymir.train");
1056        let n = LeaseName::new("ymir.train/j1").unwrap();
1057        assert_eq!(v.limits_for(&n).map(|l| (l.max_duration, l.takeover_after)), Some((Duration::from_secs(60), Duration::from_secs(300))));
1058        let r = p.rules();
1059        assert_eq!((r.role.as_deref(), r.takeover_after_ms, r.retry_backoff_ms), (Some("ymir.model"), 300_000, 60_000));
1060    }
1061}