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 fn spawn_task_lead(
77 &self,
78 goal: crate::traits::Goal,
79 task_text: String,
80 task_id: String,
81 running_surface_id: Option<String>,
82 );
83
84 fn next_model_answer_at(&self) -> Option<SystemTime>;
86
87 async fn retry_deferred_provider_requests(&self) -> usize;
89
90 async fn tainted_note_turn(&self, session_id: &str) -> anyhow::Result<String>;
92
93 async fn record_parent_visible_result_note_in_turn(
95 &self,
96 session_id: &str,
97 prefix: &str,
98 text: &str,
99 turn_id: Option<&str>,
100 ) -> anyhow::Result<()>;
101
102 async fn record_mandate_owner_input_context(
104 &self,
105 session_id: &str,
106 mandate_id: &str,
107 mandate_version: i64,
108 action_token: &str,
109 ) -> anyhow::Result<()>;
110}
111
112#[async_trait]
114pub trait NoticeDelivery: Send + Sync {
115 async fn send_text(&self, session_id: &str, text: &str) -> anyhow::Result<()>;
117
118 async fn send_text_tracked(
121 &self,
122 session_id: &str,
123 text: &str,
124 ) -> anyhow::Result<Option<String>>;
125
126 async fn owner_active_since(&self, _session_id: &str, _since: DateTime<Utc>) -> bool {
130 false
131 }
132}
133
134pub trait WorkPresenter: Send + Sync {
136 fn goal_label(&self, description: &str) -> String;
138
139 fn user_facing(&self, text: &str) -> String;
141
142 fn notification(&self, notification_type: &str, text: &str) -> String;
144
145 fn goal_task_results(
147 &self,
148 tasks: &[crate::traits::Task],
149 root_task_id: Option<&str>,
150 fallback: &str,
151 ) -> String;
152}
153
154pub const TASK_ESCALATION_SETTLE_SECS: i64 = 8;
155pub const QUEUED_NOTIFICATION_NOTE_PREFIX: &str = "Parent-visible result (goal notification)";
158
159pub fn notice_accepts_mandate_answer(notification_type: &str) -> bool {
162 matches!(notification_type, "mandate_ask" | "mandate_ask_timeout")
163}
164pub const MANDATE_REVIEW_LEASE_SECS: i64 = 30 * 60;
165pub const MANDATE_REVIEW_BATCH_SIZE: i64 = 20;
166pub const MANDATE_DISPATCH_BUSY_RETRIES: u32 = 5;
167pub const MANDATE_DISPATCH_BUSY_RETRY_SECS: i64 = 30;
168
169pub fn mandate_retry_at(mandate: &Mandate, requested_secs: Option<i64>) -> String {
170 let delay = mandate.clamp_review_secs(requested_secs);
171 (chrono::Utc::now() + chrono::Duration::seconds(delay)).to_rfc3339()
172}
173
174pub fn mandate_budget_retry_at(mandate: &Mandate, now: chrono::DateTime<Utc>) -> String {
175 let next_day = now
176 .date_naive()
177 .succ_opt()
178 .expect("the next UTC date is representable")
179 .and_hms_opt(0, 0, 0)
180 .expect("UTC midnight is representable");
181 let mut retry_at = chrono::DateTime::<Utc>::from_naive_utc_and_offset(next_day, Utc);
182 if let Some(expiry) = mandate
183 .expires_at
184 .as_deref()
185 .and_then(|value| chrono::DateTime::parse_from_rfc3339(value).ok())
186 .map(|value| value.with_timezone(&Utc))
187 {
188 retry_at = retry_at.min(expiry);
189 }
190 retry_at.to_rfc3339()
191}
192
193pub fn mandate_transient_retry_at(mandate: &Mandate, now: chrono::DateTime<Utc>) -> String {
194 let mut retry_at = now + chrono::Duration::seconds(MANDATE_DISPATCH_BUSY_RETRY_SECS);
195 if let Some(expiry) = mandate
196 .expires_at
197 .as_deref()
198 .and_then(|value| chrono::DateTime::parse_from_rfc3339(value).ok())
199 .map(|value| value.with_timezone(&Utc))
200 {
201 retry_at = retry_at.min(expiry);
202 }
203 retry_at.to_rfc3339()
204}
205
206pub async fn retry_on_busy<T, F, Fut>(
211 what: &str,
212 max_retries: usize,
213 mut op: F,
214) -> anyhow::Result<T>
215where
216 F: FnMut() -> Fut,
217 Fut: std::future::Future<Output = anyhow::Result<T>>,
218{
219 let mut retry = 0_usize;
220 loop {
221 match op().await {
222 Err(error) if retry < max_retries && is_sqlite_busy_error(&error) => {
223 let delay_ms = 25_u64 << retry;
224 retry += 1;
225 tracing::warn!(what, retry, delay_ms, %error, "SQLite busy; retrying");
226 tokio::time::sleep(std::time::Duration::from_millis(delay_ms)).await;
227 }
228 result => return result,
229 }
230 }
231}
232
233pub fn is_sqlite_busy_error(error: &anyhow::Error) -> bool {
239 const SQLITE_BUSY: i32 = 5;
240 const SQLITE_LOCKED: i32 = 6;
241 error.chain().any(|cause| {
242 let Some(sqlx::Error::Database(database)) = cause.downcast_ref::<sqlx::Error>() else {
243 return false;
244 };
245 database
246 .code()
247 .and_then(|code| code.parse::<i32>().ok())
248 .is_some_and(|code| matches!(code & 0xff, SQLITE_BUSY | SQLITE_LOCKED))
249 })
250}
251
252pub fn mandate_review_task_description(mandate: &Mandate, goal_run_id: &str) -> String {
253 format!(
257 "Run one bounded autonomous review for mandate {} version {} in goal run {}. \
258 Use only the isolated built-in mandate protocol and immutable policy supplied \
259 by the runtime.",
260 mandate.id, mandate.version, goal_run_id
261 )
262}
263
264pub fn mandate_review_task_context(mandate: &Mandate) -> String {
265 serde_json::json!({
266 "mandate_id": mandate.id,
267 "mandate_version": mandate.version,
268 "provenance": "runtime_mandate_fence_only",
269 })
270 .to_string()
271}
272
273pub fn timestamp_is_at_or_after(value: &str, lower_bound: &str) -> bool {
274 match (
275 chrono::DateTime::parse_from_rfc3339(value),
276 chrono::DateTime::parse_from_rfc3339(lower_bound),
277 ) {
278 (Ok(value), Ok(lower_bound)) => value >= lower_bound,
279 _ => value >= lower_bound,
280 }
281}
282
283pub fn goal_completion_header(tasks: &[crate::traits::Task]) -> String {
293 if tasks.is_empty() {
294 return aidaemon_channels::presentation::GOAL_COMPLETED_LEAD.to_string();
295 }
296 let total = tasks.len();
297 let done = tasks.iter().filter(|t| t.status == "completed").count();
298 if done == total {
299 return aidaemon_channels::presentation::GOAL_COMPLETED_LEAD.to_string();
300 }
301 let missing: Vec<String> = tasks
302 .iter()
303 .filter(|t| t.status != "completed")
304 .map(|t| {
305 format!(
306 "• {} ({})",
307 t.description.chars().take(80).collect::<String>(),
308 t.status
309 )
310 })
311 .collect();
312 format!(
313 "Goal partially completed ({done}/{total} tasks). Not completed:\n{}\n",
314 missing.join("\n")
315 )
316}
317
318pub fn daily_budget_exhausted(
319 budget_daily: Option<i64>,
320 tokens_used_today: i64,
321 tokens_used_day: &str,
322 today: &str,
323) -> bool {
324 match budget_daily {
325 Some(budget) => tokens_used_day == today && tokens_used_today >= budget,
326 None => false,
327 }
328}
329
330pub fn daily_budget_has_run_capacity(
331 budget_daily: Option<i64>,
332 budget_per_check: Option<i64>,
333 tokens_used_today: i64,
334 tokens_used_day: &str,
335 today: &str,
336) -> bool {
337 let (Some(daily), Some(per_run)) = (budget_daily, budget_per_check) else {
338 return true;
339 };
340 if tokens_used_day != today {
341 return true;
342 }
343 daily.saturating_sub(tokens_used_today) >= per_run.max(0)
344}
345
346pub fn parse_datetime_flexible(s: &str) -> Option<chrono::DateTime<chrono::Utc>> {
357 chrono::DateTime::parse_from_rfc3339(s)
358 .map(|d| d.with_timezone(&chrono::Utc))
359 .ok()
360 .or_else(|| {
361 chrono::NaiveDateTime::parse_from_str(s, "%Y-%m-%d %H:%M:%S")
362 .ok()
363 .map(|nd| nd.and_utc())
364 })
365}
366
367pub fn task_escalation_has_settled(created_at: &str, now: chrono::DateTime<chrono::Utc>) -> bool {
368 parse_datetime_flexible(created_at)
369 .is_none_or(|created_at| (now - created_at).num_seconds() >= TASK_ESCALATION_SETTLE_SECS)
370}
371
372pub fn task_inactivity_secs(
373 last_activity: Option<&str>,
374 started_at: &str,
375 now: chrono::DateTime<chrono::Utc>,
376) -> i64 {
377 let reference = last_activity
378 .and_then(parse_datetime_flexible)
379 .or_else(|| parse_datetime_flexible(started_at));
380 match reference {
381 Some(ts) => (now - ts).num_seconds().max(0),
382 None => 0,
383 }
384}
385
386pub fn task_status_is_terminal_failure(status: &str) -> bool {
389 matches!(
390 status,
391 "failed" | "blocked" | "interrupted" | "cancelled" | "abandoned"
392 )
393}
394
395pub fn task_is_blocked_by_terminal_dependency(
401 task: &crate::traits::Task,
402 run_tasks: &[crate::traits::Task],
403) -> bool {
404 task.status == "blocked"
405 && task.dependency_ids().is_ok_and(|dependencies| {
406 dependencies.iter().any(|dependency| {
407 run_tasks.iter().any(|other| {
408 other.id == *dependency && task_status_is_terminal_failure(&other.status)
409 })
410 })
411 })
412}
413
414pub fn task_blocks_schedule_fire(
415 task: &crate::traits::Task,
416 run_tasks: &[crate::traits::Task],
417) -> bool {
418 matches!(task.status.as_str(), "pending" | "claimed" | "running")
419 || (task.status == "blocked" && !task_is_blocked_by_terminal_dependency(task, run_tasks))
420}
421
422pub fn task_blocks_later_schedule_fire(
423 run: &crate::traits::GoalRun,
424 task: &crate::traits::Task,
425 run_tasks: &[crate::traits::Task],
426) -> bool {
427 if !matches!(run.status.as_str(), "pending" | "running" | "blocked") {
431 return false;
432 }
433 run.status != "blocked" && task_blocks_schedule_fire(task, run_tasks)
439}
440
441pub fn task_is_terminal_schedule_failure(task: &crate::traits::Task) -> bool {
442 matches!(
443 task.status.as_str(),
444 "failed" | "interrupted" | "cancelled" | "blocked"
445 )
446}
447
448pub fn scheduled_run_reconciliation_status(
453 run: &crate::traits::GoalRun,
454 tasks: &[crate::traits::Task],
455) -> Option<&'static str> {
456 if !matches!(
457 run.trigger_type.as_str(),
458 "scheduled" | "manual" | "recovery"
459 ) || !matches!(run.status.as_str(), "pending" | "running")
460 || tasks.is_empty()
461 {
462 return None;
463 }
464 let terminal_failure = tasks.iter().any(|task| {
469 if run.trigger_type == "scheduled" {
470 task_is_terminal_schedule_failure(task)
471 } else {
472 matches!(task.status.as_str(), "failed" | "interrupted" | "cancelled")
473 }
474 });
475 if terminal_failure {
476 Some("failed")
477 } else if tasks
478 .iter()
479 .all(crate::traits::Task::satisfies_run_completion)
480 {
481 Some("completed")
482 } else {
483 None
484 }
485}
486
487pub fn stranded_manual_run_matches_pending_tasks(
488 run: &crate::traits::GoalRun,
489 run_tasks: &[crate::traits::Task],
490 pending_tasks: &[&crate::traits::Task],
491) -> bool {
492 run.trigger_type == "manual"
493 && matches!(run.status.as_str(), "pending" | "running")
494 && pending_tasks
495 .iter()
496 .any(|pending| run_tasks.iter().any(|task| task.id == pending.id))
497}
498
499pub struct GoalCycle {
501 pub(crate) state: Arc<dyn SchedulerStore>,
502 pub(crate) agent: Option<Arc<dyn TaskLeadHost>>,
503 pub(crate) hub: Option<Arc<dyn NoticeDelivery>>,
504 pub(crate) presenter: Arc<dyn WorkPresenter>,
505 pub(crate) goal_token_registry: Option<GoalTokenRegistry>,
506 deferred_retry_running: Arc<AtomicBool>,
507 last_stale_goal_cleanup: Option<Instant>,
508 pub task_inactivity_timeout_secs: i64,
511 no_model_noticed: Arc<needs_model::NeedsModelNotices>,
514}
515
516pub fn needs_model_notice(name: &str) -> String {
518 format!("{name} needs a model to run. Connect one in Settings.")
519}
520
521impl GoalCycle {
522 const ESCALATED_RECOVERY_COOLDOWN_SECS: i64 = 6 * 3600;
527 const ESCALATED_RECOVERY_MAX_ATTEMPTS: u16 = 3;
530
531 pub fn new(
532 state: Arc<dyn SchedulerStore>,
533 presenter: Arc<dyn WorkPresenter>,
534 goal_token_registry: Option<GoalTokenRegistry>,
535 ) -> Self {
536 Self {
537 state,
538 agent: None,
539 hub: None,
540 presenter,
541 goal_token_registry,
542 deferred_retry_running: Arc::new(AtomicBool::new(false)),
543 last_stale_goal_cleanup: None,
544 task_inactivity_timeout_secs: 300,
545 no_model_noticed: Arc::new(needs_model::NeedsModelNotices::new(needs_model::GOALS_KEY)),
546 }
547 }
548
549 pub(crate) async fn without_model(&self) -> bool {
552 let without = self.agent.as_ref().is_some_and(|agent| !agent.has_model());
553 if !without {
554 self.no_model_noticed.clear(self.state.as_ref()).await;
555 }
556 without
557 }
558
559 pub fn needs_model_notices(&self) -> Arc<needs_model::NeedsModelNotices> {
563 self.no_model_noticed.clone()
564 }
565
566 pub(crate) async fn notice_needs_model(&self, goal: &crate::traits::Goal) {
569 if !self
570 .no_model_noticed
571 .first(self.state.as_ref(), &goal.id)
572 .await
573 {
574 return;
575 }
576 let entry = crate::traits::NotificationEntry::new(
577 &goal.id,
578 &goal.session_id,
579 "evergreen_alert",
580 &needs_model_notice(&self.presenter.goal_label(&goal.description)),
581 );
582 if let Err(error) = self.state.enqueue_notification(&entry).await {
583 warn!(goal_id = %goal.id, %error, "Failed to enqueue the needs-a-model notice");
584 }
585 }
586
587 pub fn set_task_inactivity_timeout(&mut self, secs: u64) {
589 self.task_inactivity_timeout_secs = secs as i64;
590 }
591
592 pub fn set_delivery(&mut self, delivery: Option<Arc<dyn NoticeDelivery>>) {
594 self.hub = delivery;
595 }
596
597 pub fn set_agent(&mut self, agent: Option<Arc<dyn TaskLeadHost>>) {
599 self.agent = agent;
600 }
601
602 fn live_agent(&self) -> Option<Arc<dyn TaskLeadHost>> {
604 self.agent.clone().filter(|agent| agent.available())
605 }
606
607 pub async fn startup_recovery(&self) {
609 info!("Running startup recovery");
610
611 match self.state.recover_expired_task_attempts().await {
612 Ok(tasks) if !tasks.is_empty() => {
613 info!(
614 count = tasks.len(),
615 "Startup recovery processed expired execution leases"
616 );
617 }
618 Ok(_) => {}
619 Err(error) => {
620 error!(%error, "Failed to recover expired execution leases");
621 }
622 }
623
624 match self.state.get_stuck_tasks(0).await {
629 Ok(tasks) => {
630 let mut interrupted = 0;
631 let mut auto_retried = 0;
632 for task in &tasks {
633 if let Err(e) = self.state.mark_task_interrupted(&task.id).await {
634 error!(task_id = %task.id, error = %e, "Failed to mark task interrupted");
635 continue;
636 }
637 interrupted += 1;
638
639 let goal_active = match self.state.get_goal(&task.goal_id).await {
641 Ok(Some(g)) => g.status == "active",
642 _ => false,
643 };
644
645 if !goal_active {
646 continue;
648 }
649
650 let schedules = self
656 .state
657 .get_schedules_for_goal(&task.goal_id)
658 .await
659 .unwrap_or_default();
660 if !schedules.is_empty() {
661 let active_run = self
662 .state
663 .get_scheduled_run_state(&task.goal_id)
664 .await
665 .ok()
666 .flatten();
667 if active_run.as_ref().is_none_or(|run| {
668 !timestamp_is_at_or_after(&task.created_at, &run.created_at)
669 }) {
670 continue;
671 }
672 }
673
674 if task.idempotent && task.retry_count < task.max_retries {
676 let mut retry_task = task.clone();
677 retry_task.status = "pending".to_string();
678 retry_task.retry_count += 1;
679 retry_task.result = None;
680 retry_task.error = None;
681 retry_task.blocker = None;
682 retry_task.agent_id = None;
683 retry_task.started_at = None;
684 retry_task.completed_at = None;
685 if let Err(e) = self.state.update_task(&retry_task).await {
686 error!(task_id = %task.id, error = %e, "Failed to auto-retry task");
687 } else {
688 auto_retried += 1;
689 info!(task_id = %task.id, retry = retry_task.retry_count, "Auto-retried idempotent task");
690 }
691 }
692 }
695
696 if interrupted > 0 {
697 info!(
698 count = interrupted,
699 auto_retried, "Startup recovery: marked interrupted tasks"
700 );
701 }
702 }
703 Err(e) => {
704 error!(error = %e, "Failed to get stuck tasks during recovery");
705 }
706 }
707
708 match self.state.cleanup_stale_goals(2).await {
711 Ok(count) if count > 0 => {
712 info!(count, "Startup recovery: cleaned up stale goals");
713 }
714 Err(e) => {
715 error!(error = %e, "Failed to cleanup stale goals during recovery");
716 }
717 _ => {}
718 }
719
720 if let Some(ref registry) = self.goal_token_registry {
722 match self.state.get_active_goals().await {
723 Ok(goals) => {
724 registry.rebuild_from_goals(&goals).await;
725 info!(
726 count = goals.len(),
727 "Rebuilt goal token registry from active goals"
728 );
729 }
730 Err(e) => {
731 error!(error = %e, "Failed to rebuild goal token registry");
732 }
733 }
734 }
735
736 info!("Startup recovery complete");
737 }
738
739 pub async fn tick(&mut self) -> anyhow::Result<()> {
742 let now = Instant::now();
743 let without_model = self.without_model().await;
746
747 self.block_pending_tasks_with_terminal_failed_dependencies()
751 .await;
752
753 self.check_due_mandates().await;
757
758 self.reconcile_open_scheduled_runs().await;
762
763 if !without_model {
767 self.launch_escalated_recoveries().await;
768 }
769
770 self.check_due_goal_schedules().await;
772
773 self.detect_stuck_tasks().await;
775
776 match self
778 .state
779 .cancel_stale_pending_confirmation_goals(3600)
780 .await
781 {
782 Ok(count) if count > 0 => {
783 info!(count, "Cancelled stale pending_confirmation goals");
784 }
785 Err(e) => {
786 error!(error = %e, "Failed to cancel stale pending_confirmation goals");
787 }
788 _ => {}
789 }
790
791 let should_cleanup_goals = match self.last_stale_goal_cleanup {
793 None => true,
794 Some(last) => now.duration_since(last) >= Duration::from_secs(1800),
795 };
796 if should_cleanup_goals {
797 self.last_stale_goal_cleanup = Some(now);
798 match self.state.cleanup_stale_goals(2).await {
799 Ok(count) if count > 0 => {
800 info!(count, "Periodic cleanup: marked stale goals");
801 }
802 Err(e) => {
803 error!(error = %e, "Failed to cleanup stale goals");
804 }
805 _ => {}
806 }
807 }
808
809 if !without_model {
811 self.auto_retry_failed_tasks().await;
812 }
813
814 if !without_model {
816 self.dispatch_pending_tasks().await;
817 }
818
819 self.deliver_notifications().await;
821
822 if let Some(agent) = self.live_agent().filter(|_| !without_model)
827 && !self.deferred_retry_running.swap(true, Ordering::AcqRel)
828 {
829 let running = self.deferred_retry_running.clone();
830 tokio::spawn(async move {
831 let dispatched = agent.retry_deferred_provider_requests().await;
832 running.store(false, Ordering::Release);
833 if dispatched > 0 {
834 info!(dispatched, "Re-ran requests deferred by a provider outage");
835 }
836 });
837 }
838
839 Ok(())
840 }
841}
842
843pub struct GoalCycleService {
845 cycle: tokio::sync::Mutex<GoalCycle>,
846}
847
848impl GoalCycleService {
849 pub fn new(cycle: GoalCycle) -> Self {
850 Self {
851 cycle: tokio::sync::Mutex::new(cycle),
852 }
853 }
854}
855
856#[async_trait]
857impl Service for GoalCycleService {
858 fn name(&self) -> &str {
859 "goal_cycle"
860 }
861
862 fn schedule(&self) -> Schedule {
863 Schedule::EveryTick
864 }
865
866 async fn start(&self, _ctx: &ServiceContext) -> Result<(), ServiceError> {
867 self.cycle.lock().await.startup_recovery().await;
868 Ok(())
869 }
870
871 async fn run(&self, _ctx: &ServiceContext) -> Result<(), ServiceError> {
872 self.cycle
873 .lock()
874 .await
875 .tick()
876 .await
877 .map_err(|e| ServiceError::new(e.to_string()))
878 }
879}
880
881#[cfg(test)]
882mod sqlite_busy_tests {
883 use super::is_sqlite_busy_error;
884 use sqlx::sqlite::SqliteConnectOptions;
885 use sqlx::{ConnectOptions, Connection};
886 use std::str::FromStr;
887
888 #[tokio::test]
889 async fn contention_is_read_from_the_typed_driver_error() {
890 let file = tempfile::NamedTempFile::new().unwrap();
891 let url = format!("sqlite://{}", file.path().display());
892 let options = SqliteConnectOptions::from_str(&url)
893 .unwrap()
894 .busy_timeout(std::time::Duration::ZERO);
895 let mut holder = options.connect().await.unwrap();
896 sqlx::query("CREATE TABLE t (x INTEGER)")
897 .execute(&mut holder)
898 .await
899 .unwrap();
900 sqlx::query("BEGIN EXCLUSIVE")
901 .execute(&mut holder)
902 .await
903 .unwrap();
904 let mut writer = options.connect().await.unwrap();
905 let busy = sqlx::query("INSERT INTO t VALUES (1)")
906 .execute(&mut writer)
907 .await
908 .unwrap_err();
909 let busy = anyhow::Error::from(busy).context("claiming the task");
910 assert!(is_sqlite_busy_error(&busy), "{busy:#}");
911
912 assert!(!is_sqlite_busy_error(&anyhow::anyhow!(
914 "error returned from database: (code: 5) database is locked"
915 )));
916 assert!(!is_sqlite_busy_error(&anyhow::anyhow!("SQLITE_BUSY")));
917 holder.close().await.unwrap();
918 let missing = sqlx::query("SELECT * FROM missing_table")
919 .execute(&mut writer)
920 .await
921 .unwrap_err();
922 assert!(!is_sqlite_busy_error(&anyhow::Error::from(missing)));
923 writer.close().await.unwrap();
924 }
925}