Skip to main content

troupekit_host/
runner.rs

1use crate::error::HostError;
2use crate::queue::{JobQueue, Lease};
3use futures_util::future::join_all;
4use serde_json::Value;
5use std::sync::Arc;
6use std::time::Duration;
7use tokio::sync::watch;
8use troupekit_agent::Limits;
9use troupekit_core::error::CoreError;
10use troupekit_core::ids::RunId;
11use troupekit_core::store::CheckpointStore;
12use troupekit_graph::{GraphIo, GraphOutcome, GraphRun, Stop};
13use troupekit_trace::{trace_span, Trace, TraceSink, Tracer};
14
15const DEFAULT_LEASE_MS: i64 = 300_000;
16const STORE_RETRY_MS: i64 = 1_000;
17
18/// What `process` did with one lease. `Stepped`: the run moved and was
19/// saved. `Unchanged`: it was waiting or final, nothing saved. `Lost`:
20/// another worker advanced the run first; the job was left alone.
21#[derive(Debug, Clone, PartialEq)]
22pub enum Processed {
23    Stepped(GraphOutcome),
24    Unchanged(GraphOutcome),
25    Lost,
26}
27
28/// Limits for one `tick`: at most `max_jobs` processed, and no new claim
29/// once `budget_ms` has passed. The defaults (16 jobs, 250 s) fit a
30/// serverless request capped at 300 s.
31#[derive(Debug, Clone, Copy, PartialEq, Eq)]
32pub struct TickOptions {
33    pub max_jobs: usize,
34    pub budget_ms: i64,
35}
36
37impl Default for TickOptions {
38    fn default() -> Self {
39        Self {
40            max_jobs: 16,
41            budget_ms: 250_000,
42        }
43    }
44}
45
46/// What one `tick` did: jobs processed, how many of them were lost to
47/// another worker, and the error text of each that failed.
48/// A quiet tick processes nothing.
49#[derive(Debug, Clone, Default, PartialEq, Eq)]
50pub struct TickReport {
51    pub processed: usize,
52    pub lost: usize,
53    pub errors: Vec<String>,
54}
55
56/// Worker mode settings: the options of every tick and how long to sleep
57/// when a tick found nothing to do or its claim failed.
58/// The default sleeps one second.
59#[derive(Debug, Clone, Copy, PartialEq, Eq)]
60pub struct WorkOptions {
61    pub tick: TickOptions,
62    pub idle_ms: u64,
63}
64
65impl Default for WorkOptions {
66    fn default() -> Self {
67        Self {
68            tick: TickOptions::default(),
69            idle_ms: 1_000,
70        }
71    }
72}
73
74/// Runs graph runs from a job queue: claims due jobs, loads each run's
75/// latest checkpoint, steps it once, saves it and reschedules, completes
76/// or fails the job. Time comes from the io's clock.
77pub struct Runner {
78    queue: Arc<dyn JobQueue>,
79    checkpoints: Arc<dyn CheckpointStore>,
80    io: Arc<dyn GraphIo>,
81    lease_ms: i64,
82    trace_sink: Option<Arc<dyn TraceSink>>,
83    trace_content: bool,
84}
85
86impl Runner {
87    /// Builds a runner over `queue`, `checkpoints` and `io` with a 300 s
88    /// lease. Several runners may share the same three.
89    /// Returns the runner.
90    pub fn new(
91        queue: Arc<dyn JobQueue>,
92        checkpoints: Arc<dyn CheckpointStore>,
93        io: Arc<dyn GraphIo>,
94    ) -> Self {
95        Self {
96            queue,
97            checkpoints,
98            io,
99            lease_ms: DEFAULT_LEASE_MS,
100            trace_sink: None,
101            trace_content: false,
102        }
103    }
104
105    /// Sends the trace of every run with a trace spec (set in code or by
106    /// the workflow's `trace` keys) to `sink` instead of its JSONL file.
107    /// Returns the runner.
108    pub fn with_trace_sink(mut self, sink: Arc<dyn TraceSink>) -> Self {
109        self.trace_sink = Some(sink);
110        self
111    }
112
113    /// Lets runs keep content in the trace sink when their spec also asks
114    /// for it; off by default, so a workflow file cannot turn content on
115    /// for the host's sink. Input: the flag. Returns the runner.
116    pub fn with_trace_content(mut self, content: bool) -> Self {
117        self.trace_content = content;
118        self
119    }
120
121    async fn step(&self, run: &mut GraphRun) -> GraphOutcome {
122        let io = self.io.as_ref();
123        let scope = troupekit_trace::current();
124        let (Some(sink), Some(spec), None) = (&self.trace_sink, run.trace(), scope) else {
125            return run.step(io).await;
126        };
127        let tracer = Tracer::builder()
128            .categories(spec.categories())
129            .content(self.trace_content && spec.content())
130            .name(&run.workflow().name)
131            .sink(sink.clone())
132            .build();
133        match tracer {
134            Ok(tracer) => tracer.in_scope(run.step(io)).await,
135            Err(_) => run.step(io).await,
136        }
137    }
138
139    /// Sets the lease length to `lease_ms`, which must be positive and
140    /// longer than one step takes.
141    /// Returns the runner.
142    pub fn with_lease_ms(mut self, lease_ms: i64) -> Self {
143        assert!(lease_ms > 0, "a lease lasts some time");
144        self.lease_ms = lease_ms;
145        self
146    }
147
148    fn now(&self) -> i64 {
149        self.io.agent().clock().now_ms()
150    }
151
152    /// Saves `run` as step 0 when it has no checkpoint yet and enqueues
153    /// its job now. Returns the store or queue error.
154    /// Call it once after `GraphRun::new`.
155    pub async fn enqueue(&self, run: &GraphRun) -> Result<(), HostError> {
156        if self.checkpoints.latest(run.run_id()).await?.is_none() {
157            self.checkpoints.save(run.checkpoint()).await?;
158        }
159        self.queue.enqueue(run.run_id(), self.now()).await?;
160        Ok(())
161    }
162
163    /// Processes one claimed `lease`: load, step (timed as active work, or
164    /// stopped instead once over its time limit), save when it moved, then
165    /// queue the outcome. A save conflict returns `Lost`; store errors
166    /// reschedule the job after one second and return the error.
167    pub async fn process(&self, lease: &Lease) -> Result<Processed, HostError> {
168        let mut span = trace_span!(Trace::Graphs, "graph.job", run = lease.run_id.to_string());
169        let result = span.instrument(self.process_leased(lease)).await;
170        match &result {
171            Ok(Processed::Stepped(_)) => span.record("outcome", "stepped"),
172            Ok(Processed::Unchanged(_)) => span.record("outcome", "unchanged"),
173            Ok(Processed::Lost) => span.record("outcome", "lost"),
174            Err(e) => span.fail(e.to_string()),
175        }
176        result
177    }
178
179    async fn process_leased(&self, lease: &Lease) -> Result<Processed, HostError> {
180        let cp = match self.checkpoints.latest(lease.run_id).await {
181            Ok(Some(cp)) => cp,
182            Ok(None) => {
183                self.queue.fail(lease, "no checkpoint").await?;
184                return Err(HostError::NoCheckpoint(lease.run_id));
185            }
186            Err(e) => return Err(self.store_failed(lease, e).await),
187        };
188        let mut run = match GraphRun::from_checkpoint(&cp) {
189            Ok(run) => run,
190            Err(e) => {
191                self.queue.fail(lease, &e.to_string()).await?;
192                return Err(e.into());
193            }
194        };
195        let before = run.steps();
196        let outcome = if run.over_time() {
197            let limit_ms = run.time_limit_ms().expect("only a limited run is over time");
198            let _finished = run.stop(Stop::TimeLimit { limit_ms });
199            self.step(&mut run).await
200        } else {
201            let started = self.now();
202            let outcome = self.step(&mut run).await;
203            run.add_active_ms(u64::try_from(self.now() - started).unwrap_or(0));
204            outcome
205        };
206        let moved = run.steps() != before;
207        if moved {
208            match self.checkpoints.save(run.checkpoint()).await {
209                Ok(()) => {}
210                Err(CoreError::Conflict { .. }) => return Ok(Processed::Lost),
211                Err(e) => return Err(self.store_failed(lease, e).await),
212            }
213        }
214        let queued = match &outcome {
215            GraphOutcome::Continue => self.queue.reschedule(lease, self.now()).await,
216            GraphOutcome::RetryAt { at_ms, .. } => self.queue.reschedule(lease, *at_ms).await,
217            GraphOutcome::Waiting(_) | GraphOutcome::Done(_) => self.queue.complete(lease).await,
218            GraphOutcome::Failed(error) => self.queue.fail(lease, error).await,
219        };
220        match queued {
221            Ok(()) => {}
222            Err(CoreError::Conflict { .. }) => return Ok(Processed::Lost),
223            Err(e) => return Err(e.into()),
224        }
225        Ok(if moved {
226            Processed::Stepped(outcome)
227        } else {
228            Processed::Unchanged(outcome)
229        })
230    }
231
232    async fn store_failed(&self, lease: &Lease, e: CoreError) -> HostError {
233        let _ = self
234            .queue
235            .reschedule(lease, self.now() + STORE_RETRY_MS)
236            .await;
237        e.into()
238    }
239
240    /// Step mode: claims due jobs and processes each batch concurrently,
241    /// until nothing is due, `max_jobs` were processed or `budget_ms` has
242    /// passed (checked before each claim). Returns the report or the claim error.
243    pub async fn tick(&self, opts: TickOptions) -> Result<TickReport, HostError> {
244        let start = self.now();
245        let mut report = TickReport::default();
246        while report.processed < opts.max_jobs && self.now() - start < opts.budget_ms {
247            let leases = self
248                .queue
249                .claim_due(opts.max_jobs - report.processed, self.lease_ms)
250                .await?;
251            if leases.is_empty() {
252                break;
253            }
254            assert!(leases.len() <= opts.max_jobs - report.processed);
255            for result in join_all(leases.iter().map(|l| self.process(l))).await {
256                report.processed += 1;
257                match result {
258                    Ok(Processed::Lost) => report.lost += 1,
259                    Ok(_) => {}
260                    Err(e) => report.errors.push(e.to_string()),
261                }
262            }
263        }
264        Ok(report)
265    }
266
267    /// Worker mode: ticks in a loop, sleeping `idle_ms` after a tick that
268    /// processed nothing or failed to claim. Returns once `shutdown` is
269    /// true (or its sender is gone), after the tick in progress.
270    pub async fn work(&self, opts: WorkOptions, mut shutdown: watch::Receiver<bool>) {
271        while !*shutdown.borrow() {
272            let idle = self
273                .tick(opts.tick)
274                .await
275                .map_or(true, |r| r.processed == 0);
276            if !idle || *shutdown.borrow() {
277                continue;
278            }
279            tokio::select! {
280                _ = tokio::time::sleep(Duration::from_millis(opts.idle_ms)) => {}
281                changed = shutdown.changed() => {
282                    if changed.is_err() {
283                        return;
284                    }
285                }
286            }
287        }
288    }
289
290    /// Answers human node `node` of `run_id` with `answer`, saves the run
291    /// under the next-step rule and enqueues it now. Returns `Resume` when
292    /// the answer does not fit, or `Conflict` when the run moved meanwhile.
293    pub async fn resume(&self, run_id: RunId, node: &str, answer: Value) -> Result<(), HostError> {
294        let mut run = self.load(run_id).await?;
295        run.resume(node, answer)?;
296        self.save_and_enqueue(&run).await
297    }
298
299    /// Replaces the limits of `run_id` with `limits`, resumes its budget
300    /// pauses, saves it under the next-step rule and enqueues it now.
301    /// Returns the graph, store or queue error.
302    pub async fn raise_budget(&self, run_id: RunId, limits: Limits) -> Result<(), HostError> {
303        let mut run = self.load(run_id).await?;
304        run.raise_budget(limits)?;
305        self.save_and_enqueue(&run).await
306    }
307
308    async fn load(&self, run_id: RunId) -> Result<GraphRun, HostError> {
309        let cp = self
310            .checkpoints
311            .latest(run_id)
312            .await?
313            .ok_or(HostError::NoCheckpoint(run_id))?;
314        Ok(GraphRun::from_checkpoint(&cp)?)
315    }
316
317    async fn save_and_enqueue(&self, run: &GraphRun) -> Result<(), HostError> {
318        self.checkpoints.save(run.checkpoint()).await?;
319        self.queue.enqueue(run.run_id(), self.now()).await?;
320        Ok(())
321    }
322}