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).
15use std::time::Duration;
16
17use serde::{Deserialize, Serialize};
18
19use crate::error::{Result, SyncError};
20use crate::hlc::Hlc;
21use crate::lease::{LeaseConfig, LeaseError, LeaseHandle, LeaseName, Leases, Term};
22use crate::net::SyncState;
23use crate::protocol::{decode, encode};
24
25const JOB_DOMAIN: &[u8] = b"weirdnet-sync/v1/job\n";
26/// Longest job id.
27pub const MAX_JOB_ID: usize = 128;
28
29/// A job as posted.
30#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
31#[non_exhaustive]
32pub struct JobSpec {
33    pub id: String,
34    pub kind: String,
35    #[serde(with = "crate::bytes")]
36    pub body: Vec<u8>,
37    pub priority: u8,
38    /// Attempts before a retryable failure becomes final.
39    pub max_attempts: u32,
40    /// How long each claim's lease lasts (ms).
41    pub claim_ms: u64,
42}
43
44impl JobSpec {
45    /// Three attempts, 15 s claims, priority 0.
46    pub fn new(id: impl Into<String>, kind: impl Into<String>, body: Vec<u8>) -> Self {
47        Self { id: id.into(), kind: kind.into(), body, priority: 0, max_attempts: 3, claim_ms: 15_000 }
48    }
49
50    pub fn with_priority(mut self, priority: u8) -> Self {
51        self.priority = priority;
52        self
53    }
54
55    pub fn with_max_attempts(mut self, n: u32) -> Self {
56        self.max_attempts = n.max(1);
57        self
58    }
59
60    pub fn with_claim(mut self, claim: Duration) -> Self {
61        self.claim_ms = claim.as_millis() as u64;
62        self
63    }
64
65    pub fn claim(&self) -> Duration {
66        Duration::from_millis(self.claim_ms)
67    }
68}
69
70/// One log entry for a job (record id = job id).
71#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
72#[serde(tag = "ev", rename_all = "kebab-case")]
73#[non_exhaustive]
74pub enum JobEvent {
75    Posted(JobSpec),
76    Claimed {
77        term: Term,
78        by: String,
79    },
80    /// App-defined progress (for example the items done).
81    Checkpoint {
82        term: Term,
83        seq: u64,
84        #[serde(with = "crate::bytes")]
85        data: Vec<u8>,
86    },
87    Finished {
88        term: Term,
89        #[serde(with = "crate::bytes")]
90        result: Vec<u8>,
91    },
92    Failed {
93        term: Term,
94        reason: String,
95        retry: bool,
96    },
97    Cancelled,
98}
99
100impl JobEvent {
101    fn term(&self) -> Option<Term> {
102        match self {
103            JobEvent::Claimed { term, .. } | JobEvent::Checkpoint { term, .. } | JobEvent::Finished { term, .. } | JobEvent::Failed { term, .. } => {
104                Some(*term)
105            }
106            JobEvent::Posted(_) | JobEvent::Cancelled => None,
107        }
108    }
109}
110
111#[derive(Debug, Clone, Copy, PartialEq, Eq)]
112#[non_exhaustive]
113pub enum JobStatus {
114    Open,
115    Claimed,
116    Done,
117    Failed,
118    Cancelled,
119}
120
121/// A job folded from its events.
122#[derive(Debug, Clone, PartialEq, Eq)]
123#[non_exhaustive]
124pub struct JobView {
125    pub spec: JobSpec,
126    pub status: JobStatus,
127    /// Distinct claimed terms.
128    pub attempts: u32,
129    /// The claim with the highest term: who and which term.
130    pub claim: Option<(String, Term)>,
131    /// Every checkpoint as `(term, seq, data)`, oldest first; merge them if the app's
132    /// checkpoints are partial (a union of finished items).
133    pub checkpoints: Vec<(Term, u64, Vec<u8>)>,
134    /// The last checkpoint of the highest term.
135    pub resume_from: Option<Vec<u8>>,
136    pub result: Option<Vec<u8>>,
137    /// The reason of the last failure.
138    pub failure: Option<String>,
139}
140
141fn check_id(id: &str) -> Result<()> {
142    let ok = !id.is_empty() && id.len() <= MAX_JOB_ID && id.chars().all(|c| c.is_ascii_alphanumeric() || ".-_:+#".contains(c));
143    if ok { Ok(()) } else { Err(SyncError::Protocol(format!("bad job id {id:?}"))) }
144}
145
146/// The lease a job's claim is: `<typ>/<id>`.
147pub fn job_lease(typ: &str, id: &str) -> Result<LeaseName> {
148    check_id(id)?;
149    LeaseName::new(format!("{typ}/{id}"))
150}
151
152/// The jobs under one record type (for example `ymir.jobs`).
153pub struct Jobs<'a> {
154    state: &'a mut SyncState,
155    typ: String,
156}
157
158impl<'a> Jobs<'a> {
159    pub fn new(state: &'a mut SyncState, typ: impl Into<String>) -> Self {
160        Self { state, typ: typ.into() }
161    }
162
163    fn append(&mut self, now_ms: u64, id: &str, ev: &JobEvent) -> Result<()> {
164        check_id(id)?;
165        let doc = self.state.sign_doc(JOB_DOMAIN, &self.typ, id, encode(ev)?)?;
166        self.state.write(now_ms, &self.typ, id, &encode(&doc)?)?;
167        Ok(())
168    }
169
170    /// Post a job. Posting an id twice keeps the first spec.
171    pub fn post(&mut self, now_ms: u64, spec: JobSpec) -> Result<()> {
172        let id = spec.id.clone();
173        self.append(now_ms, &id, &JobEvent::Posted(spec))
174    }
175
176    /// Record an event of the attempt `lease` holds: its term must be the lease's, and the
177    /// lease must be this job's and still valid.
178    pub fn record(&mut self, now_ms: u64, id: &str, lease: &LeaseHandle, ev: JobEvent) -> Result<()> {
179        let want = job_lease(&self.typ, id)?;
180        if lease.name() != &want || !lease.is_valid() || lease.holder() != self.state.our_cert.peer_id {
181            return Err(SyncError::NotPermitted("not holding this job's claim".into()));
182        }
183        match (&ev, ev.term()) {
184            (JobEvent::Claimed { by, .. }, _) if *by != self.state.our_cert.peer_id => {
185                return Err(SyncError::NotPermitted("a claim names its writer".into()));
186            }
187            (_, Some(t)) if t != lease.term() => return Err(SyncError::NotPermitted("the event's term is not the lease's".into())),
188            (_, None) => return Err(SyncError::Protocol("use post or cancel for that event".into())),
189            _ => {}
190        }
191        self.append(now_ms, id, &ev)
192    }
193
194    pub fn cancel(&mut self, now_ms: u64, id: &str) -> Result<()> {
195        self.append(now_ms, id, &JobEvent::Cancelled)
196    }
197
198    fn events(&self, id: &str) -> Vec<(JobEvent, String, Hlc)> {
199        let mut evs: Vec<(JobEvent, String, Hlc)> = self
200            .state
201            .signed_docs(JOB_DOMAIN, &self.typ, id)
202            .into_iter()
203            .filter_map(|(d, hlc)| decode::<JobEvent>(&d.body).ok().map(|e| (e, d.signer, hlc)))
204            .collect();
205        evs.sort_by(|a, b| a.2.cmp_total(&b.2));
206        evs
207    }
208
209    /// The job folded from its events, `None` if it was never posted.
210    pub fn view(&self, id: &str) -> Option<JobView> {
211        fold(self.events(id))
212    }
213
214    /// Ids of every job posted under this type.
215    pub fn ids(&self) -> Vec<String> {
216        let mut ids: Vec<String> = self.state.log.iter().filter(|e| e.typ == self.typ).map(|e| e.record_id.clone()).collect();
217        ids.sort();
218        ids.dedup();
219        ids
220    }
221
222    /// Jobs to (re)claim: open, or claimed and not finished (whether the claim is still alive
223    /// is the lease's to say). Highest priority first.
224    pub fn open(&self) -> Vec<JobView> {
225        let mut v: Vec<JobView> =
226            self.ids().iter().filter_map(|id| self.view(id)).filter(|j| matches!(j.status, JobStatus::Open | JobStatus::Claimed)).collect();
227        v.sort_by(|a, b| b.spec.priority.cmp(&a.spec.priority).then_with(|| a.spec.id.cmp(&b.spec.id)));
228        v
229    }
230}
231
232fn fold(evs: Vec<(JobEvent, String, Hlc)>) -> Option<JobView> {
233    let spec = evs.iter().find_map(|(e, _, _)| if let JobEvent::Posted(s) = e { Some(s.clone()) } else { None })?;
234    let mut claim: Option<(String, Term)> = None;
235    let mut terms: Vec<Term> = Vec::new();
236    let mut checkpoints = Vec::new();
237    let mut finished: Option<(Term, Vec<u8>, Hlc)> = None;
238    let mut failed: Option<(Term, String, bool)> = None;
239    let mut cancelled: Option<Hlc> = None;
240    // Who claimed each term: a term's checkpoints, result and failure count only from it.
241    let claimers: std::collections::HashMap<Term, &str> = evs
242        .iter()
243        .filter_map(|(e, signer, _)| match e {
244            JobEvent::Claimed { term, by } if by == signer => Some((*term, signer.as_str())),
245            _ => None,
246        })
247        .collect();
248    let by_claimer = |term: &Term, signer: &str| claimers.get(term).is_some_and(|c| *c == signer);
249    for (e, signer, hlc) in &evs {
250        match e {
251            // A claim counts only from the device it names.
252            JobEvent::Claimed { term, by } if by == signer => {
253                if !terms.contains(term) {
254                    terms.push(*term);
255                }
256                if claim.as_ref().is_none_or(|(_, t)| term > t) {
257                    claim = Some((by.clone(), *term));
258                }
259            }
260            JobEvent::Checkpoint { term, seq, data } if by_claimer(term, signer) => checkpoints.push((*term, *seq, data.clone())),
261            JobEvent::Finished { term, result } if by_claimer(term, signer) => {
262                if finished.as_ref().is_none_or(|(t, _, _)| term > t) {
263                    finished = Some((*term, result.clone(), hlc.clone()));
264                }
265            }
266            JobEvent::Failed { term, reason, retry } if by_claimer(term, signer) => {
267                if failed.as_ref().is_none_or(|(t, _, _)| term >= t) {
268                    failed = Some((*term, reason.clone(), *retry));
269                }
270            }
271            JobEvent::Cancelled if cancelled.is_none() => cancelled = Some(hlc.clone()),
272            _ => {}
273        }
274    }
275    let attempts = terms.len() as u32;
276    let finished_before_cancel = match (&finished, &cancelled) {
277        (Some((_, _, f)), Some(c)) => f.cmp_total(c).is_lt(),
278        _ => false,
279    };
280    let status = if cancelled.is_some() && !finished_before_cancel {
281        JobStatus::Cancelled
282    } else if finished.is_some() {
283        JobStatus::Done
284    } else {
285        match (&claim, &failed) {
286            (Some((_, ct)), Some((ft, _, retry))) if ft >= ct => {
287                if *retry && attempts < spec.max_attempts {
288                    JobStatus::Open
289                } else {
290                    JobStatus::Failed
291                }
292            }
293            (Some(_), _) => JobStatus::Claimed,
294            (None, _) => JobStatus::Open,
295        }
296    };
297    let resume_from = checkpoints.iter().max_by(|a, b| (a.0, a.1).cmp(&(b.0, b.1))).map(|c| c.2.clone());
298    Some(JobView { spec, status, attempts, claim, checkpoints, resume_from, result: finished.map(|f| f.1), failure: failed.map(|f| f.1) })
299}
300
301impl Leases {
302    /// Claim job `id` under `typ`: acquire its lease (the job's claim duration, `cfg`'s
303    /// voters) and write `Claimed`. Fails with `LeaseError::Held` while another device works
304    /// on it. Renew the handle with [`Leases::renew`] while working.
305    pub fn claim_job(&self, typ: &str, id: &str, cfg: &LeaseConfig) -> std::result::Result<LeaseHandle, LeaseError> {
306        let name = job_lease(typ, id)?;
307        let spec = {
308            let mut st = self.state().lock().map_err(|_| LeaseError::Sync("sync state lock poisoned".into()))?;
309            let jobs = Jobs::new(&mut st, typ);
310            let view = jobs.view(id).ok_or_else(|| LeaseError::Sync(format!("no job {id}")))?;
311            if !matches!(view.status, JobStatus::Open | JobStatus::Claimed) {
312                return Err(LeaseError::Sync(format!("job {id} is {:?}", view.status)));
313            }
314            view.spec
315        };
316        let cfg = cfg.clone().with_duration(spec.claim());
317        let handle = self.acquire(&name, &cfg)?;
318        let mut st = self.state().lock().map_err(|_| LeaseError::Sync("sync state lock poisoned".into()))?;
319        let me = st.our_cert.peer_id.clone();
320        Jobs::new(&mut st, typ).record(wall_ms(), id, &handle, JobEvent::Claimed { term: handle.term(), by: me })?;
321        Ok(handle)
322    }
323}
324
325fn wall_ms() -> u64 {
326    std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_millis() as u64).unwrap_or(0)
327}
328
329#[cfg(test)]
330mod tests {
331    use super::*;
332    use crate::hlc::NodeId;
333
334    fn hlc(ms: u64) -> Hlc {
335        Hlc { physical_ms: ms, counter: 0, node_id: NodeId("n".into()) }
336    }
337
338    fn evs(list: Vec<(JobEvent, &str, u64)>) -> Vec<(JobEvent, String, Hlc)> {
339        list.into_iter().map(|(e, s, t)| (e, s.to_string(), hlc(t))).collect()
340    }
341
342    fn spec() -> JobSpec {
343        JobSpec::new("j1", "batch", b"prompts".to_vec()).with_max_attempts(2)
344    }
345
346    #[test]
347    fn folding_claims_checkpoints_and_results() {
348        assert!(fold(evs(vec![(JobEvent::Cancelled, "a", 1)])).is_none(), "never posted");
349        let v = fold(evs(vec![(JobEvent::Posted(spec()), "a", 1)])).unwrap();
350        assert_eq!((v.status, v.attempts), (JobStatus::Open, 0));
351        let base = vec![
352            (JobEvent::Posted(spec()), "a", 1),
353            (JobEvent::Claimed { term: Term(1), by: "a".into() }, "a", 2),
354            (JobEvent::Checkpoint { term: Term(1), seq: 1, data: b"10".to_vec() }, "a", 3),
355        ];
356        let v = fold(evs(base.clone())).unwrap();
357        assert_eq!((v.status, v.claim.clone(), v.resume_from.clone()), (JobStatus::Claimed, Some(("a".into(), Term(1))), Some(b"10".to_vec())));
358        // A claim written by someone else for "a" doesn't count.
359        let mut forged = base.clone();
360        forged.push((JobEvent::Claimed { term: Term(9), by: "a".into() }, "b", 4));
361        assert_eq!(fold(evs(forged)).unwrap().claim, Some(("a".into(), Term(1))));
362        // b re-claims at term 2 and resumes from a's checkpoint; a late a-checkpoint loses.
363        let mut re = base.clone();
364        re.push((JobEvent::Claimed { term: Term(2), by: "b".into() }, "b", 5));
365        re.push((JobEvent::Checkpoint { term: Term(2), seq: 1, data: b"20".to_vec() }, "b", 6));
366        re.push((JobEvent::Checkpoint { term: Term(1), seq: 2, data: b"11".to_vec() }, "a", 7));
367        let v = fold(evs(re.clone())).unwrap();
368        assert_eq!((v.attempts, v.resume_from.clone(), v.checkpoints.len()), (2, Some(b"20".to_vec()), 3));
369        // Finished: the highest term wins.
370        let mut done = re.clone();
371        done.push((JobEvent::Finished { term: Term(1), result: b"late".to_vec() }, "a", 8));
372        done.push((JobEvent::Finished { term: Term(2), result: b"ok".to_vec() }, "b", 9));
373        let v = fold(evs(done.clone())).unwrap();
374        assert_eq!((v.status, v.result.clone()), (JobStatus::Done, Some(b"ok".to_vec())));
375        // A cancel after it finished doesn't undo it; one before does.
376        let mut after = done.clone();
377        after.push((JobEvent::Cancelled, "a", 10));
378        assert_eq!(fold(evs(after)).unwrap().status, JobStatus::Done);
379        let mut before = re.clone();
380        before.push((JobEvent::Cancelled, "a", 8));
381        before.push((JobEvent::Finished { term: Term(2), result: b"ok".to_vec() }, "b", 9));
382        assert_eq!(fold(evs(before)).unwrap().status, JobStatus::Cancelled);
383    }
384
385    #[test]
386    fn a_worker_whose_clock_runs_ahead_does_not_win_by_hlc() {
387        // a's clock is a day ahead: its term-1 events sort after b's term-2 ones by HLC.
388        let day = 86_400_000;
389        let e = vec![
390            (JobEvent::Posted(spec()), "a", 1),
391            (JobEvent::Claimed { term: Term(1), by: "a".into() }, "a", day + 2),
392            (JobEvent::Checkpoint { term: Term(1), seq: 7, data: b"a7".to_vec() }, "a", day + 3),
393            (JobEvent::Claimed { term: Term(2), by: "b".into() }, "b", 10),
394            (JobEvent::Checkpoint { term: Term(2), seq: 1, data: b"b1".to_vec() }, "b", 11),
395            (JobEvent::Finished { term: Term(1), result: b"a-late".to_vec() }, "a", day + 9),
396        ];
397        let mut sorted = evs(e.clone());
398        sorted.sort_by(|a, b| a.2.cmp_total(&b.2));
399        let v = fold(sorted).unwrap();
400        assert_eq!(v.claim, Some(("b".into(), Term(2))));
401        assert_eq!(v.resume_from, Some(b"b1".to_vec()));
402        // A lower term's late result still lands (jobs are idempotent per item), but the
403        // higher term's result replaces it as soon as it is written.
404        assert_eq!(v.result, Some(b"a-late".to_vec()));
405        let mut e2 = e;
406        e2.push((JobEvent::Finished { term: Term(2), result: b"b-ok".to_vec() }, "b", 12));
407        let mut sorted = evs(e2);
408        sorted.sort_by(|a, b| a.2.cmp_total(&b.2));
409        assert_eq!(fold(sorted).unwrap().result, Some(b"b-ok".to_vec()));
410    }
411
412    #[test]
413    fn only_the_claimer_of_a_term_writes_for_it() {
414        let e = vec![
415            (JobEvent::Posted(spec()), "a", 1),
416            (JobEvent::Claimed { term: Term(1), by: "a".into() }, "a", 2),
417            (JobEvent::Checkpoint { term: Term(1), seq: 1, data: b"a1".to_vec() }, "a", 3),
418            // c never claimed term 1 (or any term): its events don't count.
419            (JobEvent::Checkpoint { term: Term(1), seq: 9, data: b"c".to_vec() }, "c", 4),
420            (JobEvent::Finished { term: Term(5), result: b"forged".to_vec() }, "c", 5),
421            (JobEvent::Failed { term: Term(1), reason: "x".into(), retry: false }, "c", 6),
422        ];
423        let v = fold(evs(e)).unwrap();
424        assert_eq!((v.status, v.resume_from.clone(), v.result.clone(), v.checkpoints.len()), (JobStatus::Claimed, Some(b"a1".to_vec()), None, 1));
425    }
426
427    #[test]
428    fn retryable_failures_reopen_until_the_attempts_run_out() {
429        let mut e = vec![
430            (JobEvent::Posted(spec()), "a", 1),
431            (JobEvent::Claimed { term: Term(1), by: "a".into() }, "a", 2),
432            (JobEvent::Failed { term: Term(1), reason: "oom".into(), retry: true }, "a", 3),
433        ];
434        let v = fold(evs(e.clone())).unwrap();
435        assert_eq!((v.status, v.failure.as_deref()), (JobStatus::Open, Some("oom")));
436        e.push((JobEvent::Claimed { term: Term(2), by: "b".into() }, "b", 4));
437        assert_eq!(fold(evs(e.clone())).unwrap().status, JobStatus::Claimed);
438        e.push((JobEvent::Failed { term: Term(2), reason: "oom".into(), retry: true }, "b", 5));
439        assert_eq!(fold(evs(e.clone())).unwrap().status, JobStatus::Failed, "two attempts were allowed");
440        let final_fail = vec![
441            (JobEvent::Posted(spec()), "a", 1),
442            (JobEvent::Claimed { term: Term(1), by: "a".into() }, "a", 2),
443            (JobEvent::Failed { term: Term(1), reason: "bad input".into(), retry: false }, "a", 3),
444        ];
445        assert_eq!(fold(evs(final_fail)).unwrap().status, JobStatus::Failed);
446    }
447
448    #[test]
449    fn job_ids_make_lease_names() {
450        assert_eq!(job_lease("ymir.jobs", "42").unwrap().as_str(), "ymir.jobs/42");
451        assert!(job_lease("ymir.jobs", "a/b").is_err());
452        assert!(job_lease("ymir.jobs", "").is_err());
453    }
454}