1use super::{Execution, lookup, mutex};
3use crate::{
4 process,
5 store::{self, Receipts, receipts::Error},
6 types::{ExecutionStatus, ReuseKey},
7};
8use rusqlite::{OptionalExtension, params};
9
10pub enum Claim {
11 Owned,
12 BudgetExhausted,
13 Full,
15 Mutex {
17 eval_id: crate::types::EvalId,
18 run_id: crate::types::RunId,
19 },
20 Reuse(Box<Execution>),
21 Wait(crate::types::ExecutionId),
22 WaitHuman(crate::types::ExecutionId),
23}
24
25pub struct Capacity {
27 pub limit: u32,
28 pub stopped: Box<dyn FnOnce() -> bool + Send>,
32}
33
34pub(super) fn owner_died(
36 db: &rusqlite::Connection,
37 id: &crate::types::ExecutionId,
38 at: crate::types::Timestamp,
39) -> Result<(), Error> {
40 db.execute(
41 "UPDATE executions SET status='ERROR',data=json_set(data,'$.status','ERROR','$.error','Execution owner died.','$.errorCode','OWNER_DIED','$.result',NULL,'$.completedAt',?1,'$.provenance.completedAt',?1) WHERE id=?2 AND status='RUNNING'",
42 params![at, id],
43 )?;
44 Ok(())
45}
46
47fn held_slots(
50 db: &rusqlite::Connection,
51 backend: &str,
52 at: crate::types::Timestamp,
53) -> Result<u32, Error> {
54 let owners = {
55 let mut statement = db.prepare(
56 "SELECT id,owner_pid,owner_start_time FROM executions WHERE backend=? AND status='RUNNING'",
57 )?;
58 statement
59 .query_map([backend], |row| {
60 Ok((
61 row.get::<_, crate::types::ExecutionId>(0)?,
62 process::ChildIdentity {
63 pid: row.get(1)?,
64 start_time: row.get::<_, i64>(2)? as u64,
65 },
66 ))
67 })?
68 .collect::<Result<Vec<_>, _>>()?
69 };
70 let mut held = 0;
71 for (id, owner) in owners {
72 if process::is_alive(Some(owner)).map_err(|e| Error::Invalid(e.to_string()))? {
73 held += 1;
74 } else {
75 owner_died(db, &id, at)?;
76 }
77 }
78 Ok(held)
79}
80
81fn retire_unreadable(
84 db: &rusqlite::Connection,
85 key: Option<&ReuseKey>,
86 backend: Option<&str>,
87) -> Result<(), Error> {
88 let records = {
89 let mut statement = db.prepare("SELECT id,data FROM executions WHERE status IN ('RUNNING','WAITING_HUMAN') AND ((?1 IS NOT NULL AND key=?1) OR (?2 IS NOT NULL AND backend=?2))")?;
90 statement
91 .query_map(params![key, backend], |row| {
92 Ok((
93 row.get::<_, crate::types::ExecutionId>(0)?,
94 row.get::<_, String>(1)?,
95 ))
96 })?
97 .collect::<Result<Vec<_>, _>>()?
98 };
99 for (id, data) in records {
100 if let Err(error) = store::unreadable::decode::<Execution>("execution", id.as_str(), &data)
101 {
102 use std::io::Write;
103 let _ = writeln!(std::io::stderr().lock(), "{error}");
104 db.execute(
105 "UPDATE executions SET status='ERROR',backend=NULL WHERE id=?",
106 [id],
107 )?;
108 }
109 }
110 Ok(())
111}
112
113#[derive(Clone, Debug, PartialEq, Eq)]
116pub(super) struct ProfileIdentity(String);
117
118impl ProfileIdentity {
119 fn of(profile: &crate::config::StoredProfile) -> Result<Self, Error> {
120 Ok(Self(serde_json::to_string(profile)?))
121 }
122}
123
124impl rusqlite::ToSql for ProfileIdentity {
125 fn to_sql(&self) -> rusqlite::Result<rusqlite::types::ToSqlOutput<'_>> {
126 self.0.to_sql()
127 }
128}
129
130pub(super) fn sharing_identity(
133 key: &ReuseKey,
134 profile: &crate::config::StoredProfile,
135) -> Result<(ReuseKey, ProfileIdentity), Error> {
136 Ok((key.clone(), ProfileIdentity::of(profile)?))
137}
138
139pub(super) fn active_owner(
140 db: &rusqlite::Connection,
141 key: &ReuseKey,
142 profile: Option<&ProfileIdentity>,
143) -> Result<
144 Option<(
145 crate::types::ExecutionId,
146 process::ChildIdentity,
147 ExecutionStatus,
148 )>,
149 Error,
150> {
151 let row = db
152 .query_row(
153 "SELECT id,owner_pid,owner_start_time,status,data FROM executions WHERE key=?1 AND (?2 IS NULL OR profile_identity=?2) AND status IN ('RUNNING','WAITING_HUMAN')",
154 params![key, profile],
155 |row| {
156 Ok((
157 row.get::<_, crate::types::ExecutionId>(0)?,
158 process::ChildIdentity {
159 pid: row.get(1)?,
160 start_time: row.get::<_, i64>(2)? as u64,
161 },
162 row.get::<_, ExecutionStatus>(3)?,
163 row.get::<_, String>(4)?,
164 ))
165 },
166 )
167 .optional()?;
168 Ok(row.and_then(|(id, owner, status, data)| {
169 store::unreadable::evidence::<Execution>("execution", &data).map(|_| (id, owner, status))
170 }))
171}
172
173pub(super) fn available_to_waiter(
174 db: &rusqlite::Connection,
175 key: &ReuseKey,
176 waiting_for: Option<&crate::types::ExecutionId>,
177 profile: &ProfileIdentity,
178) -> Result<Option<Claim>, Error> {
179 if let Some(id) = waiting_for {
180 let data: Option<String> = db
181 .query_row(
182 "SELECT data FROM executions WHERE id=? AND key=? AND profile_identity=?",
183 params![id, key, profile],
184 |row| row.get(0),
185 )
186 .optional()?;
187 if let Some(data) = data
188 && let Some(execution) = store::unreadable::evidence::<Execution>("execution", &data)
189 {
190 match execution.status() {
191 ExecutionStatus::Green | ExecutionStatus::Red => {
192 return Ok(Some(Claim::Reuse(Box::new(execution))));
193 }
194 ExecutionStatus::Error
195 if !matches!(
196 execution.error_code(),
197 Some(
198 crate::types::FailureCode::Cancelled
199 | crate::types::FailureCode::OwnerDied
200 )
201 ) =>
202 {
203 return Ok(Some(Claim::Reuse(Box::new(execution))));
204 }
205 ExecutionStatus::Running
208 if process::is_alive(execution.owner)
209 .map_err(|error| Error::Invalid(error.to_string()))? =>
210 {
211 return Ok(Some(Claim::Wait(execution.id)));
212 }
213 ExecutionStatus::WaitingHuman => return Ok(Some(Claim::WaitHuman(execution.id))),
214 _ => {}
215 }
216 }
217 }
218 available(db, key, Some(profile))
219}
220
221pub(super) fn available(
222 db: &rusqlite::Connection,
223 key: &ReuseKey,
224 profile: Option<&ProfileIdentity>,
225) -> Result<Option<Claim>, Error> {
226 if let Some(execution) = lookup(db, key)? {
227 return Ok(Some(Claim::Reuse(Box::new(execution))));
228 }
229 if let Some((id, owner, status)) = active_owner(db, key, profile)? {
230 if status == ExecutionStatus::WaitingHuman {
231 return Ok(Some(Claim::WaitHuman(id)));
232 }
233 if process::is_alive(Some(owner)).map_err(|e| Error::Invalid(e.to_string()))? {
234 return Ok(Some(Claim::Wait(id)));
235 }
236 }
237 Ok(None)
238}
239
240pub(super) async fn open_read_only(
241 state: &std::path::Path,
242) -> Result<Option<tokio_rusqlite::Connection>, String> {
243 let state = crate::workspace::canonical_target(state).map_err(|e| e.to_string())?;
244 store::receipts::check_files(&state)?;
245 if !state
246 .join(store::DATABASE)
247 .try_exists()
248 .map_err(|e| e.to_string())?
249 {
250 return Ok(None);
251 }
252 tokio_rusqlite::Connection::open_with_flags(
253 state.join(store::DATABASE),
254 rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY,
255 )
256 .await
257 .map(Some)
258 .map_err(|e| e.to_string())
259}
260
261impl Receipts {
264 pub async fn claim_execution(
272 &self,
273 execution: &Execution,
274 keyed: bool,
275 waiting_for: Option<&crate::types::ExecutionId>,
276 allow_start: bool,
277 capacity: Option<Capacity>,
278 ) -> Result<Claim, String> {
279 let execution = execution.clone();
280 let waiting_for = waiting_for.cloned();
281 let identity = execution
282 .key
283 .as_ref()
284 .filter(|_| keyed)
285 .map(|key| sharing_identity(key, &execution.profile))
286 .transpose()
287 .map_err(|error| error.to_string())?;
288 self.connection
289 .call(move |db| -> Result<Claim, Error> {
290 let key = identity.as_ref().map(|(key, _)| key);
291 let profile = identity.as_ref().map(|(_, profile)| profile);
292 if let Some(key) = key {
293 let transaction = db.transaction()?;
294 if let Some(claim) =
295 available_to_waiter(&transaction, key, waiting_for.as_ref(), profile.expect("keyed identity"))?
296 {
297 return Ok(claim);
298 }
299 }
300 if !allow_start && key.is_none() {
301 return Ok(Claim::BudgetExhausted);
302 }
303 let capacity = capacity.zip(execution.backend());
304 if key.is_none() && capacity.is_none() && execution.options.mutex.is_empty() {
305 return Ok(Claim::Owned);
306 }
307 let transaction =
308 db.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
309 if let Some(key) = key
310 && let Some(claim) =
311 available_to_waiter(&transaction, key, waiting_for.as_ref(), profile.expect("keyed identity"))?
312 {
313 return Ok(claim);
314 }
315 if !allow_start {
319 return Ok(Claim::BudgetExhausted);
320 }
321 retire_unreadable(&transaction, key, capacity.as_ref().map(|(_, backend)| *backend))?;
322 if !execution.options.mutex.is_empty()
323 && let Some(conflict) = mutex::conflict(&transaction, &execution)?
324 {
325 transaction.commit()?;
326 return Ok(conflict);
327 }
328 if let Some((capacity, backend)) = capacity {
329 if (capacity.stopped)() {
330 return Ok(Claim::BudgetExhausted);
331 }
332 if held_slots(&transaction, backend, execution.started_at)? >= capacity.limit {
333 transaction.commit()?;
334 return Ok(Claim::Full);
335 }
336 }
337 if let Some(key) = key
338 && let Some((id, _, _)) = active_owner(&transaction, key, profile)?
339 {
340 owner_died(&transaction, &id, execution.started_at)?;
341 }
342 let inserted = transaction.execute(
343 "INSERT INTO executions(id,key,eval_def_hash,status,owner_pid,owner_start_time,backend,profile_identity,data) VALUES (?,?,?,?,?,?,?,?,?) ON CONFLICT(key,profile_identity) WHERE key IS NOT NULL AND status IN ('RUNNING','WAITING_HUMAN') DO NOTHING",
344 params![
345 execution.id,
346 key,
347 execution.eval_def_hash,
348 execution.status(),
349 execution.owner_pid(),
350 execution.owner_start_time() as i64,
351 execution.backend(),
352 profile,
353 serde_json::to_string(&execution)?
354 ],
355 )?;
356 let claim = match key {
357 Some(key) if inserted == 0 => Claim::Wait(
358 active_owner(&transaction, key, profile)?
359 .expect("conflicting active key")
360 .0,
361 ),
362 _ => Claim::Owned,
363 };
364 transaction.commit()?;
365 Ok(claim)
366 })
367 .await
368 .map_err(|e| e.to_string())
369 }
370}