Skip to main content

artifactize_core/store/executions/
admission.rs

1//! Claims, capacity, and the identity of in-flight executions.
2use 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    /// Every machine-wide slot of the execution's backend is held.
14    Full,
15    /// A live execution holds an equal, ancestor or descendant mutex tag.
16    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
25/// The machine-wide limit (`limits.json`) of the backend an execution would start on.
26pub struct Capacity {
27    pub limit: u32,
28    /// Whether the Run stopped admitting the backend. It is asked while the claim holds the
29    /// write lock, so the stop of a review that records it before it completes is always seen
30    /// once that review's slot is free.
31    pub stopped: Box<dyn FnOnce() -> bool + Send>,
32}
33
34/// End a RUNNING execution whose owner process is gone, which frees its key and its slot.
35pub(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
47/// How many slots of `backend` the RUNNING executions of live owners hold; the executions of
48/// dead owners end, freeing theirs.
49fn 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
81/// Corruption must not reserve a reuse key or machine-wide slot forever. Preserve its
82/// original JSON for the unreadable audit, but retire the invalid active index entry.
83fn 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/// The complete declared effective profile an in-flight execution is joined on, as its
114/// stored JSON. Only [`ProfileIdentity::of`] makes one, so every join compares one spelling.
115#[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
130/// The one definition of in-flight identity. Completed evidence still uses only its
131/// reuse key; joining additionally requires the complete declared effective profile.
132pub(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                // A joined request stays with its execution, even if an independent
206                // forced or different-profile review publishes another result meanwhile.
207                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
261/// Read the latest completed record or the live owner of each key without creating or
262/// changing the database.
263impl Receipts {
264    /// Claim an execution for its request. A `keyed` claim (a key, not forced) first reuses
265    /// the key's latest record or waits for its live execution with the same profile. Starting needs
266    /// `allow_start` and, on a backend with a machine-wide limit, a free slot: the slots the
267    /// backend's RUNNING executions hold are counted and this execution inserted RUNNING in
268    /// one write transaction. Mutex tags are also checked and held in that transaction,
269    /// including for unkeyed and forced executions. An unkeyed or forced execution without
270    /// a limit or mutex tags is saved when it completes.
271    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                // The read fast path may have observed RUNNING before publication and
316                // then a dead publisher. Confirm availability in a fresh write snapshot
317                // even when this waiter has no budget to start another execution.
318                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}