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
use super::tests::{task, test_store};
use super::*;
use crate::traits::*;
use std::sync::Arc;

async fn occurrence_fixture(
    one_shot: bool,
) -> (
    SqliteWorkStore,
    tempfile::NamedTempFile,
    Goal,
    GoalSchedule,
    Task,
) {
    let (store, file) = test_store().await;
    let goal = Goal::new_continuous("Synthetic occurrence", "synthetic-session", None, None);
    store.create_goal(&goal).await.unwrap();
    let now = chrono::Utc::now().to_rfc3339();
    let schedule = GoalSchedule {
        id: uuid::Uuid::new_v4().to_string(),
        goal_id: goal.id.clone(),
        cron_expr: "0 6 * * *".into(),
        tz: "UTC".into(),
        original_schedule: None,
        fire_policy: "always_fire".into(),
        is_one_shot: one_shot,
        is_paused: false,
        last_run_at: None,
        next_run_at: now.clone(),
        created_at: now.clone(),
        updated_at: now,
    };
    store.create_goal_schedule(&schedule).await.unwrap();
    let root = task(&goal.id, "Synthetic root", None);
    (store, file, goal, schedule, root)
}

#[tokio::test]
async fn schedule_occurrence_cas_loss_fires_nothing() {
    let (store, _file, goal, schedule, root) = occurrence_fixture(false).await;
    let next = (chrono::Utc::now() + chrono::Duration::days(1)).to_rfc3339();
    let run = store
        .enqueue_scheduled_occurrence(&schedule, &next, &goal, &root, None)
        .await
        .unwrap()
        .unwrap();
    let fresh_goal = store.get_goal(&goal.id).await.unwrap().unwrap();
    let other = task(&goal.id, "Another root", None);
    assert!(
        store
            .enqueue_scheduled_occurrence(&schedule, &next, &fresh_goal, &other, None)
            .await
            .unwrap()
            .is_none()
    );
    assert_eq!(store.get_goal_runs(&goal.id).await.unwrap().len(), 1);
    assert_eq!(
        store.get_tasks_for_goal_run(&run.id).await.unwrap().len(),
        1
    );
    assert!(store.get_task(&other.id).await.unwrap().is_none());
}

#[tokio::test]
async fn schedule_occurrence_task_failure_rolls_back_every_write() {
    for one_shot in [false, true] {
        let (store, _file, goal, schedule, root) = occurrence_fixture(one_shot).await;
        sqlx::query("CREATE TRIGGER reject_root BEFORE INSERT ON tasks BEGIN SELECT RAISE(ABORT, 'synthetic task failure'); END")
            .execute(&store.pool).await.unwrap();
        let next = (chrono::Utc::now() + chrono::Duration::days(1)).to_rfc3339();
        assert!(
            store
                .enqueue_scheduled_occurrence(&schedule, &next, &goal, &root, None)
                .await
                .is_err()
        );
        let saved = store
            .get_goal_schedule(&schedule.id)
            .await
            .unwrap()
            .unwrap();
        assert_eq!(saved.next_run_at, schedule.next_run_at);
        assert_eq!(saved.last_run_at, None);
        assert!(store.get_goal_runs(&goal.id).await.unwrap().is_empty());
        assert_eq!(
            store
                .get_goal(&goal.id)
                .await
                .unwrap()
                .unwrap()
                .last_useful_action,
            goal.last_useful_action
        );
    }
}

#[tokio::test]
async fn schedule_occurrence_one_shot_consumed_with_run_and_root() {
    let (store, _file, goal, schedule, root) = occurrence_fixture(true).await;
    let run = store
        .enqueue_scheduled_occurrence(&schedule, &schedule.next_run_at, &goal, &root, None)
        .await
        .unwrap()
        .unwrap();
    assert!(
        store
            .get_goal_schedule(&schedule.id)
            .await
            .unwrap()
            .is_none()
    );
    assert_eq!(run.root_task_id.as_deref(), Some(root.id.as_str()));
    assert_eq!(
        store.get_tasks_for_goal_run(&run.id).await.unwrap()[0].id,
        root.id
    );
    assert!(
        store
            .enqueue_scheduled_occurrence(&schedule, &schedule.next_run_at, &goal, &root, None)
            .await
            .unwrap()
            .is_none()
    );
}

