| 1 | use super::*; |
| 2 | |
| 3 | /// A schedule that went five owed slots behind produces one catch-up run for |
| 4 | /// the oldest owed slot and resumes on the next future grid slot — it must |
| 5 | /// not replay one stale slot per tick. |
| 6 | #[tokio::test] |
| 7 | async fn overdue_recurring_schedule_coalesces_to_one_catch_up_run() -> Result<()> { |
| 8 | let root = tempfile::tempdir()?; |
| 9 | let receipts = root.path().join("executions"); |
| 10 | let tasks = fixture_tasks(&root.path().join("tasks"), &receipts).await?; |
| 11 | let manager = AutomationManager::open_for_test(root.path().join("automations"))?; |
| 12 | let mut automation = automation_record_with_settings(None, None, None, None); |
| 13 | automation.id = "overdue".into(); |
| 14 | let first_due = Utc::now() - Duration::hours(5) - Duration::minutes(3); |
| 15 | automation.next_run_at = Some(first_due); |
| 16 | manager.save_automation(&automation)?; |
| 17 | let shared = Arc::new(Mutex::new(manager)); |
| 18 | |
| 19 | scheduler_tick_shared(&shared, &tasks).await?; |
| 20 | let bound_id = { |
| 21 | let manager = shared.lock().await; |
| 22 | let runs = manager.list_runs(&automation.id, None)?; |
| 23 | assert_eq!(runs.len(), 1, "one catch-up run, not one per missed slot"); |
| 24 | assert_eq!( |
| 25 | runs[0].scheduled_for, first_due, |
| 26 | "the receipt owns the oldest owed slot" |
| 27 | ); |
| 28 | let updated = manager.get_automation(&automation.id)?; |
| 29 | let next = updated |
| 30 | .next_run_at |
| 31 | .context("an hourly schedule keeps a future slot")?; |
| 32 | let now = Utc::now(); |
| 33 | assert!( |
| 34 | next > now && next <= now + Duration::hours(1), |
| 35 | "advance must land on the *first* future grid slot, got {next}" |
| 36 | ); |
| 37 | // Unanchored HOURLY keeps its established grid — minute-truncated |
| 38 | // owed slot plus exact interval multiples — never re-phased to the |
| 39 | // recovery instant. |
| 40 | let grid = first_due |
| 41 | .with_second(0) |
| 42 | .and_then(|t| t.with_nanosecond(0)) |
| 43 | .context("minute truncation")?; |
| 44 | assert_eq!( |
| 45 | (next - grid).num_seconds() % Duration::hours(1).num_seconds(), |
| 46 | 0, |
| 47 | "resume slot left the established hourly grid" |
| 48 | ); |
| 49 | runs[0].task_id.clone().context("bound task id")? |
| 50 | }; |
| 51 | let task = crate::task_manager::wait_for_terminal_state( |
| 52 | &tasks, |
| 53 | &bound_id, |
| 54 | std::time::Duration::from_secs(10), |
| 55 | ) |
| 56 | .await?; |
| 57 | assert_eq!(task.status, TaskStatus::Completed); |
| 58 | reconcile_run_statuses_shared(&shared, &tasks).await?; |
| 59 | scheduler_tick_shared(&shared, &tasks).await?; |
| 60 | assert_eq!( |
| 61 | fixture_executions(&receipts), |
| 62 | vec![bound_id], |
| 63 | "the backlog produced exactly one execution" |
| 64 | ); |
| 65 | assert_eq!( |
| 66 | shared.lock().await.list_runs(&automation.id, None)?.len(), |
| 67 | 1 |
| 68 | ); |
| 69 | tasks.shutdown(); |
| 70 | Ok(()) |
| 71 | } |
| 72 | |
| 73 | /// A weekly slot owed three weeks over collapses to the upcoming calendar |
| 74 | /// slot — same weekday and wall time — rather than replaying each missed |
| 75 | /// Monday. |
| 76 | #[test] |
| 77 | fn overdue_weekly_slots_coalesce_to_the_next_calendar_slot() { |
| 78 | let schedule = AutomationSchedule::parse_rrule("FREQ=WEEKLY;BYDAY=MO;BYHOUR=9;BYMINUTE=30") |
| 79 | .expect("weekly schedule parses"); |
| 80 | let anchor = Utc::now() - Duration::days(40); |
| 81 | let slot = schedule |
| 82 | .next_after_with_anchor(anchor, anchor) |
| 83 | .expect("first weekly slot"); |
| 84 | assert!(slot < Utc::now() - Duration::days(30)); |
| 85 | let now = Utc::now(); |
| 86 | let next = schedule |
| 87 | .next_unskipped_slot(slot, now, anchor) |
| 88 | .expect("weekly grid advance") |
| 89 | .expect("weekly schedule always has a future slot"); |
| 90 | assert!(next > now, "coalesced slot must be in the future"); |
| 91 | assert!( |
| 92 | next <= now + Duration::days(7), |
| 93 | "coalesce must land on the *next* owed slot, not a later one" |
| 94 | ); |
| 95 | let local = next.with_timezone(&Local); |
| 96 | assert_eq!(local.weekday(), Weekday::Mon); |
| 97 | assert_eq!((local.hour(), local.minute()), (9, 30)); |
| 98 | } |
| 99 | |
| 100 | /// While an occurrence is still queued or running, the next due slot is |
| 101 | /// retained as owed work. One catch-up run is admitted after the earlier run |
| 102 | /// settles, with no canceled receipt or lost one-shot occurrence. |
| 103 | #[tokio::test] |
| 104 | async fn scheduled_occurrences_wait_while_a_prior_run_is_in_flight() -> Result<()> { |
| 105 | let root = tempfile::tempdir()?; |
| 106 | let receipts = root.path().join("executions"); |
| 107 | let tasks = fixture_tasks(&root.path().join("tasks"), &receipts).await?; |
| 108 | let manager = AutomationManager::open_for_test(root.path().join("automations"))?; |
| 109 | let automation = fixture_due_automation(&manager, "overlap", 1); |
| 110 | |
| 111 | // A bound occurrence durably in flight: queued, owning a task identity, |
| 112 | // not yet admitted. |
| 113 | let mut held = queued_run_for(&automation); |
| 114 | held.scheduled_for = Utc::now() - Duration::hours(2); |
| 115 | bind_run_dispatch(&mut held, &automation, &tasks.data_dir(), true)?; |
| 116 | manager.save_run(&held)?; |
| 117 | |
| 118 | // The next slot comes due while that run is still queued. The claim must |
| 119 | // not stack a second task or consume the still-owed slot. |
| 120 | let (observed, proposed) = manager.collect_due_runs(Utc::now())?.remove(0); |
| 121 | assert!( |
| 122 | manager |
| 123 | .claim_scheduled_run(&observed, proposed, &tasks.data_dir())? |
| 124 | .is_none(), |
| 125 | "an in-flight occurrence blocks the next scheduled claim" |
| 126 | ); |
| 127 | let runs = manager.list_runs(&automation.id, None)?; |
| 128 | assert_eq!(runs.len(), 1, "only the already-admitted run has a receipt"); |
| 129 | let stored = manager.get_automation(&automation.id)?; |
| 130 | assert_eq!( |
| 131 | stored.next_run_at, automation.next_run_at, |
| 132 | "owed slot is retained" |
| 133 | ); |
| 134 | assert!( |
| 135 | fixture_executions(&receipts).is_empty(), |
| 136 | "the waiting slot produced no task" |
| 137 | ); |
| 138 | |
| 139 | // Once the earlier occurrence settles, the original owed slot admits. |
| 140 | held.status = AutomationRunStatus::Completed; |
| 141 | held.ended_at = Some(Utc::now()); |
| 142 | manager.save_run(&held)?; |
| 143 | let (observed, proposed) = manager.collect_due_runs(Utc::now())?.remove(0); |
| 144 | let admitted = manager |
| 145 | .claim_scheduled_run(&observed, proposed, &tasks.data_dir())? |
| 146 | .context("a settled history no longer gates admission")?; |
| 147 | assert_eq!(admitted.status, AutomationRunStatus::Queued); |
| 148 | assert_eq!(Some(admitted.scheduled_for), automation.next_run_at); |
| 149 | assert!(manager.get_automation(&automation.id)?.next_run_at.unwrap() > Utc::now()); |
| 150 | assert!(admitted.task_id.is_some()); |
| 151 | tasks.shutdown_and_wait().await?; |
| 152 | Ok(()) |
| 153 | } |
| 154 | |
| 155 | /// One damaged definition — or one outright unparseable file — quarantines to |
| 156 | /// a diagnostic and leaves its bytes alone; every healthy owned automation |
| 157 | /// still collects and dispatches. |
| 158 | #[tokio::test] |
| 159 | async fn damaged_definitions_quarantine_without_starving_owned_work() -> Result<()> { |
| 160 | let root = tempfile::tempdir()?; |
| 161 | let receipts = root.path().join("executions"); |
| 162 | let tasks = fixture_tasks(&root.path().join("tasks"), &receipts).await?; |
| 163 | let manager = AutomationManager::open_for_test(root.path().join("automations"))?; |
| 164 | fixture_due_automation(&manager, "healthy", 1); |
| 165 | |
| 166 | let mut broken = automation_record_with_settings(None, None, None, None); |
| 167 | broken.id = "broken".into(); |
| 168 | broken.rrule = "FREQ=HOURLY;INTERVAL=nope".into(); |
| 169 | broken.next_run_at = Some(Utc::now() - Duration::minutes(1)); |
| 170 | manager.save_automation(&broken)?; |
| 171 | |
| 172 | let garbage = manager.automations_dir.join("garbage.json"); |
| 173 | fs::write(&garbage, b"{not json")?; |
| 174 | let garbage_before = fs::read(&garbage)?; |
| 175 | |
| 176 | let shared = Arc::new(Mutex::new(manager)); |
| 177 | scheduler_tick_shared(&shared, &tasks).await?; |
| 178 | |
| 179 | // The dispatched occurrence runs asynchronously; settle it before the |
| 180 | // receipt assertions. |
| 181 | let bound_id = { |
| 182 | let manager = shared.lock().await; |
| 183 | let runs = manager.list_runs("healthy", None)?; |
| 184 | assert_eq!(runs.len(), 1, "the healthy owned automation still claimed"); |
| 185 | assert!( |
| 186 | manager.list_runs("broken", None)?.is_empty(), |
| 187 | "the unevaluable schedule never claimed a run" |
| 188 | ); |
| 189 | runs[0].task_id.clone().context("bound task id")? |
| 190 | }; |
| 191 | let task = crate::task_manager::wait_for_terminal_state( |
| 192 | &tasks, |
| 193 | &bound_id, |
| 194 | std::time::Duration::from_secs(10), |
| 195 | ) |
| 196 | .await?; |
| 197 | assert_eq!(task.status, TaskStatus::Completed); |
| 198 | assert_eq!( |
| 199 | fixture_executions(&receipts).len(), |
| 200 | 1, |
| 201 | "the healthy owned automation still dispatched" |
| 202 | ); |
| 203 | assert_eq!( |
| 204 | fs::read(&garbage)?, |
| 205 | garbage_before, |
| 206 | "unreadable definitions are preserved, never rewritten or deleted" |
| 207 | ); |
| 208 | let manager = shared.lock().await; |
| 209 | let stored = manager.get_automation("broken")?; |
| 210 | assert_eq!( |
| 211 | stored.rrule, broken.rrule, |
| 212 | "damaged schedule left untouched" |
| 213 | ); |
| 214 | assert_eq!(stored.status, AutomationStatus::Active); |
| 215 | tasks.shutdown_and_wait().await?; |
| 216 | Ok(()) |
| 217 | } |
| 218 | |
| 219 | /// A corrupt receipt quarantines only its own automation: the strict history |
| 220 | /// read inside the claim refuses to risk re-admitting that slot, while the |
| 221 | /// sibling automation's due work still dispatches. |
| 222 | #[tokio::test] |
| 223 | async fn damaged_run_receipt_quarantines_only_its_own_automation() -> Result<()> { |
| 224 | let root = tempfile::tempdir()?; |
| 225 | let receipts = root.path().join("executions"); |
| 226 | let tasks = fixture_tasks(&root.path().join("tasks"), &receipts).await?; |
| 227 | let manager = AutomationManager::open_for_test(root.path().join("automations"))?; |
| 228 | let healthy = fixture_due_automation(&manager, "healthy", 1); |
| 229 | let damaged = fixture_due_automation(&manager, "damaged", 2); |
| 230 | |
| 231 | let runs_dir = manager.runs_dir_for(&damaged.id)?; |
| 232 | fs::create_dir_all(&runs_dir)?; |
| 233 | let corrupt = runs_dir.join("corrupt.json"); |
| 234 | fs::write(&corrupt, b"{}")?; |
| 235 | |
| 236 | let shared = Arc::new(Mutex::new(manager)); |
| 237 | scheduler_tick_shared(&shared, &tasks).await?; |
| 238 | |
| 239 | // The dispatched occurrence runs asynchronously; settle it before the |
| 240 | // receipt assertions. |
| 241 | let bound_id = { |
| 242 | let manager = shared.lock().await; |
| 243 | let runs = manager.list_runs(&healthy.id, None)?; |
| 244 | assert_eq!(runs.len(), 1, "healthy automation claimed its run"); |
| 245 | runs[0].task_id.clone().context("bound task id")? |
| 246 | }; |
| 247 | let task = crate::task_manager::wait_for_terminal_state( |
| 248 | &tasks, |
| 249 | &bound_id, |
| 250 | std::time::Duration::from_secs(10), |
| 251 | ) |
| 252 | .await?; |
| 253 | assert_eq!(task.status, TaskStatus::Completed); |
| 254 | assert_eq!( |
| 255 | fixture_executions(&receipts).len(), |
| 256 | 1, |
| 257 | "healthy work dispatched despite the sibling's corrupt receipt" |
| 258 | ); |
| 259 | assert_eq!(fs::read(&corrupt)?, b"{}", "corrupt receipt is preserved"); |
| 260 | let manager = shared.lock().await; |
| 261 | assert!( |
| 262 | manager.list_runs(&healthy.id, None)?.len() == 1, |
| 263 | "healthy automation recorded its run" |
| 264 | ); |
| 265 | // The damaged automation is quarantined: still due, never advanced by a |
| 266 | // claim it cannot verify, and never silently re-admitted. |
| 267 | let stored = manager.get_automation(&damaged.id)?; |
| 268 | assert_eq!(stored.status, AutomationStatus::Active); |
| 269 | tasks.shutdown_and_wait().await?; |
| 270 | Ok(()) |
| 271 | } |
| 272 | |
| 273 | #[tokio::test] |
| 274 | async fn missed_occurrences_wait_for_an_answer_across_reopen() -> Result<()> { |
| 275 | let root = tempfile::tempdir()?; |
| 276 | let receipts = root.path().join("executions"); |
| 277 | let tasks = fixture_tasks(&root.path().join("tasks"), &receipts).await?; |
| 278 | let store = root.path().join("automations"); |
| 279 | let grace = Duration::minutes(2); |
| 280 | let closed_at = Utc::now() - Duration::hours(6); |
| 281 | let reopened_at = Utc::now() - Duration::minutes(10); |
| 282 | let manager = AutomationManager::open_for_test(store.clone())?; |
| 283 | let earlier_session = closed_at - Duration::hours(1); |
| 284 | assert_eq!( |
| 285 | manager.note_scheduler_presence(earlier_session, grace)?, |
| 286 | earlier_session |
| 287 | ); |
| 288 | assert_eq!( |
| 289 | manager.note_scheduler_presence(closed_at, Duration::hours(2))?, |
| 290 | earlier_session, |
| 291 | "a continuously ticking scheduler keeps its presence" |
| 292 | ); |
| 293 | |
| 294 | let save = |id: &str, due: DateTime<Utc>| -> Result<DateTime<Utc>> { |
| 295 | let mut automation = automation_record_with_settings(None, None, None, None); |
| 296 | automation.id = id.into(); |
| 297 | automation.name = format!("{id} automation"); |
| 298 | automation.created_at = closed_at - Duration::days(1); |
| 299 | automation.next_run_at = Some(due); |
| 300 | manager.save_automation(&automation)?; |
| 301 | Ok(due) |
| 302 | }; |
| 303 | let asked_due = save("asked", closed_at + Duration::hours(2))?; |
| 304 | let declined_due = save("declined", closed_at + Duration::hours(1))?; |
| 305 | let stopped_due = save("stopped", closed_at + Duration::minutes(30))?; |
| 306 | let skipped_due = save("skipped", closed_at + Duration::hours(3))?; |
| 307 | let once_due = save("once", closed_at + Duration::hours(4))?; |
| 308 | let current_due = save("current", reopened_at + Duration::minutes(5))?; |
| 309 | manager.set_missed_policy("skipped", Some(AutomationMissedPolicy::Skip))?; |
| 310 | manager.set_missed_policy("once", Some(AutomationMissedPolicy::RunOnce))?; |
| 311 | |
| 312 | assert_eq!( |
| 313 | manager.note_scheduler_presence(reopened_at, grace)?, |
| 314 | reopened_at, |
| 315 | "a gap longer than the grace window starts a new presence" |
| 316 | ); |
| 317 | assert_eq!( |
| 318 | manager.note_scheduler_presence(Utc::now(), Duration::minutes(15))?, |
| 319 | reopened_at |
| 320 | ); |
| 321 | let shared = Arc::new(Mutex::new(manager)); |
| 322 | scheduler_tick_shared(&shared, &tasks).await?; |
| 323 | |
| 324 | let settle = |id: &'static str, due: DateTime<Utc>| { |
| 325 | let shared = shared.clone(); |
| 326 | let tasks = tasks.clone(); |
| 327 | async move { |
| 328 | let task_id = { |
| 329 | let manager = shared.lock().await; |
| 330 | let runs = manager.list_runs(id, None)?; |
| 331 | assert_eq!(runs.len(), 1, "{id} ran exactly once"); |
| 332 | assert_eq!(runs[0].scheduled_for, due, "{id} owns its due slot"); |
| 333 | runs[0].task_id.clone().context("bound task id")? |
| 334 | }; |
| 335 | let task = crate::task_manager::wait_for_terminal_state( |
| 336 | &tasks, |
| 337 | &task_id, |
| 338 | std::time::Duration::from_secs(10), |
| 339 | ) |
| 340 | .await?; |
| 341 | assert_eq!(task.status, TaskStatus::Completed); |
| 342 | Ok::<_, anyhow::Error>(task_id) |
| 343 | } |
| 344 | }; |
| 345 | let once_task = settle("once", once_due).await?; |
| 346 | let current_task = settle("current", current_due).await?; |
| 347 | { |
| 348 | let manager = shared.lock().await; |
| 349 | for id in ["asked", "declined", "stopped", "skipped"] { |
| 350 | assert!(manager.list_runs(id, None)?.is_empty(), "{id} did not run"); |
| 351 | } |
| 352 | let skipped = manager.missed_status("skipped")?; |
| 353 | assert_eq!(skipped.owed, None); |
| 354 | assert_eq!(skipped.outcomes.len(), 1); |
| 355 | assert_eq!(skipped.outcomes[0].due_at, skipped_due); |
| 356 | assert_eq!(skipped.outcomes[0].outcome, MissedRunOutcomeKind::Skipped); |
| 357 | assert_eq!(skipped.outcomes[0].decided_by, MissedRunDecider::Policy); |
| 358 | assert!( |
| 359 | manager |
| 360 | .get_automation("skipped")? |
| 361 | .next_run_at |
| 362 | .is_some_and(|next| next > Utc::now()) |
| 363 | ); |
| 364 | let owed: Vec<_> = manager |
| 365 | .list_missed()? |
| 366 | .into_iter() |
| 367 | .map(|status| { |
| 368 | assert_eq!(status.policy, AutomationMissedPolicy::Ask); |
| 369 | assert!(status.policy_is_default); |
| 370 | (status.automation_id, status.owed.map(|owed| owed.due_at)) |
| 371 | }) |
| 372 | .collect(); |
| 373 | assert_eq!( |
| 374 | owed, |
| 375 | vec![ |
| 376 | ("stopped".to_string(), Some(stopped_due)), |
| 377 | ("declined".to_string(), Some(declined_due)), |
| 378 | ("asked".to_string(), Some(asked_due)), |
| 379 | ] |
| 380 | ); |
| 381 | } |
| 382 | |
| 383 | scheduler_tick_shared(&shared, &tasks).await?; |
| 384 | assert!( |
| 385 | shared.lock().await.list_runs("asked", None)?.is_empty(), |
| 386 | "nothing runs until the person answers" |
| 387 | ); |
| 388 | drop(shared); |
| 389 | |
| 390 | let reopened = AutomationManager::open_for_test(store)?; |
| 391 | assert_eq!( |
| 392 | reopened.list_missed()?.len(), |
| 393 | 3, |
| 394 | "owed occurrences are durable" |
| 395 | ); |
| 396 | reopened.pause_automation("stopped")?; |
| 397 | reopened.resume_automation("stopped")?; |
| 398 | let mut overlapping = new_run_record("asked", Utc::now(), Utc::now()); |
| 399 | reopened.save_run(&overlapping)?; |
| 400 | let shared = Arc::new(Mutex::new(reopened)); |
| 401 | assert!( |
| 402 | shared |
| 403 | .lock() |
| 404 | .await |
| 405 | .list_missed()? |
| 406 | .iter() |
| 407 | .all(|status| status.automation_id != "stopped"), |
| 408 | "stopping the automation withdraws its owed occurrence" |
| 409 | ); |
| 410 | |
| 411 | let refused = |
| 412 | resolve_missed_run_shared(&shared, "asked", MissedRunDecision::RunNow, &tasks).await; |
| 413 | assert!( |
| 414 | refused |
| 415 | .unwrap_err() |
| 416 | .to_string() |
| 417 | .contains("still in progress"), |
| 418 | "run now never overlaps an earlier run" |
| 419 | ); |
| 420 | overlapping.status = AutomationRunStatus::Completed; |
| 421 | shared.lock().await.save_run(&overlapping)?; |
| 422 | |
| 423 | let ran = |
| 424 | resolve_missed_run_shared(&shared, "asked", MissedRunDecision::RunNow, &tasks).await?; |
| 425 | let run = ran.run.context("run now admits the owed occurrence")?; |
| 426 | assert_eq!(run.scheduled_for, asked_due); |
| 427 | assert_eq!(ran.status.owed, None); |
| 428 | let outcome = ran.status.outcomes.last().context("ran outcome")?; |
| 429 | assert_eq!(outcome.outcome, MissedRunOutcomeKind::Ran); |
| 430 | assert_eq!(outcome.decided_by, MissedRunDecider::Person); |
| 431 | assert_eq!(outcome.run_id.as_deref(), Some(run.id.as_str())); |
| 432 | let asked_task = run.task_id.clone().context("bound task id")?; |
| 433 | let task = crate::task_manager::wait_for_terminal_state( |
| 434 | &tasks, |
| 435 | &asked_task, |
| 436 | std::time::Duration::from_secs(10), |
| 437 | ) |
| 438 | .await?; |
| 439 | assert_eq!(task.status, TaskStatus::Completed); |
| 440 | |
| 441 | let declined = |
| 442 | resolve_missed_run_shared(&shared, "declined", MissedRunDecision::Skip, &tasks).await?; |
| 443 | assert!(declined.run.is_none()); |
| 444 | let outcome = declined.status.outcomes.last().context("skip outcome")?; |
| 445 | assert_eq!(outcome.due_at, declined_due); |
| 446 | assert_eq!(outcome.outcome, MissedRunOutcomeKind::Skipped); |
| 447 | assert_eq!(outcome.decided_by, MissedRunDecider::Person); |
| 448 | assert!( |
| 449 | resolve_missed_run_shared(&shared, "declined", MissedRunDecision::Skip, &tasks) |
| 450 | .await |
| 451 | .is_err(), |
| 452 | "an answered occurrence cannot be answered twice" |
| 453 | ); |
| 454 | |
| 455 | reconcile_run_statuses_shared(&shared, &tasks).await?; |
| 456 | scheduler_tick_shared(&shared, &tasks).await?; |
| 457 | let manager = shared.lock().await; |
| 458 | assert!(manager.list_missed()?.is_empty()); |
| 459 | for id in ["asked", "declined", "stopped", "skipped", "once", "current"] { |
| 460 | let automation = manager.get_automation(id)?; |
| 461 | assert!( |
| 462 | automation.next_run_at.is_some_and(|next| next > Utc::now()), |
| 463 | "{id} resumed on a future slot" |
| 464 | ); |
| 465 | } |
| 466 | assert!(manager.list_runs("declined", None)?.is_empty()); |
| 467 | assert!(manager.list_runs("stopped", None)?.is_empty()); |
| 468 | let mut executed = fixture_executions(&receipts); |
| 469 | executed.sort(); |
| 470 | let mut expected = vec![once_task, current_task, asked_task]; |
| 471 | expected.sort(); |
| 472 | assert_eq!( |
| 473 | executed, expected, |
| 474 | "exactly the answered and on-time runs executed" |
| 475 | ); |
| 476 | drop(manager); |
| 477 | tasks.shutdown_and_wait().await?; |
| 478 | Ok(()) |
| 479 | } |
| 480 | |
| 481 | #[tokio::test] |
| 482 | async fn foreign_scope_reports_unscheduled_until_adopted_and_owned_past_slots_stay_truthful() |
| 483 | -> Result<()> { |
| 484 | let root = tempfile::tempdir()?; |
| 485 | let receipts = root.path().join("executions"); |
| 486 | let tasks = fixture_tasks(&root.path().join("tasks"), &receipts).await?; |
| 487 | let mut manager = AutomationManager::open(root.path().join("automations"))?; |
| 488 | manager.bind_task_manager(&tasks)?; |
| 489 | |
| 490 | let stale = Utc::now() - Duration::days(8); |
| 491 | let mut owned_ask = automation_record_with_settings(None, None, None, None); |
| 492 | owned_ask.id = "owned-ask".into(); |
| 493 | owned_ask.execution_scope = Some(tasks.execution_scope().to_string()); |
| 494 | owned_ask.rrule = "FREQ=WEEKLY;BYDAY=MO;BYHOUR=9;BYMINUTE=0".into(); |
| 495 | owned_ask.next_run_at = Some(stale); |
| 496 | manager.save_automation(&owned_ask)?; |
| 497 | |
| 498 | let mut owned_held = owned_ask.clone(); |
| 499 | owned_held.id = "owned-held".into(); |
| 500 | manager.save_automation(&owned_held)?; |
| 501 | manager.set_missed_policy("owned-held", Some(AutomationMissedPolicy::RunOnce))?; |
| 502 | let mut live_run = queued_run_for(&owned_held); |
| 503 | bind_run_dispatch(&mut live_run, &owned_held, &tasks.data_dir(), true)?; |
| 504 | manager.save_run(&live_run)?; |
| 505 | |
| 506 | let mut foreign = owned_ask.clone(); |
| 507 | foreign.id = "foreign-weekly".into(); |
| 508 | foreign.execution_scope = Some(crate::task_manager::test_execution_scope("gone-scope")); |
| 509 | manager.save_automation(&foreign)?; |
| 510 | |
| 511 | let listed_before = manager.list_automation_views()?; |
| 512 | let view_for = |views: &[AutomationRecordView], id: &str| { |
| 513 | views |
| 514 | .iter() |
| 515 | .find(|view| view.record.id == id) |
| 516 | .cloned() |
| 517 | .expect("listed automation") |
| 518 | }; |
| 519 | let foreign_list = view_for(&listed_before, "foreign-weekly"); |
| 520 | let foreign_read = manager.get_automation_view("foreign-weekly")?; |
| 521 | assert!(!foreign_list.scheduled_here); |
| 522 | assert_eq!( |
| 523 | foreign_list.execution_ownership, |
| 524 | AutomationExecutionOwnership::OtherRuntime |
| 525 | ); |
| 526 | assert_eq!(foreign_list.record.next_run_at, Some(stale)); |
| 527 | assert_eq!(foreign_read.scheduled_here, foreign_list.scheduled_here); |
| 528 | assert_eq!( |
| 529 | foreign_read.execution_ownership, |
| 530 | foreign_list.execution_ownership |
| 531 | ); |
| 532 | assert_eq!(foreign_read.record.next_run_at, Some(stale)); |
| 533 | |
| 534 | let ask_before = view_for(&listed_before, "owned-ask"); |
| 535 | assert!(ask_before.scheduled_here); |
| 536 | assert_eq!( |
| 537 | ask_before.execution_ownership, |
| 538 | AutomationExecutionOwnership::Owned |
| 539 | ); |
| 540 | assert_eq!(ask_before.record.next_run_at, Some(stale)); |
| 541 | |
| 542 | let shared = Arc::new(Mutex::new(manager)); |
| 543 | with_manager_blocking(&shared, |manager| { |
| 544 | manager.note_scheduler_presence(Utc::now(), Duration::seconds(120)) |
| 545 | }) |
| 546 | .await?; |
| 547 | scheduler_tick_shared(&shared, &tasks).await?; |
| 548 | |
| 549 | { |
| 550 | let guard = shared.lock().await; |
| 551 | assert_eq!(guard.get_automation("owned-ask")?.next_run_at, Some(stale)); |
| 552 | assert_eq!(guard.get_automation("owned-held")?.next_run_at, Some(stale)); |
| 553 | assert_eq!( |
| 554 | guard.get_automation("foreign-weekly")?.next_run_at, |
| 555 | Some(stale) |
| 556 | ); |
| 557 | let missed = guard.list_missed()?; |
| 558 | assert_eq!(missed.len(), 1); |
| 559 | assert_eq!(missed[0].automation_id, "owned-ask"); |
| 560 | |
| 561 | guard.adopt_automation("foreign-weekly")?; |
| 562 | let adopted_view = guard.get_automation_view("foreign-weekly")?; |
| 563 | assert!(adopted_view.scheduled_here); |
| 564 | assert_eq!( |
| 565 | adopted_view.execution_ownership, |
| 566 | AutomationExecutionOwnership::Owned |
| 567 | ); |
| 568 | assert_eq!(adopted_view.record.next_run_at, Some(stale)); |
| 569 | } |
| 570 | |
| 571 | scheduler_tick_shared(&shared, &tasks).await?; |
| 572 | { |
| 573 | let guard = shared.lock().await; |
| 574 | let missed = guard.list_missed()?; |
| 575 | assert!( |
| 576 | missed |
| 577 | .iter() |
| 578 | .any(|item| item.automation_id == "foreign-weekly"), |
| 579 | "adopted overdue automation asks per section 77: {missed:?}" |
| 580 | ); |
| 581 | } |
| 582 | |
| 583 | let resolved = |
| 584 | resolve_missed_run_shared(&shared, "foreign-weekly", MissedRunDecision::Skip, &tasks) |
| 585 | .await?; |
| 586 | assert!(resolved.status.owed.is_none()); |
| 587 | { |
| 588 | let guard = shared.lock().await; |
| 589 | let after = guard.get_automation_view("foreign-weekly")?; |
| 590 | assert!(after.scheduled_here); |
| 591 | assert!( |
| 592 | after.record.next_run_at.is_some_and(|at| at > Utc::now()), |
| 593 | "resolved missed run advances next_run_at past now: {:?}", |
| 594 | after.record.next_run_at |
| 595 | ); |
| 596 | |
| 597 | let mut foreign_continuous = owned_ask.clone(); |
| 598 | foreign_continuous.id = "foreign-continuous-ask".into(); |
| 599 | foreign_continuous.execution_scope = |
| 600 | Some(crate::task_manager::test_execution_scope("gone-scope")); |
| 601 | foreign_continuous.next_run_at = Some(stale); |
| 602 | guard.save_automation(&foreign_continuous)?; |
| 603 | |
| 604 | let mut foreign_skip = owned_ask.clone(); |
| 605 | foreign_skip.id = "foreign-continuous-skip".into(); |
| 606 | foreign_skip.execution_scope = |
| 607 | Some(crate::task_manager::test_execution_scope("gone-scope")); |
| 608 | foreign_skip.next_run_at = Some(stale); |
| 609 | guard.save_automation(&foreign_skip)?; |
| 610 | guard.set_missed_policy( |
| 611 | "foreign-continuous-skip", |
| 612 | Some(AutomationMissedPolicy::Skip), |
| 613 | )?; |
| 614 | |
| 615 | guard.note_scheduler_presence(Utc::now() - Duration::days(9), Duration::days(10))?; |
| 616 | guard.adopt_automation("foreign-continuous-ask")?; |
| 617 | let missed = guard.list_missed()?; |
| 618 | assert!( |
| 619 | missed |
| 620 | .iter() |
| 621 | .any(|item| item.automation_id == "foreign-continuous-ask"), |
| 622 | "continuous awake_since < stale < now must ask immediately on adopt: {missed:?}" |
| 623 | ); |
| 624 | guard.adopt_automation("foreign-continuous-skip")?; |
| 625 | let skipped = guard.get_automation("foreign-continuous-skip")?; |
| 626 | assert!( |
| 627 | skipped.next_run_at.is_some_and(|at| at > Utc::now()), |
| 628 | "Skip policy must advance past stale slot on adopt: {:?}", |
| 629 | skipped.next_run_at |
| 630 | ); |
| 631 | } |
| 632 | |
| 633 | scheduler_tick_shared(&shared, &tasks).await?; |
| 634 | { |
| 635 | let guard = shared.lock().await; |
| 636 | assert!(guard.list_runs("foreign-continuous-ask", None)?.is_empty()); |
| 637 | assert!(guard.list_runs("foreign-continuous-skip", None)?.is_empty()); |
| 638 | } |
| 639 | tasks.shutdown_and_wait().await?; |
| 640 | Ok(()) |
| 641 | } |
| 642 |