printobserver_core/observation.rs
1//! A periodic observation of every active print, which no detector asked for.
2//!
3//! A failure detector alerts on what it was trained to see, and a print can go
4//! wrong in ways that stay below every one of its thresholds: firmware pausing
5//! a print and cutting its heater while the host goes on reporting it printing,
6//! a fan cut at a bridge, a wall going thin. Nothing in the machine's state or
7//! the camera's frame is hidden from an agent that looks — so every interval
8//! ([`CoreConfig::observation_interval`](crate::CoreConfig::observation_interval))
9//! each active print is written a [`PeriodicObservationPayload`] event carrying
10//! the printer's telemetry, with the camera's frame as its image, and the turn
11//! that event claims is that print's agent looking at it.
12//!
13//! # Which prints are observed
14//!
15//! The printer's job is read and settled exactly as the listing's is
16//! ([`crate::listing`]): a job found over closes its prints, and a running job
17//! no open print records is adopted. When that read succeeds the print the job
18//! is — when it is one — is the one active print; a printer whose job cannot be
19//! read leaves every open print a candidate, because nothing then says which
20//! of them stopped. A printer reporting one of
21//! [`TERMINAL_STATES`](crate::TERMINAL_STATES) is not printing anything, and an
22//! ended print has nothing left to act on, so neither is observed.
23//!
24//! # No pile-up
25//!
26//! An observation claims a print's turn only when nothing holds it
27//! ([`Inboxes::claim_if_idle`](crate::Inboxes::claim_if_idle)). A print whose
28//! turn is running — on an alert, or on the last observation — is being
29//! watched already, and is given no observation to queue behind it; so at most
30//! one observation per print is ever outstanding, and every turn the agent is
31//! given still runs under the same one-agent-per-print rule and the same action
32//! policy, `safety.agent_min_interval_s` included.
33//!
34//! # An idle compaction of the session ends first
35//!
36//! A supervisor port may compact a print's session while no turn of it runs
37//! ([`SupervisorPort::idle_work_ended`](printobserver_supervisor_api::SupervisorPort::idle_work_ended)),
38//! and every other event's turn cancels that compaction at once. A scheduled
39//! check alone waits for it to end, bounded by the compaction's own timeout,
40//! because it is the turn that continues that session on the port's own
41//! cadence: cancelling it would leave the session as large as it was and the
42//! next gap no longer.
43//!
44//! # The detector's record is read first
45//!
46//! Each round begins by reading the failure detector's own record of the
47//! active print, when the composition root installed something to read it
48//! with ([`crate::scoring`]), so that every turn the round claims reads the
49//! detector's status as it stands now. A read that failed is recorded against
50//! each observation the round writes, as a port failure.
51//!
52//! # The reads, and the frame, precede the append
53//!
54//! Everywhere else the event append is the first thing the loop does
55//! ([`crate::events`]), because an alert arrives from outside and must be in
56//! the history before anything can fail on its behalf. An observation is
57//! raised here, and what it records *is* the reads, so they are taken first and
58//! the event carries them. The camera is asked for its frame before the event
59//! is written too, and the event is written together with that frame as its
60//! image in one store write, so anybody following the log — the `events` read,
61//! `printobserver watch` — reads the check with its frame the first time it
62//! reads it, rather than an event with no image that nothing sends again. A
63//! read that failed, a camera that would not answer however often it was
64//! asked ([`crate::look`]), and a store that would not keep the frame are each
65//! recorded against the event once it is written, as a port failure, as the
66//! loop records one. A camera that gives only bad frames is recorded as a
67//! `camera_degraded` after the observation, and that is the event the turn is
68//! given, so the agent is told there is no frame rather than handed one.
69
70use printobserver_printer_api::{JobSnapshot, PrinterError, PrinterSnapshot};
71use printobserver_types::{EventBody, PrintId};
72
73use crate::error::CoreError;
74use crate::events::{PendingTurn, TERMINAL_STATES};
75use crate::inbox::Arrival;
76use crate::kinds::{PeriodicObservationPayload, PortFailureSite};
77use crate::look::Frame;
78use crate::records::PrintRecord;
79use crate::supervisor::Supervisor;
80
81/// What one round of observations claimed, and what it could not write down.
82#[derive(Debug, Default)]
83pub struct Observed {
84 /// The turns the observations claimed, each to be run by
85 /// [`Supervisor::run_supervision`]: a turn claimed and never run leaves its
86 /// print claimed.
87 pub turns: Vec<PendingTurn>,
88 /// Each print whose observation the store would not write down, with the
89 /// store's own error. Such a print claimed no turn, and the next round
90 /// observes it again.
91 pub refused: Vec<(PrintId, CoreError)>,
92}
93
94impl Supervisor {
95 /// Observe every active print nobody is watching, and answer the turns
96 /// those observations claimed.
97 ///
98 /// One print's observation that could not be written down is answered in
99 /// [`Observed::refused`] and stops no other: every turn the round claimed
100 /// is answered, because a claimed turn nobody runs is a print no later
101 /// event could reach.
102 ///
103 /// # Errors
104 ///
105 /// Returns the store's own error when the open prints could not be read or
106 /// settled, before any print was claimed.
107 pub async fn observe_active_prints(&self) -> Result<Observed, CoreError> {
108 let mut observed = Observed::default();
109 let prints = self.prints_to_observe().await?;
110 let scoring_failed = self.read_scoring(&prints).await;
111 for print in prints {
112 let print_id = print.id;
113 match self.observe(print, scoring_failed.as_deref()).await {
114 Ok(Some(turn)) => observed.turns.push(turn),
115 Ok(None) => {}
116 Err(error) => observed.refused.push((print_id, error)),
117 }
118 }
119 Ok(observed)
120 }
121
122 /// The open prints an observation is owed to, once the printer's job has
123 /// settled them.
124 async fn prints_to_observe(&self) -> Result<Vec<PrintRecord>, CoreError> {
125 let resolving = self.resolving().await;
126 let active = match self.observe_job().await {
127 Some(observed) => Some(self.settle_and_adopt(&observed).await?),
128 None => None,
129 };
130 drop(resolving);
131 let open = self.stores().prints.open_prints().await?;
132 Ok(match active {
133 Some(running) => open
134 .into_iter()
135 .filter(|print| Some(print.id) == running)
136 .collect(),
137 None => open,
138 })
139 }
140
141 /// Observe one print, when it is printing and nobody is watching it.
142 async fn observe(
143 &self,
144 print: PrintRecord,
145 scoring_failed: Option<&str>,
146 ) -> Result<Option<PendingTurn>, CoreError> {
147 // A scheduled check continues the session it is about, so it lets an
148 // idle compaction of that session end rather than cancel it, and reads
149 // the printer once it has.
150 // A wait that could not be taken leaves the check to run at once.
151 let _ = self.agent().idle_work_ended(print.id).await;
152 let printer = self.read_snapshot().await;
153 if printer
154 .as_ref()
155 .is_ok_and(|snapshot| TERMINAL_STATES.contains(&snapshot.connection))
156 {
157 return Ok(None);
158 }
159 let job = self.read_job().await;
160 if let Ok(read) = &job
161 && let Some(turn) = self.follow_planned_changes(&print, read, false).await?
162 {
163 return Ok(Some(turn));
164 }
165 // A print waiting at a planned change is not checked until it carries
166 // on, nor one paused at a planned change its signal has yet to reach,
167 // and one checked as it carried on is next checked an interval after
168 // that check.
169 if !self.turns_allowed(print.id).await?
170 || job
171 .as_ref()
172 .is_ok_and(|read| self.paused_at_planned_change(&print, read))
173 || !self.observation_due(print.id)
174 {
175 return Ok(None);
176 }
177 if !self.inboxes().claim_if_idle(print.id) {
178 return Ok(None);
179 }
180 match self
181 .write_observation_down(&print, printer, job, scoring_failed)
182 .await
183 {
184 Ok(arrival) => Ok(Some(PendingTurn::new(print, arrival, Vec::new()))),
185 Err(error) => {
186 // Anything handed to the print while it was claimed is owed a
187 // turn of its own, and is answered as one rather than dropped.
188 let Some(mut left) = self.inboxes().next_or_release(print.id) else {
189 return Err(error);
190 };
191 let latest = left.pop().ok_or(error)?;
192 Ok(Some(PendingTurn::new(print, latest, left)))
193 }
194 }
195 }
196
197 /// Take the camera's frame, write one observation down with it as its
198 /// image, and record a read that failed against it.
199 async fn write_observation_down(
200 &self,
201 print: &PrintRecord,
202 printer: Result<PrinterSnapshot, PrinterError>,
203 job: Result<JobSnapshot, PrinterError>,
204 scoring_failed: Option<&str>,
205 ) -> Result<Arrival, CoreError> {
206 let fetched = self.fetch_configured_frame(Some(print.id)).await;
207 let payload = PeriodicObservationPayload {
208 interval_s: self.config().observation_interval.as_secs(),
209 printer: printer.as_ref().ok().cloned(),
210 job: job.as_ref().ok().cloned(),
211 frame_captured_at: self.frame_captured_at(fetched.as_ref()),
212 };
213 // The observation keeps the telemetry it read whatever the camera
214 // gave; a camera giving only bad frames is the turn's event instead.
215 let (fetched, degraded) = match fetched {
216 Some((_, Frame::Degraded(degraded))) => (None, Some(degraded)),
217 fetched => (fetched, None),
218 };
219 let event = self
220 .write_with_frame(Some(print.id), &payload, fetched)
221 .await?;
222 if let Err(error) = printer {
223 self.record_port_failure(
224 print.id,
225 event.id,
226 PortFailureSite::PrinterSnapshot,
227 error.to_string(),
228 )
229 .await;
230 }
231 if let Err(error) = job {
232 self.record_port_failure(
233 print.id,
234 event.id,
235 PortFailureSite::PrinterJob,
236 error.to_string(),
237 )
238 .await;
239 }
240 if let Some(detail) = scoring_failed {
241 self.record_port_failure(
242 print.id,
243 event.id,
244 PortFailureSite::DetectorScoringRead,
245 detail.to_owned(),
246 )
247 .await;
248 }
249 if let Some(degraded) = degraded {
250 let degraded = self
251 .append_system_event(print.id, EventBody::of(°raded)?)
252 .await?;
253 return Ok(Arrival {
254 event: degraded,
255 detection: None,
256 frame_captured_at: None,
257 camera_frame: crate::inbox::AlertCameraFrame::NotAsked,
258 });
259 }
260 Ok(Arrival {
261 event,
262 detection: None,
263 frame_captured_at: None,
264 camera_frame: crate::inbox::AlertCameraFrame::NotAsked,
265 })
266 }
267}