#[tokio::test]
async fn schedule_occurrence_rechecks_pause_and_backpressure() {
    let (store, _file, goal, mut schedule, root) = occurrence_fixture(false).await;
    schedule.fire_policy = "coalesce".into();
    store.update_goal_schedule(&schedule).await.unwrap();
    let mut paused = schedule.clone();
    paused.is_paused = true;
    store.update_goal_schedule(&paused).await.unwrap();
    assert!(
        store
            .enqueue_scheduled_occurrence(&schedule, &schedule.next_run_at, &goal, &root, None)
            .await
            .unwrap()
            .is_none()
    );
    store.update_goal_schedule(&schedule).await.unwrap();
    store
        .create_task(&task(&goal.id, "Existing work", None))
        .await
        .unwrap();
    assert!(
        store
            .enqueue_scheduled_occurrence(&schedule, &schedule.next_run_at, &goal, &root, None)
            .await
            .unwrap()
            .is_none()
    );
}

#[tokio::test]
async fn goal_run_empty_pending_boot_repair_allows_next_schedule() {
    for trigger in ["manual", "scheduled"] {
        let (store, _file, goal, schedule, root) = occurrence_fixture(false).await;
        let orphan = store
            .start_goal_run(&goal.id, trigger, Some(&schedule.id), None)
            .await
            .unwrap();
        sqlx::query("UPDATE goal_runs SET created_at = '2000-01-01T00:00:00Z' WHERE id = ?")
            .bind(&orphan.id)
            .execute(&store.pool)
            .await
            .unwrap();
        store
            .expire_attempts_of_previous_instance("2001-01-01T00:00:00Z")
            .await
            .unwrap();
        let repaired = store.get_goal_runs(&goal.id).await.unwrap().remove(0);
        assert_eq!(repaired.status, crate::goals::GOAL_RUN_INTERRUPTED);
        assert_eq!(
            serde_json::from_str::<serde_json::Value>(repaired.outcome_summary.as_deref().unwrap())
                .unwrap()["reason"],
            "previous_instance_stopped_before_task_creation"
        );
        assert!(
            store
                .get_current_goal_run(&goal.id)
                .await
                .unwrap()
                .is_none()
        );
        let run = store
            .enqueue_scheduled_occurrence(&schedule, &schedule.next_run_at, &goal, &root, None)
            .await
            .unwrap()
            .unwrap();
        assert_ne!(run.id, orphan.id);
        store
            .expire_attempts_of_previous_instance("2100-01-01T00:00:00Z")
            .await
            .unwrap();
        assert_eq!(
            store
                .get_current_goal_run(&goal.id)
                .await
                .unwrap()
                .unwrap()
                .id,
            run.id
        );
    }
}

#[tokio::test]
async fn goal_run_empty_pending_current_process_is_not_repaired() {
    let (store, _file, goal, _, _) = occurrence_fixture(false).await;
    let run = store
        .start_goal_run(&goal.id, "manual", None, None)
        .await
        .unwrap();
    store
        .expire_attempts_of_previous_instance("2000-01-01T00:00:00Z")
        .await
        .unwrap();
    assert_eq!(
        store
            .get_current_goal_run(&goal.id)
            .await
            .unwrap()
            .unwrap()
            .id,
        run.id
    );
}

#[tokio::test]
async fn scheduler_reminder_delivery_failure_keeps_durable_root() {
    struct Presenter;
    impl crate::scheduler::WorkPresenter for Presenter {
        fn goal_label(&self, text: &str) -> String {
            text.into()
        }
        fn user_facing(&self, text: &str) -> String {
            text.into()
        }
        fn notification(&self, _: &str, text: &str) -> String {
            text.into()
        }
        fn goal_task_results(&self, _: &[Task], _: Option<&str>, text: &str) -> String {
            text.into()
        }
    }
    let (store, _file, mut goal, schedule, _) = occurrence_fixture(true).await;
    goal.context = Some(crate::reminders::context_for_message("Synthetic reminder"));
    store.update_goal(&goal).await.unwrap();
    let state = Arc::new(store);
    let cycle = crate::scheduler::GoalCycle::new(state.clone(), Arc::new(Presenter), None);
    cycle.fire_due_schedule(schedule.clone()).await.unwrap();
    assert!(
        state
            .get_goal_schedule(&schedule.id)
            .await
            .unwrap()
            .is_none()
    );
    let run = state.get_current_goal_run(&goal.id).await.unwrap().unwrap();
    let tasks = state.get_tasks_for_goal_run(&run.id).await.unwrap();
    assert_eq!(tasks.len(), 1);
    assert_eq!(tasks[0].status, "pending");
    assert_eq!(run.root_task_id.as_deref(), Some(tasks[0].id.as_str()));
}

