Skip to main content

printobserver_core/
expiry.rs

1//! A bounded intervention expires on its own, and nothing has to ask it to.
2//!
3//! The expiry driver is a thread [`Supervisor::new`] starts. It reads the
4//! injected clock and nothing else, so expiry is driven by time passing and by
5//! nothing else, and a test drives it by advancing that clock alone.
6//!
7//! # Time passing, not the wall clock moving
8//!
9//! An intervention's deadline is persisted as an absolute instant, so that a
10//! restart knows when it was due. But a live expiry is decided on
11//! [`Clock::elapsed`](crate::Clock::elapsed), which nothing steps: each
12//! active intervention's remaining time is taken **once** from its persisted
13//! deadline — when this supervisor applies it, or, for one a previous
14//! supervisor left active, against the [`ClockReading`] this one took as it
15//! started — and is counted down on the clock nothing steps from then on. A
16//! host whose time synchronisation steps the wall clock therefore neither cuts
17//! a bounded change short nor draws it out.
18//!
19//! Expiry has exactly three outcomes and this module is the one place they are
20//! decided, so that the sweep and a print's terminal cleanup cannot drift into
21//! handling different sets of them:
22//!
23//! * **Restored** — the prior value went back, bounded by the same policy the
24//!   original request passed.
25//! * **Restore unavailable** — the printer reported no prior value, so there is
26//!   nothing to put back and nothing is sent to the machine. Writing a guessed
27//!   default would be inventing a value nobody observed.
28//! * **Restore failed** — the restoration was refused, by policy or by the
29//!   printer. The intervention is **settled** rather than left active, because
30//!   the expiry did happen, and it reads back carrying the applied value the
31//!   printer was left holding beside the prior value it should have been
32//!   returned to: a reason string alone would not say what the machine is
33//!   holding now, which is the whole point of recording it.
34//!
35//! Nothing here retries. A retry would be machinery this crate's manifest rule
36//! forbids it, and absorbing a transient store failure belongs behind the store
37//! port rather than here.
38
39use core::time::Duration;
40use std::collections::BTreeMap;
41use std::sync::Mutex;
42use std::sync::atomic::{AtomicBool, Ordering};
43
44use crate::records::{
45    Actor, Intervention, InterventionId, InterventionOutcome, MaterialObjection, PolicyDecision,
46    PrintAction, RejectionReason, SheetId, SheetObjection,
47};
48use crate::records::{CameraCheckId, CameraCheckObjection};
49use printobserver_printer_api::Adjustable;
50use printobserver_types::{PrintId, Timestamp};
51
52use crate::clock::ClockReading;
53use crate::decision::{DecisionInput, decide};
54use crate::error::CoreError;
55use crate::store::{EventDraft, SettleOutcome};
56use crate::supervisor::Supervisor;
57
58/// The active interventions this supervisor is counting down, each with the
59/// reading of [`Clock::elapsed`](crate::Clock::elapsed) it expires at.
60#[derive(Debug, Default)]
61pub(crate) struct Deadlines {
62    /// Each intervention, by its identifier, and when it expires.
63    counting: Mutex<BTreeMap<InterventionId, (Intervention, Duration)>>,
64    /// Whether the interventions a previous supervisor left active have been
65    /// read and are being counted down.
66    adopted: AtomicBool,
67}
68
69impl Deadlines {
70    /// Count one intervention down from `reading`, replacing any count of it.
71    fn count(&self, intervention: &Intervention, reading: ClockReading) {
72        let due = reading.elapsed_at(intervention.expires_at);
73        self.counting()
74            .insert(intervention.id, (intervention.clone(), due));
75    }
76
77    /// Count one intervention down from `reading`, unless it is already.
78    fn adopt(&self, intervention: &Intervention, reading: ClockReading) {
79        let due = reading.elapsed_at(intervention.expires_at);
80        self.counting()
81            .entry(intervention.id)
82            .or_insert_with(|| (intervention.clone(), due));
83    }
84
85    /// Stop counting one intervention down.
86    fn forget(&self, intervention_id: InterventionId) {
87        self.counting().remove(&intervention_id);
88    }
89
90    /// Every intervention whose count has reached `elapsed`, soonest first.
91    fn due(&self, elapsed: Duration) -> Vec<Intervention> {
92        let mut due: Vec<(Duration, Intervention)> = self
93            .counting()
94            .values()
95            .filter(|(_, at)| *at <= elapsed)
96            .map(|(intervention, at)| (*at, intervention.clone()))
97            .collect();
98        due.sort_by_key(|(at, _)| *at);
99        due.into_iter()
100            .map(|(_, intervention)| intervention)
101            .collect()
102    }
103
104    /// The counts, held for one read or write.
105    fn counting(
106        &self,
107    ) -> std::sync::MutexGuard<'_, BTreeMap<InterventionId, (Intervention, Duration)>> {
108        self.counting
109            .lock()
110            .unwrap_or_else(std::sync::PoisonError::into_inner)
111    }
112}
113
114/// The reason a restoring request carries, so the record says why it was made.
115const RESTORE_REASON: &str = "the bounded intervention expired";
116
117/// The request that puts one adjustable back to the value the print started at.
118///
119/// It carries no duration: a restoration opens no intervention of its own.
120#[must_use]
121pub fn restoring_action(adjustable: Adjustable, prior_value: f64) -> PrintAction {
122    match adjustable {
123        Adjustable::Feedrate => PrintAction::SetFeedrateFactor {
124            factor: prior_value,
125            duration_s: None,
126            reason: RESTORE_REASON.to_owned(),
127            actor: Actor::System,
128        },
129        Adjustable::Flowrate => PrintAction::SetFlowrateFactor {
130            factor: prior_value,
131            duration_s: None,
132            reason: RESTORE_REASON.to_owned(),
133            actor: Actor::System,
134        },
135        Adjustable::ToolTarget { tool } => PrintAction::SetToolTargetC {
136            tool,
137            target_c: prior_value,
138            duration_s: None,
139            reason: RESTORE_REASON.to_owned(),
140            actor: Actor::System,
141        },
142        Adjustable::BedTarget => PrintAction::SetBedTargetC {
143            target_c: prior_value,
144            duration_s: None,
145            reason: RESTORE_REASON.to_owned(),
146            actor: Actor::System,
147        },
148        Adjustable::Fan => PrintAction::SetFanPercent {
149            percent: prior_value,
150            duration_s: None,
151            reason: RESTORE_REASON.to_owned(),
152            actor: Actor::System,
153        },
154    }
155}
156
157/// What the material check objected to, naming what it compared.
158// llmlint: ignore[changed_behavior_has_e2e] suppressions.toml has the reason.
159fn material_detail(objection: &MaterialObjection) -> String {
160    match objection {
161        MaterialObjection::Mismatch(compared) => format!(
162            "the file was sliced for {}, and spool {} on tool {} is {}",
163            compared.sliced_for, compared.spool.name, compared.tool, compared.loaded
164        ),
165        MaterialObjection::Undeclared(uncompared) => format!(
166            "{} names no `filament_type`, so it cannot be compared with spool {} on tool {}, \
167             which is {}",
168            uncompared.file_name, uncompared.spool.name, uncompared.tool, uncompared.loaded
169        ),
170        MaterialObjection::Unread {
171            tool,
172            spool,
173            loaded,
174            file_name,
175            detail,
176        } => format!(
177            "the settings of {file_name} could not be read ({detail}), so it cannot be compared \
178             with spool {} on tool {tool}, which is {loaded}",
179            spool.name
180        ),
181    }
182}
183
184/// Sheets, as a list a sentence carries.
185fn listed(sheets: &[SheetId]) -> String {
186    sheets
187        .iter()
188        .map(SheetId::as_str)
189        .collect::<Vec<_>>()
190        .join(", ")
191}
192
193/// What the camera check a start names was refused for, naming the check.
194fn camera_check_detail(camera_check: CameraCheckId, objection: &CameraCheckObjection) -> String {
195    match objection {
196        CameraCheckObjection::Unknown => format!(
197            "no camera check {camera_check} is recorded: run `check-camera` on the empty sheet \
198             and name the check it answers"
199        ),
200        CameraCheckObjection::NotAligned { verdict } => format!(
201            "camera check {camera_check} found the camera {}, and only an `aligned` check may \
202             be named: check the camera again once it is",
203            verdict.as_str()
204        ),
205        CameraCheckObjection::OtherSheet {
206            checked_on,
207            declared,
208        } => format!(
209            "camera check {camera_check} was made on {}, and the manifest declares {}: check \
210             the camera on the sheet the print goes down on",
211            checked_on.as_str(),
212            declared.as_str()
213        ),
214    }
215}
216
217/// What the sheet check objected to, naming what it compared.
218// llmlint: ignore[changed_behavior_has_e2e] suppressions.toml has the reason.
219fn sheet_detail(objection: &SheetObjection) -> String {
220    match objection {
221        SheetObjection::NotAllowed(compared) => format!(
222            "the sheet table allows {} on {} and not on {}",
223            compared.material,
224            listed(&compared.allowed),
225            compared.sheet
226        ),
227        SheetObjection::UnlistedMaterial { sheet, material } => format!(
228            "the sheet table has no entry for {material}, so {sheet} is not known to suit it"
229        ),
230        SheetObjection::UnknownSheet {
231            sheet,
232            material,
233            known,
234        } => format!(
235            "no entry of the sheet table lists {sheet}, so it is not known to suit {material}; \
236             the sheets it names are {}",
237            listed(known)
238        ),
239    }
240}
241
242/// The whole seconds of the agent's minimum interval still to wait, never
243/// fewer than one: `since_last_s` is rounded down, so waiting this long is
244/// always enough.
245const fn interval_left_s(interval_s: i64, since_last_s: i64) -> i64 {
246    let left = interval_s.saturating_sub(since_last_s);
247    if left < 1 { 1 } else { left }
248}
249
250/// What a short or doubted spool was meant for: its tool, and the stretch of a
251/// file with planned changes when it was named for one.
252fn meant_for(tool: i64, segment: Option<u32>) -> String {
253    match segment {
254        Some(segment) => format!(" for segment {segment} on tool {tool}"),
255        None => format!(" on tool {tool}"),
256    }
257}
258
259/// Why policy refused a request, in words a reader of the record can act on.
260#[must_use]
261pub fn rejection_detail(reason: &RejectionReason) -> String {
262    match reason {
263        RejectionReason::OutOfBounds {
264            adjustable,
265            requested,
266            allowed,
267        } => format!(
268            "{requested} is outside the {} to {} allowed for {adjustable}",
269            allowed.min, allowed.max
270        ),
271        RejectionReason::ActorMayNotRequest {
272            actor_class,
273            action,
274        } => format!("{actor_class:?} may not request {action:?}"),
275        RejectionReason::NoActivePrint => "there is no active print to act on".to_owned(),
276        RejectionReason::InvalidFromState { state } => {
277            format!("this is not valid from {state:?}")
278        }
279        RejectionReason::MinIntervalNotElapsed {
280            interval_s,
281            since_last_s,
282        } => {
283            let left_s = interval_left_s(*interval_s, *since_last_s);
284            format!(
285                "the agent last acted {since_last_s}s ago and its minimum interval is \
286                 {interval_s}s, so {left_s}s of it are left: send the same request again after \
287                 a look that waits at least {left_s}s"
288            )
289        }
290        RejectionReason::UnsupportedAdjustable { adjustable } => {
291            format!("this printer has no {adjustable}")
292        }
293        RejectionReason::InsufficientFilament {
294            tool,
295            spool_name,
296            required_g,
297            buffer_g,
298            remaining_g,
299            segment,
300            ..
301        } => format!(
302            "spool {spool_name}{} holds {remaining_g}g, and the print needs {required_g}g and a \
303             {buffer_g}g buffer",
304            meant_for(*tool, *segment)
305        ),
306        RejectionReason::UnverifiedSpool {
307            tool,
308            spool_name,
309            segment,
310            ..
311        } => format!(
312            "spool {spool_name}{} is unverified",
313            meant_for(*tool, *segment)
314        ),
315        RejectionReason::PlannedChangeWaiting {
316            change_index,
317            layer,
318            z_mm,
319            color,
320        } => format!(
321            "the printer is waiting at planned change {}, for {} to be loaded for layer \
322             {layer} (Z {z_mm} mm): a person finishes it on the printer, and nothing pauses, \
323             resumes or adjusts the print until it carries on",
324            change_index.saturating_add(1),
325            color.as_deref().unwrap_or("the next filament")
326        ),
327        RejectionReason::AnalysisUnavailable {
328            file_name,
329            waited_s,
330        } => format!("{file_name} had no analysis after waiting {waited_s}s for one"),
331        RejectionReason::MaterialRefused { objection } => material_detail(objection),
332        RejectionReason::SheetRefused { objection } => sheet_detail(objection),
333        RejectionReason::SheetNotDeclared => "the manifest declares no `sheet`, and every start \
334             names the build sheet it goes down on; no override lets a start without one through"
335            .to_owned(),
336        RejectionReason::CameraCheckRefused {
337            camera_check,
338            objection,
339        } => camera_check_detail(*camera_check, objection),
340        RejectionReason::SpoolRefused { message, .. } => message.clone(),
341        RejectionReason::PrintAlreadyEnded => "this print's record has already ended".to_owned(),
342        RejectionReason::PrintStillActive { state } => {
343            format!("the printer shows this print's file still {state:?}")
344        }
345        RejectionReason::InterventionStillActive { intervention_id } => {
346            format!("intervention {intervention_id} has neither expired nor been restored")
347        }
348        RejectionReason::PrintNotResumable { recovery_event_id } => format!(
349            "recovery event {recovery_event_id} moved the printer while this print was paused, \
350             and resuming would print the rest of the layer at the wrong height"
351        ),
352    }
353}
354
355impl Supervisor {
356    /// Expire every bounded intervention whose time has passed.
357    ///
358    /// One intervention's failure does not cost the rest: every one that is due
359    /// is attempted on the same sweep.
360    ///
361    /// The expiry driver calls this on its own poll. Its first sweep reads the
362    /// interventions a previous supervisor left active and counts each down
363    /// from the reading this supervisor took as it started; every later one
364    /// reads nothing, because every intervention opened since is counted down
365    /// from the moment it was applied.
366    ///
367    /// # Errors
368    ///
369    /// Returns the store's own error when the interventions left active could
370    /// not be read, which the next sweep reads again. A failure settling one of
371    /// them is recorded on that intervention rather than answered here.
372    pub async fn sweep_expired(&self) -> Result<(), CoreError> {
373        self.adopt_left_active().await?;
374        for intervention in self.deadlines().due(self.clock().elapsed()) {
375            let _ = self.expire_intervention(&intervention).await;
376        }
377        Ok(())
378    }
379
380    /// Count down every intervention a previous supervisor left active, once.
381    async fn adopt_left_active(&self) -> Result<(), CoreError> {
382        let deadlines = self.deadlines();
383        if deadlines.adopted.load(Ordering::Acquire) {
384            return Ok(());
385        }
386        // Every active intervention is due by the latest instant a deadline can
387        // be recorded at, so this reads every one.
388        for intervention in self
389            .stores()
390            .actions
391            .due_interventions(Timestamp::latest())
392            .await?
393        {
394            deadlines.adopt(&intervention, self.started());
395        }
396        deadlines.adopted.store(true, Ordering::Release);
397        Ok(())
398    }
399
400    /// Count one intervention this supervisor just applied down from now.
401    pub(crate) fn count_down(&self, intervention: &Intervention) {
402        self.deadlines()
403            .count(intervention, ClockReading::of(self.clock().as_ref()));
404    }
405
406    /// Stop counting down one intervention settled other than by expiring.
407    pub(crate) fn stop_counting_down(&self, intervention_id: InterventionId) {
408        self.deadlines().forget(intervention_id);
409    }
410
411    /// Expire every intervention still active on one print.
412    ///
413    /// Each takes the same three-way behaviour an ordinary expiry takes, and
414    /// one that fails does not cost the rest.
415    ///
416    /// # Errors
417    ///
418    /// Returns the store's own error when the print's active interventions
419    /// could not be read.
420    pub(crate) async fn expire_all_active(&self, print_id: PrintId) -> Result<(), CoreError> {
421        for intervention in self.stores().actions.active_interventions(print_id).await? {
422            let _ = self.expire_intervention(&intervention).await;
423        }
424        Ok(())
425    }
426
427    /// Expire one intervention: restore, report nothing to restore, or record
428    /// that the restoration failed.
429    ///
430    /// Settling is once-only, so an intervention this and the expiry driver
431    /// both reach answers the outcome that won rather than being restored
432    /// twice. That is what lets a composition root expire what a restart left
433    /// past its bound and record the outcome, whichever of the two got there
434    /// first.
435    ///
436    /// # Errors
437    ///
438    /// Returns the store's own error when the outcome could not be settled.
439    pub async fn expire_intervention(
440        &self,
441        intervention: &Intervention,
442    ) -> Result<InterventionOutcome, CoreError> {
443        let outcome = self.expire_once(intervention).await?;
444        self.deadlines().forget(intervention.id);
445        Ok(outcome)
446    }
447
448    /// Expire one intervention, whatever was counting it down.
449    async fn expire_once(
450        &self,
451        intervention: &Intervention,
452    ) -> Result<InterventionOutcome, CoreError> {
453        if intervention.outcome != InterventionOutcome::StillActive {
454            return Ok(intervention.outcome.clone());
455        }
456        // Another expiry may have reached it first — the driver's sweep, a
457        // close-out, a start's reconciliation — so it is read again once this
458        // one holds the print's expiries, and one already settled is answered
459        // with the outcome that won rather than put back a second time.
460        let _expiring = self.expiring().acquire(intervention.print_id).await;
461        let still_active = self
462            .stores()
463            .actions
464            .active_interventions(intervention.print_id)
465            .await?
466            .iter()
467            .any(|active| active.id == intervention.id);
468        if !still_active {
469            // Settling is once-only, so this writes nothing and answers the
470            // outcome already settled.
471            return self
472                .settle(intervention, InterventionOutcome::RestoreUnavailable)
473                .await;
474        }
475        let Some(prior_value) = intervention.prior_value else {
476            return self
477                .settle(intervention, InterventionOutcome::RestoreUnavailable)
478                .await;
479        };
480        let outcome = self.restore(intervention, prior_value).await?;
481        self.settle(intervention, outcome).await
482    }
483
484    /// Put one adjustable back, bounded by the same policy the request passed.
485    async fn restore(
486        &self,
487        intervention: &Intervention,
488        prior_value: f64,
489    ) -> Result<InterventionOutcome, CoreError> {
490        let requested_at = self.clock().now();
491        let action = restoring_action(intervention.adjustable, prior_value);
492        let actor = action.actor().clone();
493        let print = self.stores().prints.print(intervention.print_id).await?;
494        let bounds = self
495            .bounds_for(print.as_ref(), intervention.print_id)
496            .await?;
497        let decision = decide(&DecisionInput {
498            action: &action,
499            actor: &actor,
500            requested_at,
501            print: print.as_ref(),
502            // A restoration is judged from no state: see `DecisionInput`.
503            printer_state: None,
504            bounds: &bounds.effective,
505            envelope: &self.config().envelope,
506            since_last_agent_action: None,
507        });
508        let request = crate::records::ActionRequest {
509            action,
510            actor,
511            requested_at,
512        };
513        let issued = self.issue_action(request, decision, None).await?;
514        if let PolicyDecision::Rejected(reason) = &issued.record.decision {
515            return Ok(InterventionOutcome::RestoreFailed {
516                reason: rejection_detail(reason),
517            });
518        }
519        if let Some(error) = issued.printer_error() {
520            return Ok(InterventionOutcome::RestoreFailed {
521                reason: error.to_string(),
522            });
523        }
524        Ok(InterventionOutcome::Restored)
525    }
526
527    /// Settle one intervention, answering the outcome that won.
528    async fn settle(
529        &self,
530        intervention: &Intervention,
531        outcome: InterventionOutcome,
532    ) -> Result<InterventionOutcome, CoreError> {
533        let settled = self
534            .stores()
535            .actions
536            .settle_intervention(intervention.id, outcome)
537            .await?;
538        Ok(match settled {
539            // Written into the print's own history, because what became of a
540            // bounded change is the whole point of it having been bounded: an
541            // outcome that reached the intervention row and went no further
542            // would be one no read of this system could answer.
543            SettleOutcome::Settled {
544                intervention: settled,
545            } => {
546                self.append_expiry_event(intervention, settled.outcome.clone())
547                    .await?;
548                settled.outcome
549            }
550            SettleOutcome::AlreadySettled { outcome } => outcome,
551        })
552    }
553
554    /// Write what became of one bounded intervention into the print's history.
555    async fn append_expiry_event(
556        &self,
557        intervention: &Intervention,
558        outcome: InterventionOutcome,
559    ) -> Result<(), CoreError> {
560        self.stores()
561            .events
562            .append_event(EventDraft {
563                print_id: Some(intervention.print_id),
564                source: crate::kinds::system_source(),
565                received_at: self.clock().now(),
566                body: printobserver_types::EventBody::of(
567                    &crate::kinds::InterventionExpiredPayload {
568                        intervention_id: intervention.id,
569                        adjustable: intervention.adjustable,
570                        outcome,
571                    },
572                )?,
573                raw: None,
574            })
575            .await?;
576        Ok(())
577    }
578}