Skip to main content

artifactize_core/store/
executions.rs

1mod mutex;
2
3use crate::types::{ExecutionStatus, Fingerprint, RequestId, ReuseKey, RunId};
4use std::{collections::BTreeMap, path::PathBuf};
5
6use rusqlite::{OptionalExtension, params};
7use serde::{Deserialize, Serialize};
8
9use super::{
10    Receipts, Request, history,
11    receipts::{Error, schema_initialized, update_request},
12};
13use crate::{config::Profile, process, runtime::Verdict};
14
15pub enum Claim {
16    Owned,
17    BudgetExhausted,
18    /// Every machine-wide slot of the execution's backend is held.
19    Full,
20    /// A live execution holds an equal, ancestor or descendant mutex tag.
21    Mutex {
22        eval_id: crate::types::EvalId,
23        run_id: crate::types::RunId,
24    },
25    Reuse(Box<Execution>),
26    Wait(crate::types::ExecutionId),
27    WaitHuman(crate::types::ExecutionId),
28}
29
30/// The machine-wide limit (`limits.json`) of the backend an execution would start on.
31pub struct Capacity {
32    pub limit: u32,
33    /// Whether the Run stopped admitting the backend. It is asked while the claim holds the
34    /// write lock, so the stop of a review that records it before it completes is always seen
35    /// once that review's slot is free.
36    pub stopped: Box<dyn FnOnce() -> bool + Send>,
37}
38
39#[derive(Debug, Clone, Serialize, Deserialize)]
40#[serde(rename_all = "camelCase")]
41pub struct Provenance {
42    #[serde(with = "crate::platform::path_serde")]
43    pub repo_path: PathBuf,
44    pub run_id: RunId,
45    pub request_id: RequestId,
46    pub eval_id: crate::types::EvalId,
47    pub eval_def_hash: crate::types::DefinitionHash,
48    pub completed_at: Option<crate::types::Timestamp>,
49    /// For Agent results: the SHA-256 of each tool's `executionPaths` when the review started,
50    /// by tool name and declared path.
51    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
52    pub execution_paths: crate::tools::pins::Pins,
53}
54
55/// One execution and, once GREEN or RED with a key, one record of its key's history. A local
56/// Agent execution holds one of its backend's machine-wide slots while RUNNING.
57#[derive(Debug, Clone, Serialize, Deserialize)]
58#[serde(try_from = "ExecutionWire", into = "ExecutionWire")]
59pub struct Execution {
60    pub state: super::ExecutionState,
61    pub id: crate::types::ExecutionId,
62    /// The reuse key; absent without a fingerprint on every Artifact the eval depends on.
63    pub key: Option<ReuseKey>,
64    /// The target Artifact's fingerprint.
65    pub fingerprint: Option<Fingerprint>,
66    /// Each Artifact the key covers, the target included, with its fingerprint.
67    pub fingerprints: BTreeMap<crate::types::ArtifactName, Fingerprint>,
68    /// Kinds of exactly the Artifacts covered by a new-format reuse key.
69    pub artifact_kinds: BTreeMap<crate::types::ArtifactName, crate::config::ArtifactKind>,
70    pub eval_def_hash: crate::types::DefinitionHash,
71    /// The local process running this execution; absent for one mirrored from a remote
72    /// review store, which no local process owns.
73    pub owner: Option<process::ChildIdentity>,
74    pub profile: crate::config::StoredProfile,
75    /// How this result was produced; never part of the key.
76    pub options: ExecutionOptions,
77    pub usage: Option<Vec<crate::llm::Attempt>>,
78    pub provenance: Provenance,
79    pub started_at: crate::types::Timestamp,
80    pub producer: Option<Producer>,
81    /// The Human claimant who submitted this result.
82    pub reviewer: Option<crate::types::ReviewerId>,
83    /// Set only on executions mirrored from a remote review store.
84    pub origin: Option<Origin>,
85    pub manifest: Option<crate::cache::Manifest>,
86}
87
88#[derive(Debug, Clone, Serialize, Deserialize)]
89#[serde(rename_all = "camelCase")]
90pub(crate) struct ExecutionWire {
91    pub id: crate::types::ExecutionId,
92    /// The reuse key; absent without a fingerprint on every Artifact the eval depends on.
93    #[serde(default)]
94    pub key: Option<ReuseKey>,
95    /// The target Artifact's fingerprint.
96    pub fingerprint: Option<Fingerprint>,
97    /// Each Artifact the key covers, the target included, with its fingerprint.
98    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
99    pub fingerprints: BTreeMap<crate::types::ArtifactName, Fingerprint>,
100    /// Kinds of exactly the Artifacts covered by a new-format reuse key.
101    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
102    pub artifact_kinds: BTreeMap<crate::types::ArtifactName, crate::config::ArtifactKind>,
103    pub eval_def_hash: crate::types::DefinitionHash,
104    pub owner_pid: u32,
105    pub owner_start_time: u64,
106    pub status: ExecutionStatus,
107    pub result: Option<super::ExecutionResult>,
108    pub error: Option<String>,
109    pub error_code: Option<crate::types::FailureCode>,
110    pub profile: crate::config::StoredProfile,
111    /// How this result was produced; never part of the key.
112    #[serde(default)]
113    pub options: ExecutionOptions,
114    pub usage: Option<Vec<crate::llm::Attempt>>,
115    pub provenance: Provenance,
116    pub started_at: crate::types::Timestamp,
117    pub completed_at: Option<crate::types::Timestamp>,
118    #[serde(default, skip_serializing_if = "Option::is_none")]
119    pub producer: Option<Producer>,
120    /// The Human claimant who submitted this result.
121    #[serde(default, skip_serializing_if = "Option::is_none")]
122    pub reviewer: Option<crate::types::ReviewerId>,
123    /// Set only on executions mirrored from a remote review store.
124    #[serde(default, skip_serializing_if = "Option::is_none")]
125    pub origin: Option<Origin>,
126    #[serde(default, skip_serializing_if = "Option::is_none")]
127    pub manifest: Option<crate::cache::Manifest>,
128}
129
130impl TryFrom<ExecutionWire> for Execution {
131    type Error = String;
132    fn try_from(wire: ExecutionWire) -> Result<Self, Self::Error> {
133        let state = super::ExecutionState::from_parts(
134            wire.status,
135            wire.result,
136            wire.error,
137            wire.error_code,
138            wire.completed_at,
139        )?;
140        Ok(Self {
141            state,
142            id: wire.id,
143            key: wire.key,
144            fingerprint: wire.fingerprint,
145            fingerprints: wire.fingerprints,
146            artifact_kinds: wire.artifact_kinds,
147            eval_def_hash: wire.eval_def_hash,
148            owner: std::num::NonZeroU32::new(wire.owner_pid).map(|pid| process::ChildIdentity {
149                pid: process::ProcessId::from(pid),
150                start_time: wire.owner_start_time,
151            }),
152            profile: wire.profile,
153            options: wire.options,
154            usage: wire.usage,
155            provenance: wire.provenance,
156            started_at: wire.started_at,
157            producer: wire.producer,
158            reviewer: wire.reviewer,
159            origin: wire.origin,
160            manifest: wire.manifest,
161        })
162    }
163}
164impl From<Execution> for ExecutionWire {
165    fn from(record: Execution) -> Self {
166        let owner_pid = record.owner_pid();
167        let owner_start_time = record.owner_start_time();
168        Self {
169            status: record.status(),
170            result: record.result().cloned(),
171            error: record.error().map(str::to_owned),
172            error_code: record.error_code(),
173            completed_at: record.completed_at(),
174            id: record.id,
175            key: record.key,
176            fingerprint: record.fingerprint,
177            fingerprints: record.fingerprints,
178            artifact_kinds: record.artifact_kinds,
179            eval_def_hash: record.eval_def_hash,
180            owner_pid,
181            owner_start_time,
182            profile: record.profile,
183            options: record.options,
184            usage: record.usage,
185            provenance: record.provenance,
186            started_at: record.started_at,
187            producer: record.producer,
188            reviewer: record.reviewer,
189            origin: record.origin,
190            manifest: record.manifest,
191        }
192    }
193}
194impl Execution {
195    pub fn status(&self) -> crate::types::ExecutionStatus {
196        self.state.status()
197    }
198    pub fn result(&self) -> Option<&super::ExecutionResult> {
199        self.state.result()
200    }
201    pub fn error(&self) -> Option<&str> {
202        self.state.error()
203    }
204    pub fn error_code(&self) -> Option<crate::types::FailureCode> {
205        self.state.error_code()
206    }
207    pub fn completed_at(&self) -> Option<crate::types::Timestamp> {
208        self.state.completed_at()
209    }
210    /// The owning process's pid, or 0 for a remote-mirrored execution with no local owner:
211    /// the `owner_pid` SQL column and wire field's sentinel for "no owner", confined to
212    /// this persistence boundary.
213    pub fn owner_pid(&self) -> u32 {
214        self.owner.map_or(0, |owner| owner.pid.get())
215    }
216    /// The owning process's start time, or 0 alongside [`Self::owner_pid`]'s sentinel.
217    pub fn owner_start_time(&self) -> u64 {
218        self.owner.map_or(0, |owner| owner.start_time)
219    }
220}
221
222/// The execution options of a result: stored next to it, never part of its key, so results
223/// from different profiles for the same key reuse each other.
224#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
225#[serde(rename_all = "camelCase")]
226pub struct ExecutionOptions {
227    #[serde(default, skip_serializing_if = "Vec::is_empty")]
228    pub mutex: Vec<crate::config::MutexTag>,
229    #[serde(default, skip_serializing_if = "Option::is_none")]
230    pub backend: Option<crate::config::Backend>,
231    #[serde(default, skip_serializing_if = "Option::is_none")]
232    pub model: Option<crate::config::ModelId>,
233    #[serde(default, skip_serializing_if = "Option::is_none")]
234    pub reasoning: Option<crate::config::Reasoning>,
235    #[serde(default, skip_serializing_if = "Option::is_none")]
236    #[serde(with = "crate::config::validation::milliseconds")]
237    pub timeout_ms: Option<std::time::Duration>,
238    #[serde(default, skip_serializing_if = "Option::is_none")]
239    pub max_tool_calls: Option<u64>,
240    #[serde(default, skip_serializing_if = "Option::is_none")]
241    pub max_tokens: Option<u64>,
242    /// The selected `profileVariants` entry; absent for the declared profile.
243    #[serde(default, skip_serializing_if = "Option::is_none")]
244    pub variant: Option<crate::config::ProfileVariantName>,
245}
246
247impl ExecutionOptions {
248    /// The declared options of an effective profile, as declared (absent means the default).
249    pub fn new(profile: &Profile, variant: Option<&crate::config::ProfileVariantName>) -> Self {
250        let mut options = Self {
251            variant: variant.cloned(),
252            ..Self::default()
253        };
254        match profile {
255            Profile::Agent {
256                backend,
257                model,
258                reasoning,
259                timeout_ms,
260                max_tool_calls,
261                max_tokens,
262            } => {
263                options.backend = Some(*backend);
264                options.model = Some(model.clone());
265                options.reasoning = *reasoning;
266                options.timeout_ms = *timeout_ms;
267                options.max_tool_calls = *max_tool_calls;
268                options.max_tokens = *max_tokens;
269            }
270            Profile::Runtime { timeout_ms, .. } => options.timeout_ms = *timeout_ms,
271            Profile::Human {} => {}
272        }
273        options
274    }
275}
276
277/// Who produced an execution: display metadata, never authentication.
278#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
279pub struct Producer {
280    /// `user@host`.
281    pub name: crate::types::ProducerId,
282    /// The producing artifactize version.
283    pub version: String,
284    /// Where an Agent review's saved conversation lives. It travels with remote records,
285    /// which older clients read without it; the conversation itself never leaves the machine.
286    #[serde(default, skip_serializing_if = "Option::is_none")]
287    pub session: Option<crate::agent::session::SessionRef>,
288}
289
290/// The name every producer without a user or host gets.
291const UNKNOWN_PRODUCER: &str = "unknown@unknown";
292
293impl Producer {
294    pub fn current() -> Self {
295        let user = crate::platform::user_name();
296        let host = crate::platform::host_name();
297        let name = format!(
298            "{}@{}",
299            user.as_deref().unwrap_or("unknown"),
300            host.as_deref()
301                .map(str::trim)
302                .filter(|host| !host.is_empty())
303                .unwrap_or("unknown")
304        );
305        // A name is printable and bounded; whatever the system reports is cut to fit.
306        let mut printable: String = name.chars().filter(|c| !c.is_control()).collect();
307        while printable.len() > crate::types::MAX_ID_BYTES {
308            printable.pop();
309        }
310        Self {
311            name: printable
312                .parse()
313                .unwrap_or_else(|_| UNKNOWN_PRODUCER.parse().expect("a valid producer name")),
314            version: env!("CARGO_PKG_VERSION").into(),
315            session: None,
316        }
317    }
318}
319
320/// The remote store, authenticated publisher and server clock of a mirrored execution.
321#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
322#[serde(rename_all = "camelCase")]
323pub struct Origin {
324    pub store: crate::types::StoreUrl,
325    pub publisher: crate::types::TokenName,
326    pub published_at: crate::types::Timestamp,
327}
328
329impl Execution {
330    /// The backend whose machine-wide slot this execution holds while RUNNING: a local Agent
331    /// review's. A mirrored record ran elsewhere.
332    fn backend(&self) -> Option<&str> {
333        self.options
334            .backend
335            .as_ref()
336            .map(|backend| backend.as_str())
337            .filter(|_| self.origin.is_none())
338    }
339
340    /// Whether this record completed after `other`, comparing `completedAt` as instants.
341    pub fn completed_after(&self, other: &Execution) -> bool {
342        self.completed_at() > other.completed_at()
343    }
344
345    pub fn verdict(&self) -> Option<Verdict> {
346        match self.status() {
347            ExecutionStatus::Green => Some(Verdict::Green),
348            ExecutionStatus::Red => Some(Verdict::Red),
349            _ => None,
350        }
351    }
352}
353
354/// The latest completed record of a key.
355pub(super) fn lookup(
356    db: &rusqlite::Connection,
357    key: &ReuseKey,
358) -> Result<Option<Execution>, Error> {
359    let data: Option<String> = db
360        .query_row(
361            &format!(
362                "SELECT e.data FROM executions e WHERE e.key=? AND {} ORDER BY {} LIMIT 1",
363                history::RECORD,
364                history::LATEST
365            ),
366            [key],
367            |row| row.get(0),
368        )
369        .optional()?;
370    Ok(data.and_then(|data| super::unreadable::evidence("execution", &data)))
371}
372
373/// End a RUNNING execution whose owner process is gone, which frees its key and its slot.
374fn owner_died(
375    db: &rusqlite::Connection,
376    id: &crate::types::ExecutionId,
377    at: crate::types::Timestamp,
378) -> Result<(), Error> {
379    db.execute(
380        "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'",
381        params![at, id],
382    )?;
383    Ok(())
384}
385
386/// How many slots of `backend` the RUNNING executions of live owners hold; the executions of
387/// dead owners end, freeing theirs.
388fn held_slots(
389    db: &rusqlite::Connection,
390    backend: &str,
391    at: crate::types::Timestamp,
392) -> Result<u32, Error> {
393    let owners = {
394        let mut statement = db.prepare(
395            "SELECT id,owner_pid,owner_start_time FROM executions WHERE backend=? AND status='RUNNING'",
396        )?;
397        statement
398            .query_map([backend], |row| {
399                Ok((
400                    row.get::<_, crate::types::ExecutionId>(0)?,
401                    process::ChildIdentity {
402                        pid: row.get(1)?,
403                        start_time: row.get::<_, i64>(2)? as u64,
404                    },
405                ))
406            })?
407            .collect::<Result<Vec<_>, _>>()?
408    };
409    let mut held = 0;
410    for (id, owner) in owners {
411        if process::is_alive(Some(owner)).map_err(|e| Error::Invalid(e.to_string()))? {
412            held += 1;
413        } else {
414            owner_died(db, &id, at)?;
415        }
416    }
417    Ok(held)
418}
419
420/// Corruption must not reserve a reuse key or machine-wide slot forever. Preserve its
421/// original JSON for the unreadable audit, but retire the invalid active index entry.
422fn retire_unreadable(
423    db: &rusqlite::Connection,
424    key: Option<&ReuseKey>,
425    backend: Option<&str>,
426) -> Result<(), Error> {
427    let records = {
428        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))")?;
429        statement
430            .query_map(params![key, backend], |row| {
431                Ok((
432                    row.get::<_, crate::types::ExecutionId>(0)?,
433                    row.get::<_, String>(1)?,
434                ))
435            })?
436            .collect::<Result<Vec<_>, _>>()?
437    };
438    for (id, data) in records {
439        if let Err(error) = super::unreadable::decode::<Execution>("execution", id.as_str(), &data)
440        {
441            use std::io::Write;
442            let _ = writeln!(std::io::stderr().lock(), "{error}");
443            db.execute(
444                "UPDATE executions SET status='ERROR',backend=NULL WHERE id=?",
445                [id],
446            )?;
447        }
448    }
449    Ok(())
450}
451
452/// The one definition of in-flight identity. Completed evidence still uses only its
453/// reuse key; joining additionally requires the complete declared effective profile.
454fn sharing_identity(
455    key: &ReuseKey,
456    profile: &crate::config::StoredProfile,
457) -> Result<(ReuseKey, String), Error> {
458    Ok((key.clone(), serde_json::to_string(profile)?))
459}
460
461fn active_owner(
462    db: &rusqlite::Connection,
463    key: &ReuseKey,
464    profile: Option<&str>,
465) -> Result<
466    Option<(
467        crate::types::ExecutionId,
468        process::ChildIdentity,
469        ExecutionStatus,
470    )>,
471    Error,
472> {
473    let row = db
474        .query_row(
475            "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')",
476            params![key, profile],
477            |row| {
478                Ok((
479                    row.get::<_, crate::types::ExecutionId>(0)?,
480                    process::ChildIdentity {
481                        pid: row.get(1)?,
482                        start_time: row.get::<_, i64>(2)? as u64,
483                    },
484                    row.get::<_, ExecutionStatus>(3)?,
485                    row.get::<_, String>(4)?,
486                ))
487            },
488        )
489        .optional()?;
490    Ok(row.and_then(|(id, owner, status, data)| {
491        super::unreadable::evidence::<Execution>("execution", &data).map(|_| (id, owner, status))
492    }))
493}
494
495fn available_to_waiter(
496    db: &rusqlite::Connection,
497    key: &ReuseKey,
498    waiting_for: Option<&crate::types::ExecutionId>,
499    profile: &str,
500) -> Result<Option<Claim>, Error> {
501    if let Some(id) = waiting_for {
502        let data: Option<String> = db
503            .query_row(
504                "SELECT data FROM executions WHERE id=? AND key=? AND profile_identity=?",
505                params![id, key, profile],
506                |row| row.get(0),
507            )
508            .optional()?;
509        if let Some(data) = data
510            && let Some(execution) = super::unreadable::evidence::<Execution>("execution", &data)
511        {
512            match execution.status() {
513                ExecutionStatus::Green | ExecutionStatus::Red => {
514                    return Ok(Some(Claim::Reuse(Box::new(execution))));
515                }
516                ExecutionStatus::Error
517                    if !matches!(
518                        execution.error_code(),
519                        Some(
520                            crate::types::FailureCode::Cancelled
521                                | crate::types::FailureCode::OwnerDied
522                        )
523                    ) =>
524                {
525                    return Ok(Some(Claim::Reuse(Box::new(execution))));
526                }
527                // A joined request stays with its execution, even if an independent
528                // forced or different-profile review publishes another result meanwhile.
529                ExecutionStatus::Running
530                    if process::is_alive(execution.owner)
531                        .map_err(|error| Error::Invalid(error.to_string()))? =>
532                {
533                    return Ok(Some(Claim::Wait(execution.id)));
534                }
535                ExecutionStatus::WaitingHuman => return Ok(Some(Claim::WaitHuman(execution.id))),
536                _ => {}
537            }
538        }
539    }
540    available(db, key, Some(profile))
541}
542
543fn available(
544    db: &rusqlite::Connection,
545    key: &ReuseKey,
546    profile: Option<&str>,
547) -> Result<Option<Claim>, Error> {
548    if let Some(execution) = lookup(db, key)? {
549        return Ok(Some(Claim::Reuse(Box::new(execution))));
550    }
551    if let Some((id, owner, status)) = active_owner(db, key, profile)? {
552        if status == ExecutionStatus::WaitingHuman {
553            return Ok(Some(Claim::WaitHuman(id)));
554        }
555        if process::is_alive(Some(owner)).map_err(|e| Error::Invalid(e.to_string()))? {
556            return Ok(Some(Claim::Wait(id)));
557        }
558    }
559    Ok(None)
560}
561
562async fn open_read_only(
563    state: &std::path::Path,
564) -> Result<Option<tokio_rusqlite::Connection>, String> {
565    let state = crate::workspace::canonical_target(state).map_err(|e| e.to_string())?;
566    super::receipts::check_files(&state)?;
567    if !state
568        .join(super::DATABASE)
569        .try_exists()
570        .map_err(|e| e.to_string())?
571    {
572        return Ok(None);
573    }
574    tokio_rusqlite::Connection::open_with_flags(
575        state.join(super::DATABASE),
576        rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY,
577    )
578    .await
579    .map(Some)
580    .map_err(|e| e.to_string())
581}
582
583/// Read the latest completed record or the live owner of each key without creating or
584/// changing the database.
585pub async fn read_keyed_executions(
586    state: &std::path::Path,
587    keys: &[ReuseKey],
588) -> Result<std::collections::BTreeMap<ReuseKey, Claim>, String> {
589    read_claims(
590        state,
591        keys.iter()
592            .map(|key| (key.clone(), key.clone(), None))
593            .collect(),
594    )
595    .await
596}
597
598pub(crate) async fn read_profiled_executions(
599    state: &std::path::Path,
600    keys: Vec<(crate::types::EvalId, ReuseKey, crate::config::StoredProfile)>,
601) -> Result<BTreeMap<crate::types::EvalId, Claim>, String> {
602    let keys = keys
603        .into_iter()
604        .map(|(id, key, profile)| {
605            sharing_identity(&key, &profile)
606                .map(|(key, profile)| (id, key, Some(profile)))
607                .map_err(|error| error.to_string())
608        })
609        .collect::<Result<Vec<_>, _>>()?;
610    read_claims(state, keys).await
611}
612
613async fn read_claims<K: Ord + Send + 'static>(
614    state: &std::path::Path,
615    keys: Vec<(K, ReuseKey, Option<String>)>,
616) -> Result<BTreeMap<K, Claim>, String> {
617    if keys.is_empty() {
618        return Ok(Default::default());
619    }
620    let Some(connection) = open_read_only(state).await? else {
621        return Ok(Default::default());
622    };
623    let result = connection
624        .call(move |db| -> Result<_, Error> {
625            db.busy_timeout(super::SQLITE_BUSY_TIMEOUT)?;
626            let transaction = db.transaction()?;
627            if !schema_initialized(&transaction)? {
628                return Ok(Default::default());
629            }
630            let mut entries = std::collections::BTreeMap::new();
631            for (id, key, profile) in keys {
632                if let Some(claim) = available(&transaction, &key, profile.as_deref())? {
633                    entries.insert(id, claim);
634                }
635            }
636            transaction.commit()?;
637            Ok(entries)
638        })
639        .await
640        .map_err(|e| e.to_string());
641    super::connection::finish(connection, result).await
642}
643
644/// The latest record per (Eval id, Eval definition hash) under any key, read-only: what a
645/// changed key is explained against.
646pub async fn read_latest_cached(
647    state: &std::path::Path,
648    keys: &[(crate::types::EvalId, crate::types::DefinitionHash)],
649) -> Result<
650    std::collections::BTreeMap<(crate::types::EvalId, crate::types::DefinitionHash), Execution>,
651    String,
652> {
653    if keys.is_empty() {
654        return Ok(Default::default());
655    }
656    let Some(connection) = open_read_only(state).await? else {
657        return Ok(Default::default());
658    };
659    let keys = keys.to_vec();
660    let result = connection
661        .call(move |db| -> Result<_, Error> {
662            db.busy_timeout(super::SQLITE_BUSY_TIMEOUT)?;
663            let transaction = db.transaction()?;
664            if !schema_initialized(&transaction)? {
665                return Ok(Default::default());
666            }
667            let mut latest = std::collections::BTreeMap::new();
668            {
669                let mut statement = transaction.prepare(&format!(
670                    "SELECT e.data FROM executions e WHERE e.eval_def_hash=? AND json_extract(e.data,'$.provenance.evalId')=? AND {} ORDER BY {} LIMIT 1",
671                    history::RECORD,
672                    history::LATEST
673                ))?;
674                for (eval_id, eval_def_hash) in keys {
675                    let data: Option<String> = statement
676                        .query_row(params![eval_def_hash, eval_id], |row| row.get(0))
677                        .optional()?;
678                    if let Some(data) = data
679                        && let Some(execution) = super::unreadable::evidence("execution", &data)
680                    {
681                        latest.insert((eval_id, eval_def_hash), execution);
682                    }
683                }
684            }
685            transaction.commit()?;
686            Ok(latest)
687        })
688        .await
689        .map_err(|e| e.to_string());
690    super::connection::finish(connection, result).await
691}
692
693impl Receipts {
694    /// The key's latest record; a hit updates its last use.
695    pub async fn cached_execution(&self, key: &str) -> Result<Option<Execution>, String> {
696        let key: ReuseKey = key.parse()?;
697        self.connection
698            .call(move |db| -> Result<_, Error> {
699                let execution = lookup(db, &key)?;
700                if let Some(execution) = &execution {
701                    history::touch(db, &execution.id, crate::broker::now())?;
702                }
703                Ok(execution)
704            })
705            .await
706            .map_err(|e| e.to_string())
707    }
708
709    /// The saved execution eligible for publication; speculative Runs hold publication
710    /// until blocked work has been withdrawn. Mirrors never publish again.
711    pub async fn published_execution(
712        &self,
713        execution_id: &str,
714    ) -> Result<Option<Execution>, String> {
715        let execution_id: crate::types::ExecutionId = execution_id.parse()?;
716        self.connection
717            .call(move |db| -> Result<_, Error> {
718                let data: Option<String> = db
719                    .query_row(
720                        &format!(
721                            "SELECT e.data FROM executions e LEFT JOIN runs r ON r.id=json_extract(e.data,'$.provenance.runId') WHERE e.id=? AND {} AND (r.id IS NULL OR r.status!='RUNNING' OR coalesce(json_extract(r.data,'$.modes.speculate'),0)=0 OR json_extract(r.data,'$.control.activity')='publishing')",
722                            history::RECORD
723                        ),
724                        [execution_id],
725                        |row| row.get(0),
726                    )
727                    .optional()?;
728                Ok(data
729                    .and_then(|data| super::unreadable::evidence::<Execution>("execution", &data))
730                    .filter(|execution| execution.origin.is_none()))
731            })
732            .await
733            .map_err(|e| e.to_string())
734    }
735
736    /// Claim an execution for its request. A `keyed` claim (a key, not forced) first reuses
737    /// the key's latest record or waits for its live execution with the same profile. Starting needs
738    /// `allow_start` and, on a backend with a machine-wide limit, a free slot: the slots the
739    /// backend's RUNNING executions hold are counted and this execution inserted RUNNING in
740    /// one write transaction. Mutex tags are also checked and held in that transaction,
741    /// including for unkeyed and forced executions. An unkeyed or forced execution without
742    /// a limit or mutex tags is saved when it completes.
743    pub async fn claim_execution(
744        &self,
745        execution: &Execution,
746        keyed: bool,
747        waiting_for: Option<&crate::types::ExecutionId>,
748        allow_start: bool,
749        capacity: Option<Capacity>,
750    ) -> Result<Claim, String> {
751        let execution = execution.clone();
752        let waiting_for = waiting_for.cloned();
753        let identity = execution
754            .key
755            .as_ref()
756            .filter(|_| keyed)
757            .map(|key| sharing_identity(key, &execution.profile))
758            .transpose()
759            .map_err(|error| error.to_string())?;
760        self.connection
761            .call(move |db| -> Result<Claim, Error> {
762                let key = identity.as_ref().map(|(key, _)| key);
763                let profile = identity.as_ref().map(|(_, profile)| profile.as_str());
764                if let Some(key) = key {
765                    let transaction = db.transaction()?;
766                    if let Some(claim) =
767                        available_to_waiter(&transaction, key, waiting_for.as_ref(), profile.expect("keyed identity"))?
768                    {
769                        return Ok(claim);
770                    }
771                }
772                if !allow_start && key.is_none() {
773                    return Ok(Claim::BudgetExhausted);
774                }
775                let capacity = capacity.zip(execution.backend());
776                if key.is_none() && capacity.is_none() && execution.options.mutex.is_empty() {
777                    return Ok(Claim::Owned);
778                }
779                let transaction =
780                    db.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
781                if let Some(key) = key
782                    && let Some(claim) =
783                        available_to_waiter(&transaction, key, waiting_for.as_ref(), profile.expect("keyed identity"))?
784                {
785                    return Ok(claim);
786                }
787                // The read fast path may have observed RUNNING before publication and
788                // then a dead publisher. Confirm availability in a fresh write snapshot
789                // even when this waiter has no budget to start another execution.
790                if !allow_start {
791                    return Ok(Claim::BudgetExhausted);
792                }
793                retire_unreadable(&transaction, key, capacity.as_ref().map(|(_, backend)| *backend))?;
794                if !execution.options.mutex.is_empty()
795                    && let Some(conflict) = mutex::conflict(&transaction, &execution)?
796                {
797                    transaction.commit()?;
798                    return Ok(conflict);
799                }
800                if let Some((capacity, backend)) = capacity {
801                    if (capacity.stopped)() {
802                        return Ok(Claim::BudgetExhausted);
803                    }
804                    if held_slots(&transaction, backend, execution.started_at)? >= capacity.limit {
805                        transaction.commit()?;
806                        return Ok(Claim::Full);
807                    }
808                }
809                if let Some(key) = key
810                    && let Some((id, _, _)) = active_owner(&transaction, key, profile)?
811                {
812                    owner_died(&transaction, &id, execution.started_at)?;
813                }
814                let inserted = transaction.execute(
815                    "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",
816                    params![
817                        execution.id,
818                        key,
819                        execution.eval_def_hash,
820                        execution.status(),
821                        execution.owner_pid(),
822                        execution.owner_start_time() as i64,
823                        execution.backend(),
824                        profile,
825                        serde_json::to_string(&execution)?
826                    ],
827                )?;
828                let claim = match key {
829                    Some(key) if inserted == 0 => Claim::Wait(
830                        active_owner(&transaction, key, profile)?
831                            .expect("conflicting active key")
832                            .0,
833                    ),
834                    _ => Claim::Owned,
835                };
836                transaction.commit()?;
837                Ok(claim)
838            })
839            .await
840            .map_err(|e| e.to_string())
841    }
842
843    pub async fn reuse_execution(&self, request: &Request) -> Result<(), String> {
844        let request = request.clone();
845        self.connection
846            .call(move |db| -> Result<(), Error> {
847                let transaction = db.transaction()?;
848                update_request(&transaction, &request)?;
849                if let (Some(execution), Some(at)) = (&request.execution_id, request.completed_at())
850                {
851                    history::touch(&transaction, execution, at)?;
852                }
853                transaction.commit()?;
854                Ok(())
855            })
856            .await
857            .map_err(|e| e.to_string())
858    }
859
860    pub async fn complete_execution(
861        &self,
862        execution: &Execution,
863        request: &Request,
864    ) -> Result<(), String> {
865        let execution = execution.clone();
866        let request = request.clone();
867        self.connection
868            .call(move |db| -> Result<(), Error> {
869                let transaction =
870                    db.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
871                let published = settle(&transaction, &execution, &request)?;
872                transaction.commit()?;
873                if published {
874                    history::collect_after(db);
875                }
876                Ok(())
877            })
878            .await
879            .map_err(|e| e.to_string())
880    }
881
882    /// Add a remote result to its key's history as a self-contained execution when it
883    /// completed after the key's latest local record, which it then replaces as the one reused;
884    /// `None` when the local record is as new. The mirrored record settles a local Human wait
885    /// for the key.
886    pub async fn mirror_execution(
887        &self,
888        execution: &Execution,
889    ) -> Result<Option<Execution>, String> {
890        let execution = execution.clone();
891        self.connection
892            .call(move |db| -> Result<Option<Execution>, Error> {
893                let (Some(key), Some(_), Some(_)) =
894                    (&execution.key, &execution.origin, execution.verdict())
895                else {
896                    return Err(Error::Invalid(
897                        "Only completed remote GREEN/RED results can be mirrored.".into(),
898                    ));
899                };
900                let data = serde_json::to_string(&execution)?;
901                if data.len() > history::MAX_ENTRY_BYTES {
902                    return Err(Error::Invalid(
903                        "Remote result exceeds the cache entry limit.".into(),
904                    ));
905                }
906                let transaction =
907                    db.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
908                if lookup(&transaction, key)?
909                    .is_some_and(|local| !execution.completed_after(&local))
910                {
911                    transaction.commit()?;
912                    return Ok(None);
913                }
914                // A mirror kept after `cache rm` or GC is reused for the same remote execution.
915                transaction.execute(
916                    "INSERT INTO executions(id,key,eval_def_hash,status,owner_pid,owner_start_time,data) VALUES (?,?,?,?,?,?,?) ON CONFLICT(id) DO NOTHING",
917                    params![
918                        execution.id,
919                        key,
920                        execution.eval_def_hash,
921                        execution.status(),
922                        execution.owner_pid(),
923                        execution.owner_start_time() as i64,
924                        data
925                    ],
926                )?;
927                let data: String = transaction
928                    .query_row(
929                        "SELECT data FROM executions WHERE id=? AND key=? AND status=?",
930                        params![execution.id, key, execution.status()],
931                        |row| row.get(0),
932                    )
933                    .optional()?
934                    .ok_or_else(|| {
935                        Error::Invalid(
936                            "Mirrored execution ID conflicts with another execution.".into(),
937                        )
938                    })?;
939                let Some(mirrored) = super::unreadable::evidence::<Execution>("execution", &data) else {
940                    transaction.commit()?;
941                    return Ok(None);
942                };
943                if let Some((completed_at, bytes)) = history::columns(&mirrored, data.len())? {
944                    transaction.execute(
945                        "UPDATE executions SET completed_at=?,bytes=?,last_used=? WHERE id=? AND completed_at IS NULL",
946                        params![completed_at, bytes, crate::broker::now(), mirrored.id],
947                    )?;
948                }
949                super::human::settle_waiting(&transaction, &mirrored)?;
950                transaction.commit()?;
951                history::collect_after(db);
952                Ok(Some(mirrored))
953            })
954            .await
955            .map_err(|e| e.to_string())
956    }
957}
958
959/// Save a finished execution and its request; a GREEN/RED with a key joins the key's history.
960/// A claimed or Human execution updates its active row; a forced or unkeyed one is inserted,
961/// or replaces the RUNNING row its limited start inserted. True when it joined the history.
962pub(super) fn settle(
963    db: &rusqlite::Connection,
964    execution: &Execution,
965    request: &Request,
966) -> Result<bool, Error> {
967    if request.status() != execution.status().into()
968        || request.execution_id.as_ref() != Some(&execution.id)
969        || request.result() != execution.result()
970        || request.error() != execution.error()
971        || request.error_code() != execution.error_code()
972    {
973        return Err(Error::Invalid(
974            "Execution and request settlement disagree.".into(),
975        ));
976    }
977    let data = serde_json::to_string(execution)?;
978    let record = history::columns(execution, data.len())?;
979    let last_used = record.as_ref().and(execution.completed_at());
980    let (completed_at, bytes) = record.unzip();
981    let claimed = execution.key.is_some() && !request.force;
982    if claimed || request.human_definition.is_some() {
983        if db.execute(
984            "UPDATE executions SET key=?,status=?,completed_at=?,bytes=?,last_used=?,data=? WHERE id=? AND owner_pid=? AND owner_start_time=? AND status IN ('RUNNING','WAITING_HUMAN')",
985            params![
986                execution.key,
987                execution.status(),
988                completed_at,
989                bytes,
990                last_used,
991                data,
992                execution.id,
993                execution.owner_pid(),
994                execution.owner_start_time() as i64
995            ],
996        )? != 1
997        {
998            return Err(Error::Invalid("Active execution not found.".into()));
999        }
1000    } else {
1001        db.execute(
1002            "INSERT INTO executions(id,key,eval_def_hash,status,owner_pid,owner_start_time,backend,completed_at,bytes,last_used,data) VALUES (?,?,?,?,?,?,?,?,?,?,?)
1003            ON CONFLICT(id) DO UPDATE SET key=excluded.key,status=excluded.status,completed_at=excluded.completed_at,bytes=excluded.bytes,last_used=excluded.last_used,data=excluded.data",
1004            params![
1005                execution.id,
1006                execution.key,
1007                execution.eval_def_hash,
1008                execution.status(),
1009                execution.owner_pid(),
1010                execution.owner_start_time() as i64,
1011                execution.backend(),
1012                completed_at,
1013                bytes,
1014                last_used,
1015                data
1016            ],
1017        )?;
1018    }
1019    update_request(db, request)?;
1020    Ok(record.is_some())
1021}