crawlrs 0.2.0

crawlrs - Enterprise-grade web scraping and crawling platform built with Rust
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
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
// Copyright (c) 2025-2026 Kirky.X🌠
// SPDX-License-Identifier: Apache-2.0

//! Retry Handler Service
//!
//! Provides unified task failure handling with retry logic.
//! Consolidates retry patterns from scrape_worker, webhook_worker, and rate_limiting_service.

use crate::domain::models::{Task, TaskStatus};
use crate::domain::repositories::task_repository::TaskRepository;
use crate::utils::retry_policy::RetryPolicy;
use chrono::{Duration, Utc};
use log::{info, warn};
use std::sync::Arc;

/// Result of handling task failure
pub enum HandleFailureResult {
    /// Task was marked for retry
    Retried {
        attempt_count: u32,
        next_retry_at: chrono::DateTime<Utc>,
    },
    /// Task exceeded max retries and was marked as failed
    Failed,
    /// 守卫写未生效(锁被其他 worker 接管/任务已被并发迁移):
    /// 本 worker 没有终结该任务,调用方不得按终态计数。
    Stale,
    /// Error occurred during handling
    Error(anyhow::Error),
}

/// Unified handler for task failure with retry logic.
///
/// This handler consolidates the retry pattern that was repeated across
/// multiple workers (scrape_worker, webhook_worker).
pub struct RetryHandler {
    repository: Arc<dyn TaskRepository>,
    retry_policy: RetryPolicy,
}

impl RetryHandler {
    /// Create a new RetryHandler
    pub fn new(repository: Arc<dyn TaskRepository>, retry_policy: RetryPolicy) -> Self {
        Self {
            repository,
            retry_policy,
        }
    }

    /// Create a RetryHandler with default policy
    pub fn with_default_policy(repository: Arc<dyn TaskRepository>) -> Self {
        Self::new(repository, RetryPolicy::default())
    }

    /// Handle task failure with retry logic
    ///
    /// # Arguments
    ///
    /// * `task` - The task that failed
    /// * `error` - Human-readable failure reason; written to
    ///   `task.payload["error"]` on the terminal (no more retries) path so the
    ///   API status endpoint can surface it instead of the generic fallback.
    ///
    /// # Returns
    ///
    /// Result indicating whether task was retried or marked as failed
    pub async fn handle_failure(&self, task: &mut Task, error: &str) -> HandleFailureResult {
        let new_attempt_count = (task.attempt_count + 1) as u32;

        // 统一重试上限:策略上限与任务自身 max_retries 取小者,
        // 避免任务声明的 max_retries(默认 3)被策略硬编码 5 架空
        let effective_max_retries = self
            .retry_policy
            .max_retries
            .min(task.max_retries.max(1) as u32);

        if new_attempt_count > effective_max_retries {
            return self
                .terminate_task(task, error, new_attempt_count, effective_max_retries)
                .await;
        }
        self.schedule_retry(task, new_attempt_count).await
    }

    /// 终结分支(自 [`RetryHandler::handle_failure`] 提取):超过有效重试
    /// 上限后标记任务失败并写入错误串。
    async fn terminate_task(
        &self,
        task: &mut Task,
        error: &str,
        new_attempt_count: u32,
        effective_max_retries: u32,
    ) -> HandleFailureResult {
        warn!(
            "Task {} exceeded max retries (effective={}, policy={}, task declared={}), marking as failed",
            task.id,
            effective_max_retries,
            self.retry_policy.max_retries,
            task.max_retries
        );

        task.attempt_count = new_attempt_count as i32;
        task.retry_count += 1;
        // 统一终态迁移:Failed + completed_at + payload["error"] + 清锁。
        // 守卫过滤要求快照锁与 DB 一致,故写前恢复锁身份;
        // update_task_guarded 会按终态语义把锁列写回 NULL。
        let snapshot_lock = task.lock_token;
        let snapshot_lock_expires = task.lock_expires_at;
        task.fail_with_reason(error);
        task.lock_token = snapshot_lock;
        task.lock_expires_at = snapshot_lock_expires;

        // 守卫式写入:锁被抢占/任务已被他方迁移时放弃终结
        let rows = match self.repository.update_task_guarded(task).await {
            Ok(rows) => rows,
            Err(e) => return HandleFailureResult::Error(e.into()),
        };
        if rows == 0 {
            warn!(
                "Task {} terminal-fail not written (guard failed: migrated by another worker)",
                task.id
            );
            return HandleFailureResult::Stale;
        }
        HandleFailureResult::Failed
    }

