1use std::collections::HashSet;
11use std::sync::Arc;
12use std::sync::atomic::{AtomicBool, Ordering};
13use std::time::{Duration, Instant, SystemTime};
14
15use aidaemon_core::{Schedule, Service, ServiceContext, ServiceError};
16use async_trait::async_trait;
17use chrono::{DateTime, Utc};
18use tracing::{error, info, warn};
19
20use crate::goal_tokens::GoalTokenRegistry;
21use crate::traits::{GoalSchedule, Mandate, MandateStatus};
22
23mod mandates;
24pub mod needs_model;
25mod notifications;
26mod schedules;
27mod tasks;
28
29pub trait SchedulerStore:
31 crate::traits::GoalStore
32 + crate::traits::TaskStore
33 + crate::traits::GoalScheduleStore
34 + crate::traits::GoalBudgetStore
35 + crate::traits::ScheduledRunStore
36 + crate::traits::TaskDispatchStore
37 + crate::traits::GoalNotificationStore
38 + crate::traits::NotificationStore
39 + crate::traits::MandateStore
40 + crate::traits::WorkCoordinationStore
41 + aidaemon_tools::services::SettingsStore
42{
43}
44
45impl<T> SchedulerStore for T where
46 T: crate::traits::GoalStore
47 + crate::traits::TaskStore
48 + crate::traits::GoalScheduleStore
49 + crate::traits::GoalBudgetStore
50 + crate::traits::ScheduledRunStore
51 + crate::traits::TaskDispatchStore
52 + crate::traits::GoalNotificationStore
53 + crate::traits::NotificationStore
54 + crate::traits::MandateStore
55 + crate::traits::WorkCoordinationStore
56 + aidaemon_tools::services::SettingsStore
57{
58}
59
60#[async_trait]
62pub trait TaskLeadHost: Send + Sync {
63 fn available(&self) -> bool;
65
66 fn has_model(&self) -> bool {
70 true
71 }
72
73 async fn task_tree_is_effect_free(
78 &self,
79 _task_ids: &[String],
80 _run_sessions: &[String],
81 ) -> anyhow::Result<bool> {
82 Ok(false)
83 }
84
85 async fn task_tree_changes_settled(
91 &self,
92 _task_ids: &[String],
93 _run_sessions: &[String],
94 ) -> anyhow::Result<bool> {
95 Ok(false)
96 }
97
98 async fn restart_resume_summary(
102 &self,
103 _task_ids: &[String],
104 _run_sessions: &[String],
105 ) -> anyhow::Result<Option<String>> {
106 Ok(None)
107 }
108
109 fn spawn_task_lead(
113 &self,
114 goal: crate::traits::Goal,
115 task_text: String,
116 task_id: String,
117 running_surface_id: Option<String>,
118 );
119
120 fn next_model_answer_at(&self) -> Option<SystemTime>;
122
123 async fn retry_deferred_provider_requests(&self) -> usize;
125
126 async fn tainted_note_turn(&self, session_id: &str) -> anyhow::Result<String>;
128
129 async fn record_parent_visible_result_note_in_turn(
131 &self,
132 session_id: &str,
133 prefix: &str,
134 text: &str,
135 turn_id: Option<&str>,
136 ) -> anyhow::Result<()>;
137
138 async fn record_mandate_owner_input_context(
140 &self,
141 session_id: &str,
142 mandate_id: &str,
143 mandate_version: i64,
144 action_token: &str,
145 ) -> anyhow::Result<()>;
146}
147
148#[async_trait]
150pub trait NoticeDelivery: Send + Sync {
151 async fn send_text(&self, session_id: &str, text: &str) -> anyhow::Result<()>;
153
154 async fn send_text_tracked(
157 &self,
158 session_id: &str,
159 text: &str,
160 ) -> anyhow::Result<Option<String>>;
161
162 async fn owner_active_since(&self, _session_id: &str, _since: DateTime<Utc>) -> bool {
166 false
167 }
168}
169
170pub trait WorkPresenter: Send + Sync {
172 fn goal_label(&self, description: &str) -> String;
174
175 fn user_facing(&self, text: &str) -> String;
177
178 fn notification(&self, notification_type: &str, text: &str) -> String;
180
181 fn goal_task_results(
183 &self,
184 tasks: &[crate::traits::Task],
185 root_task_id: Option<&str>,
186 fallback: &str,
187 ) -> String;
188}
189
190pub const TASK_ESCALATION_SETTLE_SECS: i64 = 8;
191pub const QUEUED_NOTIFICATION_NOTE_PREFIX: &str = "Parent-visible result (goal notification)";
194
195pub fn notice_accepts_mandate_answer(notification_type: &str) -> bool {
198 matches!(notification_type, "mandate_ask" | "mandate_ask_timeout")
199}
200pub const MANDATE_REVIEW_LEASE_SECS: i64 = 30 * 60;
201pub const MANDATE_REVIEW_BATCH_SIZE: i64 = 20;
202pub const MANDATE_DISPATCH_BUSY_RETRIES: u32 = 5;
203pub const MANDATE_DISPATCH_BUSY_RETRY_SECS: i64 = 30;
204
205pub fn mandate_retry_at(mandate: &Mandate, requested_secs: Option<i64>) -> String {
206 let delay = mandate.clamp_review_secs(requested_secs);
207 (chrono::Utc::now() + chrono::Duration::seconds(delay)).to_rfc3339()
208}
209
210pub fn mandate_budget_retry_at(mandate: &Mandate, now: chrono::DateTime<Utc>) -> String {
211 let next_day = now
212 .date_naive()
213 .succ_opt()
214 .expect("the next UTC date is representable")
215 .and_hms_opt(0, 0, 0)
216 .expect("UTC midnight is representable");
217 let mut retry_at = chrono::DateTime::<Utc>::from_naive_utc_and_offset(next_day, Utc);
218 if let Some(expiry) = mandate
219 .expires_at
220 .as_deref()
221 .and_then(|value| chrono::DateTime::parse_from_rfc3339(value).ok())
222 .map(|value| value.with_timezone(&Utc))
223 {
224 retry_at = retry_at.min(expiry);
225 }
226 retry_at.to_rfc3339()
227}
228
229pub fn mandate_transient_retry_at(mandate: &Mandate, now: chrono::DateTime<Utc>) -> String {
230 let mut retry_at = now + chrono::Duration::seconds(MANDATE_DISPATCH_BUSY_RETRY_SECS);
231 if let Some(expiry) = mandate
232 .expires_at
233 .as_deref()
234 .and_then(|value| chrono::DateTime::parse_from_rfc3339(value).ok())
235 .map(|value| value.with_timezone(&Utc))
236 {
237 retry_at = retry_at.min(expiry);
238 }
239 retry_at.to_rfc3339()
240}
241
242pub async fn retry_on_busy<T, F, Fut>(
247 what: &str,
248 max_retries: usize,
249 mut op: F,
250) -> anyhow::Result<T>
251where
252 F: FnMut() -> Fut,
253 Fut: std::future::Future<Output = anyhow::Result<T>>,
254{
255 let mut retry = 0_usize;
256 loop {
257 match op().await {
258 Err(error) if retry < max_retries && is_sqlite_busy_error(&error) => {
259 let delay_ms = 25_u64 << retry;
260 retry += 1;
261 tracing::warn!(what, retry, delay_ms, %error, "SQLite busy; retrying");
262 tokio::time::sleep(std::time::Duration::from_millis(delay_ms)).await;
263 }
264 result => return result,
265 }
266 }
267}
268
269pub fn is_sqlite_busy_error(error: &anyhow::Error) -> bool {
275 const SQLITE_BUSY: i32 = 5;
276 const SQLITE_LOCKED: i32 = 6;
277 error.chain().any(|cause| {
278 let Some(sqlx::Error::Database(database)) = cause.downcast_ref::<sqlx::Error>() else {
279 return false;
280 };
281 database
282 .code()
283 .and_then(|code| code.parse::<i32>().ok())
284 .is_some_and(|code| matches!(code & 0xff, SQLITE_BUSY | SQLITE_LOCKED))
285 })
286}
287
288pub fn mandate_review_task_description(mandate: &Mandate, goal_run_id: &str) -> String {
289 format!(
293 "Run one bounded autonomous review for mandate {} version {} in goal run {}. \
294 Use only the isolated built-in mandate protocol and immutable policy supplied \
295 by the runtime.",
296 mandate.id, mandate.version, goal_run_id
297 )
298}
299
300pub fn mandate_review_task_context(mandate: &Mandate) -> String {
301 serde_json::json!({
302 "mandate_id": mandate.id,
303 "mandate_version": mandate.version,
304 "provenance": "runtime_mandate_fence_only",
305 })
306 .to_string()
307}
308
309pub fn timestamp_is_at_or_after(value: &str, lower_bound: &str) -> bool {
310 match (
311 chrono::DateTime::parse_from_rfc3339(value),
312 chrono::DateTime::parse_from_rfc3339(lower_bound),
313 ) {
314 (Ok(value), Ok(lower_bound)) => value >= lower_bound,
315 _ => value >= lower_bound,
316 }
317}
318
319pub fn goal_completion_header(tasks: &[crate::traits::Task]) -> String {
329 if tasks.is_empty() {
330 return aidaemon_channels::presentation::GOAL_COMPLETED_LEAD.to_string();
331 }
332 let total = tasks.len();
333 let done = tasks.iter().filter(|t| t.status == "completed").count();
334 if done == total {
335 return aidaemon_channels::presentation::GOAL_COMPLETED_LEAD.to_string();
336 }
337 let missing: Vec<String> = tasks
338 .iter()
339 .filter(|t| t.status != "completed")
340 .map(|t| {
341 format!(
342 "• {} ({})",
343 t.description.chars().take(80).collect::<String>(),
344 t.status
345 )
346 })
347 .collect();
348 format!(
349 "Goal partially completed ({done}/{total} tasks). Not completed:\n{}\n",
350 missing.join("\n")
351 )
352}
353
354pub fn daily_budget_exhausted(
355 budget_daily: Option<i64>,
356 tokens_used_today: i64,
357 tokens_used_day: &str,
358 today: &str,
359) -> bool {
360 match budget_daily {
361 Some(budget) => tokens_used_day == today && tokens_used_today >= budget,
362 None => false,
363 }
364}
365
366pub fn daily_budget_has_run_capacity(
367 budget_daily: Option<i64>,
368 budget_per_check: Option<i64>,
369 tokens_used_today: i64,
370 tokens_used_day: &str,
371 today: &str,
372) -> bool {
373 let (Some(daily), Some(per_run)) = (budget_daily, budget_per_check) else {
374 return true;
375 };
376 if tokens_used_day != today {
377 return true;
378 }
379 daily.saturating_sub(tokens_used_today) >= per_run.max(0)
380}
381
382pub fn parse_datetime_flexible(s: &str) -> Option<chrono::DateTime<chrono::Utc>> {
393 chrono::DateTime::parse_from_rfc3339(s)
394 .map(|d| d.with_timezone(&chrono::Utc))
395 .ok()
396 .or_else(|| {
397 chrono::NaiveDateTime::parse_from_str(s, "%Y-%m-%d %H:%M:%S")
398 .ok()
399 .map(|nd| nd.and_utc())
400 })
401}
402
403pub fn task_escalation_has_settled(created_at: &str, now: chrono::DateTime<chrono::Utc>) -> bool {
404 parse_datetime_flexible(created_at)
405 .is_none_or(|created_at| (now - created_at).num_seconds() >= TASK_ESCALATION_SETTLE_SECS)
406}
407
408pub fn task_inactivity_secs(
409 last_activity: Option<&str>,
410 started_at: &str,
411 now: chrono::DateTime<chrono::Utc>,
412) -> i64 {
413 let reference = last_activity
414 .and_then(parse_datetime_flexible)
415 .or_else(|| parse_datetime_flexible(started_at));
416 match reference {
417 Some(ts) => (now - ts).num_seconds().max(0),
418 None => 0,
419 }
420}
421
422pub fn task_status_is_terminal_failure(status: &str) -> bool {
425 matches!(
426 status,
427 "failed" | "blocked" | "interrupted" | "cancelled" | "abandoned"
428 )
429}
430
431pub fn task_is_blocked_by_terminal_dependency(
437 task: &crate::traits::Task,
438 run_tasks: &[crate::traits::Task],
439) -> bool {
440 task.status == "blocked"
441 && task.dependency_ids().is_ok_and(|dependencies| {
442 dependencies.iter().any(|dependency| {
443 run_tasks.iter().any(|other| {
444 other.id == *dependency && task_status_is_terminal_failure(&other.status)
445 })
446 })
447 })
448}
449
450pub fn task_blocks_schedule_fire(
451 task: &crate::traits::Task,
452 run_tasks: &[crate::traits::Task],
453) -> bool {
454 matches!(task.status.as_str(), "pending" | "claimed" | "running")
455 || (task.status == "blocked" && !task_is_blocked_by_terminal_dependency(task, run_tasks))
456}
457
458pub fn task_blocks_later_schedule_fire(
459 run: &crate::traits::GoalRun,
460 task: &crate::traits::Task,
461 run_tasks: &[crate::traits::Task],
462) -> bool {
463 if !matches!(run.status.as_str(), "pending" | "running" | "blocked") {
467 return false;
468 }
469 run.status != "blocked" && task_blocks_schedule_fire(task, run_tasks)
475}
476
477pub fn task_is_terminal_schedule_failure(task: &crate::traits::Task) -> bool {
478 matches!(
479 task.status.as_str(),
480 "failed" | "interrupted" | "cancelled" | "blocked"
481 )
482}
483
484pub fn scheduled_run_reconciliation_status(
489 run: &crate::traits::GoalRun,
490 tasks: &[crate::traits::Task],
491) -> Option<&'static str> {
492 if !matches!(
493 run.trigger_type.as_str(),
494 "scheduled" | "manual" | "recovery"
495 ) || !matches!(run.status.as_str(), "pending" | "running")
496 || tasks.is_empty()
497 {
498 return None;
499 }
500 let terminal_failure = tasks.iter().any(|task| {
505 if run.trigger_type == "scheduled" {
506 task_is_terminal_schedule_failure(task)
507 } else {
508 matches!(task.status.as_str(), "failed" | "interrupted" | "cancelled")
509 }
510 });
511 if terminal_failure {
512 Some("failed")
513 } else if tasks
514 .iter()
515 .all(crate::traits::Task::satisfies_run_completion)
516 {
517 Some("completed")
518 } else {
519 None
520 }
521}
522
523pub fn stranded_manual_run_matches_pending_tasks(
524 run: &crate::traits::GoalRun,
525 run_tasks: &[crate::traits::Task],
526 pending_tasks: &[&crate::traits::Task],
527) -> bool {
528 run.trigger_type == "manual"
529 && matches!(run.status.as_str(), "pending" | "running")
530 && pending_tasks
531 .iter()
532 .any(|pending| run_tasks.iter().any(|task| task.id == pending.id))
533}
534
535pub struct GoalCycle {
537 pub(crate) state: Arc<dyn SchedulerStore>,
538 pub(crate) agent: Option<Arc<dyn TaskLeadHost>>,
539 pub(crate) hub: Option<Arc<dyn NoticeDelivery>>,
540 pub(crate) presenter: Arc<dyn WorkPresenter>,
541 pub(crate) goal_token_registry: Option<GoalTokenRegistry>,
542 deferred_retry_running: Arc<AtomicBool>,
543 last_stale_goal_cleanup: Option<Instant>,
544 pub task_inactivity_timeout_secs: i64,
547 no_model_noticed: Arc<needs_model::NeedsModelNotices>,
550 booted_at: Option<String>,
555}
556
557pub fn needs_model_notice(name: &str) -> String {
559 format!("{name} needs a model to run. Connect one in Settings.")
560}
561
562impl GoalCycle {
563 const ESCALATED_RECOVERY_COOLDOWN_SECS: i64 = 6 * 3600;
568 const ESCALATED_RECOVERY_MAX_ATTEMPTS: u16 = 3;
571
572 pub fn new(
573 state: Arc<dyn SchedulerStore>,
574 presenter: Arc<dyn WorkPresenter>,
575 goal_token_registry: Option<GoalTokenRegistry>,
576 ) -> Self {
577 Self {
578 state,
579 agent: None,
580 hub: None,
581 presenter,
582 goal_token_registry,
583 deferred_retry_running: Arc::new(AtomicBool::new(false)),
584 last_stale_goal_cleanup: None,
585 task_inactivity_timeout_secs: 300,
586 no_model_noticed: Arc::new(needs_model::NeedsModelNotices::new(needs_model::GOALS_KEY)),
587 booted_at: None,
588 }
589 }
590
591 pub fn set_booted_at(&mut self, booted_at: String) {
596 self.booted_at = Some(booted_at);
597 }
598
599 pub(crate) async fn without_model(&self) -> bool {
602 let without = self.agent.as_ref().is_some_and(|agent| !agent.has_model());
603 if !without {
604 self.no_model_noticed.clear(self.state.as_ref()).await;
605 }
606 without
607 }
608
609 pub fn needs_model_notices(&self) -> Arc<needs_model::NeedsModelNotices> {
613 self.no_model_noticed.clone()
614 }
615
616 pub(crate) async fn notice_needs_model(&self, goal: &crate::traits::Goal) {
619 if !self
620 .no_model_noticed
621 .first(self.state.as_ref(), &goal.id)
622 .await
623 {
624 return;
625 }
626 let entry = crate::traits::NotificationEntry::new(
627 &goal.id,
628 &goal.session_id,
629 "evergreen_alert",
630 &needs_model_notice(&self.presenter.goal_label(&goal.description)),
631 );
632 if let Err(error) = self.state.enqueue_notification(&entry).await {
633 warn!(goal_id = %goal.id, %error, "Failed to enqueue the needs-a-model notice");
634 }
635 }
636
637 pub fn set_task_inactivity_timeout(&mut self, secs: u64) {
639 self.task_inactivity_timeout_secs = secs as i64;
640 }
641
642 pub fn set_delivery(&mut self, delivery: Option<Arc<dyn NoticeDelivery>>) {
644 self.hub = delivery;
645 }
646
647 pub fn set_agent(&mut self, agent: Option<Arc<dyn TaskLeadHost>>) {
649 self.agent = agent;
650 }
651
652 fn live_agent(&self) -> Option<Arc<dyn TaskLeadHost>> {
654 self.agent.clone().filter(|agent| agent.available())
655 }
656
657 pub async fn startup_recovery(&self) {
659 info!("Running startup recovery");
660
661 if let Some(booted_at) = self.booted_at.as_deref() {
662 match self
663 .state
664 .expire_attempts_of_previous_instance(booted_at)
665 .await
666 {
667 Ok(count) => {
668 info!(
669 count,
670 "Startup recovery released execution leases of the previous process"
671 );
672 }
673 Err(error) => {
674 error!(%error, "Failed to release the previous process's execution leases");
675 }
676 }
677 }
678
679 if let Some(agent) = &self.agent {
680 let replay = async {
681 for (attempt_id, run_id) in self.state.scheduled_restart_replay_candidates().await?
682 {
683 let tasks = self.state.get_tasks_for_goal_run(&run_id).await?;
684 let ids = tasks.into_iter().map(|task| task.id).collect::<Vec<_>>();
685 let sessions = self.state.goal_run_worker_sessions(&run_id).await?;
686 if !ids.is_empty() && agent.task_tree_is_effect_free(&ids, &sessions).await? {
687 self.state
688 .replay_effect_free_scheduled_attempt(&attempt_id)
689 .await?;
690 }
691 }
692 anyhow::Ok(())
693 }
694 .await;
695 if let Err(error) = replay {
696 error!(%error, "Could not prove scheduled restart replay safe");
697 }
698 let resume = async {
703 for (attempt_id, run_id) in self.state.restart_resume_candidates().await? {
704 let tasks = self.state.get_tasks_for_goal_run(&run_id).await?;
705 let ids = tasks.into_iter().map(|task| task.id).collect::<Vec<_>>();
706 let sessions = self.state.goal_run_worker_sessions(&run_id).await?;
707 if ids.is_empty() || !agent.task_tree_changes_settled(&ids, &sessions).await? {
708 info!(%run_id, "A stopped scheduled run has an unsettled change; not resuming it");
709 continue;
710 }
711 let Some(summary) = agent.restart_resume_summary(&ids, &sessions).await? else {
712 info!(%run_id, "A stopped scheduled run's changes cannot be summarized whole; not resuming it");
713 continue;
714 };
715 if self
716 .state
717 .resume_stopped_scheduled_attempt(&attempt_id, &summary)
718 .await?
719 {
720 info!(%run_id, "Resuming a scheduled run a requested stop cut off");
721 }
722 }
723 anyhow::Ok(())
724 }
725 .await;
726 if let Err(error) = resume {
727 error!(%error, "Could not prove a stopped scheduled run safe to resume");
728 }
729 }
730
731 match self.state.recover_expired_task_attempts().await {
732 Ok(tasks) if !tasks.is_empty() => {
733 info!(
734 count = tasks.len(),
735 "Startup recovery processed expired execution leases"
736 );
737 }
738 Ok(_) => {}
739 Err(error) => {
740 error!(%error, "Failed to recover expired execution leases");
741 }
742 }
743
744 match self.state.get_stuck_tasks(0).await {
749 Ok(tasks) => {
750 let mut interrupted = 0;
751 let mut auto_retried = 0;
752 for task in &tasks {
753 if let Err(e) = self.state.mark_task_interrupted(&task.id).await {
754 error!(task_id = %task.id, error = %e, "Failed to mark task interrupted");
755 continue;
756 }
757 interrupted += 1;
758
759 let goal_active = match self.state.get_goal(&task.goal_id).await {
761 Ok(Some(g)) => g.status == "active",
762 _ => false,
763 };
764
765 if !goal_active {
766 continue;
768 }
769
770 let schedules = self
776 .state
777 .get_schedules_for_goal(&task.goal_id)
778 .await
779 .unwrap_or_default();
780 if !schedules.is_empty() {
781 let active_run = self
782 .state
783 .get_scheduled_run_state(&task.goal_id)
784 .await
785 .ok()
786 .flatten();
787 if active_run.as_ref().is_none_or(|run| {
788 !timestamp_is_at_or_after(&task.created_at, &run.created_at)
789 }) {
790 continue;
791 }
792 }
793
794 if task.idempotent && task.retry_count < task.max_retries {
796 let mut retry_task = task.clone();
797 retry_task.status = "pending".to_string();
798 retry_task.retry_count += 1;
799 retry_task.result = None;
800 retry_task.error = None;
801 retry_task.blocker = None;
802 retry_task.agent_id = None;
803 retry_task.started_at = None;
804 retry_task.completed_at = None;
805 if let Err(e) = self.state.update_task(&retry_task).await {
806 error!(task_id = %task.id, error = %e, "Failed to auto-retry task");
807 } else {
808 auto_retried += 1;
809 info!(task_id = %task.id, retry = retry_task.retry_count, "Auto-retried idempotent task");
810 }
811 }
812 }
815
816 if interrupted > 0 {
817 info!(
818 count = interrupted,
819 auto_retried, "Startup recovery: marked interrupted tasks"
820 );
821 }
822 }
823 Err(e) => {
824 error!(error = %e, "Failed to get stuck tasks during recovery");
825 }
826 }
827
828 match self.state.cleanup_stale_goals(2).await {
831 Ok(count) if count > 0 => {
832 info!(count, "Startup recovery: cleaned up stale goals");
833 }
834 Err(e) => {
835 error!(error = %e, "Failed to cleanup stale goals during recovery");
836 }
837 _ => {}
838 }
839
840 if let Some(ref registry) = self.goal_token_registry {
842 match self.state.get_active_goals().await {
843 Ok(goals) => {
844 registry.rebuild_from_goals(&goals).await;
845 info!(
846 count = goals.len(),
847 "Rebuilt goal token registry from active goals"
848 );
849 }
850 Err(e) => {
851 error!(error = %e, "Failed to rebuild goal token registry");
852 }
853 }
854 }
855
856 info!("Startup recovery complete");
857 }
858
859 pub async fn tick(&mut self) -> anyhow::Result<()> {
862 let now = Instant::now();
863 let without_model = self.without_model().await;
866
867 self.block_pending_tasks_with_terminal_failed_dependencies()
871 .await;
872
873 self.check_due_mandates().await;
877
878 self.reconcile_open_scheduled_runs().await;
882
883 if !without_model {
887 self.launch_escalated_recoveries().await;
888 }
889
890 self.check_due_goal_schedules().await;
892
893 self.detect_stuck_tasks().await;
895
896 match self
898 .state
899 .cancel_stale_pending_confirmation_goals(3600)
900 .await
901 {
902 Ok(count) if count > 0 => {
903 info!(count, "Cancelled stale pending_confirmation goals");
904 }
905 Err(e) => {
906 error!(error = %e, "Failed to cancel stale pending_confirmation goals");
907 }
908 _ => {}
909 }
910
911 let should_cleanup_goals = match self.last_stale_goal_cleanup {
913 None => true,
914 Some(last) => now.duration_since(last) >= Duration::from_secs(1800),
915 };
916 if should_cleanup_goals {
917 self.last_stale_goal_cleanup = Some(now);
918 match self.state.cleanup_stale_goals(2).await {
919 Ok(count) if count > 0 => {
920 info!(count, "Periodic cleanup: marked stale goals");
921 }
922 Err(e) => {
923 error!(error = %e, "Failed to cleanup stale goals");
924 }
925 _ => {}
926 }
927 }
928
929 if !without_model {
931 self.auto_retry_failed_tasks().await;
932 }
933
934 if !without_model {
936 self.dispatch_pending_tasks().await;
937 }
938
939 self.deliver_notifications().await;
941
942 if let Some(agent) = self.live_agent().filter(|_| !without_model)
947 && !self.deferred_retry_running.swap(true, Ordering::AcqRel)
948 {
949 let running = self.deferred_retry_running.clone();
950 tokio::spawn(async move {
951 let dispatched = agent.retry_deferred_provider_requests().await;
952 running.store(false, Ordering::Release);
953 if dispatched > 0 {
954 info!(dispatched, "Re-ran requests deferred by a provider outage");
955 }
956 });
957 }
958
959 Ok(())
960 }
961}
962
963pub struct GoalCycleService {
965 cycle: tokio::sync::Mutex<GoalCycle>,
966}
967
968impl GoalCycleService {
969 pub fn new(cycle: GoalCycle) -> Self {
970 Self {
971 cycle: tokio::sync::Mutex::new(cycle),
972 }
973 }
974}
975
976#[async_trait]
977impl Service for GoalCycleService {
978 fn name(&self) -> &str {
979 "goal_cycle"
980 }
981
982 fn schedule(&self) -> Schedule {
983 Schedule::EveryTick
984 }
985
986 async fn start(&self, _ctx: &ServiceContext) -> Result<(), ServiceError> {
987 self.cycle.lock().await.startup_recovery().await;
988 Ok(())
989 }
990
991 async fn run(&self, _ctx: &ServiceContext) -> Result<(), ServiceError> {
992 self.cycle
993 .lock()
994 .await
995 .tick()
996 .await
997 .map_err(|e| ServiceError::new(e.to_string()))
998 }
999}
1000
1001#[cfg(test)]
1002mod sqlite_busy_tests {
1003 use super::is_sqlite_busy_error;
1004 use sqlx::sqlite::SqliteConnectOptions;
1005 use sqlx::{ConnectOptions, Connection};
1006 use std::str::FromStr;
1007
1008 #[tokio::test]
1009 async fn contention_is_read_from_the_typed_driver_error() {
1010 let file = tempfile::NamedTempFile::new().unwrap();
1011 let url = format!("sqlite://{}", file.path().display());
1012 let options = SqliteConnectOptions::from_str(&url)
1013 .unwrap()
1014 .busy_timeout(std::time::Duration::ZERO);
1015 let mut holder = options.connect().await.unwrap();
1016 sqlx::query("CREATE TABLE t (x INTEGER)")
1017 .execute(&mut holder)
1018 .await
1019 .unwrap();
1020 sqlx::query("BEGIN EXCLUSIVE")
1021 .execute(&mut holder)
1022 .await
1023 .unwrap();
1024 let mut writer = options.connect().await.unwrap();
1025 let busy = sqlx::query("INSERT INTO t VALUES (1)")
1026 .execute(&mut writer)
1027 .await
1028 .unwrap_err();
1029 let busy = anyhow::Error::from(busy).context("claiming the task");
1030 assert!(is_sqlite_busy_error(&busy), "{busy:#}");
1031
1032 assert!(!is_sqlite_busy_error(&anyhow::anyhow!(
1034 "error returned from database: (code: 5) database is locked"
1035 )));
1036 assert!(!is_sqlite_busy_error(&anyhow::anyhow!("SQLITE_BUSY")));
1037 holder.close().await.unwrap();
1038 let missing = sqlx::query("SELECT * FROM missing_table")
1039 .execute(&mut writer)
1040 .await
1041 .unwrap_err();
1042 assert!(!is_sqlite_busy_error(&anyhow::Error::from(missing)));
1043 writer.close().await.unwrap();
1044 }
1045}