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()).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 async fn observe(
145 &self,
146 print: PrintRecord,
147 scoring_failed: Option<&str>,
148 ) -> Result<Option<PendingTurn>, CoreError> {
149 // A scheduled check continues the session it is about, so it lets an
150 // idle compaction of that session end rather than cancel it, and reads
151 // the printer once it has.
152 // A wait that could not be taken leaves the check to run at once.
153 // A turn ending after the wait may start idle work it never saw, so
154 // the claim below is refused when one has, leaving the check to the
155 // next round, whose wait sees that work.
156 let ended = self.inboxes().turns_ended(print.id);
157 let _ = self.agent().idle_work_ended(print.id).await;
158 let printer = self.read_snapshot().await;
159 if printer
160 .as_ref()
161 .is_ok_and(|snapshot| TERMINAL_STATES.contains(&snapshot.connection))
162 {
163 return Ok(None);
164 }
165 let job = self.read_job().await;
166 if let Ok(read) = &job
167 && let Some(turn) = self.follow_planned_changes(&print, read, false).await?
168 {
169 return Ok(Some(turn));
170 }
171 // A print waiting at a planned change is not checked until it carries
172 // on, nor one paused at a planned change its signal has yet to reach,
173 // and one checked as it carried on is next checked an interval after
174 // that check.
175 if !self.turns_allowed(print.id).await?
176 || job
177 .as_ref()
178 .is_ok_and(|read| self.paused_at_planned_change(&print, read))
179 || !self.observation_due(print.id)
180 {
181 return Ok(None);
182 }
183 if !self.inboxes().claim_if_idle_since(print.id, ended) {
184 return Ok(None);
185 }
186 match self
187 .write_observation_down(&print, printer, job, scoring_failed)
188 .await
189 {
190 Ok(arrival) => Ok(Some(PendingTurn::new(print, arrival, Vec::new()))),
191 Err(error) => {
192 // Anything handed to the print while it was claimed is owed a
193 // turn of its own, and is answered as one rather than dropped.
194 let Some(mut left) = self.inboxes().next_or_release(print.id) else {
195 return Err(error);
196 };
197 let latest = left.pop().ok_or(error)?;
198 Ok(Some(PendingTurn::new(print, latest, left)))
199 }
200 }
201 }
202
203 /// Take the camera's frame, write one observation down with it as its
204 /// image, and record a read that failed against it.
205 async fn write_observation_down(
206 &self,
207 print: &PrintRecord,
208 printer: Result<PrinterSnapshot, PrinterError>,
209 job: Result<JobSnapshot, PrinterError>,
210 scoring_failed: Option<&str>,
211 ) -> Result<Arrival, CoreError> {
212 let fetched = self.fetch_configured_frame(Some(print.id)).await;
213 let payload = PeriodicObservationPayload {
214 interval_s: self.config().observation_interval.as_secs(),
215 printer: printer.as_ref().ok().cloned(),
216 job: job.as_ref().ok().cloned(),
217 frame_captured_at: self.frame_captured_at(fetched.as_ref()),
218 };
219 // The observation keeps the telemetry it read whatever the camera
220 // gave; a camera giving only bad frames is the turn's event instead.
221 let (fetched, degraded) = match fetched {
222 Some((_, Frame::Degraded(degraded))) => (None, Some(degraded)),
223 fetched => (fetched, None),
224 };
225 let event = self
226 .write_with_frame(Some(print.id), &payload, fetched)
227 .await?;
228 if let Err(error) = printer {
229 self.record_port_failure(
230 print.id,
231 event.id,
232 PortFailureSite::PrinterSnapshot,
233 error.to_string(),
234 )
235 .await;
236 }
237 if let Err(error) = job {
238 self.record_port_failure(
239 print.id,
240 event.id,
241 PortFailureSite::PrinterJob,
242 error.to_string(),
243 )
244 .await;
245 }
246 if let Some(detail) = scoring_failed {
247 self.record_port_failure(
248 print.id,
249 event.id,
250 PortFailureSite::DetectorScoringRead,
251 detail.to_owned(),
252 )
253 .await;
254 }
255 if let Some(degraded) = degraded {
256 let degraded = self
257 .append_system_event(print.id, EventBody::of(°raded)?)
258 .await?;
259 return Ok(Arrival {
260 event: degraded,
261 detection: None,
262 frame_captured_at: None,
263 camera_frame: crate::inbox::AlertCameraFrame::NotAsked,
264 });
265 }
266 Ok(Arrival {
267 event,
268 detection: None,
269 frame_captured_at: None,
270 camera_frame: crate::inbox::AlertCameraFrame::NotAsked,
271 })
272 }
273}