schedr_db/probe.rs
1//! The round's probe (decision 485): one statement a tick answering, for each read a master's
2//! round makes, whether that read would find anything. Inside [`Database::in_round`], a read
3//! whose check said no returns nothing without going to the database; reads anywhere else (a
4//! worker's turn, the API) are never skipped.
5//!
6//! Each check is its read's own `FROM ... WHERE` text, shared through a macro defined next to
7//! the read, so the two can't drift apart; where a read takes a parameter the probe doesn't
8//! have, its check drops that condition and says yes more often, never less. A write
9//! transaction ending anywhere in this process (counted by `Database::wrote`) makes the next
10//! read whose check said no take the probe again: work a round stores for its own later parts (a
11//! run started, then its instances, then their assignment) is found in the same round.
12//!
13//! A read bounded by a time (tasks ready, retries due, scheduled DAGs due) passes the time it
14//! asks for: a probe covering an earlier time is taken again at that one, so work a part stored
15//! at its own, later clock is found too. The probe looks ahead by what the round gives it (the
16//! tick), so a round's parts, a few milliseconds apart, share one probe.
17
18use std::sync::Arc;
19
20use jiff::Timestamp;
21use sqlx::Row as _;
22
23use crate::database::{Database, DbError};
24use crate::query::{db_time, on_pool, sql_text};
25
26#[cfg(test)]
27mod tests;
28
29/// A read a round may skip, by what its check found.
30#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
31pub enum Check {
32 /// [`Database::pending_commands`].
33 Commands,
34 /// [`Database::dags_with_queued_runs`].
35 QueuedRuns,
36 /// [`Database::scheduled_due`].
37 Scheduled,
38 /// [`Database::queued_event_runs`].
39 QueuedEventRuns,
40 /// [`Database::newly_running`].
41 NewlyRunning,
42 /// [`Database::due_retries`].
43 DueRetries,
44 /// [`Database::replaced_attempts`].
45 ReplacedAttempts,
46 /// [`Database::unschedulable_instances`].
47 Unschedulable,
48 /// [`Database::removed_dags_runs`].
49 RemovedDagsRuns,
50 /// [`Database::chained_attempts`].
51 ChainedAttempts,
52 /// [`Database::ready_instances`].
53 Ready,
54 /// [`Database::waiting_cleanups`] (any time: the read may be asked for later ones).
55 WaitingCleanups,
56 /// [`Database::unstarted_attempts`] (any cutoff, any worker).
57 Unstarted,
58 /// [`Database::unstarted_cleanups`] (any cutoff, any worker).
59 UnstartedCleanups,
60 /// The master's trigger pass: a trigger of a kind the pass looks after switched on, or one
61 /// running on a worker (to be stopped when it no longer should run).
62 Triggers,
63 /// A trigger the trigger loop looks after whose stored next moment has come or isn't known
64 /// (decision 486): the tick wakes the loop.
65 TriggersDue,
66}
67
68impl Check {
69 /// Every check, in the probe's column order.
70 pub const ALL: [Self; 16] = [
71 Self::Commands,
72 Self::QueuedRuns,
73 Self::Scheduled,
74 Self::QueuedEventRuns,
75 Self::NewlyRunning,
76 Self::DueRetries,
77 Self::ReplacedAttempts,
78 Self::Unschedulable,
79 Self::RemovedDagsRuns,
80 Self::ChainedAttempts,
81 Self::Ready,
82 Self::WaitingCleanups,
83 Self::Unstarted,
84 Self::UnstartedCleanups,
85 Self::Triggers,
86 Self::TriggersDue,
87 ];
88
89 /// Its `FROM ... WHERE` text; `$1` is the round's time.
90 const fn from(self) -> &'static str {
91 match self {
92 Self::Commands => crate::commands::pending_from!(),
93 Self::QueuedRuns => crate::runs::queued_from!(),
94 Self::Scheduled => crate::dags::scheduled_due_from!(),
95 Self::QueuedEventRuns => crate::triggers::queued_event_from!(),
96 Self::NewlyRunning => crate::instances::newly_running_from!(),
97 Self::DueRetries => crate::instances::due_retries_from!(),
98 Self::ReplacedAttempts => crate::attempts::replaced_from!(),
99 Self::Unschedulable => crate::attempts::unschedulable_from!(),
100 Self::RemovedDagsRuns => crate::dags::removed_dags_runs_from!(),
101 Self::ChainedAttempts => crate::attempts::chained_from!(),
102 Self::Ready => crate::attempts::ready_from!(),
103 Self::WaitingCleanups => crate::attempts::waiting_cleanups_any_time_from!(),
104 Self::Unstarted => crate::attempts::unstarted_any_time_from!(),
105 Self::UnstartedCleanups => crate::attempts::unstarted_cleanups_any_time_from!(),
106 Self::Triggers => crate::triggers::trigger_pass_from!(),
107 Self::TriggersDue => crate::triggers::triggers_due_from!(),
108 }
109 }
110
111 const fn index(self) -> usize {
112 self as usize
113 }
114}
115
116/// What a probe found: for each check, whether its read would find anything.
117#[derive(Debug, Clone, Copy, PartialEq, Eq)]
118pub struct Probe {
119 found: [bool; Check::ALL.len()],
120}
121
122impl Probe {
123 /// Whether `check`'s read would find anything.
124 #[must_use]
125 pub const fn found(&self, check: Check) -> bool {
126 self.found[check.index()]
127 }
128}
129
130/// The probe statement: one `EXISTS` a check.
131fn statement() -> &'static str {
132 static STATEMENT: std::sync::LazyLock<String> = std::sync::LazyLock::new(|| {
133 let checks: Vec<String> = Check::ALL
134 .iter()
135 .map(|check| format!("EXISTS (SELECT 1 {})", check.from()))
136 .collect();
137 format!("SELECT {}", checks.join(", "))
138 });
139 &STATEMENT
140}
141
142tokio::task_local! {
143 static ROUND: Round;
144}
145
146/// A round under way on one database: its time, how far its probe looks ahead, and its last
147/// probe.
148#[derive(Clone)]
149struct Round {
150 database: Arc<()>,
151 now: Timestamp,
152 ahead: jiff::SignedDuration,
153 seen: Arc<std::sync::Mutex<Option<Seen>>>,
154}
155
156#[derive(Clone, Copy)]
157struct Seen {
158 /// [`Database::write_ends`] when it was taken.
159 writes: u64,
160 /// The time it was taken for: a time-bounded check covers what is due by then.
161 until: Timestamp,
162 probe: Probe,
163}
164
165impl Database {
166 /// What the probe finds at `now` (decision 485).
167 ///
168 /// # Errors
169 ///
170 /// [`DbError`] if the statement fails.
171 pub async fn probe(&self, now: Timestamp) -> Result<Probe, DbError> {
172 let found: Vec<bool> = on_pool!(self, |pool, backend| {
173 let row = sqlx::query(sql_text(backend, statement()))
174 .bind(db_time(now))
175 .fetch_one(pool)
176 .await?;
177 (0..Check::ALL.len())
178 .map(|i| row.try_get::<bool, _>(i))
179 .collect::<Result<Vec<bool>, sqlx::Error>>()?
180 });
181 let mut probe = Probe {
182 found: [false; Check::ALL.len()],
183 };
184 probe.found.copy_from_slice(&found);
185 Ok(probe)
186 }
187
188 /// Whether `check`'s read would find anything at `now`: its one `EXISTS` alone, for a loop
189 /// that needs only it (the trigger loop, decision 486).
190 ///
191 /// # Errors
192 ///
193 /// [`DbError`] if the statement fails.
194 pub async fn exists(&self, check: Check, now: Timestamp) -> Result<bool, DbError> {
195 let statement = format!("SELECT EXISTS (SELECT 1 {})", check.from());
196 let found: bool = on_pool!(self, |pool, backend| {
197 sqlx::query_scalar(sql_text(backend, &statement))
198 .bind(db_time(now))
199 .fetch_one(pool)
200 .await?
201 });
202 Ok(found)
203 }
204
205 /// Runs `work` as a master's round at `now`: its reads that the probe says find nothing are
206 /// skipped (decision 485). The probe is taken at the first such read, looking `ahead` (the
207 /// tick: a time-bounded check counts what is due by then), and again after any write
208 /// transaction ended since, or for a time-bounded read past what it covered.
209 pub async fn in_round<F: std::future::Future>(
210 &self,
211 now: Timestamp,
212 ahead: std::time::Duration,
213 work: F,
214 ) -> F::Output {
215 let round = Round {
216 database: self.identity().clone(),
217 now,
218 ahead: jiff::SignedDuration::try_from(ahead).unwrap_or(jiff::SignedDuration::ZERO),
219 seen: Arc::default(),
220 };
221 ROUND.scope(round, work).await
222 }
223
224 /// Whether this read, `check`'s, is skipped: inside a round on this database whose probe
225 /// found nothing for it (taking the probe first if none is current).
226 ///
227 /// # Errors
228 ///
229 /// [`DbError`] if the probe fails.
230 pub async fn skipped(&self, check: Check) -> Result<bool, DbError> {
231 self.skipped_by(check, None).await
232 }
233
234 /// As [`Self::skipped`], for a read bounded by `now` (what is due by then): a probe taken
235 /// for an earlier time is taken again.
236 ///
237 /// # Errors
238 ///
239 /// [`DbError`] if the probe fails.
240 pub async fn skipped_at(&self, check: Check, now: Timestamp) -> Result<bool, DbError> {
241 self.skipped_by(check, Some(now)).await
242 }
243
244 async fn skipped_by(&self, check: Check, at: Option<Timestamp>) -> Result<bool, DbError> {
245 let Some(round) = ROUND
246 .try_with(Clone::clone)
247 .ok()
248 .filter(|round| Arc::ptr_eq(&round.database, self.identity()))
249 else {
250 return Ok(false);
251 };
252 let writes = self.write_ends();
253 let current = *round
254 .seen
255 .lock()
256 .unwrap_or_else(std::sync::PoisonError::into_inner);
257 let probe = match current {
258 Some(seen) if seen.writes == writes && at.is_none_or(|at| at <= seen.until) => {
259 seen.probe
260 }
261 // Found by the last probe, before a write or for an earlier time: the read goes
262 // ahead without a new probe (not skipping is always safe), so a busy round probes
263 // only for checks that said no.
264 Some(seen) if seen.probe.found(check) => return Ok(false),
265 _ => {
266 let from = at.map_or(round.now, |at| at.max(round.now));
267 let until = from.checked_add(round.ahead).unwrap_or(from);
268 let probe = self.probe(until).await?;
269 *round
270 .seen
271 .lock()
272 .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(Seen {
273 writes,
274 until,
275 probe,
276 });
277 probe
278 }
279 };
280 Ok(!probe.found(check))
281 }
282}