#[tokio::test]
async fn schedule_occurrence_rechecks_budget_and_confirmation() {
    let (store, _file, goal, schedule, root) = occurrence_fixture(false).await;
    let mut changed = goal.clone();
    changed.status = "pending_confirmation".into();
    store.update_goal(&changed).await.unwrap();
    assert!(
        store
            .enqueue_scheduled_occurrence(&schedule, &schedule.next_run_at, &goal, &root, None)
            .await
            .unwrap()
            .is_none()
    );
    changed.status = "active".into();
    changed.budget_daily = Some(10);
    changed.tokens_used_today = 10;
    changed.tokens_used_day = chrono::Utc::now().date_naive().to_string();
    store.update_goal(&changed).await.unwrap();
    assert!(
        store
            .enqueue_scheduled_occurrence(&schedule, &schedule.next_run_at, &goal, &root, None)
            .await
            .unwrap()
            .is_none()
    );
    assert!(
        store
            .enqueue_scheduled_occurrence(
                &schedule,
                &schedule.next_run_at,
                &changed,
                &root,
                Some(10)
            )
            .await
            .unwrap()
            .is_none()
    );
    assert!(store.get_goal_runs(&goal.id).await.unwrap().is_empty());
    assert_eq!(
        store
            .get_goal_schedule(&schedule.id)
            .await
            .unwrap()
            .unwrap()
            .last_run_at,
        None
    );
}

#[tokio::test]
async fn scheduled_restart_replay_once_keeps_run_pending() {
    let (store, _file, goal, schedule, mut root) = occurrence_fixture(false).await;
    root.idempotent = false;
    root.max_retries = 0;
    let next = (chrono::Utc::now() + chrono::Duration::days(1)).to_rfc3339();
    let run = store
        .enqueue_scheduled_occurrence(&schedule, &next, &goal, &root, None)
        .await
        .unwrap()
        .unwrap();
    let attempt = store
        .claim_task_with_lease(&root.id, "synthetic-worker", None, 180)
        .await
        .unwrap()
        .unwrap();
    assert!(
        store
            .scheduled_restart_replay_candidates()
            .await
            .unwrap()
            .is_empty()
    );
    assert!(
        !store
            .replay_effect_free_scheduled_attempt(&attempt.id)
            .await
            .unwrap()
    );
    let boot = (chrono::Utc::now() + chrono::Duration::seconds(1)).to_rfc3339();
    store
        .expire_attempts_of_previous_instance(&boot)
        .await
        .unwrap();
    assert_eq!(
        store.scheduled_restart_replay_candidates().await.unwrap(),
        vec![(attempt.id.clone(), run.id.clone())]
    );
    assert!(
        store
            .replay_effect_free_scheduled_attempt(&attempt.id)
            .await
            .unwrap()
    );
    assert!(
        store
            .recover_expired_task_attempts()
            .await
            .unwrap()
            .is_empty()
    );
    let replay = store.get_task(&root.id).await.unwrap().unwrap();
    assert_eq!(replay.status, "pending");
    assert_eq!(replay.retry_count, 1);
    assert!(!replay.idempotent);
    assert_eq!(
        store.get_goal_runs(&goal.id).await.unwrap()[0].status,
        "pending"
    );
    let second = store
        .claim_task_with_lease(&root.id, "synthetic-worker", None, 180)
        .await
        .unwrap()
        .unwrap();
    assert_ne!(second.id, attempt.id);
    store
        .expire_attempts_of_previous_instance(&boot)
        .await
        .unwrap();
    assert!(
        store
            .scheduled_restart_replay_candidates()
            .await
            .unwrap()
            .is_empty()
    );
    assert!(
        !store
            .replay_effect_free_scheduled_attempt(&second.id)
            .await
            .unwrap()
    );
    store.recover_expired_task_attempts().await.unwrap();
    assert_eq!(
        store.get_task(&root.id).await.unwrap().unwrap().status,
        "blocked"
    );
}

#[tokio::test]
async fn scheduled_restart_replay_excludes_ordinary_lease_expiry() {
    let (store, _file, goal, schedule, mut root) = occurrence_fixture(false).await;
    root.idempotent = false;
    root.max_retries = 0;
    let next = (chrono::Utc::now() + chrono::Duration::days(1)).to_rfc3339();
    store
        .enqueue_scheduled_occurrence(&schedule, &next, &goal, &root, None)
        .await
        .unwrap()
        .unwrap();
    let attempt = store
        .claim_task_with_lease(&root.id, "synthetic-worker", None, 180)
        .await
        .unwrap()
        .unwrap();
    sqlx::query(
        "UPDATE task_attempts SET lease_expires_at = datetime('now', '-1 second') WHERE id = ?",
    )
    .bind(&attempt.id)
    .execute(&store.pool)
    .await
    .unwrap();
    assert!(
        store
            .scheduled_restart_replay_candidates()
            .await
            .unwrap()
            .is_empty()
    );
    assert!(
        !store
            .replay_effect_free_scheduled_attempt(&attempt.id)
            .await
            .unwrap()
    );
    store.recover_expired_task_attempts().await.unwrap();
    assert_eq!(
        store.get_task(&root.id).await.unwrap().unwrap().status,
        "blocked"
    );
}