aidaemon-work 0.29.0

Goals, mandates, tasks and work coordination with a SQLite store; internal to aidaemon, no stability promise
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
//! Scheduled run discovery must survive consumption of a one-shot schedule.
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();
    // Model an interrupted worker's persisted run status without acquiring a
    // live lease: live workers deliberately retain ownership of reconciliation.
    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);
}

/// A watching automation's review-failure notice held for the morning is
/// closed unsent once a later review of the same automation has finished;
/// one with no later review stays queued.
#[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(&current).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(&current.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);
        // The worker sessions name the task lead's own run, which no task
        // or spawn link reaches.
        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());
        }
    }
}

/// A runtime whose tree changed something (never effect-free), settled or not.
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!()
    }
}

/// A non-idempotent scheduled root claimed by a running worker, so the
/// ordinary recovery path blocks it.
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()
}

/// The shutdown's mark is written for the live attempt and changes nothing
/// else: the run is not failed, the attempt keeps its lease, no notice.
#[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()
    );
}

/// Boot resumes a requested stop's scheduled root once, only with every
/// change settled; a crash (no mark), an in-doubt change and a mandate keep
/// the ordinary recovery.
#[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;
        }
        // The resumed root's lead is handed the whole receipt summary.
        let resume = journal
            .iter()
            .find(|entry| entry.entry_type == JOURNAL_RESTART_RESUME)
            .unwrap();
        assert_eq!(resume.payload.as_deref(), Some(SYNTHETIC_SUMMARY));
        // Cut off again by another requested stop: not resumed a second time.
        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);
    }
}

/// The resume does not need the boot sweep: a marked attempt whose lease
/// ended before the next boot takes the same decision (settled: one resume;
/// in doubt: the ordinary recovery blocks it for verification).
#[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();
        // The boot sweep never saw a live lease.
        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}"
        );
    }
}

/// An executor a requested shutdown cut off leaves its task claimed (not
/// failed): the resume re-queues it with the root, so the resumed lead sees
/// it as unfinished.
#[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());
    }
}