Skip to content

armgit / kwant

Public Imported from GitHub
0

Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.

Missions: per-server runner slots, and plan() under the checkpoint store lock

Lin (kwant bot)e852b8e597c0
diff --git a/src/server/missions/autofix.rs b/src/server/missions/autofix.rs
index 8c73254e..2e8dc180 100644
--- a/src/server/missions/autofix.rs
+++ b/src/server/missions/autofix.rs
@@ -582,7 +582,7 @@ fn soon(state: &AppState, a: &Attempt) {
/// mission's runner slot is taken.
async fn busy(state: &AppState, task_id: &str) -> bool {
let Ok(Some(task)) = state.db.get_task(task_id).await else { return false };
- if task.mission_id.as_deref().is_some_and(super::runner::is_running) {
+ if task.mission_id.as_deref().is_some_and(|m| super::runner::is_running(state, m)) {
return true;
}
let claim = match state.db.open_claim(task_id).await.ok().flatten() {
@@ -647,7 +647,7 @@ async fn execute(state: &AppState, a: &Attempt) {
}
if let Some(mid) = &task.mission_id {
if let Ok(Some(m)) = state.db.get_mission(mid).await {
- if m.status == "active" && !super::runner::is_running(mid) {
+ if m.status == "active" && !super::runner::is_running(state, mid) {
let _ = super::runner::run_mission(state, &m, 1).await;
}
}
diff --git a/src/server/missions/checkpoints.rs b/src/server/missions/checkpoints.rs
index 0eb0ba61..1e663cd2 100644
--- a/src/server/missions/checkpoints.rs
+++ b/src/server/missions/checkpoints.rs
@@ -44,7 +44,8 @@ pub const NOT_UNDONE: &str = "kwant can't undo these. Check them yourself.";
/// A conflict no task's own calls account for (D11).
pub const OUTSIDE: &str = "changed outside this task";
-/// One snapshot, prune or restore at a time: blob GC never races a snapshot writing blobs.
+/// One snapshot, prune, restore or restore plan at a time: blob GC never races a snapshot writing
+/// blobs, and a plan never sees a checkpoint without its run record.
static STORE: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
pub async fn enabled(state: &AppState) -> bool {
@@ -752,7 +753,10 @@ async fn running(state: &AppState, task: &Task) -> bool {
&& matches!(state.db.open_claim(&task.id).await, Ok(Some(c)) if c.expires_at > crate::db::missions::now_ms())
}
+/// What restoring `c` would do. Holds STORE, so it never reads a run's `after_run` checkpoint
+/// before that run's paths are recorded (`note_run`), which would show no changes.
pub async fn plan(state: &AppState, task: &Task, c: &Checkpoint) -> Result<Plan, PlanError> {
+ let _store = STORE.lock().await;
let Some(manifest) = read_manifest(c) else { return Err(PlanError::NotRestorable) };
let folder = PathBuf::from(&c.folder);
let task_dir = root(state).join(&task.id);
diff --git a/src/server/missions/runner.rs b/src/server/missions/runner.rs
index 57c7ac02..b0cd3c29 100644
--- a/src/server/missions/runner.rs
+++ b/src/server/missions/runner.rs
@@ -7,20 +7,28 @@ use crate::db::missions::{ClaimRefused, Mission, Task, TaskChange};
use crate::server::routes::{scope_for, turn_once, TurnOpts};
use crate::server::AppState;
use std::collections::HashSet;
-use std::sync::{LazyLock, Mutex};
+use std::sync::{Arc, Mutex};
pub const MAX_RUNNING: usize = 2;
pub const PURPOSE: &str = "mission";
-/// Missions with a runner turn going.
-static RUNNING: LazyLock<Mutex<HashSet<String>>> = LazyLock::new(|| Mutex::new(HashSet::new()));
+/// Missions with a runner turn going, one set per server (`AppState::mission_runs`), so two
+/// servers in one process (as tests run them) never take each other's slots.
+#[derive(Default)]
+pub struct RunningMissions(Mutex<HashSet<String>>);
+
+impl RunningMissions {
+ fn set(&self) -> std::sync::MutexGuard<'_, HashSet<String>> {
+ self.0.lock().unwrap_or_else(|e| e.into_inner())
+ }
+}
/// Holds a mission's runner slot; frees it when dropped.
-struct Slot(String);
+struct Slot(Arc<RunningMissions>, String);
impl Slot {
- fn take(mission_id: &str) -> Result<Slot, &'static str> {
- let mut set = RUNNING.lock().unwrap_or_else(|e| e.into_inner());
+ fn take(running: &Arc<RunningMissions>, mission_id: &str) -> Result<Slot, &'static str> {
+ let mut set = running.set();
if set.contains(mission_id) {
return Err("a runner turn is already going for this mission");
}
@@ -28,18 +36,18 @@ impl Slot {
return Err("two missions are already running; it starts when one finishes");
}
set.insert(mission_id.to_string());
- Ok(Slot(mission_id.to_string()))
+ Ok(Slot(running.clone(), mission_id.to_string()))
}
}
impl Drop for Slot {
fn drop(&mut self) {
- RUNNING.lock().unwrap_or_else(|e| e.into_inner()).remove(&self.0);
+ self.0.set().remove(&self.1);
}
}
-pub fn is_running(mission_id: &str) -> bool {
- RUNNING.lock().unwrap_or_else(|e| e.into_inner()).contains(mission_id)
+pub fn is_running(state: &AppState, mission_id: &str) -> bool {
+ state.mission_runs.set().contains(mission_id)
}
/// One scheduler tick: leases that ran out go back to ready, then each active mission without a
@@ -56,7 +64,7 @@ pub async fn tick(state: &AppState) {
for m in state.db.active_missions().await.unwrap_or_default() {
// Evidence drift, at most every 10 minutes per mission (Phase B1)
super::graph::scan_if_due(state, &m).await;
- if is_running(&m.id) {
+ if is_running(state, &m.id) {
continue;
}
let _ = run_mission(state, &m, 1).await;
@@ -66,7 +74,7 @@ pub async fn tick(state: &AppState) {
/// Starts runner turns for up to `max` ready tasks of `mission` (one at a time, in the
/// background). Returns `(task_id, kwant_id)` of each started, and why none were if so.
pub async fn run_mission(state: &AppState, mission: &Mission, max: usize) -> (Vec<(String, String)>, Option<String>) {
- let slot = match Slot::take(&mission.id) {
+ let slot = match Slot::take(&state.mission_runs, &mission.id) {
Ok(s) => s,
Err(why) => return (Vec::new(), Some(why.into())),
};
@@ -226,3 +234,20 @@ pub async fn after_turn(state: &AppState, task_id: &str, err: Option<&str>, star
(None, None) => super::autofix::record(state, task_id, "turn", "stalled", "", "the runner turn ended without a review").await,
};
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn slots_are_per_server_and_freed_when_dropped() {
+ let (a, b) = (Arc::new(RunningMissions::default()), Arc::new(RunningMissions::default()));
+ let (one, _two) = (Slot::take(&a, "m1").unwrap(), Slot::take(&a, "m2").unwrap());
+ assert!(Slot::take(&a, "m1").err().unwrap().contains("already going"));
+ assert!(Slot::take(&a, "m3").err().unwrap().contains("two missions"));
+ // Another server's missions don't count against this one's
+ assert!(Slot::take(&b, "m3").is_ok());
+ drop(one);
+ assert!(Slot::take(&a, "m3").is_ok());
+ }
+}
diff --git a/src/server/mod.rs b/src/server/mod.rs
index 75f9dc80..a28e2afe 100644
--- a/src/server/mod.rs
+++ b/src/server/mod.rs
@@ -115,6 +115,8 @@ pub struct AppState {
pub push: Arc<push::Push>,
/// The Mac app's in-app update; unsupported (and never changing) anywhere else.
pub app_update: Arc<crate::app_update::UpdateHub>,
+ /// Missions with a runner turn going (at most `missions::runner::MAX_RUNNING`).
+ pub mission_runs: Arc<missions::runner::RunningMissions>,
}
impl AppState {
@@ -163,6 +165,7 @@ impl AppState {
setup: Default::default(),
push: Arc::new(push::Push::load(&config_data_dir)),
app_update: crate::app_update::UpdateHub::shared(),
+ mission_runs: Arc::default(),
}
}
diff --git a/tests/mission_autofix_test.rs b/tests/mission_autofix_test.rs
index 79ad70ba..72e83106 100644
--- a/tests/mission_autofix_test.rs
+++ b/tests/mission_autofix_test.rs
@@ -259,9 +259,9 @@ async fn cli_mission(e: &Env, budget: i64) -> (String, String) {
}
/// Waits until the mission's runner turn is over and its spend has landed.
-async fn runner_idle(mid: &str) {
+async fn runner_idle(state: &AppState, mid: &str) {
for _ in 0..300 {
- if !runner::is_running(mid) {
+ if !runner::is_running(state, mid) {
break;
}
tokio::time::sleep(Duration::from_millis(50)).await;
@@ -337,7 +337,7 @@ async fn a_failing_check_is_retried_with_its_diagnostics_until_the_attempts_run_
}
tokio::time::sleep(Duration::from_millis(50)).await;
}
- runner_idle(&mid).await;
+ runner_idle(&e.state, &mid).await;
let t = task(&e, &tid).await;
assert_eq!((t["state"].as_str(), t["attempts"].as_i64()), (Some("failed"), Some(3)), "{t}");
let fs = failures(&e, &tid).await;
@@ -430,7 +430,7 @@ async fn a_retry_over_the_recovery_budget_is_skipped_and_only_autofix_turns_coun
}
tokio::time::sleep(Duration::from_millis(50)).await;
}
- runner_idle(&mid).await;
+ runner_idle(&e.state, &mid).await;
let t = task(&e, &tid).await;
// The first turn was a plain run: none of it is recovery; the AutoFix retry's turn is
assert_eq!(t["spent_tokens"], 2 * PER_TURN, "{t}");
diff --git a/tests/mission_checkpoints_test.rs b/tests/mission_checkpoints_test.rs
index 28d6b22a..6cb4e50d 100644
--- a/tests/mission_checkpoints_test.rs
+++ b/tests/mission_checkpoints_test.rs
@@ -247,7 +247,7 @@ async fn cli_bot(e: &Env) -> String {
async fn cli_run(e: &Env, mid: &str, tid: &str) {
// An earlier runner turn of this mission may still be ending after its hand-in
for _ in 0..200 {
- if !kwnt::server::missions::runner::is_running(mid) {
+ if !kwnt::server::missions::runner::is_running(&e.state, mid) {
break;
}
tokio::time::sleep(Duration::from_millis(50)).await;