Skip to main content

printobserver_core/
planned.rs

1//! A print waiting at a change its own G-code plans.
2//!
3//! A single-nozzle print sliced with colour changes stops at each `M600` so a
4//! person can load the next colour, and at an `M601` so a person can do
5//! whatever the pause was planned for. To everything else this supervisor
6//! watches that wait looks like a stall: the file position freezes, the parts
7//! stop growing, and the firmware's idle timeout turns the nozzle target to
8//! zero. So a planned stop is recognised, and the print is left alone until it
9//! carries on.
10//!
11//! # Reached
12//!
13//! A change is reached when a filament-change signal arrives with the job at
14//! it, or a read of the job finds its file position at the change's line or
15//! just past it ([`GcodeIndex::change_waiting_at`]). Either writes one
16//! [`FilamentChangePlannedReachedPayload`] per change of a print, and charges
17//! the spool on tool 0 up to the change's own offset, with the
18//! `filament_change_signalled` that is the accounting record of every change.
19//! A filament-change signal arriving again for a change already reached —
20//! `Obico` repeats one every ten minutes while the printer waits — writes
21//! nothing of its own and starts nothing.
22//!
23//! # While it waits
24//!
25//! No supervision turn runs for the print: no alert's, no scheduled check's
26//! and none the printer watch would give. A pause, a resume or an adjustment
27//! from any actor is refused
28//! [`PlannedChangeWaiting`](crate::records::RejectionReason::PlannedChangeWaiting);
29//! a cancel and every spool command are not, because a person may abandon the
30//! print or load the next spool while it waits.
31//!
32//! # Resumed
33//!
34//! When a read finds the file position past the change, one
35//! [`FilamentChangePlannedResumedPayload`] is written with the camera's frame,
36//! and that event is the print's next check, at once. The growth measurement
37//! starts again from frames taken after it, and the print's next scheduled
38//! check is one observation interval after it.
39//!
40//! # What is remembered, and where
41//!
42//! The store's history is the record; this supervisor keeps a copy of each
43//! print's planned changes so an alert or a request asks nothing of the store
44//! for a print whose file plans none. A print's copy is read from the history
45//! the first time its index, once built, plans a change, and for every open
46//! print as the server starts ([`Supervisor::restore_planned_changes`]).
47//! The index of a print found open as the server starts is built by the
48//! first read of its running job the printer watch makes, once, so a
49//! restarted server reaches a change by position before any check of it.
50
51use std::collections::{BTreeMap, BTreeSet};
52use std::sync::PoisonError;
53use std::time::Duration;
54
55use printobserver_printer_api::{JobSnapshot, PrinterState};
56use printobserver_types::{EventBody, EventKind, EventPayload, EventRecord, PrintId, Timestamp};
57
58use crate::accounting::{Whereabouts, spool_on_tool};
59use crate::clock::seconds_between;
60use crate::error::CoreError;
61use crate::events::PendingTurn;
62use crate::gcode_index::{GcodeIndex, PlannedChange, PlannedChanges};
63use crate::inbox::{AlertCameraFrame, Arrival};
64use crate::kinds::{
65    FilamentChangePlannedReachedPayload, FilamentChangePlannedResumedPayload, PlannedChangeTrigger,
66};
67use crate::look::Frame;
68use crate::records::{ActionKind, FilePosition, PrintRecord, RejectionReason};
69use crate::store::{HistoryQuery, MAX_HISTORY_LIMIT};
70use crate::supervisor::Supervisor;
71
72/// The actions a print waiting at a planned change refuses, whoever asks.
73pub const REFUSED_WHILE_WAITING: [ActionKind; 7] = [
74    ActionKind::Pause,
75    ActionKind::Resume,
76    ActionKind::SetFeedrateFactor,
77    ActionKind::SetFlowrateFactor,
78    ActionKind::SetToolTargetC,
79    ActionKind::SetBedTargetC,
80    ActionKind::SetFanPercent,
81];
82
83/// The change a print is waiting at, as its `reached` recorded it.
84#[derive(Debug, Clone, PartialEq)]
85pub struct Waiting {
86    /// What the `reached` event recorded.
87    pub reached: FilamentChangePlannedReachedPayload,
88    /// When it was recorded.
89    pub since: Timestamp,
90}
91
92impl Waiting {
93    /// The refusal a pause, a resume or an adjustment is answered while it
94    /// waits.
95    #[must_use]
96    pub fn refusal(&self) -> RejectionReason {
97        let change = &self.reached.change;
98        RejectionReason::PlannedChangeWaiting {
99            change_index: change.index,
100            layer: change.layer,
101            z_mm: change.z_mm,
102            color: change.color.clone(),
103        }
104    }
105}
106
107/// A change one read has taken to record its resumption, and when the
108/// print's last check after a change had begun before it.
109#[derive(Debug)]
110struct Claimed {
111    /// The change the print waited at.
112    waiting: Waiting,
113    /// When the print's last check after a change had begun, if one had.
114    checked_before: Option<Duration>,
115}
116
117/// What this supervisor holds of one print's planned changes.
118#[derive(Debug, Clone, Default)]
119pub(crate) struct PlannedMemo {
120    /// Every change of the print's reached so far, by index.
121    reached: BTreeSet<u32>,
122    /// The change it is waiting at now.
123    waiting: Option<Waiting>,
124}
125
126/// One print's planned changes as its history records them, newest first.
127fn memo_of(history: &[EventRecord]) -> PlannedMemo {
128    let mut memo = PlannedMemo::default();
129    let mut resumed = BTreeSet::new();
130    for event in history.iter().rev() {
131        if let Some(Ok(reached)) = event.payload_as::<FilamentChangePlannedReachedPayload>() {
132            memo.reached.insert(reached.change.index);
133            memo.waiting = Some(Waiting {
134                reached,
135                since: event.received_at,
136            });
137        } else if let Some(Ok(done)) = event.payload_as::<FilamentChangePlannedResumedPayload>() {
138            resumed.insert(done.change.index);
139        }
140    }
141    memo.waiting = memo
142        .waiting
143        .filter(|waiting| !resumed.contains(&waiting.reached.change.index));
144    memo
145}
146
147/// How long a job read paused at a planned change stands at one position
148/// before that position alone reaches the change: long enough for the
149/// filament-change signal a pause there brings to arrive first, and well inside
150/// the interval between two scheduled checks.
151pub(crate) const PAUSED_AT_CHANGE_STAND: Duration = Duration::from_secs(30);
152
153/// The file position a job read reports for a print, when the job is that
154/// print's file, printing or paused, and reports one.
155fn position_of(print: &PrintRecord, job: &JobSnapshot) -> Option<u64> {
156    let running = matches!(job.state, PrinterState::Printing | PrinterState::Paused);
157    let same_file = print.file_name.is_none() || job.file_name == print.file_name;
158    job.file_position_bytes
159        .filter(|_| running && same_file)
160        .and_then(|bytes| u64::try_from(bytes).ok())
161}
162
163/// Whether an index plans any change.
164fn plans_changes(index: &GcodeIndex) -> bool {
165    index.planned_change(0).is_some()
166}
167
168impl Supervisor {
169    /// The memo of one print's planned changes, read from its history when
170    /// this supervisor holds none and its index, built, plans a change.
171    async fn planned_memo(&self, print_id: PrintId) -> Result<Option<PlannedMemo>, CoreError> {
172        if let Some(memo) = self.planned_memos().get(&print_id) {
173            return Ok(Some(memo.clone()));
174        }
175        let plans = self
176            .gcode_indexes()
177            .built(print_id)
178            .is_some_and(|index| plans_changes(&index));
179        if !plans {
180            return Ok(None);
181        }
182        self.load_planned_memo(print_id).await.map(Some)
183    }
184
185    /// Read one print's planned changes from its history into the memo.
186    async fn load_planned_memo(&self, print_id: PrintId) -> Result<PlannedMemo, CoreError> {
187        let kinds = [
188            FilamentChangePlannedReachedPayload::KIND,
189            FilamentChangePlannedResumedPayload::KIND,
190        ]
191        .into_iter()
192        .filter_map(|kind| EventKind::new(kind).ok())
193        .collect();
194        let history = self
195            .stores()
196            .events
197            .history(HistoryQuery {
198                print_id,
199                kinds,
200                since: None,
201                until: None,
202                limit: Some(MAX_HISTORY_LIMIT),
203            })
204            .await?;
205        let memo = memo_of(&history);
206        self.planned_memos().insert(print_id, memo.clone());
207        Ok(memo)
208    }
209
210    /// Take the change a print waits at from its memo, when it is still the
211    /// one numbered `index`, and mark the check after it begun, so that no
212    /// scheduled check runs while its resumption is being recorded. Nothing
213    /// when another read has claimed it first; otherwise the change and when
214    /// the print's last check after a change had begun, to put back.
215    ///
216    /// Proven against the real server by `tests/skilltest-wiring`'s replay of
217    /// the real two-colour print, whose watch and scheduled check land
218    /// together and which recorded a resumption twice before this claim, and
219    /// by the core journey `reads_past_a_change_at_once_record_its_resumption_once`,
220    /// which holds the write open to force the overlap every time.
221    fn claim_waiting(&self, print_id: PrintId, index: u32) -> Option<Claimed> {
222        let waiting = {
223            let mut memos = self.planned_memos();
224            let memo = memos.get_mut(&print_id)?;
225            if memo
226                .waiting
227                .as_ref()
228                .is_none_or(|waiting| waiting.reached.change.index != index)
229            {
230                return None;
231            }
232            memo.waiting.take()?
233        };
234        let checked_before = self
235            .checked_after_change
236            .lock()
237            .unwrap_or_else(PoisonError::into_inner)
238            .insert(print_id, self.clock().elapsed());
239        Some(Claimed {
240            waiting,
241            checked_before,
242        })
243    }
244
245    /// Put a claimed change back as the one a print waits at, when recording
246    /// its resumption failed, so that the next read records it instead.
247    ///
248    /// No test drives this through the real server: making its store refuse
249    /// one append mid-resumption would mean building a fault-injecting store
250    /// into the server for this one path. The core journeys
251    /// `a_resumption_the_store_refused_is_recorded_by_the_next_read` (no
252    /// earlier check) and `a_later_refused_resumption_keeps_the_earlier_checks_schedule`
253    /// (an earlier one) drive both arms through the supervisor instead.
254    fn unclaim_waiting(&self, print_id: PrintId, claimed: Claimed) {
255        {
256            let mut checked = self
257                .checked_after_change
258                .lock()
259                .unwrap_or_else(PoisonError::into_inner);
260            match claimed.checked_before {
261                Some(before) => checked.insert(print_id, before),
262                None => checked.remove(&print_id),
263            };
264        }
265        let mut memos = self.planned_memos();
266        let memo = memos.entry(print_id).or_default();
267        if memo.waiting.is_none() {
268            memo.waiting = Some(claimed.waiting);
269        }
270    }
271
272    /// The memos, held for one read or write.
273    fn planned_memos(&self) -> std::sync::MutexGuard<'_, BTreeMap<PrintId, PlannedMemo>> {
274        self.planned_memos
275            .lock()
276            .unwrap_or_else(PoisonError::into_inner)
277    }
278
279    /// Read every open print's planned changes from the history, as a server
280    /// starts: a print that was waiting at a change when the last one stopped
281    /// is still waiting at it, and is left alone from the first read on.
282    ///
283    /// # Errors
284    ///
285    /// The store's own error when the open prints or a history could not be
286    /// read.
287    pub async fn restore_planned_changes(&self) -> Result<(), CoreError> {
288        for print in self.stores().prints.open_prints().await? {
289            self.load_planned_memo(print.id).await?;
290            self.index_owed
291                .lock()
292                .unwrap_or_else(PoisonError::into_inner)
293                .insert(print.id);
294        }
295        Ok(())
296    }
297
298    /// The planned change one print is waiting at, when it is waiting at one.
299    ///
300    /// # Errors
301    ///
302    /// The store's own error when the print's history had to be read and
303    /// could not be.
304    pub async fn planned_change_waiting(
305        &self,
306        print_id: PrintId,
307    ) -> Result<Option<Waiting>, CoreError> {
308        Ok(self
309            .planned_memo(print_id)
310            .await?
311            .and_then(|memo| memo.waiting))
312    }
313
314    /// One print's planned changes, the one it waits at and the colour
315    /// expected where its job stands, as the status read answers them:
316    /// nothing for a print whose file plans none or could not be read.
317    ///
318    /// # Errors
319    ///
320    /// The store's own error when the print's history could not be read.
321    pub async fn planned_changes(
322        &self,
323        print: &PrintRecord,
324        job: Option<&JobSnapshot>,
325    ) -> Result<Option<PlannedChanges>, CoreError> {
326        if print.ended_at.is_some() {
327            return Ok(None);
328        }
329        let Some(index) = self.print_gcode_index(print.id).await else {
330            return Ok(None);
331        };
332        if !plans_changes(&index) {
333            return Ok(None);
334        }
335        let waiting = self.planned_change_waiting(print.id).await?;
336        let position = job.and_then(|job| position_of(print, job));
337        Ok(Some(PlannedChanges {
338            changes: index.planned_changes(),
339            segments: index.planned_segments(),
340            waiting: waiting.map(|waiting| waiting.reached.change.index),
341            expected_color: position.and_then(|position| {
342                index.expected_color_at(i64::try_from(position).unwrap_or(i64::MAX))
343            }),
344        }))
345    }
346
347    /// Whether a print may be given a supervision turn now: not while it
348    /// waits at a planned change.
349    pub(crate) async fn turns_allowed(&self, print_id: PrintId) -> Result<bool, CoreError> {
350        Ok(self.planned_change_waiting(print_id).await?.is_none())
351    }
352
353    /// Follow one read of a print's job against the changes its file plans:
354    /// record a change it has reached, or one it has carried on from, and
355    /// answer the check carrying on claims.
356    ///
357    /// A print a restart found open, whose index this supervisor has not
358    /// built, has its index built here when `build` asks, once per print: the
359    /// printer watch asks, so a change is reached by position from the first
360    /// read of the job after a restart, with no check or signal to build it
361    /// first. A scheduled check does not, so it is recorded as it begins
362    /// rather than after a whole file is read; it builds the index itself. A
363    /// print this supervisor started is never read here: its index is built
364    /// by its first check, as it always was, so a start whose preflight is off
365    /// reads nothing of its file. A build that fails is left to the next
366    /// check, as every failed build is.
367    ///
368    /// # Errors
369    ///
370    /// The store's own error when what changed could not be recorded.
371    pub(crate) async fn follow_planned_changes(
372        &self,
373        print: &PrintRecord,
374        job: &JobSnapshot,
375        build: bool,
376    ) -> Result<Option<PendingTurn>, CoreError> {
377        let Some(position) = position_of(print, job) else {
378            return Ok(None);
379        };
380        if build
381            && self.gcode_indexes().built(print.id).is_none()
382            && self
383                .index_owed
384                .lock()
385                .unwrap_or_else(PoisonError::into_inner)
386                .remove(&print.id)
387        {
388            // Built or not, the build is the index the next read finds.
389            let _ = self.print_gcode_index(print.id).await;
390        }
391        let Some(memo) = self.planned_memo(print.id).await? else {
392            return Ok(None);
393        };
394        if let Some(waiting) = memo.waiting {
395            let change = &waiting.reached.change;
396            if position > change.offset_bytes + crate::gcode_index::PLANNED_CHANGE_REACH_BYTES {
397                // Claimed before the first await, so that of two reads past the
398                // change at once only one records its resumption.
399                let Some(claimed) = self.claim_waiting(print.id, change.index) else {
400                    return Ok(None);
401                };
402                let resumed = self
403                    .resume_planned_change(print, claimed.waiting.clone(), job, position)
404                    .await;
405                if resumed.is_err() {
406                    self.unclaim_waiting(print.id, claimed);
407                }
408                return resumed;
409            }
410            return Ok(None);
411        }
412        let Some(index) = self.gcode_indexes().built(print.id) else {
413            return Ok(None);
414        };
415        let Some(change) = index.change_waiting_at(position).cloned() else {
416            self.forget_paused_at_change(print.id);
417            return Ok(None);
418        };
419        if !memo.reached.contains(&change.index)
420            && (job.state != PrinterState::Paused || self.stood_paused_at(print.id, position))
421        {
422            self.forget_paused_at_change(print.id);
423            self.reach_planned_change(
424                print,
425                &index,
426                change,
427                PlannedChangeTrigger::Position,
428                job,
429                None,
430            )
431            .await?;
432        }
433        Ok(None)
434    }
435
436    /// Whether a job read paused at a planned change has stood at this one
437    /// position for [`PAUSED_AT_CHANGE_STAND`], counting from the first such
438    /// read. A pause at the change is when `Obico`'s filament-change signal
439    /// arrives, so the signal reaches it first, and the position reaches it
440    /// alone only when no signal came, as at an `M601`.
441    fn stood_paused_at(&self, print_id: PrintId, position: u64) -> bool {
442        let now = self.clock().elapsed();
443        let mut held = self
444            .paused_at_change
445            .lock()
446            .unwrap_or_else(PoisonError::into_inner);
447        match held.get(&print_id) {
448            Some(&(at, since)) if at == position => {
449                now.saturating_sub(since) >= PAUSED_AT_CHANGE_STAND
450            }
451            _ => {
452                held.insert(print_id, (position, now));
453                false
454            }
455        }
456    }
457
458    /// Forget where a print's job stood paused at a planned change.
459    fn forget_paused_at_change(&self, print_id: PrintId) {
460        self.paused_at_change
461            .lock()
462            .unwrap_or_else(PoisonError::into_inner)
463            .remove(&print_id);
464    }
465
466    /// Whether a job stands paused at a planned change of its print's index:
467    /// reached or not, the print is a person's to change, and no check runs.
468    pub(crate) fn paused_at_planned_change(&self, print: &PrintRecord, job: &JobSnapshot) -> bool {
469        job.state == PrinterState::Paused
470            && position_of(print, job).is_some_and(|position| {
471                self.gcode_indexes()
472                    .built(print.id)
473                    .is_some_and(|index| index.change_waiting_at(position).is_some())
474            })
475    }
476
477    /// Whether a filament-change signal is one about a planned change: one
478    /// the print is already waiting at, which is answered with nothing more,
479    /// or one the job stands at now, which is recorded reached. Answers
480    /// whether it was, so a signal at no planned change is accounted as every
481    /// unplanned one is.
482    ///
483    /// # Errors
484    ///
485    /// The store's own error when what it reached could not be recorded.
486    pub(crate) async fn signal_at_planned_change(
487        &self,
488        print: &PrintRecord,
489        source_kind: &EventKind,
490    ) -> Result<bool, CoreError> {
491        if self.planned_change_waiting(print.id).await?.is_some() {
492            return Ok(true);
493        }
494        let Some(index) = self.print_gcode_index(print.id).await else {
495            return Ok(false);
496        };
497        if !plans_changes(&index) {
498            return Ok(false);
499        }
500        let Some(memo) = self.planned_memo(print.id).await? else {
501            return Ok(false);
502        };
503        let Ok(job) = self.read_job().await else {
504            return Ok(false);
505        };
506        let Some(change) = position_of(print, &job)
507            .and_then(|position| index.change_waiting_at(position))
508            .filter(|change| !memo.reached.contains(&change.index))
509            .cloned()
510        else {
511            return Ok(false);
512        };
513        self.reach_planned_change(
514            print,
515            &index,
516            change,
517            PlannedChangeTrigger::Signal,
518            &job,
519            Some(source_kind),
520        )
521        .await?;
522        Ok(true)
523    }
524
525    /// Record one planned change reached, and charge the spool feeding it up
526    /// to the change's offset.
527    async fn reach_planned_change(
528        &self,
529        print: &PrintRecord,
530        index: &GcodeIndex,
531        change: PlannedChange,
532        trigger: PlannedChangeTrigger,
533        job: &JobSnapshot,
534        signal_kind: Option<&EventKind>,
535    ) -> Result<(), CoreError> {
536        let now = self.clock().now();
537        let segments = index.planned_segments();
538        let segment = |at: u32| segments.iter().find(|segment| segment.segment == at);
539        let next = change.index + 1;
540        let next_spool_id = self
541            .stores()
542            .prints
543            .manifest(print.id)
544            .await?
545            .and_then(|manifest| {
546                manifest
547                    .segment_spools
548                    .iter()
549                    .find(|named| named.segment == next)
550                    .map(|named| named.spool_id)
551            });
552        let loaded = self.stores().filament.loaded_spools().await?;
553        let offset = i64::try_from(change.offset_bytes).unwrap_or(i64::MAX);
554        let payload = FilamentChangePlannedReachedPayload {
555            previous_color: segment(change.index).and_then(|segment| segment.color.clone()),
556            trigger,
557            position: FilePosition {
558                bytes: job.file_position_bytes.unwrap_or(offset),
559                size_bytes: job.size_bytes.filter(|size| *size > 0),
560                observed_at: now,
561            },
562            spool_id: spool_on_tool(&loaded, 0).map(|spool| spool.id),
563            next_spool_id,
564            next_segment_filament_mm: segment(next).map_or(0.0, |segment| segment.filament_mm),
565            change: change.clone(),
566        };
567        let event = self
568            .append_system_event(print.id, EventBody::of(&payload)?)
569            .await?;
570        {
571            let mut memos = self.planned_memos();
572            let memo = memos.entry(print.id).or_default();
573            memo.reached.insert(change.index);
574            memo.waiting = Some(Waiting {
575                reached: payload,
576                since: event.received_at,
577            });
578        }
579        let charged_at = FilePosition {
580            bytes: offset,
581            size_bytes: job.size_bytes.filter(|size| *size > 0),
582            observed_at: now,
583        };
584        let source_kind = signal_kind.cloned().unwrap_or_else(|| event.kind().clone());
585        self.charge_filament_change(
586            print,
587            &source_kind,
588            Whereabouts::ReadNow(charged_at),
589            Some(job.clone()),
590            Some(change.index),
591        )
592        .await
593    }
594
595    /// Record a print carried on from the change it waited at, with the
596    /// camera's frame, and claim the check that event is.
597    async fn resume_planned_change(
598        &self,
599        print: &PrintRecord,
600        waiting: Waiting,
601        job: &JobSnapshot,
602        position: u64,
603    ) -> Result<Option<PendingTurn>, CoreError> {
604        let now = self.clock().now();
605        let payload = FilamentChangePlannedResumedPayload {
606            change: waiting.reached.change.clone(),
607            previous_color: waiting.reached.previous_color.clone(),
608            waited_s: seconds_between(waiting.since, now).max(0),
609            position: FilePosition {
610                bytes: i64::try_from(position).unwrap_or(i64::MAX),
611                size_bytes: job.size_bytes.filter(|size| *size > 0),
612                observed_at: now,
613            },
614        };
615        let fetched = self.fetch_configured_frame(Some(print.id)).await;
616        let (fetched, degraded) = match fetched {
617            Some((_, Frame::Degraded(degraded))) => (None, Some(degraded)),
618            fetched => (fetched, None),
619        };
620        let event = self
621            .write_with_frame(Some(print.id), &payload, fetched)
622            .await?;
623        if let Some(degraded) = degraded {
624            self.append_system_event(print.id, EventBody::of(&degraded)?)
625                .await?;
626        }
627        if let Some(memo) = self.planned_memos().get_mut(&print.id) {
628            memo.waiting = None;
629        }
630        if let Some(images) = self.check_images.get() {
631            images.restart_growth(print.id);
632        }
633        self.checked_after_change
634            .lock()
635            .unwrap_or_else(PoisonError::into_inner)
636            .insert(print.id, self.clock().elapsed());
637        let arrival = Arrival {
638            event,
639            detection: None,
640            frame_captured_at: None,
641            camera_frame: AlertCameraFrame::NotAsked,
642        };
643        Ok(self
644            .inboxes()
645            .claim_or_hand_over(print.id, arrival.clone())
646            .then(|| PendingTurn::new(print.clone(), arrival, Vec::new())))
647    }
648
649    /// Whether a print's scheduled check is due: not until one observation
650    /// interval after the check its last planned change's resumption ran.
651    pub(crate) fn observation_due(&self, print_id: PrintId) -> bool {
652        let checked = self
653            .checked_after_change
654            .lock()
655            .unwrap_or_else(PoisonError::into_inner)
656            .get(&print_id)
657            .copied();
658        checked.is_none_or(|checked| {
659            self.clock().elapsed().saturating_sub(checked) >= self.config().observation_interval
660        })
661    }
662
663    /// How long the periodic observation should wait before its next round:
664    /// one interval, or less when a print's check after a planned change makes
665    /// its next scheduled check due sooner.
666    #[must_use]
667    pub fn until_next_observation(&self) -> Duration {
668        let interval = self.config().observation_interval;
669        let now = self.clock().elapsed();
670        self.checked_after_change
671            .lock()
672            .unwrap_or_else(PoisonError::into_inner)
673            .values()
674            .map(|checked| (*checked + interval).saturating_sub(now))
675            .filter(|left| !left.is_zero())
676            .min()
677            .map_or(interval, |left| left.min(interval))
678    }
679
680    /// Forget what this supervisor holds of a print's planned changes, once
681    /// it has closed.
682    pub(crate) fn forget_planned_changes(&self, print_id: PrintId) {
683        self.planned_memos().remove(&print_id);
684        self.index_owed
685            .lock()
686            .unwrap_or_else(PoisonError::into_inner)
687            .remove(&print_id);
688        self.checked_after_change
689            .lock()
690            .unwrap_or_else(PoisonError::into_inner)
691            .remove(&print_id);
692    }
693}