use super::*;
use crate::sqlite::{SqliteWorkStore, open_for_tests};
use crate::traits::*;
impl aidaemon_tools::services::SettingsStore for SqliteWorkStore {}
struct Presenter;
impl WorkPresenter for Presenter {
fn goal_label(&self, description: &str) -> String {
description.into()
}
fn user_facing(&self, text: &str) -> String {
text.into()
}
fn notification(&self, _: &str, text: &str) -> String {
text.into()
}
fn goal_task_results(&self, _: &[Task], _: Option<&str>, fallback: &str) -> String {
fallback.into()
}
}
async fn fixture(
state: &SqliteWorkStore,
trigger: &str,
run_status: &str,
task_status: &str,
consumed: bool,
) -> (Goal, GoalRun, GoalSchedule) {
let goal = Goal::new_continuous(
"Synthetic scheduled objective",
"synthetic-session",
None,
None,
);
state.create_goal(&goal).await.unwrap();
let now = Utc::now().to_rfc3339();
let schedule = GoalSchedule {
id: uuid::Uuid::new_v4().to_string(),
goal_id: goal.id.clone(),
cron_expr: "0 6 * * *".into(),
tz: "UTC".into(),
original_schedule: None,
fire_policy: "coalesce".into(),
is_one_shot: consumed,
is_paused: false,
last_run_at: Some(now.clone()),
next_run_at: (Utc::now() + chrono::Duration::days(1)).to_rfc3339(),
created_at: now.clone(),
updated_at: now.clone(),
};
state.create_goal_schedule(&schedule).await.unwrap();
let task = Task {
id: uuid::Uuid::new_v4().to_string(),
goal_id: goal.id.clone(),
description: "Synthetic root task".into(),
status: task_status.into(),
priority: "normal".into(),
task_order: 0,
parallel_group: None,
depends_on: None,
agent_id: None,
context: None,
result: (task_status == "completed").then(|| "Synthetic result".into()),
error: (task_status == "failed").then(|| "Synthetic failure".into()),
blocker: None,
idempotent: true,
retry_count: 0,
max_retries: 1,
created_at: now.clone(),
started_at: Some(now.clone()),
completed_at: Some(now),
};
let run = state
.start_goal_run(&goal.id, trigger, Some(&schedule.id), Some(&task.id))
.await
.unwrap();
state.create_task(&task).await.unwrap();
sqlx::query("UPDATE goal_runs SET status = ? WHERE id = ?")
.bind(run_status)
.bind(&run.id)
.execute(&state.pool())
.await
.unwrap();
if consumed {
assert!(state.delete_goal_schedule(&schedule.id).await.unwrap());
}
(goal, run, schedule)
}
#[tokio::test]
async fn consumed_one_shot_reconciliation_closes_completed_and_failed_roots() {
for trigger in ["scheduled", "manual", "recovery"] {
for run_status in ["pending", "running"] {
for outcome in ["completed", "failed"] {
let db = tempfile::NamedTempFile::new().unwrap();
let state = Arc::new(open_for_tests(db.path().to_str().unwrap()).await);
let cycle = GoalCycle::new(state.clone(), Arc::new(Presenter), None);
let (goal, run, _) = fixture(&state, trigger, run_status, outcome, true).await;
assert!(state.get_scheduled_goals().await.unwrap().is_empty());
let candidates = state.get_goals_with_open_scheduled_runs().await.unwrap();
assert_eq!(candidates.len(), 1);
assert_eq!(candidates[0].id, goal.id);
cycle.reconcile_open_scheduled_runs().await;
let runs = state.get_goal_runs(&goal.id).await.unwrap();
assert_eq!(runs.len(), 1);
assert_eq!(runs[0].id, run.id);
assert_eq!(runs[0].status, outcome, "{trigger}/{run_status}");
assert!(runs[0].completed_at.is_some());
assert!(
state
.get_goals_with_open_scheduled_runs()
.await
.unwrap()
.is_empty()
);
}
}
}
}
#[tokio::test]
async fn consumed_one_shot_reconciliation_excludes_other_lifecycles() {
let db = tempfile::NamedTempFile::new().unwrap();
let state = Arc::new(open_for_tests(db.path().to_str().unwrap()).await);
let cycle = GoalCycle::new(state.clone(), Arc::new(Presenter), None);
for (trigger, status) in [
("mandate", "pending"),
("mandate", "running"),
("finite", "pending"),
("legacy", "running"),
("scheduled", "blocked"),
("scheduled", "completed"),
("scheduled", "failed"),
("scheduled", "cancelled"),
] {
let (goal, _, _) = fixture(&state, trigger, status, "completed", true).await;
assert!(
state
.get_goals_with_open_scheduled_runs()
.await
.unwrap()
.is_empty()
);
cycle.reconcile_open_scheduled_runs().await;
assert_eq!(
state.get_goal_runs(&goal.id).await.unwrap()[0].status,
status
);
}
}
#[tokio::test]
async fn scheduled_reconciliation_preserves_recurring_schedule_and_closes_run_once() {
let db = tempfile::NamedTempFile::new().unwrap();
let state = Arc::new(open_for_tests(db.path().to_str().unwrap()).await);
let (goal, _, schedule) = fixture(&state, "scheduled", "running", "completed", false).await;
assert_eq!(state.get_scheduled_goals().await.unwrap().len(), 1);
assert_eq!(
state
.get_goals_with_open_scheduled_runs()
.await
.unwrap()
.len(),
1
);
sqlx::query("CREATE TABLE reconciliation_updates (run_id TEXT)")
.execute(&state.pool())
.await
.unwrap();
sqlx::query(
"CREATE TRIGGER count_reconciliation AFTER UPDATE OF status ON goal_runs
BEGIN INSERT INTO reconciliation_updates VALUES (NEW.id); END",
)
.execute(&state.pool())
.await
.unwrap();
let cycle = GoalCycle::new(state.clone(), Arc::new(Presenter), None);
cycle.reconcile_open_scheduled_runs().await;
cycle.reconcile_open_scheduled_runs().await;
let updates: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM reconciliation_updates")
.fetch_one(&state.pool())
.await
.unwrap();
assert_eq!(updates, 1);
assert_eq!(
state.get_goal_runs(&goal.id).await.unwrap()[0].status,
"completed"
);
let kept = state
.get_goal_schedule(&schedule.id)
.await
.unwrap()
.unwrap();
assert_eq!(kept.next_run_at, schedule.next_run_at);
assert!(!kept.is_one_shot);
assert_eq!(state.get_scheduled_goals().await.unwrap().len(), 1);
}
#[tokio::test]
async fn a_held_review_failure_notice_is_dropped_once_a_later_review_finishes() {
let database = tempfile::NamedTempFile::new().unwrap();
let state = Arc::new(open_for_tests(database.path().to_str().unwrap()).await);
let cycle = GoalCycle::new(state.clone(), Arc::new(Presenter), None);
let recovered = Goal::new_continuous(
"Synthetic watched objective",
"synthetic-session",
None,
None,
);
let still_failing = Goal::new_continuous(
"Synthetic second objective",
"synthetic-session",
None,
None,
);
state.create_goal(&recovered).await.unwrap();
state.create_goal(&still_failing).await.unwrap();
let mut stale = NotificationEntry::new(
&recovered.id,
"synthetic-session",
"mandate_review_failed",
"A review was interrupted before it decided anything.",
);
stale.created_at = (Utc::now() - chrono::Duration::hours(8)).to_rfc3339();
state.enqueue_notification(&stale).await.unwrap();
let mut current = NotificationEntry::new(
&still_failing.id,
"synthetic-session",
"mandate_review_failed",
"A review was interrupted before it decided anything.",
);
current.created_at = stale.created_at.clone();
state.enqueue_notification(¤t).await.unwrap();
let run = state
.start_goal_run(&recovered.id, "mandate", None, None)
.await
.unwrap();
state
.finish_goal_run(&run.id, "completed", Some("mandate_act_satisfied"))
.await
.unwrap();
cycle.process_notification_queue().await;
let pending: Vec<String> = state
.get_pending_notifications(10)
.await
.unwrap()
.into_iter()
.map(|entry| entry.id)
.collect();
assert!(!pending.contains(&stale.id), "{pending:?}");
assert!(pending.contains(¤t.id), "{pending:?}");
}
struct RestartProofHost {
effect_free: bool,
expected_tasks: Vec<String>,
expected_sessions: Vec<String>,
}
#[async_trait]
impl TaskLeadHost for RestartProofHost {
fn available(&self) -> bool {
true
}
async fn task_tree_is_effect_free(
&self,
tasks: &[String],
run_sessions: &[String],
) -> anyhow::Result<bool> {
let mut actual = tasks.to_vec();
actual.sort();
let mut expected = self.expected_tasks.clone();
expected.sort();
assert_eq!(actual, expected);
assert_eq!(run_sessions, self.expected_sessions.as_slice());
Ok(self.effect_free)
}
fn spawn_task_lead(&self, _: Goal, _: String, _: String, _: Option<String>) {
panic!("startup recovery must not dispatch");
}
fn next_model_answer_at(&self) -> Option<SystemTime> {
None
}
async fn retry_deferred_provider_requests(&self) -> usize {
0
}
async fn tainted_note_turn(&self, _: &str) -> anyhow::Result<String> {
unreachable!()
}
async fn record_parent_visible_result_note_in_turn(
&self,
_: &str,
_: &str,
_: &str,
_: Option<&str>,
) -> anyhow::Result<()> {
unreachable!()
}
async fn record_mandate_owner_input_context(
&self,
_: &str,
_: &str,
_: i64,
_: &str,
) -> anyhow::Result<()> {
unreachable!()
}
}
#[tokio::test]
async fn scheduled_restart_replay_startup_requires_tree_proof_and_preserves_children() {
for effect_free in [true, false] {
let db = tempfile::NamedTempFile::new().unwrap();
let state = Arc::new(open_for_tests(db.path().to_str().unwrap()).await);
let (goal, run, _) = fixture(&state, "scheduled", "pending", "pending", false).await;
let root_id = run.root_task_id.as_deref().unwrap();
let mut root = state.get_task(root_id).await.unwrap().unwrap();
root.idempotent = false;
root.max_retries = 0;
state.update_task(&root).await.unwrap();
let mut child = root.clone();
child.id = uuid::Uuid::new_v4().to_string();
child.task_order = 1;
state.create_task(&child).await.unwrap();
for task in [&root, &child] {
state
.claim_task_with_lease(&task.id, "synthetic-worker", None, 180)
.await
.unwrap()
.unwrap();
}
let mut cycle = GoalCycle::new(state.clone(), Arc::new(Presenter), None);
cycle.set_agent(Some(Arc::new(RestartProofHost {
effect_free,
expected_tasks: vec![root.id.clone(), child.id.clone()],
expected_sessions: vec!["synthetic-worker".to_string()],
})));
cycle.set_booted_at((Utc::now() + chrono::Duration::seconds(1)).to_rfc3339());
cycle.startup_recovery().await;
for task in [&root, &child] {
assert_eq!(
state.get_task(&task.id).await.unwrap().unwrap().status,
if effect_free { "pending" } else { "blocked" }
);
}
if effect_free {
cycle.reconcile_open_scheduled_runs().await;
let runs = state.get_goal_runs(&goal.id).await.unwrap();
assert_eq!(runs.len(), 1);
assert_eq!(runs[0].id, run.id);
assert_eq!(runs[0].status, "pending");
assert!(runs[0].completed_at.is_none());
}
}
}
struct ResumeProofHost {
settled: bool,
}
const SYNTHETIC_SUMMARY: &str = "- wrote /synthetic/post.md (write_file): done";
#[async_trait]
impl TaskLeadHost for ResumeProofHost {
fn available(&self) -> bool {
true
}
async fn task_tree_is_effect_free(&self, _: &[String], _: &[String]) -> anyhow::Result<bool> {
Ok(false)
}
async fn task_tree_changes_settled(&self, _: &[String], _: &[String]) -> anyhow::Result<bool> {
Ok(self.settled)
}
async fn restart_resume_summary(
&self,
_: &[String],
_: &[String],
) -> anyhow::Result<Option<String>> {
Ok(Some(SYNTHETIC_SUMMARY.to_string()))
}
fn spawn_task_lead(&self, _: Goal, _: String, _: String, _: Option<String>) {
panic!("startup recovery must not dispatch");
}
fn next_model_answer_at(&self) -> Option<SystemTime> {
None
}
async fn retry_deferred_provider_requests(&self) -> usize {
0
}
async fn tainted_note_turn(&self, _: &str) -> anyhow::Result<String> {
unreachable!()
}
async fn record_parent_visible_result_note_in_turn(
&self,
_: &str,
_: &str,
_: &str,
_: Option<&str>,
) -> anyhow::Result<()> {
unreachable!()
}
async fn record_mandate_owner_input_context(
&self,
_: &str,
_: &str,
_: i64,
_: &str,
) -> anyhow::Result<()> {
unreachable!()
}
}
async fn running_scheduled_root(state: &SqliteWorkStore, mandate: bool) -> (Goal, Task) {
let goal = Goal::new_continuous(
"Synthetic scheduled objective",
"synthetic-session",
None,
None,
);
if mandate {
let mandate = Mandate::new(
&goal.id,
None,
"Observe a bounded synthetic domain",
"synthetic-session",
MandateAuthority::default(),
60,
3_600,
300,
);
state
.create_mandate_controller(&goal, &mandate)
.await
.unwrap();
} else {
state.create_goal(&goal).await.unwrap();
}
let run = state
.start_goal_run(&goal.id, "scheduled", None, None)
.await
.unwrap();
let now = Utc::now().to_rfc3339();
let task = Task {
id: uuid::Uuid::new_v4().to_string(),
goal_id: goal.id.clone(),
description: "Synthetic root task".into(),
status: "pending".into(),
priority: "normal".into(),
task_order: 0,
parallel_group: None,
depends_on: None,
agent_id: None,
context: None,
result: None,
error: None,
blocker: None,
idempotent: false,
retry_count: 0,
max_retries: 0,
created_at: now.clone(),
started_at: None,
completed_at: None,
};
state.create_task(&task).await.unwrap();
sqlx::query("UPDATE goal_runs SET root_task_id = ? WHERE id = ?")
.bind(&task.id)
.bind(&run.id)
.execute(&state.pool())
.await
.unwrap();
state
.claim_task_with_lease(&task.id, "synthetic-worker", None, 180)
.await
.unwrap()
.unwrap();
(goal, task)
}
async fn boot(state: &Arc<SqliteWorkStore>, settled: bool) {
let mut cycle = GoalCycle::new(state.clone(), Arc::new(Presenter), None);
cycle.set_agent(Some(Arc::new(ResumeProofHost { settled })));
cycle.set_booted_at((Utc::now() + chrono::Duration::seconds(1)).to_rfc3339());
cycle.startup_recovery().await;
}
fn journal_kinds(journal: &[TaskJournalEntry], kind: &str) -> usize {
journal
.iter()
.filter(|entry| entry.entry_type == kind)
.count()
}
#[tokio::test]
async fn requested_stop_journals_the_live_attempt_and_nothing_else() {
let db = tempfile::NamedTempFile::new().unwrap();
let state = Arc::new(open_for_tests(db.path().to_str().unwrap()).await);
let (goal, task) = running_scheduled_root(&state, false).await;
assert_eq!(
state
.journal_live_attempts_stopped_on_request()
.await
.unwrap(),
1
);
let attempt = state
.get_current_task_attempt(&task.id)
.await
.unwrap()
.unwrap();
assert_eq!(attempt.status, "claimed");
let journal = state.get_task_journal(&task.id, 50).await.unwrap();
let marks: Vec<_> = journal
.iter()
.filter(|entry| entry.entry_type == JOURNAL_STOPPED_ON_REQUEST)
.collect();
assert_eq!(marks.len(), 1);
assert_eq!(marks[0].attempt_id.as_deref(), Some(attempt.id.as_str()));
assert_eq!(
state.get_task(&task.id).await.unwrap().unwrap().status,
"claimed"
);
let run = state.get_current_goal_run(&goal.id).await.unwrap().unwrap();
assert_eq!(run.status, "running");
assert!(
state
.get_pending_notifications(10)
.await
.unwrap()
.is_empty()
);
}
#[tokio::test]
async fn requested_stop_resumes_a_settled_scheduled_root_once() {
for (marked, settled, mandate, resumes) in [
(true, true, false, true),
(true, false, false, false),
(false, true, false, false),
(true, true, true, false),
] {
let db = tempfile::NamedTempFile::new().unwrap();
let state = Arc::new(open_for_tests(db.path().to_str().unwrap()).await);
let (_, task) = running_scheduled_root(&state, mandate).await;
if marked {
state
.journal_live_attempts_stopped_on_request()
.await
.unwrap();
}
boot(&state, settled).await;
let root = state.get_task(&task.id).await.unwrap().unwrap();
let journal = state.get_task_journal(&task.id, 50).await.unwrap();
let case = format!("marked={marked} settled={settled} mandate={mandate}");
assert_eq!(root.status == "pending", resumes, "{case}: {}", root.status);
assert_eq!(
journal_kinds(&journal, JOURNAL_RESTART_RESUME),
usize::from(resumes),
"{case}"
);
if !resumes {
continue;
}
let resume = journal
.iter()
.find(|entry| entry.entry_type == JOURNAL_RESTART_RESUME)
.unwrap();
assert_eq!(resume.payload.as_deref(), Some(SYNTHETIC_SUMMARY));
state
.claim_task_with_lease(&task.id, "synthetic-worker-2", None, 180)
.await
.unwrap()
.unwrap();
state
.journal_live_attempts_stopped_on_request()
.await
.unwrap();
boot(&state, true).await;
let root = state.get_task(&task.id).await.unwrap().unwrap();
assert_ne!(root.status, "pending");
let journal = state.get_task_journal(&task.id, 50).await.unwrap();
assert_eq!(journal_kinds(&journal, JOURNAL_RESTART_RESUME), 1);
}
}
#[tokio::test]
async fn requested_stop_resume_holds_after_the_lease_ended_before_boot() {
for settled in [true, false] {
let db = tempfile::NamedTempFile::new().unwrap();
let state = Arc::new(open_for_tests(db.path().to_str().unwrap()).await);
let (_, task) = running_scheduled_root(&state, false).await;
state
.journal_live_attempts_stopped_on_request()
.await
.unwrap();
sqlx::query("UPDATE task_attempts SET lease_expires_at = datetime('now', '-1 hour')")
.execute(&state.pool())
.await
.unwrap();
boot(&state, settled).await;
let journal = state.get_task_journal(&task.id, 50).await.unwrap();
assert_eq!(
journal_kinds(&journal, JOURNAL_PREVIOUS_INSTANCE_STOPPED),
0
);
assert_eq!(
journal_kinds(&journal, JOURNAL_RESTART_RESUME),
usize::from(settled)
);
let root = state.get_task(&task.id).await.unwrap().unwrap();
assert_eq!(
root.status,
if settled { "pending" } else { "blocked" },
"settled={settled}"
);
}
}
#[tokio::test]
async fn requested_stop_resume_requeues_a_cut_off_executor_task() {
let db = tempfile::NamedTempFile::new().unwrap();
let state = Arc::new(open_for_tests(db.path().to_str().unwrap()).await);
let (_, root) = running_scheduled_root(&state, false).await;
let mut child = root.clone();
child.id = uuid::Uuid::new_v4().to_string();
child.task_order = 1;
child.status = "pending".into();
state.create_task(&child).await.unwrap();
state
.claim_task_with_lease(&child.id, "synthetic-executor", None, 180)
.await
.unwrap()
.unwrap();
state
.journal_live_attempts_stopped_on_request()
.await
.unwrap();
boot(&state, true).await;
for task in [&root, &child] {
let task = state.get_task(&task.id).await.unwrap().unwrap();
assert_eq!(task.status, "pending");
assert!(task.error.is_none());
}
}