Skip to main content

weirdnet_sync/
jobs.rs

1//! A job log (since 0.8): jobs posted to the op log, claimed under a per-job lease, with
2//! checkpoints, results and re-claims after a failure.
3//!
4//! Claiming a job is acquiring the lease `<type>/<job id>` with the same voters as any lease
5//! ([`Leases::claim_job`]); its term is the attempt's fencing token. The holder renews while it
6//! works and writes [`JobEvent::Checkpoint`]s. If it dies, its claim lapses at the voters and
7//! another eligible device acquires the next term and carries on from
8//! [`JobView::resume_from`].
9//!
10//! Every event is signed by the writing device's node key and counts only while its signer is
11//! active; folding is deterministic, so every device computes the same [`JobView`]. A holder
12//! that lost its lease mid-write may still land a late event from a lower term: jobs must be
13//! idempotent per item, and side effects that must happen once are fenced with
14//! [`FenceGuard`](crate::lease::FenceGuard).
15//!
16//! Since 0.8.1 a job can carry [`JobRules`]: who may claim it (candidates and a role grant,
17//! enforced in the fold and by voters), how long voters wait after a claim lapses before
18//! granting it to another device, and a backoff after a retryable failure. Jobs can be
19//! paused ([`JobEvent::Paused`], not counted as an attempt) and resumed
20//! ([`JobEvent::Resumed`]), and holders can keep last-writer-wins [`JobEvent::Note`]s. Jobs
21//! posted without rules fold exactly as in 0.8.0, and 0.8.0 devices skip the new events.
22use std::collections::{BTreeMap, HashMap};
23use std::time::Duration;
24
25use serde::{Deserialize, Serialize};
26
27use crate::error::{Result, SyncError};
28use crate::hlc::Hlc;
29use crate::lease::{LeaseConfig, LeaseError, LeaseHandle, LeaseLimits, LeaseName, Leases, Term};
30use crate::net::SyncState;
31use crate::protocol::{decode, encode};
32use crate::roster::Roster;
33
34const JOB_DOMAIN: &[u8] = b"weirdnet-sync/v1/job\n";
35/// Longest job id.
36pub const MAX_JOB_ID: usize = 128;
37/// The longest claim a voter grants from a job's own [`JobSpec::claim_ms`] (one hour).
38pub const MAX_JOB_CLAIM: Duration = Duration::from_secs(3_600);
39
40/// Who may claim a job and how claims hand over (since 0.8.1).
41#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
42#[non_exhaustive]
43pub struct JobRules {
44    /// After a claim lapses (its holder stopped renewing without letting go), voters refuse
45    /// another device for this long (ms). A clean release (pause, failure, finish) has no wait.
46    #[serde(default)]
47    pub takeover_after_ms: u64,
48    /// After a retryable failure the job can't be claimed for this long (ms), counted from
49    /// the failure's HLC time.
50    #[serde(default)]
51    pub retry_backoff_ms: u64,
52    /// Peer ids that may claim it; empty means any device (with [`role`](Self::role) if set).
53    #[serde(default)]
54    pub candidates: Vec<String>,
55    /// The role grant a claimer must hold (`Roster::has_role`).
56    #[serde(default)]
57    pub role: Option<String>,
58}
59
60impl JobRules {
61    pub fn new() -> Self {
62        Self::default()
63    }
64
65    pub fn with_takeover_after(mut self, wait: Duration) -> Self {
66        self.takeover_after_ms = wait.as_millis() as u64;
67        self
68    }
69
70    pub fn with_retry_backoff(mut self, wait: Duration) -> Self {
71        self.retry_backoff_ms = wait.as_millis() as u64;
72        self
73    }
74
75    pub fn with_candidates<S: Into<String>>(mut self, peers: impl IntoIterator<Item = S>) -> Self {
76        self.candidates = peers.into_iter().map(Into::into).collect();
77        self
78    }
79
80    pub fn with_role(mut self, role: impl Into<String>) -> Self {
81        self.role = Some(role.into());
82        self
83    }
84
85    pub fn takeover_after(&self) -> Duration {
86        Duration::from_millis(self.takeover_after_ms)
87    }
88
89    pub fn retry_backoff(&self) -> Duration {
90        Duration::from_millis(self.retry_backoff_ms)
91    }
92
93    /// Whether `peer` may claim under these rules.
94    pub fn allows(&self, roster: &Roster, peer: &str) -> bool {
95        self.allows_with(peer, &|p, r| roster.has_role(p, r))
96    }
97
98    fn allows_with(&self, peer: &str, has_role: &dyn Fn(&str, &str) -> bool) -> bool {
99        (self.candidates.is_empty() || self.candidates.iter().any(|c| c == peer)) && self.role.as_deref().is_none_or(|r| has_role(peer, r))
100    }
101}
102
103/// A job as posted.
104#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
105#[non_exhaustive]
106pub struct JobSpec {
107    pub id: String,
108    pub kind: String,
109    #[serde(with = "crate::bytes")]
110    pub body: Vec<u8>,
111    pub priority: u8,
112    /// Attempts before a retryable failure becomes final.
113    pub max_attempts: u32,
114    /// How long each claim's lease lasts (ms).
115    pub claim_ms: u64,
116    /// Claim rules (since 0.8.1); `None` folds as in 0.8.0. Left off the wire when unset.
117    #[serde(default, skip_serializing_if = "Option::is_none")]
118    pub rules: Option<JobRules>,
119}
120
121impl JobSpec {
122    /// Three attempts, 15 s claims, priority 0, no rules.
123    pub fn new(id: impl Into<String>, kind: impl Into<String>, body: Vec<u8>) -> Self {
124        Self { id: id.into(), kind: kind.into(), body, priority: 0, max_attempts: 3, claim_ms: 15_000, rules: None }
125    }
126
127    pub fn with_priority(mut self, priority: u8) -> Self {
128        self.priority = priority;
129        self
130    }
131
132    pub fn with_max_attempts(mut self, n: u32) -> Self {
133        self.max_attempts = n.max(1);
134        self
135    }
136
137    pub fn with_claim(mut self, claim: Duration) -> Self {
138        self.claim_ms = claim.as_millis() as u64;
139        self
140    }
141
142    /// Claim rules (since 0.8.1).
143    pub fn with_rules(mut self, rules: JobRules) -> Self {
144        self.rules = Some(rules);
145        self
146    }
147
148    pub fn claim(&self) -> Duration {
149        Duration::from_millis(self.claim_ms)
150    }
151}
152
153/// One log entry for a job (record id = job id).
154#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
155#[serde(tag = "ev", rename_all = "kebab-case")]
156#[non_exhaustive]
157pub enum JobEvent {
158    Posted(JobSpec),
159    Claimed {
160        term: Term,
161        by: String,
162    },
163    /// App-defined progress (for example the items done).
164    Checkpoint {
165        term: Term,
166        seq: u64,
167        #[serde(with = "crate::bytes")]
168        data: Vec<u8>,
169    },
170    Finished {
171        term: Term,
172        #[serde(with = "crate::bytes")]
173        result: Vec<u8>,
174    },
175    Failed {
176        term: Term,
177        reason: String,
178        retry: bool,
179    },
180    Cancelled,
181    /// The job stops without failing (since 0.8.1). With a term, its holder lets go and that
182    /// claim is not counted as an attempt; without one, the owner holds the job and a running
183    /// holder should pause. Either way it stays [`JobStatus::Paused`] until
184    /// [`Resumed`](Self::Resumed).
185    Paused {
186        #[serde(default, skip_serializing_if = "Option::is_none")]
187        term: Option<Term>,
188    },
189    /// The owner puts a paused job back up for claims (since 0.8.1).
190    Resumed,
191    /// A holder's last-writer-wins note under `key` (since 0.8.1): progress, or which devices
192    /// hold a copy of a checkpoint, without writing a new checkpoint.
193    Note {
194        term: Term,
195        key: String,
196        #[serde(with = "crate::bytes")]
197        data: Vec<u8>,
198    },
199}
200
201impl JobEvent {
202    fn term(&self) -> Option<Term> {
203        match self {
204            JobEvent::Claimed { term, .. }
205            | JobEvent::Checkpoint { term, .. }
206            | JobEvent::Finished { term, .. }
207            | JobEvent::Failed { term, .. }
208            | JobEvent::Note { term, .. } => Some(*term),
209            JobEvent::Paused { term } => *term,
210            JobEvent::Posted(_) | JobEvent::Cancelled | JobEvent::Resumed => None,
211        }
212    }
213}
214
215#[derive(Debug, Clone, Copy, PartialEq, Eq)]
216#[non_exhaustive]
217pub enum JobStatus {
218    Open,
219    Claimed,
220    Done,
221    Failed,
222    Cancelled,
223    /// Paused by its holder or owner until resumed (since 0.8.1).
224    Paused,
225}
226
227/// A job folded from its events.
228#[derive(Debug, Clone, PartialEq, Eq)]
229#[non_exhaustive]
230pub struct JobView {
231    pub spec: JobSpec,
232    pub status: JobStatus,
233    /// Distinct claimed terms, less the ones their holder paused.
234    pub attempts: u32,
235    /// The claim with the highest term: who and which term.
236    pub claim: Option<(String, Term)>,
237    /// Every checkpoint as `(term, seq, data)`, oldest first; merge them if the app's
238    /// checkpoints are partial (a union of finished items).
239    pub checkpoints: Vec<(Term, u64, Vec<u8>)>,
240    /// The last checkpoint of the highest term.
241    pub resume_from: Option<Vec<u8>>,
242    pub result: Option<Vec<u8>>,
243    /// The reason of the last failure.
244    pub failure: Option<String>,
245    /// The device that posted it (since 0.8.1).
246    pub owner: String,
247    /// When it was posted, as the post's HLC wall time in ms (since 0.8.1).
248    pub posted_ms: u64,
249    /// Not claimable before this wall time (ms), after a retryable failure under
250    /// [`JobRules::retry_backoff_ms`] (since 0.8.1).
251    pub not_before_ms: Option<u64>,
252    /// HLC wall time (ms) of the newest event from the current claim's holder (since 0.8.1).
253    pub last_seen_ms: Option<u64>,
254    /// The newest note per key from a claim's holder, highest term first (since 0.8.1).
255    pub notes: BTreeMap<String, (Term, Vec<u8>)>,
256    /// When the status became what it is, as an HLC wall time in ms (since 0.8.1).
257    pub changed_ms: u64,
258}
259
260impl JobView {
261    /// Whether a device may try to claim it at wall time `now_ms`: open (or claimed, whose
262    /// lease may have lapsed; the voters decide) and past any backoff.
263    pub fn claimable_at(&self, now_ms: u64) -> bool {
264        matches!(self.status, JobStatus::Open | JobStatus::Claimed) && self.not_before_ms.is_none_or(|t| now_ms >= t)
265    }
266}
267
268fn check_id(id: &str) -> Result<()> {
269    let ok = !id.is_empty() && id.len() <= MAX_JOB_ID && id.chars().all(|c| c.is_ascii_alphanumeric() || ".-_:+#".contains(c));
270    if ok { Ok(()) } else { Err(SyncError::Protocol(format!("bad job id {id:?}"))) }
271}
272
273/// The lease a job's claim is: `<typ>/<id>`.
274pub fn job_lease(typ: &str, id: &str) -> Result<LeaseName> {
275    check_id(id)?;
276    LeaseName::new(format!("{typ}/{id}"))
277}
278
279/// The jobs under one record type (for example `ymir.jobs`).
280pub struct Jobs<'a> {
281    state: &'a mut SyncState,
282    typ: String,
283}
284
285impl<'a> Jobs<'a> {
286    pub fn new(state: &'a mut SyncState, typ: impl Into<String>) -> Self {
287        Self { state, typ: typ.into() }
288    }
289
290    fn append(&mut self, now_ms: u64, id: &str, ev: &JobEvent) -> Result<()> {
291        check_id(id)?;
292        let doc = self.state.sign_doc(JOB_DOMAIN, &self.typ, id, encode(ev)?)?;
293        self.state.write(now_ms, &self.typ, id, &encode(&doc)?)?;
294        Ok(())
295    }
296
297    /// Post a job. Posting an id twice keeps the first spec.
298    pub fn post(&mut self, now_ms: u64, spec: JobSpec) -> Result<()> {
299        let id = spec.id.clone();
300        self.append(now_ms, &id, &JobEvent::Posted(spec))
301    }
302
303    /// Record an event of the attempt `lease` holds: its term must be the lease's, and the
304    /// lease must be this job's and still valid.
305    pub fn record(&mut self, now_ms: u64, id: &str, lease: &LeaseHandle, ev: JobEvent) -> Result<()> {
306        let want = job_lease(&self.typ, id)?;
307        if lease.name() != &want || !lease.is_valid() || lease.holder() != self.state.our_cert.peer_id {
308            return Err(SyncError::NotPermitted("not holding this job's claim".into()));
309        }
310        match (&ev, ev.term()) {
311            (JobEvent::Claimed { by, .. }, _) if *by != self.state.our_cert.peer_id => {
312                return Err(SyncError::NotPermitted("a claim names its writer".into()));
313            }
314            (_, Some(t)) if t != lease.term() => return Err(SyncError::NotPermitted("the event's term is not the lease's".into())),
315            (_, None) => return Err(SyncError::Protocol("use post, pause, resume or cancel for that event".into())),
316            _ => {}
317        }
318        self.append(now_ms, id, &ev)
319    }
320
321    /// Cancel a job. Under [`JobRules`] only its owner or a full (non-service) device of the
322    /// user may (others' cancels are ignored by the fold).
323    pub fn cancel(&mut self, now_ms: u64, id: &str) -> Result<()> {
324        self.check_owner(id)?;
325        self.append(now_ms, id, &JobEvent::Cancelled)
326    }
327
328    /// Hold a job as its owner (since 0.8.1): it stays paused until [`resume`](Self::resume),
329    /// and a running holder should pause.
330    pub fn pause(&mut self, now_ms: u64, id: &str) -> Result<()> {
331        self.check_owner(id)?;
332        self.append(now_ms, id, &JobEvent::Paused { term: None })
333    }
334
335    /// Put a paused job back up for claims (since 0.8.1).
336    pub fn resume(&mut self, now_ms: u64, id: &str) -> Result<()> {
337        self.check_owner(id)?;
338        self.append(now_ms, id, &JobEvent::Resumed)
339    }
340
341    fn check_owner(&self, id: &str) -> Result<()> {
342        let me = self.state.our_cert.peer_id.as_str();
343        match view_in(self.state, &self.typ, id) {
344            Some(v) if !owner_may(&v.spec, &v.owner, me, &|p| self.state.roster.is_service(p)) => {
345                Err(SyncError::NotPermitted("only the job's owner or a full device may do that".into()))
346            }
347            _ => Ok(()),
348        }
349    }
350
351    /// The job folded from its events, `None` if it was never posted.
352    pub fn view(&self, id: &str) -> Option<JobView> {
353        view_in(self.state, &self.typ, id)
354    }
355
356    /// Ids of every job posted under this type.
357    pub fn ids(&self) -> Vec<String> {
358        ids_in(self.state, &self.typ)
359    }
360
361    /// Jobs to (re)claim: open, or claimed and not finished (whether the claim is still alive
362    /// is the lease's to say). Highest priority first.
363    pub fn open(&self) -> Vec<JobView> {
364        let mut v: Vec<JobView> =
365            self.ids().iter().filter_map(|id| self.view(id)).filter(|j| matches!(j.status, JobStatus::Open | JobStatus::Claimed)).collect();
366        v.sort_by(|a, b| b.spec.priority.cmp(&a.spec.priority).then_with(|| a.spec.id.cmp(&b.spec.id)));
367        v
368    }
369}
370
371fn ids_in(state: &SyncState, typ: &str) -> Vec<String> {
372    let mut ids: Vec<String> = state.log.iter().filter(|e| e.typ == typ).map(|e| e.record_id.clone()).collect();
373    ids.sort();
374    ids.dedup();
375    ids
376}
377
378fn events_in(state: &SyncState, typ: &str, id: &str) -> Vec<(JobEvent, String, Hlc)> {
379    let mut evs: Vec<(JobEvent, String, Hlc)> = state
380        .signed_docs(JOB_DOMAIN, typ, id)
381        .into_iter()
382        .filter_map(|(d, hlc)| decode::<JobEvent>(&d.body).ok().map(|e| (e, d.signer, hlc)))
383        .collect();
384    evs.sort_by(|a, b| a.2.cmp_total(&b.2));
385    evs
386}
387
388fn view_in(state: &SyncState, typ: &str, id: &str) -> Option<JobView> {
389    let roster = &state.roster;
390    fold(events_in(state, typ, id), &|p, r| roster.has_role(p, r), &|p| roster.is_service(p))
391}
392
393/// Whether `signer` may pause, resume or cancel: anyone without rules (as in 0.8.0), else the
394/// owner or a full device of the user.
395fn owner_may(spec: &JobSpec, owner: &str, signer: &str, is_service: &dyn Fn(&str) -> bool) -> bool {
396    spec.rules.is_none() || signer == owner || !is_service(signer)
397}
398
399type RoleCheck<'a> = &'a dyn Fn(&str, &str) -> bool;
400type ServiceCheck<'a> = &'a dyn Fn(&str) -> bool;
401
402fn fold(evs: Vec<(JobEvent, String, Hlc)>, has_role: RoleCheck, is_service: ServiceCheck) -> Option<JobView> {
403    let (spec, owner, posted) =
404        evs.iter().find_map(|(e, s, h)| if let JobEvent::Posted(sp) = e { Some((sp.clone(), s.clone(), h.clone())) } else { None })?;
405    let may_claim = |signer: &str| spec.rules.as_ref().is_none_or(|r| r.allows_with(signer, has_role));
406    let owner_op = |signer: &str| owner_may(&spec, &owner, signer, is_service);
407    let mut claim: Option<(String, Term)> = None;
408    let mut terms: Vec<Term> = Vec::new();
409    let mut checkpoints = Vec::new();
410    let mut finished: Option<(Term, Vec<u8>, Hlc)> = None;
411    let mut failed: Option<(Term, String, bool, Hlc)> = None;
412    let mut cancelled: Option<Hlc> = None;
413    let mut notes: BTreeMap<String, (Term, Vec<u8>, Hlc)> = BTreeMap::new();
414    let mut holder_paused: Vec<Term> = Vec::new();
415    // Who claimed each term: a term's checkpoints, result and failure count only from it, and
416    // under rules only claims from allowed devices count at all.
417    let claimers: HashMap<Term, &str> = evs
418        .iter()
419        .filter_map(|(e, signer, _)| match e {
420            JobEvent::Claimed { term, by } if by == signer && may_claim(signer) => Some((*term, signer.as_str())),
421            _ => None,
422        })
423        .collect();
424    let by_claimer = |term: &Term, signer: &str| claimers.get(term).is_some_and(|c| *c == signer);
425    let top = claimers.keys().max().copied();
426    // Paused or not, in HLC order; a holder's pause counts only for the highest term.
427    let mut paused: Option<bool> = None;
428    let mut paused_at = posted.clone();
429    for (e, signer, hlc) in &evs {
430        match e {
431            // A claim counts only from the device it names (and, under rules, an allowed one).
432            JobEvent::Claimed { term, by } if by == signer && by_claimer(term, signer) => {
433                if !terms.contains(term) {
434                    terms.push(*term);
435                }
436                if claim.as_ref().is_none_or(|(_, t)| term > t) {
437                    claim = Some((by.clone(), *term));
438                }
439            }
440            JobEvent::Checkpoint { term, seq, data } if by_claimer(term, signer) => checkpoints.push((*term, *seq, data.clone())),
441            JobEvent::Finished { term, result } if by_claimer(term, signer) => {
442                if finished.as_ref().is_none_or(|(t, _, _)| term > t) {
443                    finished = Some((*term, result.clone(), hlc.clone()));
444                }
445            }
446            JobEvent::Failed { term, reason, retry } if by_claimer(term, signer) => {
447                if failed.as_ref().is_none_or(|(t, _, _, _)| term >= t) {
448                    failed = Some((*term, reason.clone(), *retry, hlc.clone()));
449                }
450            }
451            JobEvent::Note { term, key, data } if by_claimer(term, signer) => {
452                let newer = notes.get(key).is_none_or(|(t, _, h)| term > t || (term == t && hlc.cmp_total(h).is_gt()));
453                if newer {
454                    notes.insert(key.clone(), (*term, data.clone(), hlc.clone()));
455                }
456            }
457            JobEvent::Paused { term: Some(t) } if by_claimer(t, signer) => {
458                if !holder_paused.contains(t) {
459                    holder_paused.push(*t);
460                }
461                if Some(*t) == top {
462                    paused = Some(true);
463                    paused_at = hlc.clone();
464                }
465            }
466            JobEvent::Paused { term: None } if owner_op(signer) => {
467                // The owner's pause ends the attempt in progress without counting it, whether
468                // or not its holder gets its own pause into the log before its lease runs out
469                // (voters stop renewing a paused job's claim).
470                if let Some((_, t)) = &claim {
471                    let ended = finished.as_ref().is_some_and(|f| f.0 == *t) || failed.as_ref().is_some_and(|f| f.0 == *t);
472                    if !ended && !holder_paused.contains(t) {
473                        holder_paused.push(*t);
474                    }
475                }
476                paused = Some(true);
477                paused_at = hlc.clone();
478            }
479            JobEvent::Resumed if owner_op(signer) && paused == Some(true) => {
480                paused = Some(false);
481                paused_at = hlc.clone();
482            }
483            JobEvent::Cancelled if cancelled.is_none() && owner_op(signer) => cancelled = Some(hlc.clone()),
484            _ => {}
485        }
486    }
487    let attempts = terms.iter().filter(|t| !holder_paused.contains(t)).count() as u32;
488    let finished_before_cancel = match (&finished, &cancelled) {
489        (Some((_, _, f)), Some(c)) => f.cmp_total(c).is_lt(),
490        _ => false,
491    };
492    let failure_state = match (&claim, &failed) {
493        (Some((_, ct)), Some((ft, _, retry, _))) if ft >= ct => {
494            Some(if *retry && attempts < spec.max_attempts { JobStatus::Open } else { JobStatus::Failed })
495        }
496        _ => None,
497    };
498    let holder_let_go = claim.as_ref().is_some_and(|(_, ct)| holder_paused.contains(ct));
499    let mut changed = claim
500        .as_ref()
501        .and_then(|(by, t)| evs.iter().find(|(e, s, _)| matches!(e, JobEvent::Claimed { term, .. } if term == t) && s == by).map(|x| x.2.clone()))
502        .unwrap_or_else(|| posted.clone());
503    let status = if let Some(c) = cancelled.as_ref().filter(|_| !finished_before_cancel) {
504        changed = c.clone();
505        JobStatus::Cancelled
506    } else if let Some((_, _, f)) = &finished {
507        changed = f.clone();
508        JobStatus::Done
509    } else if failure_state == Some(JobStatus::Failed) {
510        changed = failed.as_ref().map(|f| f.3.clone()).unwrap_or(changed);
511        JobStatus::Failed
512    } else if paused == Some(true) {
513        changed = paused_at.clone();
514        JobStatus::Paused
515    } else if let Some(s) = failure_state {
516        changed = failed.as_ref().map(|f| f.3.clone()).unwrap_or(changed);
517        if paused == Some(false) && paused_at.cmp_total(&changed).is_gt() {
518            changed = paused_at.clone();
519        }
520        s
521    } else if holder_let_go || claim.is_none() {
522        if paused == Some(false) {
523            changed = paused_at.clone();
524        }
525        JobStatus::Open
526    } else {
527        JobStatus::Claimed
528    };
529    let not_before_ms = match (&failure_state, &failed, &spec.rules) {
530        (Some(JobStatus::Open), Some((_, _, _, h)), Some(r)) if r.retry_backoff_ms > 0 => Some(h.physical_ms.saturating_add(r.retry_backoff_ms)),
531        _ => None,
532    };
533    let last_seen_ms =
534        claim.as_ref().and_then(|(by, t)| evs.iter().filter(|(e, s, _)| s == by && e.term() == Some(*t)).map(|(_, _, h)| h.physical_ms).max());
535    let resume_from = checkpoints.iter().max_by(|a, b| (a.0, a.1).cmp(&(b.0, b.1))).map(|c| c.2.clone());
536    Some(JobView {
537        spec,
538        status,
539        attempts,
540        claim,
541        checkpoints,
542        resume_from,
543        result: finished.map(|f| f.1),
544        failure: failed.map(|f| f.1),
545        owner,
546        posted_ms: posted.physical_ms,
547        not_before_ms,
548        last_seen_ms,
549        notes: notes.into_iter().map(|(k, (t, d, _))| (k, (t, d))).collect(),
550        changed_ms: changed.physical_ms,
551    })
552}
553
554impl SyncState {
555    /// What a voter applies to an ask for lease `name` when it is a job's claim lease and
556    /// this device has the job with [`JobRules`]: the job's claim time as the longest grant
557    /// (up to [`MAX_JOB_CLAIM`]) and its takeover wait. `Err` carries why the asker can't
558    /// have it (not a candidate, the job isn't claimable, or it is in its backoff).
559    pub(crate) fn job_lease_limits(&self, name: &LeaseName, from: &str, renew: bool) -> std::result::Result<Option<LeaseLimits>, &'static str> {
560        let Some((typ, id)) = name.as_str().rsplit_once('/') else { return Ok(None) };
561        if check_id(id).is_err() {
562            return Ok(None);
563        }
564        let Some(view) = view_in(self, typ, id) else { return Ok(None) };
565        let Some(rules) = view.spec.rules.as_ref() else { return Ok(None) };
566        if !rules.allows(&self.roster, from) {
567            return Err("not-a-candidate");
568        }
569        if !matches!(view.status, JobStatus::Open | JobStatus::Claimed) {
570            return Err("job-closed");
571        }
572        if !renew && view.not_before_ms.is_some_and(|t| wall_ms() < t) {
573            return Err("job-backoff");
574        }
575        Ok(Some(LeaseLimits::new(view.spec.claim().min(MAX_JOB_CLAIM), rules.takeover_after())))
576    }
577}
578
579impl Leases {
580    /// Claim job `id` under `typ`: acquire its lease (the job's claim duration, `cfg`'s
581    /// voters) and write `Claimed`. Fails with `LeaseError::Held` while another device works
582    /// on it (or voters still wait out a lapsed claim's takeover time),
583    /// `LeaseError::NotEligible` when the job's rules leave this device out, and
584    /// `LeaseError::NotYet` during a retry backoff. Renew the handle with [`Leases::renew`]
585    /// (with `cfg` set to the job's claim time, see [`LeaseConfig::with_duration`]) while
586    /// working.
587    pub fn claim_job(&self, typ: &str, id: &str, cfg: &LeaseConfig) -> std::result::Result<LeaseHandle, LeaseError> {
588        let name = job_lease(typ, id)?;
589        let spec = {
590            let st = self.state().lock().map_err(|_| LeaseError::Sync("sync state lock poisoned".into()))?;
591            let view = view_in(&st, typ, id).ok_or_else(|| LeaseError::Sync(format!("no job {id}")))?;
592            if !matches!(view.status, JobStatus::Open | JobStatus::Claimed) {
593                return Err(LeaseError::Sync(format!("job {id} is {:?}", view.status)));
594            }
595            if let Some(r) = &view.spec.rules
596                && !r.allows(&st.roster, &st.our_cert.peer_id)
597            {
598                return Err(LeaseError::NotEligible);
599            }
600            let now = wall_ms();
601            if let Some(t) = view.not_before_ms.filter(|t| now < *t) {
602                return Err(LeaseError::NotYet { retry_in: Duration::from_millis(t - now) });
603            }
604            view.spec
605        };
606        let cfg = cfg.clone().with_duration(spec.claim());
607        let handle = self.acquire(&name, &cfg)?;
608        let mut st = self.state().lock().map_err(|_| LeaseError::Sync("sync state lock poisoned".into()))?;
609        let me = st.our_cert.peer_id.clone();
610        Jobs::new(&mut st, typ).record(wall_ms(), id, &handle, JobEvent::Claimed { term: handle.term(), by: me })?;
611        Ok(handle)
612    }
613}
614
615fn wall_ms() -> u64 {
616    std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_millis() as u64).unwrap_or(0)
617}
618
619#[cfg(test)]
620mod tests {
621    use super::*;
622    use crate::hlc::NodeId;
623
624    /// Folds with nobody holding a role and every signer a full device.
625    fn fold(evs: Vec<(JobEvent, String, Hlc)>) -> Option<JobView> {
626        super::fold(evs, &|_, _| false, &|_| false)
627    }
628
629    fn hlc(ms: u64) -> Hlc {
630        Hlc { physical_ms: ms, counter: 0, node_id: NodeId("n".into()) }
631    }
632
633    fn evs(list: Vec<(JobEvent, &str, u64)>) -> Vec<(JobEvent, String, Hlc)> {
634        list.into_iter().map(|(e, s, t)| (e, s.to_string(), hlc(t))).collect()
635    }
636
637    fn spec() -> JobSpec {
638        JobSpec::new("j1", "batch", b"prompts".to_vec()).with_max_attempts(2)
639    }
640
641    #[test]
642    fn folding_claims_checkpoints_and_results() {
643        assert!(fold(evs(vec![(JobEvent::Cancelled, "a", 1)])).is_none(), "never posted");
644        let v = fold(evs(vec![(JobEvent::Posted(spec()), "a", 1)])).unwrap();
645        assert_eq!((v.status, v.attempts), (JobStatus::Open, 0));
646        let base = vec![
647            (JobEvent::Posted(spec()), "a", 1),
648            (JobEvent::Claimed { term: Term(1), by: "a".into() }, "a", 2),
649            (JobEvent::Checkpoint { term: Term(1), seq: 1, data: b"10".to_vec() }, "a", 3),
650        ];
651        let v = fold(evs(base.clone())).unwrap();
652        assert_eq!((v.status, v.claim.clone(), v.resume_from.clone()), (JobStatus::Claimed, Some(("a".into(), Term(1))), Some(b"10".to_vec())));
653        // A claim written by someone else for "a" doesn't count.
654        let mut forged = base.clone();
655        forged.push((JobEvent::Claimed { term: Term(9), by: "a".into() }, "b", 4));
656        assert_eq!(fold(evs(forged)).unwrap().claim, Some(("a".into(), Term(1))));
657        // b re-claims at term 2 and resumes from a's checkpoint; a late a-checkpoint loses.
658        let mut re = base.clone();
659        re.push((JobEvent::Claimed { term: Term(2), by: "b".into() }, "b", 5));
660        re.push((JobEvent::Checkpoint { term: Term(2), seq: 1, data: b"20".to_vec() }, "b", 6));
661        re.push((JobEvent::Checkpoint { term: Term(1), seq: 2, data: b"11".to_vec() }, "a", 7));
662        let v = fold(evs(re.clone())).unwrap();
663        assert_eq!((v.attempts, v.resume_from.clone(), v.checkpoints.len()), (2, Some(b"20".to_vec()), 3));
664        // Finished: the highest term wins.
665        let mut done = re.clone();
666        done.push((JobEvent::Finished { term: Term(1), result: b"late".to_vec() }, "a", 8));
667        done.push((JobEvent::Finished { term: Term(2), result: b"ok".to_vec() }, "b", 9));
668        let v = fold(evs(done.clone())).unwrap();
669        assert_eq!((v.status, v.result.clone()), (JobStatus::Done, Some(b"ok".to_vec())));
670        // A cancel after it finished doesn't undo it; one before does.
671        let mut after = done.clone();
672        after.push((JobEvent::Cancelled, "a", 10));
673        assert_eq!(fold(evs(after)).unwrap().status, JobStatus::Done);
674        let mut before = re.clone();
675        before.push((JobEvent::Cancelled, "a", 8));
676        before.push((JobEvent::Finished { term: Term(2), result: b"ok".to_vec() }, "b", 9));
677        assert_eq!(fold(evs(before)).unwrap().status, JobStatus::Cancelled);
678    }
679
680    #[test]
681    fn a_worker_whose_clock_runs_ahead_does_not_win_by_hlc() {
682        // a's clock is a day ahead: its term-1 events sort after b's term-2 ones by HLC.
683        let day = 86_400_000;
684        let e = vec![
685            (JobEvent::Posted(spec()), "a", 1),
686            (JobEvent::Claimed { term: Term(1), by: "a".into() }, "a", day + 2),
687            (JobEvent::Checkpoint { term: Term(1), seq: 7, data: b"a7".to_vec() }, "a", day + 3),
688            (JobEvent::Claimed { term: Term(2), by: "b".into() }, "b", 10),
689            (JobEvent::Checkpoint { term: Term(2), seq: 1, data: b"b1".to_vec() }, "b", 11),
690            (JobEvent::Finished { term: Term(1), result: b"a-late".to_vec() }, "a", day + 9),
691        ];
692        let mut sorted = evs(e.clone());
693        sorted.sort_by(|a, b| a.2.cmp_total(&b.2));
694        let v = fold(sorted).unwrap();
695        assert_eq!(v.claim, Some(("b".into(), Term(2))));
696        assert_eq!(v.resume_from, Some(b"b1".to_vec()));
697        // A lower term's late result still lands (jobs are idempotent per item), but the
698        // higher term's result replaces it as soon as it is written.
699        assert_eq!(v.result, Some(b"a-late".to_vec()));
700        let mut e2 = e;
701        e2.push((JobEvent::Finished { term: Term(2), result: b"b-ok".to_vec() }, "b", 12));
702        let mut sorted = evs(e2);
703        sorted.sort_by(|a, b| a.2.cmp_total(&b.2));
704        assert_eq!(fold(sorted).unwrap().result, Some(b"b-ok".to_vec()));
705    }
706
707    #[test]
708    fn only_the_claimer_of_a_term_writes_for_it() {
709        let e = vec![
710            (JobEvent::Posted(spec()), "a", 1),
711            (JobEvent::Claimed { term: Term(1), by: "a".into() }, "a", 2),
712            (JobEvent::Checkpoint { term: Term(1), seq: 1, data: b"a1".to_vec() }, "a", 3),
713            // c never claimed term 1 (or any term): its events don't count.
714            (JobEvent::Checkpoint { term: Term(1), seq: 9, data: b"c".to_vec() }, "c", 4),
715            (JobEvent::Finished { term: Term(5), result: b"forged".to_vec() }, "c", 5),
716            (JobEvent::Failed { term: Term(1), reason: "x".into(), retry: false }, "c", 6),
717        ];
718        let v = fold(evs(e)).unwrap();
719        assert_eq!((v.status, v.resume_from.clone(), v.result.clone(), v.checkpoints.len()), (JobStatus::Claimed, Some(b"a1".to_vec()), None, 1));
720    }
721
722    #[test]
723    fn retryable_failures_reopen_until_the_attempts_run_out() {
724        let mut e = vec![
725            (JobEvent::Posted(spec()), "a", 1),
726            (JobEvent::Claimed { term: Term(1), by: "a".into() }, "a", 2),
727            (JobEvent::Failed { term: Term(1), reason: "oom".into(), retry: true }, "a", 3),
728        ];
729        let v = fold(evs(e.clone())).unwrap();
730        assert_eq!((v.status, v.failure.as_deref()), (JobStatus::Open, Some("oom")));
731        e.push((JobEvent::Claimed { term: Term(2), by: "b".into() }, "b", 4));
732        assert_eq!(fold(evs(e.clone())).unwrap().status, JobStatus::Claimed);
733        e.push((JobEvent::Failed { term: Term(2), reason: "oom".into(), retry: true }, "b", 5));
734        assert_eq!(fold(evs(e.clone())).unwrap().status, JobStatus::Failed, "two attempts were allowed");
735        let final_fail = vec![
736            (JobEvent::Posted(spec()), "a", 1),
737            (JobEvent::Claimed { term: Term(1), by: "a".into() }, "a", 2),
738            (JobEvent::Failed { term: Term(1), reason: "bad input".into(), retry: false }, "a", 3),
739        ];
740        assert_eq!(fold(evs(final_fail)).unwrap().status, JobStatus::Failed);
741    }
742
743    #[test]
744    fn job_ids_make_lease_names() {
745        assert_eq!(job_lease("ymir.jobs", "42").unwrap().as_str(), "ymir.jobs/42");
746        assert!(job_lease("ymir.jobs", "a/b").is_err());
747        assert!(job_lease("ymir.jobs", "").is_err());
748    }
749
750    fn ruled() -> JobSpec {
751        JobSpec::new("j2", "train", b"t".to_vec())
752            .with_max_attempts(2)
753            .with_rules(JobRules::new().with_role("ymir.model").with_candidates(["a", "b", "c"]).with_retry_backoff(Duration::from_millis(100)))
754    }
755
756    /// `a`, `b` and `z` hold the role; `z` is not a candidate; `svc` is a service device.
757    fn fold_r(evs: Vec<(JobEvent, String, Hlc)>) -> Option<JobView> {
758        super::fold(evs, &|p, r| r == "ymir.model" && ["a", "b", "z"].contains(&p), &|p| p == "svc" || p == "b")
759    }
760
761    #[test]
762    fn rules_leave_out_claims_from_outside_the_role_or_candidates() {
763        let e = vec![
764            (JobEvent::Posted(ruled()), "a", 1),
765            // z holds the role but is not a candidate; c is a candidate without the role.
766            (JobEvent::Claimed { term: Term(1), by: "z".into() }, "z", 2),
767            (JobEvent::Claimed { term: Term(2), by: "c".into() }, "c", 3),
768            (JobEvent::Checkpoint { term: Term(2), seq: 1, data: b"c".to_vec() }, "c", 4),
769        ];
770        let v = fold_r(evs(e.clone())).unwrap();
771        assert_eq!((v.status, v.claim.clone(), v.attempts, v.resume_from.clone()), (JobStatus::Open, None, 0, None));
772        // Without rules the same claims count, as in 0.8.0.
773        let mut plain = e.clone();
774        plain[0] = (JobEvent::Posted(spec()), "a", 1);
775        assert_eq!(fold_r(evs(plain)).unwrap().attempts, 2);
776        let mut ok = e;
777        ok.push((JobEvent::Claimed { term: Term(3), by: "b".into() }, "b", 5));
778        let v = fold_r(evs(ok)).unwrap();
779        assert_eq!((v.status, v.claim, v.attempts, v.owner.as_str()), (JobStatus::Claimed, Some(("b".into(), Term(3))), 1, "a"));
780    }
781
782    #[test]
783    fn a_holder_pause_is_not_an_attempt_and_resume_reopens() {
784        let mut e = vec![
785            (JobEvent::Posted(ruled()), "a", 1),
786            (JobEvent::Claimed { term: Term(1), by: "a".into() }, "a", 2),
787            (JobEvent::Checkpoint { term: Term(1), seq: 1, data: b"s100".to_vec() }, "a", 3),
788            (JobEvent::Paused { term: Some(Term(1)) }, "a", 4),
789        ];
790        let v = fold_r(evs(e.clone())).unwrap();
791        assert_eq!((v.status, v.attempts, v.changed_ms), (JobStatus::Paused, 0, 4));
792        // A service device that is not the owner can't resume it.
793        e.push((JobEvent::Resumed, "svc", 5));
794        assert_eq!(fold_r(evs(e.clone())).unwrap().status, JobStatus::Paused);
795        e.push((JobEvent::Resumed, "a", 6));
796        let v = fold_r(evs(e.clone())).unwrap();
797        assert_eq!((v.status, v.attempts, v.resume_from.clone(), v.changed_ms), (JobStatus::Open, 0, Some(b"s100".to_vec()), 6));
798        e.push((JobEvent::Claimed { term: Term(2), by: "b".into() }, "b", 7));
799        let v = fold_r(evs(e.clone())).unwrap();
800        assert_eq!((v.status, v.attempts, v.resume_from.clone()), (JobStatus::Claimed, 1, Some(b"s100".to_vec())));
801        // A late pause from the old term doesn't pause the new claim.
802        e.push((JobEvent::Paused { term: Some(Term(1)) }, "a", 8));
803        assert_eq!(fold_r(evs(e)).unwrap().status, JobStatus::Claimed);
804    }
805
806    #[test]
807    fn the_owner_pauses_and_resumes_and_a_service_device_cannot() {
808        let mut e = vec![(JobEvent::Posted(ruled()), "a", 1), (JobEvent::Claimed { term: Term(1), by: "b".into() }, "b", 2)];
809        e.push((JobEvent::Paused { term: None }, "svc", 3));
810        e.push((JobEvent::Cancelled, "svc", 4));
811        assert_eq!(fold_r(evs(e.clone())).unwrap().status, JobStatus::Claimed, "a service device is not the owner");
812        e.push((JobEvent::Paused { term: None }, "a", 5));
813        let v = fold_r(evs(e.clone())).unwrap();
814        assert_eq!((v.status, v.attempts), (JobStatus::Paused, 0), "the owner's pause doesn't use an attempt");
815        // The holder stops and lets go; its claim is not an attempt.
816        e.push((JobEvent::Paused { term: Some(Term(1)) }, "b", 6));
817        e.push((JobEvent::Resumed, "a", 7));
818        let v = fold_r(evs(e.clone())).unwrap();
819        assert_eq!((v.status, v.attempts), (JobStatus::Open, 0));
820        e.push((JobEvent::Cancelled, "a", 8));
821        assert_eq!(fold_r(evs(e)).unwrap().status, JobStatus::Cancelled);
822    }
823
824    #[test]
825    fn an_owner_pause_spares_only_the_attempt_in_progress() {
826        let mut e = vec![
827            (JobEvent::Posted(ruled()), "a", 1),
828            (JobEvent::Claimed { term: Term(1), by: "a".into() }, "a", 2),
829            (JobEvent::Failed { term: Term(1), reason: "oom".into(), retry: true }, "a", 3),
830            (JobEvent::Claimed { term: Term(2), by: "b".into() }, "b", 200),
831            // The holder's lease ran out before it could write its own pause.
832            (JobEvent::Paused { term: None }, "a", 300),
833        ];
834        let v = fold_r(evs(e.clone())).unwrap();
835        assert_eq!((v.status, v.attempts), (JobStatus::Paused, 1), "the failed attempt still counts");
836        e.push((JobEvent::Resumed, "a", 400));
837        e.push((JobEvent::Claimed { term: Term(3), by: "a".into() }, "a", 500));
838        assert_eq!(fold_r(evs(e)).unwrap().attempts, 2);
839    }
840
841    #[test]
842    fn a_retryable_failure_waits_out_the_backoff_and_attempts_run_out() {
843        let mut e = vec![
844            (JobEvent::Posted(ruled()), "a", 1),
845            (JobEvent::Claimed { term: Term(1), by: "a".into() }, "a", 2),
846            (JobEvent::Failed { term: Term(1), reason: "oom".into(), retry: true }, "a", 1_000),
847        ];
848        let v = fold_r(evs(e.clone())).unwrap();
849        assert_eq!((v.status, v.not_before_ms), (JobStatus::Open, Some(1_100)));
850        assert!(!v.claimable_at(1_050) && v.claimable_at(1_100));
851        // A lapsed claim (no event after it) counts as an attempt too.
852        e.push((JobEvent::Claimed { term: Term(2), by: "b".into() }, "b", 1_200));
853        let v = fold_r(evs(e.clone())).unwrap();
854        assert_eq!((v.status, v.attempts, v.not_before_ms), (JobStatus::Claimed, 2, None));
855        e.push((JobEvent::Failed { term: Term(2), reason: "oom".into(), retry: true }, "b", 1_300));
856        assert_eq!(fold_r(evs(e)).unwrap().status, JobStatus::Failed, "max_attempts 2");
857    }
858
859    #[test]
860    fn notes_keep_the_newest_per_key_from_the_holder() {
861        let e = vec![
862            (JobEvent::Posted(ruled()), "a", 1),
863            (JobEvent::Claimed { term: Term(1), by: "a".into() }, "a", 2),
864            (JobEvent::Note { term: Term(1), key: "progress".into(), data: b"1".to_vec() }, "a", 3),
865            (JobEvent::Note { term: Term(1), key: "progress".into(), data: b"2".to_vec() }, "a", 4),
866            (JobEvent::Note { term: Term(1), key: "progress".into(), data: b"forged".to_vec() }, "b", 5),
867            (JobEvent::Note { term: Term(1), key: "holders".into(), data: b"a,b".to_vec() }, "a", 6),
868        ];
869        let v = fold_r(evs(e)).unwrap();
870        assert_eq!(v.notes.get("progress"), Some(&(Term(1), b"2".to_vec())));
871        assert_eq!(v.notes.get("holders"), Some(&(Term(1), b"a,b".to_vec())));
872        assert_eq!(v.last_seen_ms, Some(6));
873    }
874
875    /// `JobSpec` and `JobEvent` as 0.8.0 published them.
876    mod v080 {
877        use serde::{Deserialize, Serialize};
878
879        #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
880        pub struct JobSpec {
881            pub id: String,
882            pub kind: String,
883            #[serde(with = "crate::bytes")]
884            pub body: Vec<u8>,
885            pub priority: u8,
886            pub max_attempts: u32,
887            pub claim_ms: u64,
888        }
889
890        #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
891        #[serde(tag = "ev", rename_all = "kebab-case")]
892        pub enum JobEvent {
893            Posted(JobSpec),
894            Claimed { term: crate::lease::Term, by: String },
895            Cancelled,
896        }
897    }
898
899    #[test]
900    fn events_stay_readable_both_ways_with_0_8_0() {
901        let old = v080::JobEvent::Posted(v080::JobSpec {
902            id: "j1".into(),
903            kind: "batch".into(),
904            body: b"prompts".to_vec(),
905            priority: 0,
906            max_attempts: 2,
907            claim_ms: 15_000,
908        });
909        let new = JobEvent::Posted(spec());
910        assert_eq!(encode(&old).unwrap(), encode(&new).unwrap(), "a spec without rules encodes as in 0.8.0");
911        assert_eq!(decode::<JobEvent>(&encode(&old).unwrap()).unwrap(), new);
912        // A 0.8.0 device reads a spec with rules (ignoring them) and skips the new events.
913        let ruled_old: v080::JobEvent = decode(&encode(&JobEvent::Posted(ruled())).unwrap()).unwrap();
914        assert!(matches!(ruled_old, v080::JobEvent::Posted(s) if s.id == "j2"));
915        for ev in [JobEvent::Paused { term: Some(Term(1)) }, JobEvent::Paused { term: None }, JobEvent::Resumed] {
916            assert!(decode::<v080::JobEvent>(&encode(&ev).unwrap()).is_err());
917            assert_eq!(decode::<JobEvent>(&encode(&ev).unwrap()).unwrap(), ev);
918        }
919        let note = JobEvent::Note { term: Term(1), key: "k".into(), data: vec![1, 2] };
920        assert_eq!(decode::<JobEvent>(&encode(&note).unwrap()).unwrap(), note);
921    }
922}