use super::tests::{task, test_store};
use super::*;
use crate::traits::*;
use std::sync::Arc;
async fn occurrence_fixture(
one_shot: bool,
) -> (
SqliteWorkStore,
tempfile::NamedTempFile,
Goal,
GoalSchedule,
Task,
) {
let (store, file) = test_store().await;
let goal = Goal::new_continuous("Synthetic occurrence", "synthetic-session", None, None);
store.create_goal(&goal).await.unwrap();
let now = chrono::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: "always_fire".into(),
is_one_shot: one_shot,
is_paused: false,
last_run_at: None,
next_run_at: now.clone(),
created_at: now.clone(),
updated_at: now,
};
store.create_goal_schedule(&schedule).await.unwrap();
let root = task(&goal.id, "Synthetic root", None);
(store, file, goal, schedule, root)
}
#[tokio::test]
async fn schedule_occurrence_cas_loss_fires_nothing() {
let (store, _file, goal, schedule, root) = occurrence_fixture(false).await;
let next = (chrono::Utc::now() + chrono::Duration::days(1)).to_rfc3339();
let run = store
.enqueue_scheduled_occurrence(&schedule, &next, &goal, &root, None)
.await
.unwrap()
.unwrap();
let fresh_goal = store.get_goal(&goal.id).await.unwrap().unwrap();
let other = task(&goal.id, "Another root", None);
assert!(
store
.enqueue_scheduled_occurrence(&schedule, &next, &fresh_goal, &other, None)
.await
.unwrap()
.is_none()
);
assert_eq!(store.get_goal_runs(&goal.id).await.unwrap().len(), 1);
assert_eq!(
store.get_tasks_for_goal_run(&run.id).await.unwrap().len(),
1
);
assert!(store.get_task(&other.id).await.unwrap().is_none());
}
#[tokio::test]
async fn schedule_occurrence_task_failure_rolls_back_every_write() {
for one_shot in [false, true] {
let (store, _file, goal, schedule, root) = occurrence_fixture(one_shot).await;
sqlx::query("CREATE TRIGGER reject_root BEFORE INSERT ON tasks BEGIN SELECT RAISE(ABORT, 'synthetic task failure'); END")
.execute(&store.pool).await.unwrap();
let next = (chrono::Utc::now() + chrono::Duration::days(1)).to_rfc3339();
assert!(
store
.enqueue_scheduled_occurrence(&schedule, &next, &goal, &root, None)
.await
.is_err()
);
let saved = store
.get_goal_schedule(&schedule.id)
.await
.unwrap()
.unwrap();
assert_eq!(saved.next_run_at, schedule.next_run_at);
assert_eq!(saved.last_run_at, None);
assert!(store.get_goal_runs(&goal.id).await.unwrap().is_empty());
assert_eq!(
store
.get_goal(&goal.id)
.await
.unwrap()
.unwrap()
.last_useful_action,
goal.last_useful_action
);
}
}
#[tokio::test]
async fn schedule_occurrence_one_shot_consumed_with_run_and_root() {
let (store, _file, goal, schedule, root) = occurrence_fixture(true).await;
let run = store
.enqueue_scheduled_occurrence(&schedule, &schedule.next_run_at, &goal, &root, None)
.await
.unwrap()
.unwrap();
assert!(
store
.get_goal_schedule(&schedule.id)
.await
.unwrap()
.is_none()
);
assert_eq!(run.root_task_id.as_deref(), Some(root.id.as_str()));
assert_eq!(
store.get_tasks_for_goal_run(&run.id).await.unwrap()[0].id,
root.id
);
assert!(
store
.enqueue_scheduled_occurrence(&schedule, &schedule.next_run_at, &goal, &root, None)
.await
.unwrap()
.is_none()
);
}
#[tokio::test]
async fn schedule_occurrence_rechecks_pause_and_backpressure() {
let (store, _file, goal, mut schedule, root) = occurrence_fixture(false).await;
schedule.fire_policy = "coalesce".into();
store.update_goal_schedule(&schedule).await.unwrap();
let mut paused = schedule.clone();
paused.is_paused = true;
store.update_goal_schedule(&paused).await.unwrap();
assert!(
store
.enqueue_scheduled_occurrence(&schedule, &schedule.next_run_at, &goal, &root, None)
.await
.unwrap()
.is_none()
);
store.update_goal_schedule(&schedule).await.unwrap();
store
.create_task(&task(&goal.id, "Existing work", None))
.await
.unwrap();
assert!(
store
.enqueue_scheduled_occurrence(&schedule, &schedule.next_run_at, &goal, &root, None)
.await
.unwrap()
.is_none()
);
}
#[tokio::test]
async fn goal_run_empty_pending_boot_repair_allows_next_schedule() {
for trigger in ["manual", "scheduled"] {
let (store, _file, goal, schedule, root) = occurrence_fixture(false).await;
let orphan = store
.start_goal_run(&goal.id, trigger, Some(&schedule.id), None)
.await
.unwrap();
sqlx::query("UPDATE goal_runs SET created_at = '2000-01-01T00:00:00Z' WHERE id = ?")
.bind(&orphan.id)
.execute(&store.pool)
.await
.unwrap();
store
.expire_attempts_of_previous_instance("2001-01-01T00:00:00Z")
.await
.unwrap();
let repaired = store.get_goal_runs(&goal.id).await.unwrap().remove(0);
assert_eq!(repaired.status, crate::goals::GOAL_RUN_INTERRUPTED);
assert_eq!(
serde_json::from_str::<serde_json::Value>(repaired.outcome_summary.as_deref().unwrap())
.unwrap()["reason"],
"previous_instance_stopped_before_task_creation"
);
assert!(
store
.get_current_goal_run(&goal.id)
.await
.unwrap()
.is_none()
);
let run = store
.enqueue_scheduled_occurrence(&schedule, &schedule.next_run_at, &goal, &root, None)
.await
.unwrap()
.unwrap();
assert_ne!(run.id, orphan.id);
store
.expire_attempts_of_previous_instance("2100-01-01T00:00:00Z")
.await
.unwrap();
assert_eq!(
store
.get_current_goal_run(&goal.id)
.await
.unwrap()
.unwrap()
.id,
run.id
);
}
}
#[tokio::test]
async fn goal_run_empty_pending_current_process_is_not_repaired() {
let (store, _file, goal, _, _) = occurrence_fixture(false).await;
let run = store
.start_goal_run(&goal.id, "manual", None, None)
.await
.unwrap();
store
.expire_attempts_of_previous_instance("2000-01-01T00:00:00Z")
.await
.unwrap();
assert_eq!(
store
.get_current_goal_run(&goal.id)
.await
.unwrap()
.unwrap()
.id,
run.id
);
}
#[tokio::test]
async fn scheduler_reminder_delivery_failure_keeps_durable_root() {
struct Presenter;
impl crate::scheduler::WorkPresenter for Presenter {
fn goal_label(&self, text: &str) -> String {
text.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>, text: &str) -> String {
text.into()
}
}
let (store, _file, mut goal, schedule, _) = occurrence_fixture(true).await;
goal.context = Some(crate::reminders::context_for_message("Synthetic reminder"));
store.update_goal(&goal).await.unwrap();
let state = Arc::new(store);
let cycle = crate::scheduler::GoalCycle::new(state.clone(), Arc::new(Presenter), None);
cycle.fire_due_schedule(schedule.clone()).await.unwrap();
assert!(
state
.get_goal_schedule(&schedule.id)
.await
.unwrap()
.is_none()
);
let run = state.get_current_goal_run(&goal.id).await.unwrap().unwrap();
let tasks = state.get_tasks_for_goal_run(&run.id).await.unwrap();
assert_eq!(tasks.len(), 1);
assert_eq!(tasks[0].status, "pending");
assert_eq!(run.root_task_id.as_deref(), Some(tasks[0].id.as_str()));
}
#[tokio::test]
async fn schedule_occurrence_rechecks_budget_and_confirmation() {
let (store, _file, goal, schedule, root) = occurrence_fixture(false).await;
let mut changed = goal.clone();
changed.status = "pending_confirmation".into();
store.update_goal(&changed).await.unwrap();
assert!(
store
.enqueue_scheduled_occurrence(&schedule, &schedule.next_run_at, &goal, &root, None)
.await
.unwrap()
.is_none()
);
changed.status = "active".into();
changed.budget_daily = Some(10);
changed.tokens_used_today = 10;
changed.tokens_used_day = chrono::Utc::now().date_naive().to_string();
store.update_goal(&changed).await.unwrap();
assert!(
store
.enqueue_scheduled_occurrence(&schedule, &schedule.next_run_at, &goal, &root, None)
.await
.unwrap()
.is_none()
);
assert!(
store
.enqueue_scheduled_occurrence(
&schedule,
&schedule.next_run_at,
&changed,
&root,
Some(10)
)
.await
.unwrap()
.is_none()
);
assert!(store.get_goal_runs(&goal.id).await.unwrap().is_empty());
assert_eq!(
store
.get_goal_schedule(&schedule.id)
.await
.unwrap()
.unwrap()
.last_run_at,
None
);
}
#[tokio::test]
async fn scheduled_restart_replay_once_keeps_run_pending() {
let (store, _file, goal, schedule, mut root) = occurrence_fixture(false).await;
root.idempotent = false;
root.max_retries = 0;
let next = (chrono::Utc::now() + chrono::Duration::days(1)).to_rfc3339();
let run = store
.enqueue_scheduled_occurrence(&schedule, &next, &goal, &root, None)
.await
.unwrap()
.unwrap();
let attempt = store
.claim_task_with_lease(&root.id, "synthetic-worker", None, 180)
.await
.unwrap()
.unwrap();
assert!(
store
.scheduled_restart_replay_candidates()
.await
.unwrap()
.is_empty()
);
assert!(
!store
.replay_effect_free_scheduled_attempt(&attempt.id)
.await
.unwrap()
);
let boot = (chrono::Utc::now() + chrono::Duration::seconds(1)).to_rfc3339();
store
.expire_attempts_of_previous_instance(&boot)
.await
.unwrap();
assert_eq!(
store.scheduled_restart_replay_candidates().await.unwrap(),
vec![(attempt.id.clone(), run.id.clone())]
);
assert!(
store
.replay_effect_free_scheduled_attempt(&attempt.id)
.await
.unwrap()
);
assert!(
store
.recover_expired_task_attempts()
.await
.unwrap()
.is_empty()
);
let replay = store.get_task(&root.id).await.unwrap().unwrap();
assert_eq!(replay.status, "pending");
assert_eq!(replay.retry_count, 1);
assert!(!replay.idempotent);
assert_eq!(
store.get_goal_runs(&goal.id).await.unwrap()[0].status,
"pending"
);
let second = store
.claim_task_with_lease(&root.id, "synthetic-worker", None, 180)
.await
.unwrap()
.unwrap();
assert_ne!(second.id, attempt.id);
store
.expire_attempts_of_previous_instance(&boot)
.await
.unwrap();
assert!(
store
.scheduled_restart_replay_candidates()
.await
.unwrap()
.is_empty()
);
assert!(
!store
.replay_effect_free_scheduled_attempt(&second.id)
.await
.unwrap()
);
store.recover_expired_task_attempts().await.unwrap();
assert_eq!(
store.get_task(&root.id).await.unwrap().unwrap().status,
"blocked"
);
}
#[tokio::test]
async fn scheduled_restart_replay_excludes_ordinary_lease_expiry() {
let (store, _file, goal, schedule, mut root) = occurrence_fixture(false).await;
root.idempotent = false;
root.max_retries = 0;
let next = (chrono::Utc::now() + chrono::Duration::days(1)).to_rfc3339();
store
.enqueue_scheduled_occurrence(&schedule, &next, &goal, &root, None)
.await
.unwrap()
.unwrap();
let attempt = store
.claim_task_with_lease(&root.id, "synthetic-worker", None, 180)
.await
.unwrap()
.unwrap();
sqlx::query(
"UPDATE task_attempts SET lease_expires_at = datetime('now', '-1 second') WHERE id = ?",
)
.bind(&attempt.id)
.execute(&store.pool)
.await
.unwrap();
assert!(
store
.scheduled_restart_replay_candidates()
.await
.unwrap()
.is_empty()
);
assert!(
!store
.replay_effect_free_scheduled_attempt(&attempt.id)
.await
.unwrap()
);
store.recover_expired_task_attempts().await.unwrap();
assert_eq!(
store.get_task(&root.id).await.unwrap().unwrap().status,
"blocked"
);
}