Skip to main content

xmtp_mls_core/worker/
tasks.rs

1pub use crate::task_channels::TaskWorkerChannels;
2use crate::{
3    context::CoreContext,
4    events::InternalEvent,
5    worker::{
6        BoxedWorker, EVENT_BUFFER, NeedsDbReconnect, NewWorker, Worker, WorkerFactory, WorkerKind,
7        WorkerResult,
8    },
9};
10use std::{marker::PhantomData, sync::Arc};
11use xmtp_common::{MaybeSend, MaybeSync, RetryableError};
12use xmtp_db::tasks::{QueryTasks, Task as DbTask, TaskDataHash};
13use xmtp_db::{StorageError, diesel};
14use xmtp_events::{EventEnvelope, EventFilter, EventKind, Subscription};
15use xmtp_proto::xmtp::mls::database::PullInDeadline;
16
17/// One task-runner turn for handler tests that run outside a running worker.
18#[cfg(any(test, feature = "test-utils"))]
19#[doc(hidden)]
20pub mod test_support {
21    use super::{DbTask, PullInDeadline, StorageError, TaskHandlers, TaskWorker};
22    use crate::context::CoreContext;
23    use xmtp_db::tasks::{NewTask, QueryTasks, TaskDataHash, data_hash_for};
24    use xmtp_proto::xmtp::mls::database::{Task as TaskProto, task::Task as TaskKind};
25
26    /// Run `task` through one turn of `worker`: the expiry and due checks,
27    /// the dispatch, and the delete or reschedule that follows.
28    pub async fn run_and_reschedule_task<Context, Handlers>(
29        worker: &TaskWorker<Context, Handlers>,
30        task: DbTask,
31    ) -> Result<(), Handlers::Error>
32    where
33        Context: CoreContext,
34        Handlers: TaskHandlers<Context>,
35    {
36        worker.run_and_reschedule_task(task).await
37    }
38
39    /// A unique one-shot payload: a PullInDeadline aimed at a random, nonexistent
40    /// target. Applying it is a no-op; its data_hash is unique per call.
41    pub fn unique_proto() -> TaskProto {
42        TaskProto {
43            task: Some(TaskKind::PullInDeadline(PullInDeadline {
44                target_data_hash: xmtp_common::rand_vec::<32>(),
45                not_later_than_ns: 0,
46            })),
47        }
48    }
49
50    /// Insert a task row and return the stored row (found by its data_hash).
51    pub fn seed(
52        db: &impl QueryTasks,
53        proto: TaskProto,
54        next: i64,
55        expires: i64,
56        attempts: i32,
57        max: i32,
58    ) -> DbTask {
59        let hash = data_hash_for(&proto);
60        let task = NewTask::builder()
61            .originating_message_sequence_id(0)
62            .next_attempt_at_ns(next)
63            .expires_at_ns(expires)
64            .attempts(attempts)
65            .max_attempts(max)
66            .build(proto)
67            .expect("a task row");
68        db.create_or_ignore_task(task).expect("a stored task");
69        db.get_tasks()
70            .expect("the stored tasks")
71            .into_iter()
72            .find(|t| t.data_hash == hash.as_ref())
73            .expect("the seeded task")
74    }
75
76    /// Queue a pull-in of the task with `target_data_hash`, as a nudge does.
77    pub fn enqueue_pull_in<Context: CoreContext>(
78        context: &Context,
79        target_data_hash: TaskDataHash,
80        not_later_than_ns: i64,
81        expires_at_ns: i64,
82    ) -> Result<(), StorageError> {
83        super::enqueue_pull_in(context, target_data_hash, not_later_than_ns, expires_at_ns)
84    }
85}
86
87/// `Done` = one-shot, row deleted. `RescheduleAt(ns)` = recurring, row kept and
88/// advanced to that absolute deadline.
89#[derive(Debug, PartialEq, Eq)]
90pub enum TaskOutcome {
91    Done,
92    RescheduleAt(i64),
93}
94
95/// Task-runner controls for tests. The runner reads them; tests set them.
96/// Each assumes process-per-test isolation.
97#[cfg(any(test, feature = "test-hooks"))]
98#[doc(hidden)]
99pub mod test_hooks {
100    use std::sync::Mutex;
101
102    static FAIL_RESCHEDULE: Mutex<bool> = Mutex::new(false);
103    type ScheduledWitness = (Vec<u8>, tokio::sync::oneshot::Sender<()>);
104    static TASK_SCHEDULED_CONSUMED: Mutex<Option<ScheduledWitness>> = Mutex::new(None);
105
106    /// Makes the runner's next retry schedule write fail, once.
107    pub fn fail_next_reschedule() {
108        *FAIL_RESCHEDULE.lock().expect("task test hooks") = true;
109    }
110
111    pub(super) fn take_reschedule_failure() -> bool {
112        std::mem::take(&mut *FAIL_RESCHEDULE.lock().expect("task test hooks"))
113    }
114
115    /// Sends on `consumed` once the task runner of `installation_id` reads a
116    /// `TaskScheduled` event.
117    pub fn on_task_scheduled_consumed(
118        installation_id: Vec<u8>,
119        consumed: tokio::sync::oneshot::Sender<()>,
120    ) {
121        *TASK_SCHEDULED_CONSUMED.lock().expect("task test hooks") =
122            Some((installation_id, consumed));
123    }
124
125    pub(super) fn take_task_scheduled_witness(
126        installation_id: &[u8],
127    ) -> Option<tokio::sync::oneshot::Sender<()>> {
128        let mut hook = TASK_SCHEDULED_CONSUMED.lock().expect("task test hooks");
129        if hook
130            .as_ref()
131            .is_some_and(|(installation, _)| installation.as_slice() == installation_id)
132        {
133            hook.take().map(|(_, consumed)| consumed)
134        } else {
135            None
136        }
137    }
138}
139
140/// The handlers a [`TaskWorker`] runs. The runner owns each task's schedule:
141/// expiry, attempts, backoff and rate-limit holds. The handlers run one row.
142#[xmtp_common::async_trait]
143pub trait TaskHandlers<Context>: MaybeSend + MaybeSync {
144    /// The error of a failed run. The runner reads its rate-limit delay and
145    /// its reconnect signal, and reports its own storage failures as this type.
146    type Error: RetryableError
147        + NeedsDbReconnect
148        + From<StorageError>
149        + std::error::Error
150        + MaybeSend
151        + MaybeSync
152        + 'static;
153
154    /// Run one due task. Gets the whole row: handlers use `task.id`, for
155    /// example to delete it.
156    async fn dispatch(&self, context: &Context, task: &DbTask) -> Result<TaskOutcome, Self::Error>;
157
158    /// Runs when the runner starts, before it reads a task.
159    fn on_start(&self, _context: &Context) -> Result<(), Self::Error> {
160        Ok(())
161    }
162
163    /// Runs once for each batch of events the runner reads that holds an
164    /// event other than its own `TaskScheduled`, and gets the whole batch.
165    /// Public events such as `ConsentChanged` and `ArchiveRestored` arrive here.
166    fn on_events(
167        &self,
168        _context: &Context,
169        _events: &[EventEnvelope<InternalEvent>],
170    ) -> Result<(), Self::Error> {
171        Ok(())
172    }
173}
174
175/// Durably enqueue a `PullInDeadline` for `target_data_hash`, then emit its fact.
176/// The row is committed before the event; duplicates coalesce on data_hash. Lifetime is
177/// bounded by `expires_at_ns` alone (pass `NEVER_EXPIRES` for critical nudges).
178/// Callers must commit the target row FIRST: a pull-in never waits for its target —
179/// a miss is dropped (debug-logged), since a missing target is normally a completed
180/// one-shot and retrying would spin forever on never-expiring nudges.
181pub fn enqueue_pull_in<Context: CoreContext>(
182    context: &Context,
183    target_data_hash: TaskDataHash,
184    not_later_than_ns: i64,
185    expires_at_ns: i64,
186) -> Result<(), xmtp_db::StorageError> {
187    let now = xmtp_common::time::now_ns();
188    let task = xmtp_db::tasks::NewTask::builder()
189        .originating_message_sequence_id(0)
190        .next_attempt_at_ns(now) // the pull-in itself is due immediately
191        .expires_at_ns(expires_at_ns)
192        .max_attempts(i32::MAX) // lifetime bounded by expires_at_ns, not retries
193        .build(xmtp_proto::xmtp::mls::database::Task {
194            task: Some(xmtp_proto::xmtp::mls::database::task::Task::PullInDeadline(
195                PullInDeadline {
196                    target_data_hash: target_data_hash.to_vec(),
197                    not_later_than_ns,
198                },
199            )),
200        })?;
201    context.db().create_or_ignore_task(task)?;
202    use xmtp_events::EventWriter;
203    context
204        .events()
205        .emit(None, Some(InternalEvent::TaskScheduled));
206    Ok(())
207}
208
209/// Run a `PullInDeadline` task: lower its target's deadline to the ceiling.
210pub fn apply_pull_in<Context: CoreContext>(
211    context: &Context,
212    task: &DbTask,
213    pull_in: PullInDeadline,
214) -> Result<(), StorageError> {
215    // Runs on the worker thread — the sole rescheduler of existing
216    // rows' `next_attempt_at_ns` — so no transaction is needed
217    // (inserts happen off-thread; only deadline mutation is guarded).
218    let matched = match TaskDataHash::try_from(pull_in.target_data_hash.as_slice()) {
219        Ok(h) => {
220            // A target in failure backoff keeps its stored schedule,
221            // which holds any rate-limit delay, across restarts too.
222            // implements: RATE-041
223            let backing_off = context
224                .db()
225                .get_tasks()?
226                .iter()
227                .any(|target| target.data_hash == h.as_ref() && target.attempts > 0);
228            backing_off
229                || context
230                    .db()
231                    .pull_in_task_deadline(&h, pull_in.not_later_than_ns)?
232        }
233        Err(_) => false, // malformed length: fall through to the miss log
234    };
235    if !matched {
236        // Completed one-shot target, or a producer broke the
237        // commit-target-first contract. Drop either way (retrying
238        // would spin forever on never-expiring nudges). warn: every
239        // in-tree pull-in targets a never-deleted singleton, so a
240        // miss is always anomalous today.
241        tracing::warn!(
242            target_data_hash = hex::encode(&pull_in.target_data_hash),
243            "pull-in target missing; dropping nudge for task {}",
244            task.id
245        );
246    }
247    Ok(())
248}
249
250/// What wakes the runner: its own `TaskScheduled`, and the changes the
251/// notification task follows.
252fn event_interest() -> (EventFilter<InternalEvent>, Option<usize>) {
253    let filter = EventFilter::new([
254        EventKind::ConsentChanged,
255        EventKind::ConversationJoined,
256        EventKind::ConversationRemoved,
257        EventKind::HmacKeysUpdated,
258        // implements: PUSH-260
259        // An import writes consent without consent.changed.
260        EventKind::ArchiveRestored,
261    ])
262    .with_internal(|event| {
263        matches!(
264            event,
265            InternalEvent::TaskScheduled
266                | InternalEvent::NotificationSettingsChanged
267                | InternalEvent::GroupJoined { .. }
268                | InternalEvent::PreferencesChanged { .. }
269        )
270    });
271    (filter, Some(EVENT_BUFFER))
272}
273
274pub struct Factory<Context, Handlers> {
275    context: Context,
276    handlers: PhantomData<fn() -> Handlers>,
277}
278
279impl<Context, Handlers> WorkerFactory for Factory<Context, Handlers>
280where
281    Context: CoreContext + 'static,
282    Handlers: TaskHandlers<Context> + Default + 'static,
283{
284    fn kind(&self) -> WorkerKind {
285        WorkerKind::TaskRunner
286    }
287
288    fn event_interest(&self) -> Option<(EventFilter<InternalEvent>, Option<usize>)> {
289        Some(event_interest())
290    }
291
292    fn create(&self) -> BoxedWorker {
293        Box::new(TaskWorker::new(self.context.clone(), Handlers::default()))
294    }
295}
296
297pub struct TaskWorker<Context, Handlers> {
298    context: Context,
299    handlers: Handlers,
300    subscription: Option<Arc<Subscription<InternalEvent>>>,
301}
302
303impl<Context, Handlers> NewWorker<Context> for TaskWorker<Context, Handlers>
304where
305    Context: CoreContext + 'static,
306    Handlers: TaskHandlers<Context> + Default + 'static,
307{
308    fn factory(context: Context) -> impl WorkerFactory + 'static {
309        Factory::<Context, Handlers> {
310            context,
311            handlers: PhantomData,
312        }
313    }
314}
315
316#[xmtp_common::async_trait]
317impl<Context, Handlers> Worker for TaskWorker<Context, Handlers>
318where
319    Context: CoreContext + 'static,
320    Handlers: TaskHandlers<Context> + 'static,
321{
322    fn kind(&self) -> WorkerKind {
323        WorkerKind::TaskRunner
324    }
325
326    fn set_subscription(&mut self, subscription: Arc<Subscription<InternalEvent>>) {
327        self.subscription = Some(subscription);
328    }
329
330    async fn run_tasks(&mut self) -> WorkerResult<()> {
331        self.run().await.map_err(|e| Box::new(e) as _)
332    }
333}
334
335impl<Context, Handlers> TaskWorker<Context, Handlers>
336where
337    Context: CoreContext,
338    Handlers: TaskHandlers<Context>,
339{
340    pub fn new(context: Context, handlers: Handlers) -> Self {
341        Self {
342            context,
343            handlers,
344            subscription: None,
345        }
346    }
347
348    #[cfg(any(test, feature = "test-hooks"))]
349    fn record_task_fact(&self, event: &xmtp_events::EventEnvelope<InternalEvent>) {
350        if !matches!(&event.internal, Some(InternalEvent::TaskScheduled)) {
351            return;
352        }
353        let witness =
354            test_hooks::take_task_scheduled_witness(&self.context.installation_id().to_vec());
355        if let Some(received) = witness {
356            let _ = received.send(());
357        }
358    }
359
360    pub async fn run(&mut self) -> Result<(), Handlers::Error> {
361        if self.subscription.is_none() {
362            let (filter, depth) = event_interest();
363            self.subscription = Some(Arc::new(self.context.events().subscribe(filter, depth)));
364        }
365        let subscription = self
366            .subscription
367            .as_ref()
368            .expect("subscription is initialized")
369            .clone();
370        self.handlers.on_start(&self.context)?;
371        loop {
372            let drained = subscription.drain();
373            #[cfg(any(test, feature = "test-hooks"))]
374            for event in &drained {
375                self.record_task_fact(event);
376            }
377            self.forward_events(&drained)?;
378            let next_task = self.context.db().get_next_task()?;
379            let next_wakeup = Self::next_wakeup(
380                next_task.as_ref().map(|t| t.next_attempt_at_ns),
381                xmtp_common::time::now_ns(),
382            );
383            tokio::select! {
384                event = subscription.next() => {
385                    let Some(event) = event else { break Ok(()); };
386                    #[cfg(any(test, feature = "test-hooks"))]
387                    self.record_task_fact(&event);
388                    let mut events = vec![event];
389                    events.extend(subscription.drain());
390                    self.forward_events(&events)?;
391                }
392                () = xmtp_common::time::sleep(next_wakeup) => {
393                    if let Some(task) = next_task {
394                        self.run_and_reschedule_task(task).await?;
395                    }
396                }
397            }
398        }
399    }
400
401    /// Hand a batch of events to the handlers, unless it holds only the
402    /// runner's own `TaskScheduled` facts.
403    fn forward_events(
404        &self,
405        events: &[EventEnvelope<InternalEvent>],
406    ) -> Result<(), Handlers::Error> {
407        if events
408            .iter()
409            .any(|event| !matches!(event.internal, Some(InternalEvent::TaskScheduled)))
410        {
411            self.handlers.on_events(&self.context, events)?;
412        }
413        Ok(())
414    }
415
416    #[tracing::instrument(skip_all, fields(worker = "TaskRunner", operation = "worker_turn"))]
417    pub(crate) async fn run_and_reschedule_task(
418        &self,
419        task: DbTask,
420    ) -> Result<(), Handlers::Error> {
421        let context = &self.context;
422        let now = xmtp_common::time::now_ns();
423        if task.expires_at_ns < now || task.attempts >= task.max_attempts {
424            context.db().delete_task(task.id)?;
425            return Ok(());
426        }
427        if task.next_attempt_at_ns > now {
428            // This will get called again — expected scheduler behavior, not a
429            // warning (it was ~3k warns/day in prod).
430            tracing::debug!(
431                task_id = task.id,
432                "Task {} called before next attempt at {}. Now: {now}",
433                task.id,
434                task.next_attempt_at_ns
435            );
436            return Ok(());
437        }
438        match self.handlers.dispatch(context, &task).await {
439            Ok(TaskOutcome::Done) => {
440                context.db().delete_task(task.id)?;
441            }
442            Ok(TaskOutcome::RescheduleAt(t)) => {
443                // Plain advance + attempts=0. A MIN floor here would pin a just-run
444                // (past-due) row and hot-loop it.
445                match context.db().update_task(task.id, 0, now, t) {
446                    Ok(_) => {}
447                    Err(StorageError::DieselResult(diesel::result::Error::NotFound)) => {
448                        tracing::debug!("Task {} vanished before reschedule; skipping", task.id);
449                    }
450                    Err(e) => return Err(e.into()),
451                }
452            }
453            Err(error) => {
454                // Every kind backs off from when its run finished, so a long
455                // run does not use up its own backoff.
456                let finished = xmtp_common::time::now_ns();
457                let mut attempts = task.attempts + 1;
458                let attempt_scaling_factor = (task.backoff_scaling_factor as f64).powi(attempts);
459                let next_attempt_duration = (((task.initial_backoff_duration_ns as f64)
460                    * attempt_scaling_factor) as i64)
461                    .min(task.max_backoff_duration_ns);
462                let backoff_at_ns = finished.saturating_add(next_attempt_duration);
463                let mut next_attempt_at_ns = backoff_at_ns;
464                let mut expires_at_ns = task.expires_at_ns;
465                // A rate-limited request waits at least the delay, counted from
466                // when the rejection arrived, not from when the turn started.
467                // Neither the wait it adds past the backoff nor the refused turn
468                // counts against the task's lifetime or its attempts, so a rate
469                // limit never expires or deletes the refused work. At least one
470                // attempt is recorded, which marks the task as backing off, so
471                // a pull-in keeps it on its schedule.
472                // implements: RATE-041
473                if let Some(delay) = error.rate_limit_delay() {
474                    attempts = task.attempts.max(1);
475                    let until = finished
476                        .saturating_add(i64::try_from(delay.as_nanos()).unwrap_or(i64::MAX));
477                    next_attempt_at_ns = next_attempt_at_ns.max(until);
478                    expires_at_ns = expires_at_ns
479                        .saturating_add(next_attempt_at_ns.saturating_sub(backoff_at_ns));
480                }
481                let next_attempt_duration = next_attempt_at_ns.saturating_sub(finished);
482                tracing::warn!(%error, "Task {} retry failed. Retrying in {next_attempt_duration}ns", task.id);
483                #[cfg(any(test, feature = "test-hooks"))]
484                let fail_reschedule = test_hooks::take_reschedule_failure();
485                #[cfg(not(any(test, feature = "test-hooks")))]
486                let fail_reschedule = false;
487                let stored = if fail_reschedule {
488                    Err(StorageError::DieselResult(
489                        diesel::result::Error::BrokenTransactionManager,
490                    ))
491                } else {
492                    context.db().update_task_and_expiry(
493                        task.id,
494                        attempts,
495                        now,
496                        next_attempt_at_ns,
497                        expires_at_ns,
498                    )
499                };
500                match stored {
501                    Ok(_) => {}
502                    // The row was concurrently deleted (e.g. a dead-row cleanup in
503                    // upsert_pending_self_remove_task crossed this retry). Nothing
504                    // left to reschedule — don't abort the worker loop.
505                    Err(StorageError::DieselResult(diesel::result::Error::NotFound)) => {
506                        tracing::debug!("Task {} vanished before reschedule; skipping", task.id);
507                    }
508                    // The task stays due, so a restarted worker would resend
509                    // it at once. Return the rejection instead: the worker then
510                    // restarts only after the delay.
511                    // implements: RATE-041
512                    Err(e) if error.rate_limit_delay().is_some() => {
513                        tracing::warn!(%e, "Task {} rate-limit hold not stored", task.id);
514                        return Err(error);
515                    }
516                    Err(e) => return Err(e.into()),
517                }
518            }
519        }
520        Ok(())
521    }
522
523    fn next_wakeup(
524        next_attempt_at_ns: Option<i64>,
525        // these are passed in for testing
526        now: i64,
527    ) -> xmtp_common::time::Duration {
528        use xmtp_common::r#const::NS_IN_DAY;
529        let now_plus_one_day = now.saturating_add(NS_IN_DAY);
530        let next_task_wakeup = next_attempt_at_ns.unwrap_or(i64::MAX).min(now_plus_one_day);
531        if now > next_task_wakeup {
532            xmtp_common::time::Duration::from_nanos(0)
533        } else {
534            std::time::Duration::from_nanos((next_task_wakeup - now) as u64)
535        }
536    }
537}
538
539#[cfg(test)]
540mod tests {
541    use super::test_support::{seed, unique_proto};
542    use super::*;
543    use crate::identity::IdentityError;
544    use crate::test_context::real_context;
545    use prost::Message;
546    use xmtp_db::tasks::data_hash_for;
547    use xmtp_proto::xmtp::mls::database::{Task as TaskProto, task::Task as TaskKind};
548
549    /// Handlers that apply each task's pull-in, as the client's dispatch
550    /// does, and finish the task.
551    struct PullInHandler;
552
553    #[xmtp_common::async_trait]
554    impl<Context: CoreContext> TaskHandlers<Context> for PullInHandler {
555        type Error = IdentityError;
556
557        async fn dispatch(
558            &self,
559            context: &Context,
560            task: &DbTask,
561        ) -> Result<TaskOutcome, IdentityError> {
562            let task_proto = TaskProto::decode(task.data.as_slice()).expect("a stored task");
563            let Some(TaskKind::PullInDeadline(pull_in)) = task_proto.task else {
564                panic!("only pull-in tasks are seeded");
565            };
566            apply_pull_in(context, task, pull_in)?;
567            Ok(TaskOutcome::Done)
568        }
569    }
570
571    /// Handlers that reschedule the task with `data_hash` to `target`.
572    struct RescheduleAtHandler {
573        data_hash: Vec<u8>,
574        target: i64,
575    }
576
577    #[xmtp_common::async_trait]
578    impl<Context: CoreContext> TaskHandlers<Context> for RescheduleAtHandler {
579        type Error = IdentityError;
580
581        async fn dispatch(
582            &self,
583            _context: &Context,
584            task: &DbTask,
585        ) -> Result<TaskOutcome, IdentityError> {
586            assert_eq!(task.data_hash, self.data_hash, "only one task is seeded");
587            Ok(TaskOutcome::RescheduleAt(self.target))
588        }
589    }
590
591    /// The failure a [`FailAfter`] run ends with: not retryable, no
592    /// rate-limit delay and no reconnect, as an invalid task hash is.
593    #[derive(Debug, thiserror::Error)]
594    enum TaskFixtureError {
595        #[error(transparent)]
596        Storage(#[from] StorageError),
597        #[error("invalid hash for {id}, expected: {expected}, got: {got}")]
598        InvalidHash {
599            id: i64,
600            expected: String,
601            got: String,
602        },
603    }
604
605    impl RetryableError for TaskFixtureError {
606        fn is_retryable(&self) -> bool {
607            false
608        }
609    }
610
611    impl NeedsDbReconnect for TaskFixtureError {
612        fn needs_db_reconnect(&self) -> bool {
613            false
614        }
615    }
616
617    /// Handlers whose every run works for the given time, then fails.
618    struct FailAfter(xmtp_common::time::Duration);
619
620    #[xmtp_common::async_trait]
621    impl<Context: CoreContext> TaskHandlers<Context> for FailAfter {
622        type Error = TaskFixtureError;
623
624        async fn dispatch(
625            &self,
626            _context: &Context,
627            task: &DbTask,
628        ) -> Result<TaskOutcome, TaskFixtureError> {
629            xmtp_common::time::sleep(self.0).await;
630            Err(TaskFixtureError::InvalidHash {
631                id: task.id.into(),
632                expected: String::new(),
633                got: String::new(),
634            })
635        }
636    }
637
638    #[xmtp_common::test(unwrap_try = true)]
639    async fn done_deletes() {
640        let context = real_context().await;
641        let db = context.db();
642        let now = xmtp_common::time::now_ns();
643        let row = seed(&db, unique_proto(), now - 1, i64::MAX, 0, i32::MAX);
644        TaskWorker::new(context.clone(), PullInHandler)
645            .run_and_reschedule_task(row)
646            .await?;
647        assert!(db.get_tasks()?.is_empty(), "Done task must be deleted");
648    }
649
650    /// A failed task backs off from when its run finished, so a long run
651    /// does not use up its own backoff.
652    #[xmtp_common::test(unwrap_try = true)]
653    async fn failed_task_backs_off_from_run_finish() {
654        use xmtp_common::time::Duration;
655        let context = real_context().await;
656        let db = context.db();
657        let proto = unique_proto();
658        let hash = data_hash_for(&proto);
659        let row = seed(
660            &db,
661            proto,
662            xmtp_common::time::now_ns() - 1,
663            i64::MAX,
664            0,
665            i32::MAX,
666        );
667        let backoff = (row.initial_backoff_duration_ns as f64
668            * (row.backoff_scaling_factor as f64).powi(1)) as i64;
669        let work = Duration::from_secs(2);
670        let started = xmtp_common::time::now_ns();
671        TaskWorker::new(context.clone(), FailAfter(work))
672            .run_and_reschedule_task(row)
673            .await?;
674        let failed = db
675            .get_tasks()?
676            .into_iter()
677            .find(|t| t.data_hash == hash.as_ref())
678            .expect("the failed task is kept");
679        assert_eq!(failed.attempts, 1);
680        assert!(failed.next_attempt_at_ns >= started + work.as_nanos() as i64 + backoff);
681    }
682
683    #[xmtp_common::test(unwrap_try = true)]
684    async fn recurring_task_advances_and_does_not_hot_loop() {
685        let context = real_context().await;
686        let db = context.db();
687        let now = xmtp_common::time::now_ns();
688        let proto = unique_proto();
689        // High attempts + past-due: only the i64::MAX/i32::MAX seed keeps the
690        // reaper (expires < now || attempts >= max) from deleting it.
691        let row = seed(&db, proto.clone(), now - 1, i64::MAX, 1_000_000, i32::MAX);
692        let target = now + xmtp_common::NS_IN_DAY;
693        let handler = RescheduleAtHandler {
694            data_hash: data_hash_for(&proto).to_vec(),
695            target,
696        };
697
698        TaskWorker::new(context.clone(), handler)
699            .run_and_reschedule_task(row)
700            .await?;
701
702        let after = db.get_tasks()?.pop().expect("recurring row must survive");
703        assert_eq!(
704            after.next_attempt_at_ns, target,
705            "deadline must ADVANCE, not stay past-due"
706        );
707        assert_eq!(after.attempts, 0, "success resets the backoff counter");
708    }
709
710    #[xmtp_common::test(unwrap_try = true)]
711    async fn not_yet_due_task_is_not_run_early() {
712        let context = real_context().await;
713        let db = context.db();
714        let now = xmtp_common::time::now_ns();
715        let proto = unique_proto();
716        let far = now + 30 * xmtp_common::NS_IN_DAY;
717        let row = seed(&db, proto.clone(), far, i64::MAX, 0, i32::MAX);
718        // If the guard failed and the task ran, the handler would rewrite next_attempt.
719        let handler = RescheduleAtHandler {
720            data_hash: data_hash_for(&proto).to_vec(),
721            target: now,
722        };
723
724        TaskWorker::new(context.clone(), handler)
725            .run_and_reschedule_task(row)
726            .await?;
727
728        let after = db.get_tasks()?.pop().unwrap();
729        assert_eq!(
730            after.next_attempt_at_ns, far,
731            "not-yet-due task must not run on a 1-day-cap wake"
732        );
733        assert_eq!(
734            after.attempts, 0,
735            "not-yet-due task must not have its attempts incremented"
736        );
737    }
738}