1use super::*;
2
3fn background_spawn_from_row(row: &sqlx::sqlite::SqliteRow) -> crate::traits::BackgroundSpawn {
4 crate::traits::BackgroundSpawn {
5 id: row.get("id"),
6 session_id: row.get("session_id"),
7 mission: row.get("mission"),
8 started_at: row.get("started_at"),
9 }
10}
11
12pub(super) async fn enqueue_mandate_run_notification_on_connection(
20 connection: &mut sqlx::SqliteConnection,
21 notice: &crate::traits::MandateRunNotification,
22) -> anyhow::Result<bool> {
23 notice.validate().map_err(|error| anyhow::anyhow!(error))?;
24 let named;
28 let notice = if notice.objective.is_some() && notice.name.is_some() {
29 notice
30 } else {
31 let stored = sqlx::query("SELECT name, objective FROM mandates WHERE id = ?")
32 .bind(¬ice.mandate_id)
33 .fetch_optional(&mut *connection)
34 .await?;
35 let (name, objective) = stored.map_or((None, None), |row| {
36 (
37 row.get::<Option<String>, _>("name"),
38 row.get::<Option<String>, _>("objective"),
39 )
40 });
41 let mut filled = notice.clone();
42 if filled.name.is_none() {
43 filled.name = name;
44 }
45 if filled.objective.is_none() {
46 filled.objective = objective;
47 }
48 named = filled;
49 &named
50 };
51 let entry = notice.to_notification_entry();
52 if entry.priority != "critical" || entry.expires_at.is_some() {
53 anyhow::bail!("mandate owner notifications must be critical and non-expiring");
54 }
55
56 let inserted = sqlx::query(
57 "INSERT INTO notification_queue
58 (id, goal_id, session_id, notification_type, priority, message,
59 created_at, delivered_at, attempts, expires_at, task_id, action_token)
60 VALUES (?, ?, ?, ?, ?, ?, ?, NULL, 0, NULL, NULL, ?)
61 ON CONFLICT(id) DO NOTHING",
62 )
63 .bind(&entry.id)
64 .bind(&entry.goal_id)
65 .bind(&entry.session_id)
66 .bind(&entry.notification_type)
67 .bind(&entry.priority)
68 .bind(&entry.message)
69 .bind(&entry.created_at)
70 .bind(&entry.action_token)
71 .execute(&mut *connection)
72 .await?
73 .rows_affected();
74
75 if inserted == 1 {
76 return Ok(true);
77 }
78
79 let existing = sqlx::query(
80 "SELECT goal_id, session_id, notification_type, priority, message,
81 created_at, expires_at, task_id, action_token
82 FROM notification_queue
83 WHERE id = ?",
84 )
85 .bind(&entry.id)
86 .fetch_optional(&mut *connection)
87 .await?
88 .ok_or_else(|| {
89 anyhow::anyhow!(
90 "mandate notification insert reported a conflict but no row exists for {}",
91 entry.id
92 )
93 })?;
94
95 let matches = existing.get::<String, _>("goal_id") == entry.goal_id
96 && existing.get::<String, _>("session_id") == entry.session_id
97 && existing.get::<String, _>("notification_type") == entry.notification_type
98 && existing.get::<String, _>("priority") == entry.priority
99 && existing.get::<String, _>("created_at") == entry.created_at
102 && existing.get::<Option<String>, _>("expires_at") == entry.expires_at
103 && existing.get::<Option<String>, _>("task_id") == entry.task_id
104 && existing.get::<Option<String>, _>("action_token") == entry.action_token;
105 if !matches {
106 anyhow::bail!(
107 "mandate notification id {} already belongs to different immutable content",
108 entry.id
109 );
110 }
111 Ok(false)
112}
113
114#[async_trait]
115impl<S: WorkDatabase> crate::traits::NotificationStore for S {
116 async fn record_background_spawn(
117 &self,
118 spawn: &crate::traits::BackgroundSpawn,
119 ) -> anyhow::Result<()> {
120 sqlx::query(
121 "INSERT OR REPLACE INTO background_spawns (id, session_id, mission, started_at)
122 VALUES (?, ?, ?, ?)",
123 )
124 .bind(&spawn.id)
125 .bind(&spawn.session_id)
126 .bind(&spawn.mission)
127 .bind(&spawn.started_at)
128 .execute(self.work_pool())
129 .await?;
130 Ok(())
131 }
132
133 async fn finish_background_spawn(&self, id: &str) -> anyhow::Result<()> {
134 sqlx::query("DELETE FROM background_spawns WHERE id = ?")
135 .bind(id)
136 .execute(self.work_pool())
137 .await?;
138 Ok(())
139 }
140
141 async fn background_spawns_for_session(
142 &self,
143 session_id: &str,
144 ) -> anyhow::Result<Vec<crate::traits::BackgroundSpawn>> {
145 let rows = sqlx::query(
146 "SELECT id, session_id, mission, started_at FROM background_spawns
147 WHERE session_id = ? ORDER BY started_at",
148 )
149 .bind(session_id)
150 .fetch_all(self.work_pool())
151 .await?;
152 Ok(rows.iter().map(background_spawn_from_row).collect())
153 }
154
155 async fn take_background_spawns(&self) -> anyhow::Result<Vec<crate::traits::BackgroundSpawn>> {
156 let rows = sqlx::query(
157 "DELETE FROM background_spawns RETURNING id, session_id, mission, started_at",
158 )
159 .fetch_all(self.work_pool())
160 .await?;
161 Ok(rows.iter().map(background_spawn_from_row).collect())
162 }
163
164 async fn enqueue_notification(
165 &self,
166 entry: &crate::traits::NotificationEntry,
167 ) -> anyhow::Result<()> {
168 sqlx::query(
169 "INSERT INTO notification_queue
170 (id, goal_id, session_id, notification_type, priority, message,
171 created_at, delivered_at, attempts, expires_at, task_id, action_token,
172 untrusted)
173 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
174 )
175 .bind(&entry.id)
176 .bind(&entry.goal_id)
177 .bind(&entry.session_id)
178 .bind(&entry.notification_type)
179 .bind(&entry.priority)
180 .bind(&entry.message)
181 .bind(&entry.created_at)
182 .bind(&entry.delivered_at)
183 .bind(entry.attempts)
184 .bind(&entry.expires_at)
185 .bind(&entry.task_id)
186 .bind(&entry.action_token)
187 .bind(entry.untrusted)
188 .execute(self.work_pool())
189 .await?;
190 Ok(())
191 }
192
193 async fn enqueue_goal_notification(
194 &self,
195 entry: &crate::traits::NotificationEntry,
196 ) -> anyhow::Result<bool> {
197 let mut tx = self.work_pool().begin_with("BEGIN IMMEDIATE").await?;
198 let notified_at = chrono::Utc::now().to_rfc3339();
199 let claimed = sqlx::query(
200 "UPDATE goals
201 SET notified_at = ?, notification_attempts = notification_attempts + 1
202 WHERE id = ? AND notified_at IS NULL",
203 )
204 .bind(¬ified_at)
205 .bind(&entry.goal_id)
206 .execute(&mut *tx)
207 .await?
208 .rows_affected();
209
210 if claimed == 0 {
211 tx.rollback().await?;
212 return Ok(false);
213 }
214
215 sqlx::query(
216 "INSERT INTO notification_queue
217 (id, goal_id, session_id, notification_type, priority, message,
218 created_at, delivered_at, attempts, expires_at, task_id, action_token,
219 untrusted)
220 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
221 )
222 .bind(&entry.id)
223 .bind(&entry.goal_id)
224 .bind(&entry.session_id)
225 .bind(&entry.notification_type)
226 .bind(&entry.priority)
227 .bind(&entry.message)
228 .bind(&entry.created_at)
229 .bind(&entry.delivered_at)
230 .bind(entry.attempts)
231 .bind(&entry.expires_at)
232 .bind(&entry.task_id)
233 .bind(&entry.action_token)
234 .bind(entry.untrusted)
235 .execute(&mut *tx)
236 .await?;
237
238 tx.commit().await?;
239 Ok(true)
240 }
241
242 async fn get_pending_notifications(
243 &self,
244 limit: i64,
245 ) -> anyhow::Result<Vec<crate::traits::NotificationEntry>> {
246 let rows = sqlx::query(
247 "SELECT id, goal_id, session_id, notification_type, priority, message,
248 created_at, delivered_at, attempts, expires_at, task_id, action_token,
249 untrusted
250 FROM notification_queue
251 WHERE delivered_at IS NULL
252 AND (expires_at IS NULL OR datetime(expires_at) > datetime('now'))
253 AND (
254 notification_type NOT IN ('progress', 'status_update')
255 OR NOT EXISTS (
256 SELECT 1
257 FROM notification_queue AS terminal
258 WHERE terminal.goal_id = notification_queue.goal_id
259 AND terminal.session_id = notification_queue.session_id
260 AND terminal.notification_type IN ('completed', 'failed', 'stalled')
261 AND julianday(terminal.created_at) >= julianday(notification_queue.created_at)
262 )
263 )
264 AND (
265 priority = 'critical'
266 OR (
267 attempts < 10
268 AND datetime(created_at) > datetime('now', '-24 hours')
269 )
270 )
271 ORDER BY
272 -- Normally deliver durable outcomes first. If critical work
273 -- already fills this whole page, reserve the front of the page
274 -- for fresh progress so a dead delivery route cannot starve
275 -- every live update forever.
276 CASE
277 WHEN (
278 SELECT COUNT(*) FROM notification_queue AS critical_backlog
279 WHERE critical_backlog.delivered_at IS NULL
280 AND critical_backlog.priority = 'critical'
281 ) >= ?
282 THEN CASE priority WHEN 'status_update' THEN 0 ELSE 1 END
283 ELSE CASE priority WHEN 'critical' THEN 0 ELSE 1 END
284 END ASC,
285 julianday(created_at) DESC,
286 id DESC
287 LIMIT ?",
288 )
289 .bind(limit)
290 .bind(limit)
291 .fetch_all(self.work_pool())
292 .await?;
293
294 let mut entries = Vec::with_capacity(rows.len());
295 for row in &rows {
296 entries.push(crate::traits::NotificationEntry {
297 id: row.get("id"),
298 goal_id: row.get("goal_id"),
299 session_id: row.get("session_id"),
300 notification_type: row.get("notification_type"),
301 priority: row.get("priority"),
302 message: row.get("message"),
303 created_at: row.get("created_at"),
304 delivered_at: row.get("delivered_at"),
305 attempts: row.get("attempts"),
306 expires_at: row.get("expires_at"),
307 task_id: row.get("task_id"),
308 action_token: row.get("action_token"),
309 untrusted: row.get("untrusted"),
310 });
311 }
312 Ok(entries)
313 }
314
315 async fn mark_notification_delivered(&self, notification_id: &str) -> anyhow::Result<()> {
316 sqlx::query("UPDATE notification_queue SET delivered_at = datetime('now') WHERE id = ?")
317 .bind(notification_id)
318 .execute(self.work_pool())
319 .await?;
320 Ok(())
321 }
322
323 async fn increment_notification_attempt(&self, notification_id: &str) -> anyhow::Result<()> {
324 sqlx::query("UPDATE notification_queue SET attempts = attempts + 1 WHERE id = ?")
325 .bind(notification_id)
326 .execute(self.work_pool())
327 .await?;
328 Ok(())
329 }
330
331 async fn notices_delivered_since(
332 &self,
333 session_id: &str,
334 since: chrono::DateTime<chrono::Utc>,
335 ) -> anyhow::Result<Vec<crate::traits::DeliveredNotice>> {
336 let rows = sqlx::query(
338 "SELECT n.id, n.notification_type, n.message, n.delivered_at,
339 (SELECT m.id FROM mandates m WHERE m.goal_id = n.goal_id LIMIT 1) AS mandate_id
340 FROM notification_queue n
341 WHERE n.session_id = ?
342 AND n.delivered_at IS NOT NULL
343 AND datetime(n.delivered_at) >= datetime(?)
344 ORDER BY datetime(n.delivered_at), n.created_at",
345 )
346 .bind(session_id)
347 .bind(since.format("%Y-%m-%d %H:%M:%S").to_string())
348 .fetch_all(self.work_pool())
349 .await?;
350 Ok(rows
351 .iter()
352 .map(|row| {
353 let delivered_at: String = row.get("delivered_at");
354 crate::traits::DeliveredNotice {
355 id: row.get("id"),
356 notification_type: row.get("notification_type"),
357 message: row.get("message"),
358 delivered_at: chrono::NaiveDateTime::parse_from_str(
359 &delivered_at,
360 "%Y-%m-%d %H:%M:%S",
361 )
362 .map(|at| at.and_utc().to_rfc3339())
363 .unwrap_or(delivered_at),
364 mandate_id: row.get("mandate_id"),
365 }
366 })
367 .collect())
368 }
369
370 async fn cleanup_expired_notifications(&self) -> anyhow::Result<i64> {
371 let result = sqlx::query(
372 "DELETE FROM notification_queue
373 WHERE delivered_at IS NULL
374 AND expires_at IS NOT NULL
375 AND datetime(expires_at) <= datetime('now')",
376 )
377 .execute(self.work_pool())
378 .await?;
379 Ok(result.rows_affected() as i64)
380 }
381}
382
383#[cfg(test)]
384mod tests {
385 use super::*;
386 use crate::traits::*;
387 use crate::traits::{
388 MandateRunNotification, MandateRunNotificationKind, MandateRunProofCounts,
389 };
390
391 async fn test_store() -> (SqliteWorkStore, tempfile::NamedTempFile) {
392 let database = tempfile::NamedTempFile::new().unwrap();
393 let store = open_for_tests(database.path().to_str().unwrap()).await;
394 (store, database)
395 }
396
397 fn notice(kind: MandateRunNotificationKind) -> MandateRunNotification {
398 MandateRunNotification::new(
399 "mandate-12345678",
400 7,
401 "goal-12345678",
402 "run-12345678",
403 "owner-session",
404 kind,
405 MandateRunProofCounts {
406 non_root_tasks: 1,
407 mutation_reservations: 1,
408 succeeded_mutations: 1,
409 ..MandateRunProofCounts::default()
410 },
411 "2026-08-02T12:00:00Z",
412 )
413 }
414
415 #[tokio::test]
419 async fn named_mandate_notice_reaches_the_turn_that_was_running() {
420 let (store, _database) = test_store().await;
421 let goal = Goal::new_continuous(
422 "Watch the status page",
423 "owner-session",
424 Some(10_000),
425 Some(50_000),
426 );
427 let mut mandate = Mandate::new(
428 &goal.id,
429 None,
430 "Every hour, check the status page and notify the owner when it is down",
431 "owner-session",
432 MandateAuthority::default(),
433 60,
434 3_600,
435 300,
436 );
437 mandate.name = Some("Status watch".to_string());
438 store
439 .create_mandate_controller(&goal, &mandate)
440 .await
441 .unwrap();
442 let turn_started = chrono::Utc::now() - chrono::Duration::seconds(5);
443 let failed = MandateRunNotification::new(
444 &mandate.id,
445 mandate.version,
446 &goal.id,
447 "run-synthetic-1",
448 "owner-session",
449 MandateRunNotificationKind::ReviewFailed {
450 reason: MandateFinalizationRejectReason::DeliberatorFailed,
451 },
452 MandateRunProofCounts::default(),
453 "2026-08-02T12:00:00Z",
454 )
455 .with_objective(Some(&mandate.objective));
457 let mut tx = store.pool.begin().await.unwrap();
458 assert!(
459 enqueue_mandate_run_notification_on_connection(&mut tx, &failed)
460 .await
461 .unwrap()
462 );
463 tx.commit().await.unwrap();
464 let entry_id = failed.notification_id();
465 store.mark_notification_delivered(&entry_id).await.unwrap();
466
467 let delivered = store
468 .notices_delivered_since("owner-session", turn_started)
469 .await
470 .unwrap();
471 assert_eq!(delivered.len(), 1);
472 assert_eq!(delivered[0].id, entry_id);
473 assert_eq!(
474 delivered[0].mandate_id.as_deref(),
475 Some(mandate.id.as_str())
476 );
477 assert_eq!(
478 delivered[0].message,
479 "Your automation \"Status watch\": a review stopped before it finished. Ask me what \
480 it got to if you want the details. It's still active and will retry automatically."
481 );
482 let context = crate::goals::notices_turn_context(&delivered).unwrap();
483 assert!(context.contains(&mandate.id), "{context}");
484 assert!(context.contains("mandate_review_failed"), "{context}");
485
486 assert!(
488 store
489 .notices_delivered_since("other-session", turn_started)
490 .await
491 .unwrap()
492 .is_empty()
493 );
494 assert!(
495 store
496 .notices_delivered_since(
497 "owner-session",
498 chrono::Utc::now() + chrono::Duration::seconds(5)
499 )
500 .await
501 .unwrap()
502 .is_empty()
503 );
504 assert_eq!(crate::goals::notices_turn_context(&[]), None);
505 }
506
507 #[tokio::test]
508 async fn mandate_notice_rolls_back_with_its_enclosing_state_transaction() {
509 let (store, _database) = test_store().await;
510 let mut tx = store.pool.begin().await.unwrap();
511 assert!(
512 enqueue_mandate_run_notification_on_connection(
513 &mut tx,
514 ¬ice(MandateRunNotificationKind::ActSatisfied),
515 )
516 .await
517 .unwrap()
518 );
519 tx.rollback().await.unwrap();
520
521 let count =
522 sqlx::query_scalar::<_, i64>("SELECT COUNT(*) FROM notification_queue WHERE id = ?")
523 .bind("mandate-run-notice:run-12345678")
524 .fetch_one(&store.pool)
525 .await
526 .unwrap();
527 assert_eq!(count, 0);
528 }
529
530 #[tokio::test]
531 async fn mandate_notice_commit_and_duplicate_retry_are_idempotent() {
532 let (store, _database) = test_store().await;
533 let act_notice = notice(MandateRunNotificationKind::ActSatisfied);
534 let mut tx = store.pool.begin().await.unwrap();
535 assert!(
536 enqueue_mandate_run_notification_on_connection(&mut tx, &act_notice)
537 .await
538 .unwrap()
539 );
540 tx.commit().await.unwrap();
541
542 let mut retry = store.pool.begin().await.unwrap();
543 assert!(
544 !enqueue_mandate_run_notification_on_connection(&mut retry, &act_notice)
545 .await
546 .unwrap()
547 );
548 retry.commit().await.unwrap();
549
550 let pending = store.get_pending_notifications(10).await.unwrap();
551 assert_eq!(pending.len(), 1);
552 assert_eq!(pending[0].id, act_notice.notification_id());
553 assert_eq!(pending[0].priority, "critical");
554 assert!(pending[0].expires_at.is_none());
555 assert_eq!(
556 pending[0].action_token.as_deref(),
557 Some(pending[0].id.as_str())
558 );
559
560 let mut conflicting_retry = store.pool.begin().await.unwrap();
561 let conflict = enqueue_mandate_run_notification_on_connection(
562 &mut conflicting_retry,
563 ¬ice(MandateRunNotificationKind::Ask),
564 )
565 .await;
566 assert!(conflict.is_err());
567 conflicting_retry.rollback().await.unwrap();
568 }
569
570 #[tokio::test]
571 async fn critical_mandate_notice_survives_unbounded_delivery_retries() {
572 let (store, _database) = test_store().await;
573 let notice = notice(MandateRunNotificationKind::Ask);
574 let mut tx = store.pool.begin().await.unwrap();
575 enqueue_mandate_run_notification_on_connection(&mut tx, ¬ice)
576 .await
577 .unwrap();
578 tx.commit().await.unwrap();
579
580 for _ in 0..12 {
581 store
582 .increment_notification_attempt(¬ice.notification_id())
583 .await
584 .unwrap();
585 }
586 let pending = store.get_pending_notifications(10).await.unwrap();
587 assert_eq!(pending.len(), 1);
588 assert_eq!(pending[0].attempts, 12);
589
590 store
591 .mark_notification_delivered(¬ice.notification_id())
592 .await
593 .unwrap();
594 assert!(
595 store
596 .get_pending_notifications(10)
597 .await
598 .unwrap()
599 .is_empty()
600 );
601 }
602
603 #[tokio::test]
604 async fn live_status_updates_are_not_starved_by_critical_backlog() {
605 let (store, _database) = test_store().await;
606 for index in 0..25 {
607 let entry = crate::traits::NotificationEntry::new(
608 "old-goal",
609 "unroutable-session",
610 "failed",
611 &format!("old critical failure {index}"),
612 );
613 store.enqueue_notification(&entry).await.unwrap();
614 }
615 let progress = crate::traits::NotificationEntry::new(
616 "live-goal",
617 "owner-session",
618 "status_update",
619 "The current run is making progress.",
620 );
621 store.enqueue_notification(&progress).await.unwrap();
622
623 let pending = store.get_pending_notifications(20).await.unwrap();
624 assert_eq!(pending[0].id, progress.id);
625 assert_eq!(pending[0].priority, "status_update");
626 }
627
628 #[tokio::test]
629 async fn terminal_outcome_supersedes_older_live_status_update() {
630 let (store, _database) = test_store().await;
631 let mut progress = crate::traits::NotificationEntry::new(
632 "goal-12345678",
633 "owner-session",
634 "status_update",
635 "Starting the recovered run now.",
636 );
637 progress.created_at = "2026-08-03T14:40:06Z".to_string();
638 store.enqueue_notification(&progress).await.unwrap();
639
640 let mut completed = crate::traits::NotificationEntry::new(
641 "goal-12345678",
642 "owner-session",
643 "completed",
644 "The recovered run completed.",
645 );
646 completed.created_at = "2026-08-03T14:42:18Z".to_string();
647 store.enqueue_notification(&completed).await.unwrap();
648
649 let pending = store.get_pending_notifications(10).await.unwrap();
650 assert_eq!(pending.len(), 1);
651 assert_eq!(pending[0].id, completed.id);
652 }
653}