Skip to main content

printobserver_server/
alignment.rs

1//! Each print's first-layer alignment verdict and its camera view: whether the
2//! camera calibration's projection lands on that print's printed first layer,
3//! and the correction every later drawing of the print goes through.
4//!
5//! A projection can be wrong with the camera unmoved, and a camera that has
6//! shifted a little is ordinary on a real printer, so each print judges its
7//! own. Once the print's first object layer is down, every scheduled check's
8//! own stored frame is judged ([`Alignments::judge`]), at most once a check
9//! and with no camera fetch of its own, until one passes: the layer clearly
10//! found, on a frame the toolhead does not cover
11//! ([`printobserver_panels::judge_first_layer`]). A covered or unclear frame
12//! is inconclusive and the next check's is judged again. A check taken while
13//! the printer reports the print paused is not judged: its bed is lowered off
14//! the plan's height. Only a frame of another size or stream fails, and that
15//! holds for the rest of the print.
16//!
17//! A pass puts the print's correction in force, a translation every later
18//! drawing goes through, kept with the landmarks found agreeing on that frame as
19//! its reference. Its translation is the pass's found shift when the frame
20//! stood within one layer of the first layer
21//! ([`printobserver_panels::alignment::correction_shift`]), and none from a
22//! taller frame, where the search scores the part's body. Every later frame's view is judged against that
23//! reference ([`printobserver_panels::judge_found`]); one showing the camera
24//! moved again sets the alignment back to pending, to take a fresh correction
25//! from a later check. Nothing is kept across prints: a sheet sits a few
26//! millimetres apart from one print to the next.
27//!
28//! Every judgement is written into the print's history, naming the stored
29//! frame it was made on ([`crate::judgements`]).
30//!
31//! The verdict is written to `<state_dir>/alignment/<print id>.json` and the
32//! correction, the last inconclusive reason and the last check's image to
33//! `<state_dir>/camera-view/<print id>.json`, so they stand through a restart
34//! while the print is open, and are deleted once the print closes. A verdict
35//! file an earlier release left failed on its offset is read as pending and
36//! judged again.
37//!
38//! Which check draws the toolpath on its image reads the verdict through
39//! [`Alignments::print_alignment`] and draws only for a print that `Passed`.
40//!
41//! Beside each verdict is kept the frame the print's last check was given,
42//! which the next check's image shows as the previous one
43//! ([`Alignments::previous_check`]): written under
44//! `<state_dir>/previous-check/<print id>.json`, standing through a restart
45//! while the print is open, and swept with the verdict once it closes.
46//!
47//! And beside that, the frames of the print's recent checks with the height
48//! the plan had reached at each ([`Alignments::checked_frames`]): written
49//! under `<state_dir>/checked-frames/<print id>.json`, kept and swept the same
50//! way, so that a check can measure whether the parts grew since one far
51//! enough below it ([`Alignments::growth_reference`]).
52
53use std::path::{Path, PathBuf};
54use std::sync::Arc;
55use std::time::Duration;
56
57use printobserver_core::PlanPosition;
58use printobserver_core::store::PrintStore;
59use printobserver_panels::{
60    AlignmentInputs, CameraCalibration, ComposeError, FirstLayerInputs, FirstLayerVerdict,
61    FrameField, InconclusiveReason, ReferenceLandmark, ViewCorrection, ViewJudgement, ViewOutcome,
62    judge_first_layer, judge_found, landmarks_in_frame,
63};
64use printobserver_supervisor_api::{ImageFallback, ImageKind};
65use printobserver_types::contract::Sample;
66use printobserver_types::schemars::JsonSchema;
67use printobserver_types::serde::{Deserialize, Serialize};
68use printobserver_types::{EventBody, EventPayload, PrintId, Timestamp};
69
70/// Why a print's alignment failed.
71#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
72#[serde(
73    crate = "printobserver_types::serde",
74    tag = "failure",
75    rename_all = "snake_case"
76)]
77#[schemars(crate = "printobserver_types::schemars")]
78pub enum AlignmentFailure {
79    /// The printed first layer lies further from its projection than the
80    /// calibration allows. No longer written: a frame that does not clearly
81    /// find the layer is inconclusive, and a verdict file an earlier release
82    /// left holding this is read as pending.
83    Offset {
84        /// How far, in calibration pixels.
85        offset_px: f64,
86    },
87    /// The camera's frames are not the calibration's resolution.
88    Resolution {
89        /// The calibration's, `[width, height]`.
90        expected: [u32; 2],
91        /// The frame's.
92        got: [u32; 2],
93    },
94    /// The camera configured is not the stream the calibration was fitted on.
95    Stream,
96}
97
98/// One print's first-layer alignment verdict, as it is kept under the state
99/// directory — which the real-print suite's record reads.
100#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
101#[serde(
102    crate = "printobserver_types::serde",
103    tag = "verdict",
104    rename_all = "snake_case"
105)]
106#[schemars(crate = "printobserver_types::schemars")]
107pub enum PrintAlignment {
108    /// Nothing can be checked: no calibration is configured, or the print's
109    /// G-code lays no object.
110    Unavailable,
111    /// The first object layer is not down yet, or no frame of it has been
112    /// judged.
113    Pending,
114    /// The projected first layer lands on the printed one.
115    Passed {
116        /// How far it lies from it, in calibration pixels.
117        offset_px: f64,
118        /// The first-layer correction applied to every later drawing of the
119        /// print, `[dx, dy]` calibration pixels: the shift the layer was found
120        /// at. `[0, 0]` in a verdict an earlier release wrote.
121        #[serde(default)]
122        correction_px: [f64; 2],
123    },
124    /// It does not, or the frames cannot be judged against the calibration.
125    Failed {
126        /// Why.
127        reason: AlignmentFailure,
128    },
129}
130
131impl Sample for PrintAlignment {
132    fn sample_full() -> Self {
133        Self::Passed {
134            offset_px: 14.6,
135            correction_px: [14.0, 4.0],
136        }
137    }
138
139    fn sample_minimal() -> Self {
140        Self::Pending
141    }
142
143    fn sample_alternates() -> Vec<Self> {
144        vec![
145            Self::Unavailable,
146            Self::Failed {
147                reason: AlignmentFailure::Offset { offset_px: 48.5 },
148            },
149            Self::Failed {
150                reason: AlignmentFailure::Resolution {
151                    expected: [1920, 1080],
152                    got: [1280, 720],
153                },
154            },
155            Self::Failed {
156                reason: AlignmentFailure::Stream,
157            },
158        ]
159    }
160}
161
162/// The frame one print's last check was given, and when it was captured.
163#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
164#[serde(crate = "printobserver_types::serde")]
165pub struct PreviousCheck {
166    /// The stored frame's path.
167    pub frame: PathBuf,
168    /// When it was captured.
169    pub captured_at: printobserver_types::Timestamp,
170}
171
172/// One check's frame and the height the plan had reached as it was captured.
173#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
174#[serde(crate = "printobserver_types::serde")]
175pub struct CheckedFrame {
176    /// The stored frame's path.
177    pub frame: PathBuf,
178    /// When it was captured.
179    pub captured_at: printobserver_types::Timestamp,
180    /// The print's height in its plan then, in millimetres.
181    pub print_z_mm: f64,
182}
183
184/// The most checked frames one print keeps; past it the oldest are dropped.
185const MAX_CHECKED_FRAMES: usize = 512;
186
187/// The alignment verdicts of every print, what decides them, the frame each
188/// print's last check was given, and its recent checks' frames and heights.
189pub struct Alignments {
190    /// Where each print's verdict is kept.
191    directory: PathBuf,
192    /// Where each print's last check's frame is named.
193    previous_directory: PathBuf,
194    /// Where each print's recent checks' frames and heights are kept.
195    checked_directory: PathBuf,
196    /// Where each print's correction, last inconclusive reason and last
197    /// check's image are kept.
198    view_directory: PathBuf,
199    /// The camera's calibration, when one is configured.
200    calibration: Option<Arc<CameraCalibration>>,
201    /// The prints, to tell which are open.
202    prints: Arc<dyn PrintStore>,
203}
204
205impl core::fmt::Debug for Alignments {
206    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
207        formatter
208            .debug_struct("Alignments")
209            .field("directory", &self.directory)
210            .field("calibrated", &self.calibration.is_some())
211            .finish_non_exhaustive()
212    }
213}
214
215/// The directory verdicts are kept in, under a state directory.
216#[must_use]
217pub fn verdict_dir(state_dir: &Path) -> PathBuf {
218    state_dir.join("alignment")
219}
220
221/// The directory each print's last check's frame is named in, under a state
222/// directory.
223#[must_use]
224pub fn previous_check_dir(state_dir: &Path) -> PathBuf {
225    state_dir.join("previous-check")
226}
227
228/// The directory each print's recent checks' frames and heights are kept in,
229/// under a state directory.
230#[must_use]
231pub fn checked_frames_dir(state_dir: &Path) -> PathBuf {
232    state_dir.join("checked-frames")
233}
234
235/// The directory each print's correction, last inconclusive reason and last
236/// check's image are kept in, under a state directory.
237#[must_use]
238pub fn camera_view_dir(state_dir: &Path) -> PathBuf {
239    state_dir.join("camera-view")
240}
241
242impl Alignments {
243    /// The verdicts kept under one state directory.
244    ///
245    /// # Errors
246    ///
247    /// The filesystem's own error when the directory cannot be made.
248    pub fn new(
249        state_dir: &Path,
250        calibration: Option<Arc<CameraCalibration>>,
251        prints: Arc<dyn PrintStore>,
252    ) -> std::io::Result<Self> {
253        let directory = verdict_dir(state_dir);
254        std::fs::create_dir_all(&directory)?;
255        let previous_directory = previous_check_dir(state_dir);
256        std::fs::create_dir_all(&previous_directory)?;
257        let checked_directory = checked_frames_dir(state_dir);
258        std::fs::create_dir_all(&checked_directory)?;
259        let view_directory = camera_view_dir(state_dir);
260        std::fs::create_dir_all(&view_directory)?;
261        Ok(Self {
262            directory,
263            previous_directory,
264            checked_directory,
265            view_directory,
266            calibration,
267            prints,
268        })
269    }
270
271    /// Where one print's verdict is kept.
272    fn path_of(&self, print_id: PrintId) -> PathBuf {
273        self.directory.join(format!("{print_id}.json"))
274    }
275
276    /// The camera calibration in force, when one is configured.
277    #[must_use]
278    pub fn calibration(&self) -> Option<&CameraCalibration> {
279        self.calibration.as_deref()
280    }
281
282    /// Where one print's last check's frame is named.
283    fn previous_path_of(&self, print_id: PrintId) -> PathBuf {
284        self.previous_directory.join(format!("{print_id}.json"))
285    }
286
287    /// The frame one print's last check was given; nothing before its first
288    /// check, or when the record cannot be read back.
289    #[must_use]
290    pub fn previous_check(&self, print_id: PrintId) -> Option<PreviousCheck> {
291        std::fs::read(self.previous_path_of(print_id))
292            .ok()
293            .and_then(|bytes| printobserver_types::serde_json::from_slice(&bytes).ok())
294    }
295
296    /// Name the frame one print's check was given, which its next check shows
297    /// as the previous. A record the filesystem refuses for a moment is
298    /// replaced once the refusal passes ([`replace_file`]); one it goes on
299    /// refusing is said on the log and leaves the record before it standing,
300    /// so the next check shows an older frame as the previous rather than
301    /// none. No test makes the refusal last: that needs the state directory
302    /// made to refuse writes beneath a running server, which refuses the
303    /// store's own writes first. What a check makes of a record it cannot use
304    /// — an empty panel 3 — is proved by
305    /// `a_lost_previous_frame_empties_panel_3_and_the_record_goes_with_the_print`.
306    pub fn record_check(&self, print_id: PrintId, check: &PreviousCheck) {
307        let Ok(bytes) = printobserver_types::serde_json::to_vec(check) else {
308            return;
309        };
310        if let Err(error) = replace_file(&self.previous_path_of(print_id), &bytes) {
311            eprintln!(
312                "printobserver: print {print_id}: the last check's frame could not be recorded, so the next check shows an older one or none: {error}"
313            );
314        }
315    }
316
317    /// Where one print's recent checks' frames and heights are kept.
318    fn checked_path_of(&self, print_id: PrintId) -> PathBuf {
319        self.checked_directory.join(format!("{print_id}.json"))
320    }
321
322    /// One print's recent checks' frames and heights, oldest first; none
323    /// before its first check with a height, or when the record cannot be
324    /// read back.
325    #[must_use]
326    pub fn checked_frames(&self, print_id: PrintId) -> Vec<CheckedFrame> {
327        std::fs::read(self.checked_path_of(print_id))
328            .ok()
329            .and_then(|bytes| printobserver_types::serde_json::from_slice(&bytes).ok())
330            .unwrap_or_default()
331    }
332
333    /// Forget one print's checked frames, so its growth is measured only from
334    /// checks made after now: the print waited at a planned change, and a frame
335    /// from before the wait would count the wait as no growth. A record the
336    /// filesystem will not remove is said on the log and left, so a later check
337    /// measures from a frame before the wait, which says no more than that a
338    /// check could not tell.
339    pub fn restart_growth(&self, print_id: PrintId) {
340        let path = self.checked_path_of(print_id);
341        if let Err(error) = std::fs::remove_file(&path)
342            && error.kind() != std::io::ErrorKind::NotFound
343        {
344            eprintln!(
345                "printobserver: print {print_id}: its checked frames could not be forgotten after a planned change, so a later check may measure growth across the wait: {error}"
346            );
347        }
348    }
349
350    /// The frame a check at `print_z_mm` measures growth from: the newest
351    /// checked frame of the print at least `rise_mm` below it in the plan.
352    #[must_use]
353    pub fn growth_reference(
354        &self,
355        print_id: PrintId,
356        print_z_mm: f64,
357        rise_mm: f64,
358    ) -> Option<CheckedFrame> {
359        reference_in(&self.checked_frames(print_id), print_z_mm, rise_mm).cloned()
360    }
361
362    /// Keep one check's frame and height among the print's, keeping only what
363    /// a later check at `rise_mm` above some kept height can still measure
364    /// from: the newest frame at least that far below this one and every
365    /// frame after it. A height below the last kept one is a plan that went
366    /// back down, as a print of one object after another does, and starts the
367    /// record again. A record the filesystem refuses is said on the log and
368    /// leaves the one before standing, as [`record_check`](Self::record_check)
369    /// does.
370    pub fn record_checked_frame(&self, print_id: PrintId, checked: CheckedFrame, rise_mm: f64) {
371        let kept = kept_with(self.checked_frames(print_id), checked, rise_mm);
372        let Ok(bytes) = printobserver_types::serde_json::to_vec(&kept) else {
373            return;
374        };
375        if let Err(error) = replace_file(&self.checked_path_of(print_id), &bytes) {
376            eprintln!(
377                "printobserver: print {print_id}: a check's frame and height could not be recorded, so a later check measures growth from an older one or none: {error}"
378            );
379        }
380    }
381
382    /// One print's verdict as it stands.
383    #[must_use]
384    pub fn print_alignment(&self, print_id: PrintId) -> PrintAlignment {
385        if self.calibration.is_none() {
386            return PrintAlignment::Unavailable;
387        }
388        match std::fs::read(self.path_of(print_id))
389            .ok()
390            .and_then(|bytes| printobserver_types::serde_json::from_slice(&bytes).ok())
391        {
392            // A failure on the offset is what an earlier release wrote for a
393            // frame that did not find the layer, which is now inconclusive.
394            Some(PrintAlignment::Failed {
395                reason: AlignmentFailure::Offset { .. },
396            })
397            | None => PrintAlignment::Pending,
398            Some(verdict) => verdict,
399        }
400    }
401
402    /// Where one print's camera view is kept.
403    fn view_path_of(&self, print_id: PrintId) -> PathBuf {
404        self.view_directory.join(format!("{print_id}.json"))
405    }
406
407    /// One print's camera view as it stands: nothing kept before its first
408    /// judgement, or when the record cannot be read back.
409    fn view_state(&self, print_id: PrintId) -> CameraViewState {
410        std::fs::read(self.view_path_of(print_id))
411            .ok()
412            .and_then(|bytes| printobserver_types::serde_json::from_slice(&bytes).ok())
413            .unwrap_or_default()
414    }
415
416    /// Keep one print's camera view. A record the filesystem refuses is said
417    /// on the log and leaves the one before standing, as
418    /// [`record_check`](Self::record_check) does.
419    fn keep_view_state(&self, print_id: PrintId, state: &CameraViewState) {
420        let Ok(bytes) = printobserver_types::serde_json::to_vec(state) else {
421            return;
422        };
423        if let Err(error) = replace_file(&self.view_path_of(print_id), &bytes) {
424            eprintln!(
425                "printobserver: print {print_id}: its camera view could not be recorded, so a later check reads the one before: {error}"
426            );
427        }
428    }
429
430    /// Keep a verdict, and say it. A verdict the filesystem goes on refusing
431    /// ([`replace_file`]) is said on the log and leaves the one before
432    /// standing, so the next check judges again from it.
433    fn decide(&self, print_id: PrintId, verdict: &PrintAlignment) {
434        let Ok(bytes) = printobserver_types::serde_json::to_vec(verdict) else {
435            return;
436        };
437        match replace_file(&self.path_of(print_id), &bytes) {
438            Ok(()) => eprintln!(
439                "printobserver: print {print_id}: first-layer alignment {}",
440                said(verdict)
441            ),
442            Err(error) => eprintln!(
443                "printobserver: print {print_id}: first-layer alignment {} could not be recorded: {error}",
444                said(verdict)
445            ),
446        }
447    }
448
449    /// The correction in force for one print: the one its last pass took, or,
450    /// for a pass an earlier release recorded with no reference, its
451    /// correction held against the calibration's own landmarks where it
452    /// placed them. Nothing unless the print's alignment passed.
453    #[must_use]
454    pub fn correction_in_force(&self, print_id: PrintId) -> Option<ViewCorrection> {
455        let calibration = self.calibration.as_deref()?;
456        let PrintAlignment::Passed { correction_px, .. } = self.print_alignment(print_id) else {
457            return None;
458        };
459        Some(self.view_state(print_id).correction.unwrap_or_else(|| {
460            ViewCorrection::translation(
461                correction_px,
462                calibration
463                    .landmarks
464                    .iter()
465                    .map(|landmark| ReferenceLandmark {
466                        name: landmark.name.clone(),
467                        offset_px: [0.0, 0.0],
468                        score: 1.0,
469                    })
470                    .collect(),
471            )
472        }))
473    }
474
475    /// Why the print's alignment was last left pending, when the frame judged
476    /// last was inconclusive.
477    #[must_use]
478    pub fn inconclusive(&self, print_id: PrintId) -> Option<InconclusiveReason> {
479        self.view_state(print_id).inconclusive
480    }
481
482    /// The image the print's last check was shown, and when its frame was
483    /// captured; nothing before its first check.
484    #[must_use]
485    pub fn last_check_image(&self, print_id: PrintId) -> Option<LastCheckImage> {
486        self.view_state(print_id).last_check_image
487    }
488
489    /// Keep the image one check of a print was shown, and answer the change
490    /// notice owed for it: on the print's first check image, and whenever its
491    /// kind or its fallback's code differs from the last one kept.
492    #[must_use]
493    pub fn note_check_image(
494        &self,
495        print_id: PrintId,
496        shown: LastCheckImage,
497        frame_sha256: &str,
498    ) -> Option<EventBody> {
499        let mut state = self.view_state(print_id);
500        let code = |image: &LastCheckImage| image.fallback.as_ref().map(|fallback| fallback.code);
501        let changed = state
502            .last_check_image
503            .as_ref()
504            .is_none_or(|last| last.kind != shown.kind || code(last) != code(&shown));
505        let notice = changed.then(|| {
506            body_of(&crate::judgements::CheckImageChangedPayload {
507                kind: shown.kind,
508                fallback: shown.fallback.clone(),
509                frame_sha256: frame_sha256.to_owned(),
510            })
511        });
512        state.last_check_image = Some(shown);
513        self.keep_view_state(print_id, &state);
514        notice.flatten()
515    }
516
517    /// Judge one frame of a print — its view always, and its first-layer
518    /// alignment when `judging` asks and the alignment is due — keeping what
519    /// the judgement decided and answering it with the records to append.
520    ///
521    /// The alignment is due on a frame of the configured camera once the
522    /// plan has passed the print's first object layer: while it is pending,
523    /// for [`AlignmentJudging::WhilePending`], and whatever it stands at for
524    /// [`AlignmentJudging::Afresh`], a latched failure included. A frame whose
525    /// view shows the camera moved again since the correction in force was
526    /// taken sets the alignment back to pending, and is not judged for it: a
527    /// later check's frame takes the fresh correction.
528    ///
529    /// Nothing is judged without a calibration, and a frame that is no JPEG is
530    /// answered as such, with nothing recorded.
531    #[must_use]
532    pub fn judge(&self, print_id: PrintId, judging: &Judging<'_>) -> Judged {
533        let Some(calibration) = self.calibration.as_deref() else {
534            return Judged::unjudged(PrintAlignment::Unavailable);
535        };
536        let mut judged = Judged::unjudged(self.print_alignment(print_id));
537        let mut state = self.view_state(print_id);
538        let in_force = self.correction_in_force(print_id);
539        let sha = judging.frame_sha256;
540        let landmarks = match landmarks_in_frame(
541            calibration,
542            judging.frame_jpeg,
543            judging.camera_snapshot_url,
544        ) {
545            Ok(landmarks) => landmarks,
546            Err(error @ ComposeError::FrameMismatch { .. }) => {
547                let reason = error.to_string();
548                judged
549                    .records
550                    .extend(body_of(&crate::judgements::CameraViewJudgedPayload {
551                        frame_sha256: sha.to_owned(),
552                        outcome: ViewOutcome::FrameMismatch,
553                        view_correction: in_force.clone(),
554                        reason: Some(reason.clone()),
555                    }));
556                if Self::alignment_due(&judged.alignment, judging).is_some() {
557                    let failure = failure_of(&error, calibration);
558                    judged.records.extend(body_of(
559                        &crate::judgements::FirstLayerAlignmentJudgedPayload {
560                            verdict: crate::judgements::AlignmentJudgedVerdict::Failed,
561                            offset_px: None,
562                            correction_px: None,
563                            match_strength: None,
564                            reason: failure_sentence(&failure),
565                            frame_sha256: sha.to_owned(),
566                            view_correction: in_force.clone(),
567                        },
568                    ));
569                    judged.alignment = PrintAlignment::Failed { reason: failure };
570                    self.decide(print_id, &judged.alignment);
571                    state.correction = None;
572                    state.inconclusive = None;
573                    self.keep_view_state(print_id, &state);
574                }
575                judged.correction = in_force.filter(|_| judged.alignment.passed());
576                judged.mismatch = Some(reason);
577                return judged;
578            }
579            Err(error) => {
580                judged.unreadable = Some(error.to_string());
581                return judged;
582            }
583        };
584        // A plan laying no object leaves nothing a frame could be judged
585        // against: the verdict file says so, and records nothing.
586        if judging.alignment != AlignmentJudging::Never
587            && judged.alignment == PrintAlignment::Pending
588            && judging
589                .plan
590                .is_some_and(|plan| plan.index.first_object_layer().is_none())
591        {
592            judged.alignment = PrintAlignment::Unavailable;
593            self.decide(print_id, &judged.alignment);
594        }
595        let due = Self::alignment_due(&judged.alignment, judging);
596        let view = match (due, &judged.alignment) {
597            (None, PrintAlignment::Passed { .. }) => {
598                let view = judge_found(calibration, landmarks, in_force.as_ref());
599                if view.outcome == ViewOutcome::ViewRefitRejected {
600                    judged.alignment = PrintAlignment::Pending;
601                    self.decide(print_id, &judged.alignment);
602                    state.correction = None;
603                    state.inconclusive = None;
604                    self.keep_view_state(print_id, &state);
605                    judged.rejected.clone_from(&view.reason);
606                } else {
607                    judged.correction.clone_from(&in_force);
608                }
609                judged
610                    .records
611                    .extend(view_record(sha, &view, in_force.clone()));
612                view
613            }
614            (Some(first), _) => self.judge_alignment(
615                print_id,
616                calibration,
617                landmarks,
618                &first,
619                judging,
620                in_force,
621                &mut state,
622                &mut judged,
623            ),
624            (None, _) => {
625                let view = judge_found(calibration, landmarks, None);
626                judged.records.extend(view_record(sha, &view, None));
627                view
628            }
629        };
630        judged.inconclusive = state.inconclusive;
631        judged.view = Some((view.outcome, view.reason));
632        judged
633    }
634
635    /// Judge the first layer on a frame it is due on, and the frame's view
636    /// against what that leaves in force.
637    #[expect(
638        clippy::too_many_arguments,
639        reason = "the one judgement's inputs and the two records it updates"
640    )]
641    fn judge_alignment(
642        &self,
643        print_id: PrintId,
644        calibration: &CameraCalibration,
645        landmarks: Vec<printobserver_panels::FoundLandmark>,
646        first: &DueAlignment,
647        judging: &Judging<'_>,
648        in_force: Option<ViewCorrection>,
649        state: &mut CameraViewState,
650        judged: &mut Judged,
651    ) -> ViewJudgement {
652        let sha = judging.frame_sha256;
653        let uncorrected = judge_found(calibration, landmarks.clone(), None);
654        let judgement = judge_first_layer(&FirstLayerInputs {
655            alignment: AlignmentInputs {
656                frame_jpeg: judging.frame_jpeg,
657                camera_snapshot_url: judging.camera_snapshot_url,
658                first_layer: &first.first_layer,
659                print_z_mm: first.print_z_mm,
660                calibration,
661            },
662            nozzle_xy_mm: first.nozzle_xy_mm,
663        });
664        let Ok(judgement) = judgement else {
665            // The frame was decoded and held to the calibration above, so no
666            // refusal is reached here; one that is leaves the alignment as it
667            // stood, judged again on the next check's frame.
668            judged.records.extend(view_record(sha, &uncorrected, None));
669            return uncorrected;
670        };
671        let found = judgement.found;
672        let (verdict, correction_px, reason) = match judgement.verdict {
673            FirstLayerVerdict::Passed => (
674                crate::judgements::AlignmentJudgedVerdict::Passed,
675                found.map(|found| {
676                    printobserver_panels::alignment::correction_shift(
677                        &found,
678                        &first.first_layer,
679                        first.print_z_mm,
680                    )
681                }),
682                "clearly_found".to_owned(),
683            ),
684            FirstLayerVerdict::Inconclusive(why) => (
685                crate::judgements::AlignmentJudgedVerdict::Inconclusive,
686                None,
687                why.as_str().to_owned(),
688            ),
689        };
690        judged.records.extend(body_of(
691            &crate::judgements::FirstLayerAlignmentJudgedPayload {
692                verdict,
693                offset_px: found.map(|found| found.offset_px),
694                correction_px,
695                match_strength: found.map(|found| found.match_strength),
696                reason,
697                frame_sha256: sha.to_owned(),
698                view_correction: in_force,
699            },
700        ));
701        match (judgement.verdict, found) {
702            (FirstLayerVerdict::Passed, Some(found)) => {
703                let shift = printobserver_panels::alignment::correction_shift(
704                    &found,
705                    &first.first_layer,
706                    first.print_z_mm,
707                );
708                eprintln!(
709                    "printobserver: print {print_id}: the first layer was found shifted [{:.0}, {:.0}] px at Z {:.2}, at a contrast of {:.1}; corrected by [{:.0}, {:.0}] px",
710                    found.shift_px[0],
711                    found.shift_px[1],
712                    first.print_z_mm,
713                    found.match_strength,
714                    shift[0],
715                    shift[1]
716                );
717                let correction = ViewCorrection::translation(shift, uncorrected.agreeing());
718                judged.alignment = PrintAlignment::Passed {
719                    offset_px: found.offset_px,
720                    correction_px: shift,
721                };
722                self.decide(print_id, &judged.alignment);
723                state.correction = Some(correction.clone());
724                state.inconclusive = None;
725                self.keep_view_state(print_id, state);
726                if uncorrected.moved(calibration) {
727                    judged
728                        .records
729                        .extend(body_of(&crate::judgements::CameraViewRefitPayload {
730                            frame_sha256: sha.to_owned(),
731                            view_correction: correction.clone(),
732                        }));
733                }
734                let view = judge_found(calibration, landmarks, Some(&correction));
735                judged
736                    .records
737                    .extend(view_record(sha, &view, Some(correction.clone())));
738                judged.correction = Some(correction);
739                view
740            }
741            (FirstLayerVerdict::Inconclusive(why), _) => {
742                // Written even when it was pending already: a reader of the
743                // verdict file learns a frame was judged.
744                judged.alignment = PrintAlignment::Pending;
745                self.decide(print_id, &judged.alignment);
746                state.correction = None;
747                state.inconclusive = Some(why);
748                self.keep_view_state(print_id, state);
749                judged.records.extend(view_record(sha, &uncorrected, None));
750                uncorrected
751            }
752            (FirstLayerVerdict::Passed, None) => {
753                judged.records.extend(view_record(sha, &uncorrected, None));
754                uncorrected
755            }
756        }
757    }
758
759    /// The first layer a frame's judgement scores, when the alignment is due
760    /// on it; nothing otherwise.
761    fn alignment_due(alignment: &PrintAlignment, judging: &Judging<'_>) -> Option<DueAlignment> {
762        let asked = match judging.alignment {
763            AlignmentJudging::Never => false,
764            AlignmentJudging::WhilePending => *alignment == PrintAlignment::Pending,
765            AlignmentJudging::Afresh => true,
766        };
767        if !asked {
768            return None;
769        }
770        let plan = judging.plan?;
771        let index = &plan.index;
772        let position = plan.file_position_bytes;
773        let (first, ends) = index.first_object_layer()?;
774        if position <= ends {
775            return None;
776        }
777        Some(DueAlignment {
778            first_layer: index.layer_toolpath(first).ok()?,
779            print_z_mm: index
780                .layer_at(position)
781                .and_then(|layer| index.layer_z_mm(layer))?,
782            nozzle_xy_mm: index.planned_head_at(position).ok().flatten(),
783        })
784    }
785
786    /// Delete the verdict, the last check's record, the checked frames and the
787    /// camera view of every print that is not open.
788    ///
789    /// An open print's record still being written — the `.json.part` beside it
790    /// that [`replace_file`] renames over it — is its own, and kept: the watch
791    /// sweeps after every read, so a sweep removing it between the write and the
792    /// rename lost that record, and the print's next check showed no previous
793    /// frame.
794    ///
795    /// A store that cannot list the open prints, a directory that cannot be
796    /// listed and a file that cannot be removed each leave a verdict behind,
797    /// which the next read's sweep tries again. No test makes either refuse,
798    /// since that needs a store or filesystem made to fail beneath a running
799    /// server; the `aligning` journeys prove the sweep removes a closed
800    /// print's verdict and keeps an open one's, after a close and at start.
801    pub async fn sweep(&self) {
802        let Ok(open) = self.prints.open_prints().await else {
803            return;
804        };
805        let open: Vec<String> = open
806            .iter()
807            .flat_map(|print| {
808                [
809                    format!("{}.json", print.id),
810                    format!("{}.json.part", print.id),
811                ]
812            })
813            .collect();
814        for directory in [
815            &self.directory,
816            &self.previous_directory,
817            &self.checked_directory,
818            &self.view_directory,
819        ] {
820            let Ok(entries) = std::fs::read_dir(directory) else {
821                continue;
822            };
823            for entry in entries.flatten() {
824                let name = entry.file_name();
825                if !open.iter().any(|kept| name.to_str() == Some(kept.as_str())) {
826                    let _ = std::fs::remove_file(entry.path());
827                }
828            }
829        }
830    }
831}
832
833/// The newest of a print's checked frames, oldest first, at least `rise_mm`
834/// below `print_z_mm` in the plan.
835fn reference_in(kept: &[CheckedFrame], print_z_mm: f64, rise_mm: f64) -> Option<&CheckedFrame> {
836    kept.iter()
837        .rev()
838        .find(|checked| checked.print_z_mm <= print_z_mm - rise_mm)
839}
840
841/// A print's checked frames once `checked` is kept among them: the newest
842/// earlier frame at least `rise_mm` below it and every frame after that, then
843/// it, at most [`MAX_CHECKED_FRAMES`] of them, the oldest dropped first; or it
844/// alone when it is below the last kept, a plan gone back down.
845fn kept_with(
846    mut kept: Vec<CheckedFrame>,
847    checked: CheckedFrame,
848    rise_mm: f64,
849) -> Vec<CheckedFrame> {
850    if kept
851        .last()
852        .is_some_and(|last| checked.print_z_mm < last.print_z_mm)
853    {
854        kept.clear();
855    }
856    if let Some(reference) = kept
857        .iter()
858        .rposition(|earlier| earlier.print_z_mm <= checked.print_z_mm - rise_mm)
859    {
860        kept.drain(..reference);
861    }
862    kept.push(checked);
863    if kept.len() > MAX_CHECKED_FRAMES {
864        kept.drain(..kept.len() - MAX_CHECKED_FRAMES);
865    }
866    kept
867}
868
869/// How many times one file's replacement is attempted while the filesystem
870/// refuses it for a moment, and the pause between two attempts: half a second
871/// in all, on a check that is otherwise waiting on no one.
872const REPLACE_ATTEMPTS: u32 = 20;
873const REPLACE_PAUSE: Duration = Duration::from_millis(25);
874
875/// Put `bytes` at `path` whole: written beside it, then renamed over it, so a
876/// reader finds the old file or the new one and never part of either.
877///
878/// Windows refuses to replace a file another process holds open without
879/// letting it be deleted — a scanner reading what was just written does — and
880/// that refusal ends when the other process closes it. So a refusal of that
881/// kind is attempted again, up to [`REPLACE_ATTEMPTS`] times; any other, or
882/// one that outlasts them, is answered, with the file beside it removed.
883///
884/// # Errors
885///
886/// The filesystem's own error for the last attempt.
887fn replace_file(path: &Path, bytes: &[u8]) -> std::io::Result<()> {
888    let held = path.with_extension("json.part");
889    attempt_while_refused(
890        || {
891            std::fs::write(&held, bytes)?;
892            std::fs::rename(&held, path)
893        },
894        refused_for_a_moment,
895        REPLACE_ATTEMPTS,
896        REPLACE_PAUSE,
897    )
898    .inspect_err(|_| {
899        let _ = std::fs::remove_file(&held);
900    })
901}
902
903/// Run `attempt` until it succeeds, fails with an error `refused` does not
904/// call momentary, or has been run `attempts` times, pausing between two.
905fn attempt_while_refused(
906    mut attempt: impl FnMut() -> std::io::Result<()>,
907    refused: impl Fn(&std::io::Error) -> bool,
908    attempts: u32,
909    pause: Duration,
910) -> std::io::Result<()> {
911    let mut made = 1;
912    loop {
913        match attempt() {
914            Err(error) if made < attempts && refused(&error) => {
915                std::thread::sleep(pause);
916                made += 1;
917            }
918            answered => return answered,
919        }
920    }
921}
922
923/// Whether Windows refused a replacement only because another handle has the
924/// file open: `ERROR_ACCESS_DENIED` (5) or `ERROR_SHARING_VIOLATION` (32).
925#[cfg(windows)]
926fn refused_for_a_moment(error: &std::io::Error) -> bool {
927    matches!(error.raw_os_error(), Some(5 | 32))
928}
929
930/// Elsewhere a rename replaces a file whoever has it open, so no refusal is
931/// momentary.
932#[cfg(not(windows))]
933fn refused_for_a_moment(_error: &std::io::Error) -> bool {
934    false
935}
936
937/// A frame size as the refusal spells it, `<w>x<h>`.
938fn size_of(text: &str) -> [u32; 2] {
939    let mut parts = text.split('x').map(|part| part.parse().unwrap_or(0));
940    [parts.next().unwrap_or(0), parts.next().unwrap_or(0)]
941}
942
943/// A verdict as the log says it.
944fn said(verdict: &PrintAlignment) -> String {
945    match verdict {
946        PrintAlignment::Unavailable => "unavailable: the G-code lays no object".to_owned(),
947        PrintAlignment::Pending => "pending".to_owned(),
948        PrintAlignment::Passed {
949            offset_px,
950            correction_px,
951        } => format!(
952            "passed, offset {offset_px:.1} px, corrected by [{:.0}, {:.0}] px",
953            correction_px[0], correction_px[1]
954        ),
955        PrintAlignment::Failed {
956            reason: AlignmentFailure::Offset { offset_px },
957        } => format!("failed, offset {offset_px:.1} px"),
958        PrintAlignment::Failed {
959            reason: AlignmentFailure::Resolution { expected, got },
960        } => format!(
961            "failed: the camera's frames are {}x{}, the calibration's {}x{}",
962            got[0], got[1], expected[0], expected[1]
963        ),
964        PrintAlignment::Failed {
965            reason: AlignmentFailure::Stream,
966        } => "failed: the camera is not the stream the calibration was fitted on".to_owned(),
967    }
968}
969
970/// One print's camera view as it is kept.
971#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
972#[serde(crate = "printobserver_types::serde")]
973struct CameraViewState {
974    /// The correction the print's last pass took, with its reference.
975    #[serde(default)]
976    correction: Option<ViewCorrection>,
977    /// Why the frame judged last was inconclusive, while the alignment is
978    /// pending.
979    #[serde(default)]
980    inconclusive: Option<InconclusiveReason>,
981    /// The image the print's last check was shown.
982    #[serde(default)]
983    last_check_image: Option<LastCheckImage>,
984}
985
986/// The image a print's last check was shown, and when its frame was captured.
987#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
988#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
989#[schemars(crate = "printobserver_types::schemars")]
990pub struct LastCheckImage {
991    /// When the check's frame was captured.
992    pub at: Timestamp,
993    /// Which image the check was shown.
994    pub kind: ImageKind,
995    /// Why it was the whole frame; null for the three-panel image.
996    pub fallback: Option<ImageFallback>,
997}
998
999impl Sample for LastCheckImage {
1000    fn sample_full() -> Self {
1001        Self {
1002            at: Timestamp::sample_full(),
1003            kind: ImageKind::WholeFrame,
1004            fallback: Some(ImageFallback::sample_full()),
1005        }
1006    }
1007
1008    fn sample_minimal() -> Self {
1009        Self {
1010            at: Timestamp::sample_full(),
1011            kind: ImageKind::ThreePanel,
1012            fallback: None,
1013        }
1014    }
1015}
1016
1017/// Whether a judgement of a frame judges the print's first-layer alignment.
1018#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1019pub enum AlignmentJudging {
1020    /// Never: a look, or a frame not the configured camera's own.
1021    Never,
1022    /// While the alignment is pending: every scheduled check's frame.
1023    WhilePending,
1024    /// Whatever it stands at, a latched failure included: the operator's
1025    /// recheck of the camera.
1026    Afresh,
1027}
1028
1029/// One frame to judge.
1030#[derive(Debug, Clone, Copy)]
1031pub struct Judging<'a> {
1032    /// The frame's bytes.
1033    pub frame_jpeg: &'a [u8],
1034    /// The stored frame's SHA-256, which every record names.
1035    pub frame_sha256: &'a str,
1036    /// The stream it is of.
1037    pub camera_snapshot_url: &'a str,
1038    /// Where the print stood in its plan as it was taken.
1039    pub plan: Option<&'a PlanPosition>,
1040    /// Whether the first-layer alignment is judged.
1041    pub alignment: AlignmentJudging,
1042}
1043
1044/// What one judgement of a frame decided, and the records it owes.
1045#[derive(Debug, Clone, PartialEq)]
1046pub struct Judged {
1047    /// The records to append, in order, each naming the frame.
1048    pub records: Vec<EventBody>,
1049    /// The print's alignment once judged.
1050    pub alignment: PrintAlignment,
1051    /// The correction the frame may be drawn through, when the alignment
1052    /// passed and the view allows it.
1053    pub correction: Option<ViewCorrection>,
1054    /// The view's outcome and its refusal's reason; nothing when the frame was
1055    /// not judged for its view.
1056    pub view: Option<(ViewOutcome, Option<String>)>,
1057    /// Why the correction in force was given up on this frame: the camera
1058    /// moved again.
1059    pub rejected: Option<String>,
1060    /// Why the frame is not the calibration's size or stream.
1061    pub mismatch: Option<String>,
1062    /// Why the frame could not be read at all.
1063    pub unreadable: Option<String>,
1064    /// Why the alignment was left pending, when the frame judged last was
1065    /// inconclusive.
1066    pub inconclusive: Option<InconclusiveReason>,
1067}
1068
1069impl Judged {
1070    /// Nothing that could be judged of a frame — no calibration, or no stream
1071    /// it was fitted on — the alignment standing as it is, and the one record
1072    /// the frame is kept with.
1073    #[must_use]
1074    pub fn nothing_to_judge(alignment: PrintAlignment, kept_with: Option<EventBody>) -> Self {
1075        Self {
1076            records: kept_with.into_iter().collect(),
1077            ..Self::unjudged(alignment)
1078        }
1079    }
1080
1081    /// Nothing judged, the alignment standing as it is.
1082    const fn unjudged(alignment: PrintAlignment) -> Self {
1083        Self {
1084            records: Vec::new(),
1085            alignment,
1086            correction: None,
1087            view: None,
1088            rejected: None,
1089            mismatch: None,
1090            unreadable: None,
1091            inconclusive: None,
1092        }
1093    }
1094}
1095
1096impl PrintAlignment {
1097    /// Whether it passed.
1098    #[must_use]
1099    pub const fn passed(&self) -> bool {
1100        matches!(self, Self::Passed { .. })
1101    }
1102}
1103
1104/// What a first-layer judgement due on a frame scores.
1105struct DueAlignment {
1106    /// The first object layer's toolpath.
1107    first_layer: printobserver_core::LayerToolpath,
1108    /// The print's height in its plan as the frame was taken.
1109    print_z_mm: f64,
1110    /// Where the plan has the nozzle then.
1111    nozzle_xy_mm: Option<[f64; 2]>,
1112}
1113
1114/// One payload as the body appended for it; nothing for one that will not
1115/// render, which no declared payload is.
1116fn body_of<P: EventPayload>(payload: &P) -> Option<EventBody> {
1117    EventBody::of(payload).ok()
1118}
1119
1120/// The record of one view judgement, its reason the fallback it leads to: a
1121/// refit view, its landmarks moved from the calibration, is drawn on no more
1122/// than a refused one.
1123fn view_record(
1124    frame_sha256: &str,
1125    view: &ViewJudgement,
1126    view_correction: Option<ViewCorrection>,
1127) -> Option<EventBody> {
1128    let reason = if view.outcome == ViewOutcome::Refit {
1129        Some(crate::check_images::CALIBRATION_STALE.to_owned())
1130    } else {
1131        view.reason.clone()
1132    };
1133    body_of(&crate::judgements::CameraViewJudgedPayload {
1134        frame_sha256: frame_sha256.to_owned(),
1135        outcome: view.outcome,
1136        view_correction,
1137        reason,
1138    })
1139}
1140
1141/// The failure a frame refused for its size or stream latches.
1142fn failure_of(error: &ComposeError, calibration: &CameraCalibration) -> AlignmentFailure {
1143    match error {
1144        ComposeError::FrameMismatch {
1145            field: FrameField::Resolution,
1146            got,
1147            ..
1148        } => AlignmentFailure::Resolution {
1149            expected: calibration.image_size_px,
1150            got: size_of(got),
1151        },
1152        _ => AlignmentFailure::Stream,
1153    }
1154}
1155
1156/// A failure in the sentence its record and its fallback give it in.
1157#[must_use]
1158pub fn failure_sentence(failure: &AlignmentFailure) -> String {
1159    match failure {
1160        AlignmentFailure::Offset { offset_px } => format!(
1161            "the printed first layer lies {offset_px:.1} px from where the calibration projects it"
1162        ),
1163        AlignmentFailure::Resolution { expected, got } => format!(
1164            "the camera's frames are {}x{} and the calibration's {}x{}",
1165            got[0], got[1], expected[0], expected[1]
1166        ),
1167        AlignmentFailure::Stream => {
1168            "the camera is not the stream the calibration was fitted on".to_owned()
1169        }
1170    }
1171}
1172
1173#[cfg(test)]
1174mod tests {
1175    use super::{CheckedFrame, MAX_CHECKED_FRAMES, attempt_while_refused, kept_with, reference_in};
1176    use std::cell::Cell;
1177    use std::io::{Error, ErrorKind};
1178    use std::time::Duration;
1179
1180    /// An attempt that is refused `refusals` times and then succeeds, counting
1181    /// how often it was made.
1182    fn refused_then_done(refusals: u32, made: &Cell<u32>) -> impl FnMut() -> std::io::Result<()> {
1183        move || {
1184            made.set(made.get() + 1);
1185            if made.get() <= refusals {
1186                Err(Error::from(ErrorKind::PermissionDenied))
1187            } else {
1188                Ok(())
1189            }
1190        }
1191    }
1192
1193    #[test]
1194    fn a_momentary_refusal_is_attempted_again_until_it_passes() {
1195        let made = Cell::new(0);
1196        let answered =
1197            attempt_while_refused(refused_then_done(2, &made), |_| true, 5, Duration::ZERO);
1198        assert!(answered.is_ok(), "{answered:?}");
1199        assert_eq!(made.get(), 3);
1200    }
1201
1202    #[test]
1203    fn a_refusal_that_outlasts_every_attempt_is_answered() {
1204        let made = Cell::new(0);
1205        let answered =
1206            attempt_while_refused(refused_then_done(9, &made), |_| true, 4, Duration::ZERO);
1207        assert_eq!(
1208            answered.map_err(|error| error.kind()),
1209            Err(ErrorKind::PermissionDenied)
1210        );
1211        assert_eq!(made.get(), 4);
1212    }
1213
1214    #[test]
1215    fn a_refusal_that_is_not_momentary_is_answered_at_once() {
1216        let made = Cell::new(0);
1217        let answered =
1218            attempt_while_refused(refused_then_done(9, &made), |_| false, 4, Duration::ZERO);
1219        assert!(answered.is_err());
1220        assert_eq!(made.get(), 1);
1221    }
1222
1223    /// The refusal the retry answers, made the way Windows makes it: the
1224    /// record held open by another handle that does not allow deleting it,
1225    /// and let go a moment later.
1226    #[cfg(windows)]
1227    #[test]
1228    fn a_record_held_open_by_another_handle_is_replaced_once_it_is_let_go() {
1229        use std::os::windows::fs::OpenOptionsExt;
1230        let directory = tempfile::TempDir::new().expect("a directory");
1231        let path = directory.path().join("record.json");
1232        std::fs::write(&path, b"before").expect("a record");
1233        let held = std::fs::OpenOptions::new()
1234            .read(true)
1235            .share_mode(0)
1236            .open(&path)
1237            .expect("the record held");
1238        let release = std::thread::spawn(move || {
1239            std::thread::sleep(Duration::from_millis(150));
1240            drop(held);
1241        });
1242        super::replace_file(&path, b"after").expect("the record replaced");
1243        release.join().expect("the handle let go");
1244        assert_eq!(std::fs::read(&path).expect("the record"), b"after");
1245        assert!(!path.with_extension("json.part").exists());
1246    }
1247
1248    #[cfg(windows)]
1249    #[test]
1250    fn only_a_held_file_is_a_momentary_refusal_on_windows() {
1251        assert!(super::refused_for_a_moment(&Error::from_raw_os_error(5)));
1252        assert!(super::refused_for_a_moment(&Error::from_raw_os_error(32)));
1253        assert!(!super::refused_for_a_moment(&Error::from_raw_os_error(2)));
1254    }
1255
1256    /// A checked frame at `z` mm, captured `second` seconds into a print.
1257    fn at(second: i64, z: f64) -> CheckedFrame {
1258        CheckedFrame {
1259            frame: format!("frame-{second}.jpg").into(),
1260            captured_at: printobserver_types::Timestamp::from_unix_seconds(1_791_489_600 + second)
1261                .expect("a time"),
1262            print_z_mm: z,
1263        }
1264    }
1265
1266    /// The heights of checked frames, in their order.
1267    fn heights(kept: &[CheckedFrame]) -> Vec<f64> {
1268        kept.iter().map(|checked| checked.print_z_mm).collect()
1269    }
1270
1271    /// Once a print carries on from a planned change, its growth is measured
1272    /// only from frames checked after: one from before the wait, however far
1273    /// below, is no longer a reference, and the first checked after it is.
1274    #[test]
1275    fn after_a_planned_change_growth_is_measured_from_frames_after_it() {
1276        let state = tempfile::TempDir::new().expect("a state directory");
1277        let store =
1278            printobserver_store_sqlite::MemoryStore::new(state.path()).expect("an in-memory store");
1279        let alignments = super::Alignments::new(state.path(), None, std::sync::Arc::new(store))
1280            .expect("the verdicts' directories");
1281        let print_id = printobserver_types::PrintId::new();
1282        for (second, z) in [(0, 0.2), (60, 0.6)] {
1283            alignments.record_checked_frame(print_id, at(second, z), 0.4);
1284        }
1285        let before = alignments.growth_reference(print_id, 1.0, 0.4);
1286        assert_eq!(before.map(|checked| checked.print_z_mm), Some(0.6));
1287
1288        alignments.restart_growth(print_id);
1289        assert_eq!(alignments.growth_reference(print_id, 1.0, 0.4), None);
1290        alignments.record_checked_frame(print_id, at(3_000, 0.8), 0.4);
1291        alignments.record_checked_frame(print_id, at(3_120, 1.4), 0.4);
1292        let after = alignments.growth_reference(print_id, 1.4, 0.4);
1293        assert_eq!(
1294            after.map(|checked| checked.captured_at),
1295            Some(at(3_000, 0.8).captured_at)
1296        );
1297        // A second change with nothing checked since forgets nothing more.
1298        alignments.restart_growth(print_id);
1299        alignments.restart_growth(print_id);
1300        assert!(alignments.checked_frames(print_id).is_empty());
1301    }
1302
1303    #[test]
1304    fn a_check_measures_from_the_newest_frame_far_enough_below_it() {
1305        let kept = [at(0, 0.2), at(60, 0.8), at(120, 2.0), at(180, 2.6)];
1306        assert_eq!(
1307            reference_in(&kept, 5.8, 3.0).map(|checked| checked.print_z_mm),
1308            Some(2.6)
1309        );
1310        assert_eq!(
1311            reference_in(&kept, 3.5, 3.0).map(|checked| checked.print_z_mm),
1312            Some(0.2)
1313        );
1314        assert_eq!(reference_in(&kept, 3.1, 3.0), None, "none is 3 mm below");
1315    }
1316
1317    #[test]
1318    fn only_what_a_later_check_can_measure_from_is_kept() {
1319        let mut kept = Vec::new();
1320        for (second, z) in [(0, 0.2), (60, 0.8), (120, 2.0), (180, 3.4), (240, 4.0)] {
1321            kept = kept_with(kept, at(second, z), 3.0);
1322        }
1323        assert_eq!(
1324            heights(&kept),
1325            [0.8, 2.0, 3.4, 4.0],
1326            "0.2 is below 0.8, which is itself 3 mm below 4.0, so no later check needs it"
1327        );
1328        assert_eq!(
1329            heights(&kept_with(kept, at(300, 1.0), 3.0)),
1330            [1.0],
1331            "a plan gone back down starts the record again"
1332        );
1333    }
1334
1335    #[test]
1336    fn the_oldest_checked_frames_go_past_the_most_kept() {
1337        let mut kept = Vec::new();
1338        for second in 0..=i64::try_from(MAX_CHECKED_FRAMES).expect("a count") {
1339            kept = kept_with(kept, at(second, 5.0), 3.0);
1340        }
1341        assert_eq!(kept.len(), MAX_CHECKED_FRAMES);
1342        assert_eq!(kept[0].captured_at, at(1, 5.0).captured_at);
1343    }
1344}