    /// 重试分支(自 [`RetryHandler::handle_failure`] 提取):计算退避并
    /// 守卫式调度下一次重试。
    async fn schedule_retry(&self, task: &mut Task, new_attempt_count: u32) -> HandleFailureResult {
        // Calculate backoff and schedule next retry
        let backoff = self.retry_policy.calculate_backoff(new_attempt_count);
        let next_retry = Utc::now() + Duration::milliseconds(backoff.as_millis() as i64);

        task.attempt_count = new_attempt_count as i32;
        task.retry_count += 1;
        task.scheduled_at = Some(next_retry);
        task.status = TaskStatus::Queued;
        task.started_at = None;
        task.completed_at = None;

        // 守卫式写入:锁被抢占时任务不会重回队列(避免陈旧 worker 覆盖并发迁移)
        let rows = match self.repository.update_task_guarded(task).await {
            Ok(rows) => rows,
            Err(e) => return HandleFailureResult::Error(e.into()),
        };
        if rows == 0 {
            warn!(
                "Task {} retry requeue not written (guard failed: migrated by another worker)",
                task.id
            );
            return HandleFailureResult::Stale;
        }

        info!(
            "Scheduled retry {}/{} for task {} in {:?}",
            new_attempt_count, task.max_retries, task.id, backoff
        );

        HandleFailureResult::Retried {
            attempt_count: new_attempt_count,
            next_retry_at: next_retry,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::domain::models::{Task, TaskStatus, TaskType};
    use crate::domain::repositories::task_repository::{
        RepositoryError, TaskQueryParams, TaskRepository,
    };
    use crate::utils::retry_policy::RetryPolicy;
    use async_trait::async_trait;
    use std::collections::HashSet;
    use std::sync::Arc;
    use std::sync::Mutex;

    /// Mock TaskRepository that records `update` calls and can simulate failures.
    struct MockTaskRepository {
        /// Last task passed to `update` (None if never called)
        last_updated: Mutex<Option<Task>>,
        /// When true, `update` returns an error
        fail_update: Mutex<bool>,
    }

    impl MockTaskRepository {
        fn new() -> Self {
            Self {
                last_updated: Mutex::new(None),
                fail_update: Mutex::new(false),
            }
        }

        fn set_fail_update(&self, fail: bool) {
            *self.fail_update.lock().expect("lock fail_update") = fail;
        }

        fn last_updated_task(&self) -> Option<Task> {
            self.last_updated.lock().expect("lock last_updated").clone()
        }
    }

    #[async_trait]
    impl TaskRepository for MockTaskRepository {
        async fn create(&self, _task: &Task) -> Result<Task, RepositoryError> {
            Err(RepositoryError::Database(anyhow::anyhow!(
                "not implemented"
            )))
        }

        async fn find_by_id(
            &self,
            _id: crate::domain::id::Id,
        ) -> Result<Option<Task>, RepositoryError> {
            Ok(None)
        }

        async fn update(&self, task: &Task) -> Result<Task, RepositoryError> {
            if *self.fail_update.lock().expect("lock fail_update") {
                return Err(RepositoryError::Database(anyhow::anyhow!(
                    "mock update failure"
                )));
            }
            *self.last_updated.lock().expect("lock last_updated") = Some(task.clone());
            Ok(task.clone())
        }

        async fn update_task_guarded(&self, task: &Task) -> Result<u64, RepositoryError> {
            if *self.fail_update.lock().expect("lock fail_update") {
                return Err(RepositoryError::Database(anyhow::anyhow!(
                    "mock update failure"
                )));
            }
            *self.last_updated.lock().expect("lock last_updated") = Some(task.clone());
            Ok(1)
        }

        async fn acquire_next(
            &self,
            _worker_id: crate::domain::id::Id,
        ) -> Result<Option<Task>, RepositoryError> {
            Ok(None)
        }

        async fn mark_completed(
            &self,
            _id: crate::domain::id::Id,
            _lock_token: Option<crate::domain::id::Id>,
        ) -> Result<u64, RepositoryError> {
            Ok(1)
        }

        async fn mark_failed(
            &self,
            _id: crate::domain::id::Id,
            _lock_token: Option<crate::domain::id::Id>,
        ) -> Result<u64, RepositoryError> {
            Ok(1)
        }

        async fn mark_cancelled(&self, _id: crate::domain::id::Id) -> Result<u64, RepositoryError> {
            Ok(1)
        }

        async fn exists_by_url(&self, _url: &str) -> Result<bool, RepositoryError> {
            Ok(false)
        }

        async fn find_existing_urls(
            &self,
            _urls: &[String],
        ) -> Result<HashSet<String>, RepositoryError> {
            Ok(HashSet::new())
        }

        async fn reset_stuck_tasks(
            &self,
            _timeout: chrono::Duration,
        ) -> Result<u64, RepositoryError> {
            Ok(0)
        }

        async fn cancel_tasks_by_crawl_id(
            &self,
            _crawl_id: crate::domain::id::Id,
        ) -> Result<u64, RepositoryError> {
            Ok(0)
        }

        async fn expire_tasks(&self) -> Result<u64, RepositoryError> {
            Ok(0)
        }

        async fn find_by_crawl_id(
            &self,
            _crawl_id: crate::domain::id::Id,
        ) -> Result<Vec<Task>, RepositoryError> {
            Ok(vec![])
        }

        async fn query_tasks(
            &self,
            _params: TaskQueryParams,
        ) -> Result<(Vec<Task>, u64), RepositoryError> {
            Ok((vec![], 0))
        }

        async fn batch_cancel(
            &self,
            _task_ids: Vec<crate::domain::id::Id>,
            _team_id: crate::domain::id::Id,
            _force: bool,
        ) -> Result<
            (
                Vec<crate::domain::id::Id>,
                Vec<(crate::domain::id::Id, String)>,
            ),
            RepositoryError,
        > {
            Ok((vec![], vec![]))
        }

        async fn renew_lock(
            &self,
            _task_id: crate::domain::id::Id,
            _worker_id: crate::domain::id::Id,
            _extend_seconds: i64,
        ) -> Result<bool, RepositoryError> {
            Ok(true)
        }
    }

    /// Build a minimal Task for retry tests
    fn make_task(attempt_count: i32, max_retries: i32) -> Task {
        let mut task = Task::new(
            crate::domain::id::Id::generate(),
            TaskType::Scrape,
            crate::domain::id::Id::generate(),
            crate::domain::id::Id::generate(),
            "https://example.com".to_string(),
            serde_json::json!({}),
        );
        task.attempt_count = attempt_count;
        task.max_retries = max_retries;
        task
    }

    // RetryHandler::new / with_default_policy tests

    #[test]
    fn test_new_stores_repository_and_policy() {
        let repo: Arc<dyn TaskRepository> = Arc::new(MockTaskRepository::new());
        let policy = RetryPolicy::fast();
        let handler = RetryHandler::new(repo.clone(), policy.clone());
        // No direct accessor; verify via behavior in later tests.
        // Just ensure construction does not panic.
        let _ = &handler;
    }

    #[test]
    fn test_with_default_policy_uses_default_retry_policy() {
        let repo: Arc<dyn TaskRepository> = Arc::new(MockTaskRepository::new());
        let handler = RetryHandler::with_default_policy(repo.clone());
        let _ = &handler;
    }

    // handle_failure - retry path

    #[tokio::test]
    async fn test_handle_failure_retries_when_below_max() {
        let mock = Arc::new(MockTaskRepository::new());
        let repo: Arc<dyn TaskRepository> = mock.clone();
        // Policy: max_retries=5, no jitter for deterministic timing
        let policy = RetryPolicy {
            enable_jitter: false,
            ..Default::default()
        };
        let handler = RetryHandler::new(repo, policy);

        let before = Utc::now();
        let mut task = make_task(0, 5);
        let result = handler.handle_failure(&mut task, "boom").await;

        match result {
            HandleFailureResult::Retried {
                attempt_count,
                next_retry_at,
            } => {
                assert_eq!(attempt_count, 1, "attempt_count should be incremented to 1");
                assert!(
                    next_retry_at > before,
                    "next_retry_at should be in the future"
                );
            }
            _ => panic!("expected Retried, got different variant"),
        }

        // Task should be mutated correctly
        assert_eq!(task.attempt_count, 1);
        assert_eq!(task.retry_count, 1);
        assert_eq!(task.status, TaskStatus::Queued);
        assert!(task.scheduled_at.is_some(), "scheduled_at should be set");
        assert!(task.started_at.is_none(), "started_at should be cleared");
        assert!(
            task.completed_at.is_none(),
            "completed_at should be cleared"
        );

        // Repository should have received the updated task
        let updated = mock
            .last_updated_task()
            .expect("update should have been called");
        assert_eq!(updated.id, task.id);
        assert_eq!(updated.status, TaskStatus::Queued);
    }

    #[tokio::test]
    async fn test_handle_failure_retries_increments_attempt_count_correctly() {
        let mock = Arc::new(MockTaskRepository::new());
        let repo: Arc<dyn TaskRepository> = mock.clone();
        let policy = RetryPolicy {
            enable_jitter: false,
            ..Default::default()
        };
        let handler = RetryHandler::new(repo, policy);

        // Start at attempt_count=2, should retry (3 < 5)
        let mut task = make_task(2, 5);
        let result = handler.handle_failure(&mut task, "boom").await;

        match result {
            HandleFailureResult::Retried { attempt_count, .. } => {
                assert_eq!(
                    attempt_count, 3,
                    "attempt_count should be 3 after increment"
                );
            }
            _ => panic!("expected Retried, got different variant"),
        }
        assert_eq!(task.attempt_count, 3);
        assert_eq!(task.retry_count, 1);
    }

    // handle_failure - failed path

    #[tokio::test]
    async fn test_handle_failure_fails_when_max_retries_exceeded() {
        let mock = Arc::new(MockTaskRepository::new());
        let repo: Arc<dyn TaskRepository> = mock.clone();
        // Policy max_retries=0 means should_retry(1) = 1 < 0 = false -> immediate fail
        let policy = RetryPolicy {
            max_retries: 0,
            ..Default::default()
        };
        let handler = RetryHandler::new(repo, policy);

        let before = Utc::now();
        // attempt_count=0 -> new_attempt_count=1, should_retry(1)=false (policy max_retries=0)
        let mut task = make_task(0, 5);
        let result = handler.handle_failure(&mut task, "boom").await;

        match result {
            HandleFailureResult::Failed => { /* expected */ }
            _ => panic!("expected Failed, got different variant"),
        }

        // Task should be marked as failed
        assert_eq!(task.attempt_count, 1);
        assert_eq!(task.retry_count, 1);
        assert_eq!(task.status, TaskStatus::Failed);
        assert!(
            task.completed_at.is_some(),
            "completed_at should be set on failure"
        );
        assert!(
            task.completed_at.expect("completed_at set") >= before,
            "completed_at should be ~now"
        );

        // Repository should have received the failed task
        let updated = mock
            .last_updated_task()
            .expect("update should have been called");
        assert_eq!(updated.status, TaskStatus::Failed);
    }

    #[tokio::test]
    async fn test_handle_failure_fails_when_attempt_reaches_max() {
        let mock = Arc::new(MockTaskRepository::new());
        let repo: Arc<dyn TaskRepository> = mock.clone();
        let handler = RetryHandler::new(repo, RetryPolicy::default());

        // 统一重试上限:effective = min(policy.max_retries=5, task.max_retries=3) = 3
        // attempt_count=3 -> new_attempt_count=4 > 3 -> fail(任务声明的上限生效)
        let mut task = make_task(3, 3);
        let result = handler.handle_failure(&mut task, "boom").await;

        assert!(
            matches!(result, HandleFailureResult::Failed),
            "should fail when attempt_count exceeds task.max_retries"
        );
        assert_eq!(task.status, TaskStatus::Failed);
        assert_eq!(task.attempt_count, 4);
    }

    #[tokio::test]
    async fn test_handle_failure_terminal_writes_payload_error() {
        // 终结分支必须写 payload["error"],API 侧不再回退泛化文案。
        let mock = Arc::new(MockTaskRepository::new());
        let repo: Arc<dyn TaskRepository> = mock.clone();
        let policy = RetryPolicy {
            max_retries: 0,
            ..Default::default()
        };
        let handler = RetryHandler::new(repo, policy);

        let mut task = make_task(0, 5);
        let result = handler
            .handle_failure(&mut task, "connection timeout")
            .await;
        assert!(matches!(result, HandleFailureResult::Failed));
        assert_eq!(
            task.payload.get("error").and_then(|v| v.as_str()),
            Some("connection timeout"),
            "terminal path must record error string in payload"
        );
        let updated = mock
            .last_updated_task()
            .expect("update should have been called");
        assert_eq!(
            updated.payload.get("error").and_then(|v| v.as_str()),
            Some("connection timeout")
        );
    }

    #[tokio::test]
    async fn test_handle_failure_retry_path_does_not_write_payload_error() {
        // 重试分支不写 error(终结时才写,避免中间态污染)。
        let mock = Arc::new(MockTaskRepository::new());
        let repo: Arc<dyn TaskRepository> = mock.clone();
        let policy = RetryPolicy {
            enable_jitter: false,
            ..Default::default()
        };
        let handler = RetryHandler::new(repo, policy);

        let mut task = make_task(0, 5);
        let result = handler.handle_failure(&mut task, "transient").await;
        assert!(matches!(result, HandleFailureResult::Retried { .. }));
        assert!(
            task.payload.get("error").is_none(),
            "retry path must not write payload.error"
        );
    }

    #[tokio::test]
    async fn test_handle_failure_terminal_empty_error_writes_nothing() {
        // 空串不写,保留"真无错误串才回退"语义。
        let mock = Arc::new(MockTaskRepository::new());
        let repo: Arc<dyn TaskRepository> = mock.clone();
        let policy = RetryPolicy {
            max_retries: 0,
            ..Default::default()
        };
        let handler = RetryHandler::new(repo, policy);

        let mut task = make_task(0, 5);
        let result = handler.handle_failure(&mut task, "").await;
        assert!(matches!(result, HandleFailureResult::Failed));
        assert!(
            task.payload.get("error").is_none(),
            "empty error must not create payload.error"
        );
    }

    #[tokio::test]
    async fn test_handle_failure_policy_cap_cannot_exceed_task_max_retries() {
        // 任务声明 max_retries=2 时,即使策略允许 5 次,也在第 3 次尝试前终止
        let mock = Arc::new(MockTaskRepository::new());
        let repo: Arc<dyn TaskRepository> = mock.clone();
        let handler = RetryHandler::new(repo, RetryPolicy::default());

        let mut task = make_task(2, 2);
        let result = handler.handle_failure(&mut task, "boom").await;

        assert!(
            matches!(result, HandleFailureResult::Failed),
            "task.max_retries=2 must cap retries below policy max_retries=5"
        );
        assert_eq!(task.status, TaskStatus::Failed);
    }

    // handle_failure - error path

    #[tokio::test]
    async fn test_handle_failure_returns_error_when_update_fails_on_retry() {
        let mock = Arc::new(MockTaskRepository::new());
        mock.set_fail_update(true);
        let repo: Arc<dyn TaskRepository> = mock.clone();
        let handler = RetryHandler::new(repo, RetryPolicy::default());

        let mut task = make_task(0, 5);
        let result = handler.handle_failure(&mut task, "boom").await;

        match result {
            HandleFailureResult::Error(err) => {
                assert!(
                    err.to_string().contains("mock update failure"),
                    "error should contain mock message: {}",
                    err
                );
            }
            _ => panic!("expected Error, got different variant"),
        }

        // Task should still have been mutated (attempt_count incremented, status set to Queued)
        // even though the repository update failed
        assert_eq!(task.attempt_count, 1);
        assert_eq!(task.retry_count, 1);
        assert_eq!(task.status, TaskStatus::Queued);
    }

    #[tokio::test]
    async fn test_handle_failure_returns_error_when_update_fails_on_fail() {
        let mock = Arc::new(MockTaskRepository::new());
        mock.set_fail_update(true);
        let repo: Arc<dyn TaskRepository> = mock.clone();
        // Policy max_retries=0 -> immediate fail path
        let policy = RetryPolicy {
            max_retries: 0,
            ..Default::default()
        };
        let handler = RetryHandler::new(repo, policy);

        // attempt_count=0 -> new_attempt_count=1, should_retry(1)=false (policy max_retries=0)
        let mut task = make_task(0, 5);
        let result = handler.handle_failure(&mut task, "boom").await;

        match result {
            HandleFailureResult::Error(err) => {
                assert!(
                    err.to_string().contains("mock update failure"),
                    "error should contain mock message: {}",
                    err
                );
            }
            _ => panic!("expected Error, got different variant"),
        }

        // Task should still have been mutated (status set to Failed) before the error
        assert_eq!(task.status, TaskStatus::Failed);
        assert_eq!(task.attempt_count, 1);
        assert!(task.completed_at.is_some());
    }

    // HandleFailureResult variant coverage

    #[test]
    fn test_handle_failure_result_reried_carries_correct_fields() {
        let now = Utc::now();
        let result = HandleFailureResult::Retried {
            attempt_count: 3,
            next_retry_at: now,
        };
        match result {
            HandleFailureResult::Retried {
                attempt_count,
                next_retry_at,
            } => {
                assert_eq!(attempt_count, 3);
                assert_eq!(next_retry_at, now);
            }
            _ => panic!("wrong variant"),
        }
    }

    #[test]
    fn test_handle_failure_result_failed_is_unit() {
        let result = HandleFailureResult::Failed;
        assert!(matches!(result, HandleFailureResult::Failed));
    }

    #[test]
    fn test_handle_failure_result_error_carries_message() {
        let result = HandleFailureResult::Error(anyhow::anyhow!("boom"));
        match result {
            HandleFailureResult::Error(e) => assert!(e.to_string().contains("boom")),
            _ => panic!("wrong variant"),
        }
    }

    #[tokio::test]
    async fn test_mock_task_repository_stub_methods_return_expected_defaults() {
        // handle_failure only exercises `update`; the remaining TaskRepository
        // methods on MockTaskRepository are stubs. Calling them here documents
        // their stub contract and keeps coverage accounting honest.
        let mock = MockTaskRepository::new();
        let task = make_task(0, 5);

        // create is stubbed to return an error (not used by handle_failure)
        assert!(mock.create(&task).await.is_err());

        // Read/query stubs return "not found" / empty results
        assert!(mock.find_by_id(task.id).await.unwrap().is_none());
        assert!(mock
            .acquire_next(crate::domain::id::Id::generate())
            .await
            .unwrap()
            .is_none());
        assert!(!mock.exists_by_url("https://example.com").await.unwrap());
        assert!(mock
            .find_existing_urls(&["https://example.com".to_string()])
            .await
            .unwrap()
            .is_empty());
        assert!(mock
            .find_by_crawl_id(crate::domain::id::Id::generate())
            .await
            .unwrap()
            .is_empty());

        // State-transition stubs are no-ops returning Ok
        mock.mark_completed(task.id, None).await.unwrap();
        mock.mark_failed(task.id, None).await.unwrap();
        mock.mark_cancelled(task.id).await.unwrap();

        // Maintenance stubs return zero counts
        assert_eq!(
            mock.reset_stuck_tasks(Duration::seconds(60)).await.unwrap(),
            0
        );
        assert_eq!(
            mock.cancel_tasks_by_crawl_id(crate::domain::id::Id::generate())
                .await
                .unwrap(),
            0
        );
        assert_eq!(mock.expire_tasks().await.unwrap(), 0);

        // batch_cancel returns empty (successful, failed) tuples
        let (success, failed) = mock
            .batch_cancel(vec![task.id], task.team_id, false)
            .await
            .unwrap();
        assert!(success.is_empty());
        assert!(failed.is_empty());
    }
}