Skip to main content

speccoder_runtime/
resume.rs

1//! Resuming an attempt a killed process left behind.
2//!
3//! Before an attempt, a marker records its admission key, the checkpoint it
4//! started from and the acceptance tests it is judged by. A run that ends in
5//! any ordinary way removes it ([`Guard`]); a killed process cannot, so a
6//! marker on disk means an attempt was interrupted. The next run then keeps
7//! the worktree as the attempt left it and admits the attempt under the same
8//! key: agentplane finds the interrupted run and resumes it from its journal
9//! — model calls and tool calls that finished are read back, not repeated —
10//! and a run that had already finished is read back whole and judged again
11//! (a task that passed just before the kill is ticked now).
12
13use std::path::{Path, PathBuf};
14
15use serde::{Deserialize, Serialize};
16use sha2::{Digest as _, Sha256};
17
18/// An attempt in progress.
19#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
20pub struct Marker {
21    /// The agentplane admission key.
22    pub key: String,
23    /// The checkpoint the attempt started from.
24    pub before: String,
25    /// The worktree's HEAD then; a different HEAD means the marker is stale.
26    pub head: String,
27    /// Which attempt of the task run.
28    pub attempt: u32,
29    /// Which best-of-n sample (0-based).
30    pub sample: usize,
31    /// The acceptance tests prepared for the task run.
32    pub acceptance: Option<serde_json::Value>,
33    /// The run the attempt belongs to: an invocation resuming it adopts it.
34    #[serde(default)]
35    pub run_id: Option<String>,
36    /// The run's prompts when the attempt started.
37    #[serde(default)]
38    pub asked: u32,
39    /// The run's grants when it started.
40    #[serde(default)]
41    pub run_grants: Vec<crate::tools::policy::Object>,
42}
43
44/// Where the marker of `feature/task` lives.
45#[must_use]
46pub fn path(plane_dir: &Path, feature: &str, task: &str) -> PathBuf {
47    plane_dir
48        .join("resume")
49        .join(feature)
50        .join(format!("{task}.json"))
51}
52
53/// The marker, if an attempt was interrupted.
54#[must_use]
55pub fn load(path: &Path) -> Option<Marker> {
56    serde_json::from_str(&std::fs::read_to_string(path).ok()?).ok()
57}
58
59/// Records `marker` (written whole, then renamed: never half a marker).
60pub fn save(path: &Path, marker: &Marker) -> std::io::Result<()> {
61    if let Some(dir) = path.parent() {
62        std::fs::create_dir_all(dir)?;
63    }
64    let tmp = path.with_extension("json.tmp");
65    std::fs::write(
66        &tmp,
67        serde_json::to_vec(marker).map_err(std::io::Error::other)?,
68    )?;
69    std::fs::rename(tmp, path)
70}
71
72/// A fresh admission key: unique per attempt, so an ordinary rerun never
73/// meets an old attempt's run.
74#[must_use]
75pub fn new_key(feature: &str, task: &str) -> String {
76    static COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
77    let nanos = std::time::SystemTime::now()
78        .duration_since(std::time::UNIX_EPOCH)
79        .map_or(0, |d| d.as_nanos());
80    let n = COUNTER.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
81    let digest = Sha256::digest(format!(
82        "{feature}/{task}/{nanos}/{}/{n}",
83        std::process::id()
84    ));
85    let hex: String = digest.iter().take(16).map(|b| format!("{b:02x}")).collect();
86    format!("attempt-{hex}")
87}
88
89/// Removes the marker when a task run that started an attempt ends in any
90/// ordinary way. A run refused before its attempt starts (a session check,
91/// a worktree held by a waiting call) leaves an interrupted or waiting
92/// attempt's marker alone: that attempt still resumes.
93#[derive(Debug)]
94pub struct Guard {
95    path: PathBuf,
96    armed: std::cell::Cell<bool>,
97}
98
99impl Guard {
100    /// A guard for the marker at `path`, not yet armed.
101    #[must_use]
102    pub fn new(path: PathBuf) -> Self {
103        Self {
104            path,
105            armed: std::cell::Cell::new(false),
106        }
107    }
108
109    /// An attempt is starting: the marker goes when the run ends.
110    pub fn arm(&self) {
111        self.armed.set(true);
112    }
113
114    /// Leaves the marker in place: the attempt waits for a person and the
115    /// next run resumes it.
116    pub fn keep(self) {
117        self.armed.set(false);
118    }
119}
120
121impl Drop for Guard {
122    fn drop(&mut self) {
123        if self.armed.get() {
124            let _ = std::fs::remove_file(&self.path);
125        }
126    }
127}