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_since`](crate::Inboxes::claim_if_idle_since)). 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. A turn of the print that ends after that wait may start
43//! idle work of its own, which the wait never saw; so a check that one ended
44//! under claims nothing, and the next round's wait sees that work.
45//!
46//! # The detector's record is read first
47//!
48//! Each round begins by reading the failure detector's own record of the
49//! active print, when the composition root installed something to read it
50//! with ([`crate::scoring`]), so that every turn the round claims reads the
51//! detector's status as it stands now. A read that failed is recorded against
52//! each observation the round writes, as a port failure.
53//!
54//! # The reads, and the frame, precede the append
55//!
56//! Everywhere else the event append is the first thing the loop does
57//! ([`crate::events`]), because an alert arrives from outside and must be in
58//! the history before anything can fail on its behalf. An observation is
59//! raised here, and what it records *is* the reads, so they are taken first and
60//! the event carries them. The camera is asked for its frame before the event
61//! is written too, and the event is written together with that frame as its
62//! image in one store write, so anybody following the log — the `events` read,
63//! `printobserver watch` — reads the check with its frame the first time it
64//! reads it, rather than an event with no image that nothing sends again. A
65//! read that failed, a camera that would not answer however often it was
66//! asked ([`crate::look`]), and a store that would not keep the frame are each
67//! recorded against the event once it is written, as a port failure, as the
68//! loop records one. A camera that gives only bad frames is recorded as a
69//! `camera_degraded` after the observation, and that is the event the turn is
70//! given, so the agent is told there is no frame rather than handed one.
71
72use printobserver_printer_api::{JobSnapshot, PrinterError, PrinterSnapshot};
73use printobserver_types::{EventBody, PrintId};
74
75use crate::error::CoreError;
76use crate::events::{PendingTurn, TERMINAL_STATES};
77use crate::inbox::Arrival;
78use crate::kinds::{PeriodicObservationPayload, PortFailureSite};
79use crate::look::Frame;
80use crate::records::PrintRecord;
81use crate::supervisor::Supervisor;
82
83/// What one round of observations claimed, and what it could not write down.
84#[derive(Debug, Default)]
85pub struct Observed {
86 /// The turns the observations claimed, each to be run by
87 /// [`Supervisor::run_supervision`]: a turn claimed and never run leaves its
88 /// print claimed.
89 pub turns: Vec<PendingTurn>,
90 /// Each print whose observation the store would not write down, with the
91 /// store's own error. Such a print claimed no turn, and the next round
92 /// observes it again.
93 pub refused: Vec<(PrintId, CoreError)>,
94}
95
96impl Supervisor {
97 /// Observe every active print nobody is watching, and answer the turns
98 /// those observations claimed.
99 ///
100 /// One print's observation that could not be written down is answered in
101 /// [`Observed::refused`] and stops no other: every turn the round claimed
102 /// is answered, because a claimed turn nobody runs is a print no later
103 /// event could reach.
104 ///
105 /// # Errors
106 ///
107 /// Returns the store's own error when the open prints could not be read or
108 /// settled, before any print was claimed.
109 pub async fn observe_active_prints(&self) -> Result<Observed, CoreError> {
110 let mut observed = Observed::default();
111 let prints = self.prints_to_observe().await?;
112 let scoring_failed = self.read_scoring(&prints).await;
113 for print in prints {
114 let print_id = print.id;
115 match self.observe(print, scoring_failed.as_deref(), false).await {
116 Ok(Some(turn)) => observed.turns.push(turn),
117 Ok(None) => {}
118 Err(error) => observed.refused.push((print_id, error)),
119 }
120 }
121 Ok(observed)
122 }
123
124 /// The open prints an observation is owed to, once the printer's job has
125 /// settled them.
126 async fn prints_to_observe(&self) -> Result<Vec<PrintRecord>, CoreError> {
127 let resolving = self.resolving().await;
128 let active = match self.observe_job().await {
129 Some(observed) => Some(self.settle_and_adopt(&observed).await?),
130 None => None,
131 };
132 drop(resolving);
133 let open = self.stores().prints.open_prints().await?;
134 Ok(match active {
135 Some(running) => open
136 .into_iter()
137 .filter(|print| Some(print.id) == running)
138 .collect(),
139 None => open,
140 })
141 }
142
143 /// Observe one print, when it is printing and nobody is watching it:
144 /// when its scheduled check is due, or — `at_resume` — at once, because it
145 /// has just carried on from a pause ([`crate::resumes`]).
146 pub(crate) async fn observe(
147 &self,
148 print: PrintRecord,
149 scoring_failed: Option<&str>,
150 at_resume: bool,
151 ) -> Result<Option<PendingTurn>, CoreError> {
152 // A scheduled check continues the session it is about, so it lets an
153 // idle compaction of that session end rather than cancel it, and reads
154 // the printer once it has.
155 // A wait that could not be taken leaves the check to run at once.
156 // A turn ending after the wait may start idle work it never saw, so
157 // the claim below is refused when one has, leaving the check to the
158 // next round, whose wait sees that work.
159 // A look as the print carries on is an event's, and starts at once.
160 let ended = self.inboxes().turns_ended(print.id);
161 if !at_resume {
162 let _ = self.agent().idle_work_ended(print.id).await;
163 }
164 let printer = self.read_snapshot().await;
165 if printer
166 .as_ref()
167 .is_ok_and(|snapshot| TERMINAL_STATES.contains(&snapshot.connection))
168 {
169 return Ok(None);
170 }
171 let job = self.read_job().await;
172 if let Ok(read) = &job
173 && let Some(turn) = self.follow_planned_changes(&print, read, false).await?
174 {
175 return Ok(Some(turn));
176 }
177 // A print waiting at a planned change is not checked until it carries
178 // on, nor one paused at a planned change its signal has yet to reach,
179 // nor one its agent's own pause holds; and one checked as it carried
180 // on is next checked an interval after that check.
181 if !self.turns_allowed(print.id).await?
182 || job.as_ref().is_ok_and(|read| {
183 self.paused_at_planned_change(&print, read)
184 || self.agent_pause_holds(print.id, read)
185 })
186 || !(at_resume || self.observation_due(print.id))
187 {
188 return Ok(None);
189 }
190 let printing = job
191 .as_ref()
192 .is_ok_and(|read| read.state == printobserver_printer_api::PrinterState::Printing);
193 let claimed = if at_resume {
194 self.inboxes().claim_if_idle(print.id)
195 } else {
196 self.inboxes().claim_if_idle_since(print.id, ended)
197 };
198 if !claimed {
199 return Ok(None);
200 }
201 match self
202 .write_observation_down(&print, printer, job, scoring_failed)
203 .await
204 {
205 Ok(arrival) => {
206 self.note_looked(print.id, printing);
207 Ok(Some(PendingTurn::new(print, arrival, Vec::new())))
208 }
209 Err(error) => {
210 // Anything handed to the print while it was claimed is owed a
211 // turn of its own, and is answered as one rather than dropped.
212 let Some(mut left) = self.inboxes().next_or_release(print.id) else {
213 return Err(error);
214 };
215 let latest = left.pop().ok_or(error)?;
216 Ok(Some(PendingTurn::new(print, latest, left)))
217 }
218 }
219 }
220
221 /// Take the camera's frame, write one observation down with it as its
222 /// image, and record a read that failed against it.
223 async fn write_observation_down(
224 &self,
225 print: &PrintRecord,
226 printer: Result<PrinterSnapshot, PrinterError>,
227 job: Result<JobSnapshot, PrinterError>,
228 scoring_failed: Option<&str>,
229 ) -> Result<Arrival, CoreError> {
230 let fetched = self.fetch_configured_frame(Some(print.id)).await;
231 let payload = PeriodicObservationPayload {
232 interval_s: self.config().observation_interval.as_secs(),
233 printer: printer.as_ref().ok().cloned(),
234 job: job.as_ref().ok().cloned(),
235 frame_captured_at: self.frame_captured_at(fetched.as_ref()),
236 };
237 // The observation keeps the telemetry it read whatever the camera
238 // gave; a camera giving only bad frames is the turn's event instead.
239 let (fetched, degraded) = match fetched {
240 Some((_, Frame::Degraded(degraded))) => (None, Some(degraded)),
241 fetched => (fetched, None),
242 };
243 let event = self
244 .write_with_frame(Some(print.id), &payload, fetched)
245 .await?;
246 if let Err(error) = printer {
247 self.record_port_failure(
248 print.id,
249 event.id,
250 PortFailureSite::PrinterSnapshot,
251 error.to_string(),
252 )
253 .await;
254 }
255 if let Err(error) = job {
256 self.record_port_failure(
257 print.id,
258 event.id,
259 PortFailureSite::PrinterJob,
260 error.to_string(),
261 )
262 .await;
263 }
264 if let Some(detail) = scoring_failed {
265 self.record_port_failure(
266 print.id,
267 event.id,
268 PortFailureSite::DetectorScoringRead,
269 detail.to_owned(),
270 )
271 .await;
272 }
273 if let Some(degraded) = degraded {
274 let degraded = self
275 .append_system_event(print.id, EventBody::of(°raded)?)
276 .await?;
277 return Ok(Arrival {
278 event: degraded,
279 detection: None,
280 frame_captured_at: None,
281 camera_frame: crate::inbox::AlertCameraFrame::NotAsked,
282 });
283 }
284 Ok(Arrival {
285 event,
286 detection: None,
287 frame_captured_at: None,
288 camera_frame: crate::inbox::AlertCameraFrame::NotAsked,
289 })
290 }
291}