Skip to main content

printobserver_core/
scoring.rs

1//! Whether the failure detector is scoring the active print.
2//!
3//! This system never receives the detector's per-frame scores. Its health
4//! check ([`crate::DetectorProbe`]) says whether the detector's service
5//! answers, and its failure alerts arrive by webhook — and neither says that
6//! the detector is looking at this print at all. What does is the detector's
7//! own record of the printer's live prediction: the print it is watching, its
8//! latest snapshot and its latest score. A [`ScoringProbe`] the server supplies
9//! reads that record once per observation interval, at the start of every
10//! round of periodic observations.
11//!
12//! # Scoring evidence
13//!
14//! The record carries no instant for its prediction, and a score of zero means
15//! both "no score yet" and "scored, nothing flagged", so a single read proves
16//! nothing. The evidence is a change: the detector is scoring the active print
17//! when the print its record names is that print, and its snapshot or its
18//! score moved between two of this server's reads within the last
19//! [`EVIDENCE_INTERVALS`] observation intervals — both reads inside that
20//! window, so a read after reads failed for longer is compared with nothing
21//! and begins anew. A read naming another print,
22//! or an earlier one, is evidence that it is not, and ends any evidence held.
23//! A read that fails is recorded as a port failure against each observation
24//! the round writes, and leaves the evidence standing until it is older than
25//! those intervals.
26//!
27//! The status names it flagged once a failure alert of the detector's own has
28//! arrived for the print — noted as the alert is received, and read back out
29//! of the print's history at each read, so a server started again during the
30//! print still says so. A history that cannot be read takes nothing from that
31//! round's read, and is recorded as the read failing.
32//!
33//! # Which print the record names
34//!
35//! By the provider's own identifier when the open print carries one. Otherwise
36//! by its file and its start, held tighter than an alert's: the start the record
37//! names must lie within [`JOB_IDENTITY_TOLERANCE_S`] of the earliest start
38//! this server has sighted for the print's job, on either side.
39//!
40//! The earliest sighting, not the start the print records now, because a
41//! resume moves the recorded start later by the length of the pause — the
42//! printer takes the pause back out of the job's running time — while the
43//! provider keeps the job's own start. The earliest sighting was taken before
44//! any pause this server watched, so it stays at the job's own start; an
45//! earlier job of the same file began long before it, which an alert's rule
46//! (an earlier start is no objection) could not tell apart. A print this
47//! server first sighted only after a pause is matched by nothing until an
48//! alert names its provider identifier: its status then reads no scoring
49//! rather than another print's. Nor is a print matched with either start
50//! missing: a file name alone names every job of that file.
51
52use std::collections::{BTreeMap, BTreeSet};
53use std::time::Duration;
54
55use printobserver_printer_api::BoxFuture;
56use printobserver_types::{EventKind, PrintId, Timestamp};
57use printobserver_vision_api::ProviderPrint;
58
59use crate::clock::seconds_between;
60use crate::error::CoreError;
61use crate::listing::JOB_IDENTITY_TOLERANCE_S;
62use crate::records::PrintRecord;
63use crate::store::HistoryQuery;
64use crate::supervisor::Supervisor;
65use crate::watch::ScoringVerdict;
66
67/// How many observation intervals scoring evidence stands for.
68pub const EVIDENCE_INTERVALS: u32 = 2;
69
70/// What reads the failure detector's own record of the printer's live
71/// prediction for the status.
72pub trait ScoringProbe: Send + Sync {
73    /// Read the record once.
74    fn read_scoring(&self) -> BoxFuture<'_, ScoringRead>;
75
76    /// The kind the detector's own failure alerts are written down under, so
77    /// a print's history says whether one has arrived for it.
78    fn alert_kind(&self) -> EventKind;
79}
80
81/// What one read of the detector's record answered.
82#[derive(Debug, Clone, PartialEq, Eq)]
83pub enum ScoringRead {
84    /// No read was made, and why: the server cannot yet say which record to
85    /// read.
86    NotRead(String),
87    /// The read failed, in the port's own words.
88    Failed(String),
89    /// What the record says.
90    Read(ScoringReading),
91}
92
93/// The detector's record, as far as the status needs it: nothing else of the
94/// answer is kept.
95#[derive(Debug, Clone, PartialEq, Eq)]
96pub struct ScoringReading {
97    /// The print the detector says it is watching, when it names one.
98    pub print: Option<ProviderPrint>,
99    /// A fingerprint of its latest snapshot and score: it changes when either
100    /// does.
101    pub evidence: u64,
102}
103
104/// Scoring found of one print, as the status answers it.
105#[derive(Debug, Clone, Copy, PartialEq, Eq)]
106pub(crate) struct Scoring {
107    /// When the evidence began.
108    pub since: Timestamp,
109    /// Whether a failure alert of the detector's own has arrived for it.
110    pub verdict: ScoringVerdict,
111}
112
113/// What the reads of the detector's record have found, held between them.
114#[derive(Debug, Clone, Default, PartialEq, Eq)]
115pub(crate) struct ScoringState {
116    /// The last successful read's fingerprint, the open print it named, and
117    /// when on the elapsed clock it was read.
118    last: Option<(PrintId, u64, Duration)>,
119    /// The evidence held: the print, when on the elapsed clock it last moved,
120    /// and the instant the evidence began.
121    evidence: Option<(PrintId, Duration, Timestamp)>,
122    /// The prints a failure alert of the detector's own has arrived for.
123    flagged: BTreeSet<PrintId>,
124    /// Why the record is not being read, or what the last read failed with.
125    unread: Option<String>,
126    /// The earliest start of its job this server has sighted, by print.
127    first_starts: BTreeMap<PrintId, Timestamp>,
128}
129
130impl ScoringState {
131    /// The scoring the evidence shows of one print — or of whichever print it
132    /// is of — at `now` on the elapsed clock.
133    pub(crate) fn scoring(
134        &self,
135        print_id: Option<PrintId>,
136        now: Duration,
137        window: Duration,
138    ) -> Option<Scoring> {
139        let (of, moved, since) = self.evidence?;
140        if print_id.is_some_and(|wanted| wanted != of) || now.saturating_sub(moved) > window {
141            return None;
142        }
143        Some(Scoring {
144            since,
145            verdict: if self.flagged.contains(&of) {
146                ScoringVerdict::Flagged
147            } else {
148                ScoringVerdict::NothingFlagged
149            },
150        })
151    }
152
153    /// Why the record is not being read, or what the last read failed with.
154    pub(crate) fn unread(&self) -> Option<&str> {
155        self.unread.as_deref()
156    }
157}
158
159/// Whether the print a record names is one open print, whose job this server
160/// first sighted starting at `first_start`.
161fn names(print: &PrintRecord, first_start: Option<Timestamp>, named: &ProviderPrint) -> bool {
162    match print.provider_print_id {
163        Some(id) => id == named.id,
164        None => {
165            named.file_name.is_some()
166                && print.file_name == named.file_name
167                && match (first_start, named.started_at) {
168                    (Some(ours), Some(theirs)) => {
169                        seconds_between(ours, theirs).abs() <= JOB_IDENTITY_TOLERANCE_S
170                    }
171                    // A file name alone names any job of that file.
172                    _ => false,
173                }
174        }
175    }
176}
177
178impl Supervisor {
179    /// Note one start a read put a print's job at, keeping the earliest.
180    pub(crate) fn note_sighted_start(&self, print_id: PrintId, started_at: Timestamp) {
181        self.watch_state()
182            .scoring
183            .first_starts
184            .entry(print_id)
185            .and_modify(|held| *held = (*held).min(started_at))
186            .or_insert(started_at);
187    }
188
189    /// Note that a failure alert of the detector's own arrived for one print.
190    pub(crate) fn note_flagged(&self, print_id: PrintId) {
191        self.watch_state().scoring.flagged.insert(print_id);
192    }
193
194    /// Read the detector's record once, for the prints a round observes, and
195    /// answer what failed, for the round to record against what it writes.
196    ///
197    /// No print active, nothing held: evidence is only ever of an active
198    /// print.
199    pub(crate) async fn read_scoring(&self, active: &[PrintRecord]) -> Option<String> {
200        let probe = self.scoring_probe()?;
201        if active.is_empty() {
202            let mut held = self.watch_state();
203            held.scoring.last = None;
204            held.scoring.evidence = None;
205            return None;
206        }
207        let read = probe.read_scoring().await;
208        let reading = match read {
209            ScoringRead::NotRead(why) => {
210                self.watch_state().scoring.unread = Some(why);
211                return None;
212            }
213            ScoringRead::Failed(detail) => {
214                self.watch_state().scoring.unread = Some(format!(
215                    "the last read of the detector's record failed: {detail}"
216                ));
217                return Some(detail);
218            }
219            ScoringRead::Read(reading) => reading,
220        };
221        for print in active {
222            if let Some(started_at) = print.job_started_at {
223                self.note_sighted_start(print.id, started_at);
224            }
225        }
226        let first_starts = {
227            let mut held = self.watch_state();
228            held.scoring
229                .first_starts
230                .retain(|print_id, _| active.iter().any(|print| print.id == *print_id));
231            held.scoring.first_starts.clone()
232        };
233        let named = reading.print.as_ref().and_then(|named| {
234            active
235                .iter()
236                .find(|print| names(print, first_starts.get(&print.id).copied(), named))
237                .map(|print| print.id)
238        });
239        let flagged = match named {
240            Some(print_id) => match self.flagged_in_history(print_id, probe.alert_kind()).await {
241                Ok(flagged) => flagged,
242                Err(error) => {
243                    // Whether the detector flagged the print cannot be said, so
244                    // nothing read this round is taken: a status saying nothing
245                    // was flagged would be a claim nobody could check.
246                    let detail = format!(
247                        "the print's history could not be read to say whether the detector \
248                         flagged it: {error}"
249                    );
250                    self.watch_state().scoring.unread = Some(detail.clone());
251                    return Some(detail);
252                }
253            },
254            None => false,
255        };
256        let now = self.clock().elapsed();
257        let wall = self.clock().now();
258        let window = self
259            .config()
260            .observation_interval
261            .saturating_mul(EVIDENCE_INTERVALS);
262        let mut held = self.watch_state();
263        let state = &mut held.scoring;
264        state.unread = None;
265        let Some(print_id) = named else {
266            // The detector is watching another print, or none: whatever was
267            // held of the active one is over.
268            state.last = None;
269            state.evidence = None;
270            return None;
271        };
272        if flagged {
273            state.flagged.insert(print_id);
274        }
275        // Two reads compared are both inside the window: one taken before an
276        // outage longer than that says nothing about what moved since.
277        let moved = state.last.is_some_and(|(last, evidence, read_at)| {
278            last == print_id
279                && evidence != reading.evidence
280                && now.saturating_sub(read_at) <= window
281        });
282        state.last = Some((print_id, reading.evidence, now));
283        if moved {
284            // A stretch of evidence goes on only while it stands; one that
285            // expired before this read is over, and this read begins another.
286            let since = match state.evidence {
287                Some((of, last_moved, since))
288                    if of == print_id && now.saturating_sub(last_moved) <= window =>
289                {
290                    since
291                }
292                _ => wall,
293            };
294            state.evidence = Some((print_id, now, since));
295        } else if state.evidence.is_some_and(|(of, _, _)| of != print_id) {
296            state.evidence = None;
297        }
298        None
299    }
300
301    /// Whether a print's history holds a failure alert of the detector's own.
302    async fn flagged_in_history(
303        &self,
304        print_id: PrintId,
305        kind: EventKind,
306    ) -> Result<bool, CoreError> {
307        Ok(!self
308            .stores()
309            .events
310            .history(HistoryQuery {
311                print_id,
312                kinds: vec![kind],
313                since: None,
314                until: None,
315                limit: Some(1),
316            })
317            .await?
318            .is_empty())
319    }
320}