O1: Rust crate, profiles, persistent run state (#9)
This commit was merged in pull request #9.
This commit is contained in:
1 parent
29c08130c2
commit
fb434c670c
9 files changed
+1128
No files matched your search
+172
@@ -0,0 +1,172 @@
|
||||
//! Persistent run state: one JSON file per run in `<state>/runs/ID.json`, written atomically.
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// queued -> running -> gating -> done | failed. (retry and needs-human arrive with O2.)
|
||||
#[derive(Serialize, Deserialize, Clone, Copy, PartialEq, Eq, Debug)]
|
||||
#[serde(rename_all = "kebab-case")]
|
||||
pub enum Status {
|
||||
Queued,
|
||||
Running,
|
||||
Gating,
|
||||
Done,
|
||||
Failed,
|
||||
}
|
||||
|
||||
impl Status {
|
||||
pub fn active(self) -> bool {
|
||||
matches!(self, Status::Queued | Status::Running | Status::Gating)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Clone, Debug)]
|
||||
pub struct Run {
|
||||
pub id: String,
|
||||
pub title: String,
|
||||
pub profile: String,
|
||||
pub repo: PathBuf,
|
||||
pub branch: String,
|
||||
pub worktree: PathBuf,
|
||||
pub status: Status,
|
||||
/// Why a run failed: hx-failed, gate-failed, timeout, budget:<what>, interrupted, setup:<err>.
|
||||
pub reason: Option<String>,
|
||||
pub orch_pid: u32,
|
||||
pub hx_pid: Option<u32>,
|
||||
pub started: u64,
|
||||
pub ended: Option<u64>,
|
||||
pub hx_exit: Option<i32>,
|
||||
pub gate_exit: Option<i32>,
|
||||
pub input_tokens: u64,
|
||||
pub output_tokens: u64,
|
||||
pub session: Option<String>,
|
||||
}
|
||||
|
||||
pub fn now() -> u64 {
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map_or(0, |d| d.as_secs())
|
||||
}
|
||||
|
||||
pub fn runs_dir() -> PathBuf {
|
||||
crate::state_dir().join("runs")
|
||||
}
|
||||
|
||||
pub fn log_path(id: &str) -> PathBuf {
|
||||
runs_dir().join(format!("{id}.log"))
|
||||
}
|
||||
|
||||
fn valid_id(id: &str) -> bool {
|
||||
!id.is_empty() && !id.contains(['/', '\\']) && !id.starts_with('.')
|
||||
}
|
||||
|
||||
impl Run {
|
||||
pub fn save(&self) -> Result<()> {
|
||||
let dir = runs_dir();
|
||||
std::fs::create_dir_all(&dir)?;
|
||||
let tmp = dir.join(format!("{}.json.tmp", self.id));
|
||||
std::fs::write(&tmp, serde_json::to_vec_pretty(self)?)?;
|
||||
std::fs::rename(&tmp, dir.join(format!("{}.json", self.id)))?; // atomic: no half-written state on crash
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn load(id: &str) -> Result<Self> {
|
||||
anyhow::ensure!(valid_id(id), "bad run id {id:?}");
|
||||
let p = runs_dir().join(format!("{id}.json"));
|
||||
let mut r: Run =
|
||||
serde_json::from_slice(&std::fs::read(&p).with_context(|| format!("run {id}"))?)?;
|
||||
r.reconcile()?;
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
pub fn list() -> Result<Vec<Self>> {
|
||||
let mut v = vec![];
|
||||
let Ok(rd) = std::fs::read_dir(runs_dir()) else {
|
||||
return Ok(v);
|
||||
};
|
||||
for e in rd.flatten() {
|
||||
if let Some(id) = e.file_name().to_str().and_then(|n| n.strip_suffix(".json")) {
|
||||
v.push(Self::load(id)?);
|
||||
}
|
||||
}
|
||||
v.sort_by(|a, b| (a.started, &a.id).cmp(&(b.started, &b.id)));
|
||||
Ok(v)
|
||||
}
|
||||
|
||||
/// An active run whose orchestrator died (crash, kill -9, reboot) is marked failed/interrupted and
|
||||
/// its hx process group is killed, so status never lies and no orphan keeps spending tokens.
|
||||
/// ponytail: pid reuse can make a dead orch look alive; store a start time (or flock) in O4.
|
||||
pub fn reconcile(&mut self) -> Result<()> {
|
||||
if self.status.active() && !alive(self.orch_pid) {
|
||||
if let Some(p) = self.hx_pid {
|
||||
kill_group(p);
|
||||
}
|
||||
self.status = Status::Failed;
|
||||
self.reason = Some("interrupted".into());
|
||||
self.ended = Some(now());
|
||||
self.save()?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub fn alive(pid: u32) -> bool {
|
||||
// SAFETY: signal 0 only checks existence.
|
||||
unsafe { libc::kill(pid as i32, 0) == 0 || *libc::__errno_location() == libc::EPERM }
|
||||
}
|
||||
|
||||
pub fn kill_group(pgid: u32) {
|
||||
// SAFETY: plain syscall; hx is spawned with process_group(0) so pgid == its pid.
|
||||
unsafe { libc::killpg(pgid as i32, libc::SIGKILL) };
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn sample(id: &str, pid: u32) -> Run {
|
||||
Run {
|
||||
id: id.into(),
|
||||
title: "t".into(),
|
||||
profile: "p".into(),
|
||||
repo: "/r".into(),
|
||||
branch: "b".into(),
|
||||
worktree: "/w".into(),
|
||||
status: Status::Running,
|
||||
reason: None,
|
||||
orch_pid: pid,
|
||||
hx_pid: None,
|
||||
started: 1,
|
||||
ended: None,
|
||||
hx_exit: None,
|
||||
gate_exit: None,
|
||||
input_tokens: 0,
|
||||
output_tokens: 0,
|
||||
session: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn roundtrip_and_stale_detection() {
|
||||
let d = std::env::temp_dir().join(format!("orch-state-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
// SAFETY: single test touching this var; other tests in this binary do not read it.
|
||||
unsafe { std::env::set_var("ORCH_STATE_DIR", &d) };
|
||||
let mut c = std::process::Command::new("true").spawn().unwrap();
|
||||
let dead = c.id();
|
||||
c.wait().unwrap();
|
||||
sample("live", std::process::id()).save().unwrap();
|
||||
sample("dead", dead).save().unwrap();
|
||||
let live = Run::load("live").unwrap();
|
||||
assert_eq!(live.status, Status::Running);
|
||||
let dead = Run::load("dead").unwrap();
|
||||
assert_eq!(
|
||||
(dead.status, dead.reason.as_deref()),
|
||||
(Status::Failed, Some("interrupted"))
|
||||
);
|
||||
assert_eq!(Run::list().unwrap().len(), 2);
|
||||
assert!(Run::load("../x").is_err());
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user