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
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
// Copyright (c) 2025-2026 Kirky.X🌠
// SPDX-License-Identifier: Apache-2.0

use crate::common::error::{RepositoryResultExt, WorkerError};
use crate::config::Settings;
use crate::domain::models::task_domain::TaskStatus;
use crate::domain::repositories::{
    task_repository::TaskRepository,
    tasks_backlog_repository::{TasksBacklog, TasksBacklogRepository},
};
use crate::domain::services::rate_limiting_service::{
    ConcurrencyResult, RateLimitingError, RateLimitingService,
};
use crate::i18n::{tr_log, tr_log_args};
use crate::workers::worker::{ProcessResult, WorkerProcess};
use async_trait::async_trait;
use chrono::Utc;
use log::{error, info, warn};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;

/// 积压任务处理Worker
///
/// 该Worker负责定期处理积压的任务,当团队并发限制释放时
/// 将积压任务重新加入执行队列
pub struct BacklogWorker {
    tasks_backlog_repository: Arc<dyn TasksBacklogRepository>,
    task_repository: Arc<dyn TaskRepository>,
    rate_limiting_service: Arc<dyn RateLimitingService>,
    settings: Arc<Settings>,
    cleanup_cycle_counter: AtomicU64,
}

/// `process_single_backlog` 的分类结果。
///
/// 取代原先的 `bool`:`Ok(false)` 曾把"过期/并发拒绝/意外排队/重试耗尽"全部
/// 混为一谈,process_backlog 无法分类计数。
enum BacklogOutcome {
    /// 成功重新激活任务(或任务已处终态,积压项随之标记完成)
    Reactivated,
    /// 积压项已过期,标记为 Expired
    Expired,
    /// 重试次数耗尽,标记为 Failed
    RetryExhausted,
    /// 团队并发未释放,积压项保持 Pending 等待下一周期
    Denied,
    /// 并发检查返回意外的 Queued
    Queued,
    /// 积压项非 Pending(已被他方处理),跳过
    Skipped,
}

/// 积压处理分类计数(按 `BacklogOutcome` 独立统计)。
#[derive(Default)]
struct BacklogCounts {
    reactivated: usize,
    expired: usize,
    retry_exhausted: usize,
    denied: usize,
    queued: usize,
    skipped: usize,
    failed: usize,
}

impl BacklogCounts {
    /// 合并另一批计数。
    fn add(&mut self, other: Self) {
        self.reactivated += other.reactivated;
        self.expired += other.expired;
        self.retry_exhausted += other.retry_exhausted;
        self.denied += other.denied;
        self.queued += other.queued;
        self.skipped += other.skipped;
        self.failed += other.failed;
    }
}

impl BacklogWorker {
    pub fn new(
        tasks_backlog_repository: Arc<dyn TasksBacklogRepository>,
        task_repository: Arc<dyn TaskRepository>,
        rate_limiting_service: Arc<dyn RateLimitingService>,
        settings: Arc<Settings>,
    ) -> Self {
        Self {
            tasks_backlog_repository,
            task_repository,
            rate_limiting_service,
            settings,
            cleanup_cycle_counter: AtomicU64::new(1),
        }
    }

    /// 处理积压任务
    async fn process_backlog(&self) -> Result<(), WorkerError> {
        info!("{}", tr_log("backlog-processing-started"));

        let batch_size = self.settings.concurrency.default_team_limit as usize;

        let pending_backlogs = self
            .tasks_backlog_repository
            .get_pending_tasks(None, Some(batch_size as u64))
            .await
            .repo_err()?;

        if pending_backlogs.is_empty() {
            info!("{}", tr_log("backlog-none-pending"));
            return Ok(());
        }

        info!(
            "{}",
            tr_log_args(
                "backlog-pending-found",
                &[("count", pending_backlogs.len().to_string())],
            )
        );

        // 2. 按团队分组处理任务
        let backlogs_by_team = group_backlogs_by_team(pending_backlogs);

        // 分类计数:Ok(false) 曾把 expired/denied/queued/
        // 重试耗尽全部混为"过期",现按 BacklogOutcome 独立计数并分类输出。
        let mut counts = BacklogCounts::default();

        for (team_id, team_backlogs) in backlogs_by_team {
            counts.add(self.process_team_backlogs(team_id, team_backlogs).await);
        }

        log_backlog_summary(&counts);

        Ok(())
    }

    /// 处理单个团队的积压任务,返回按 `BacklogOutcome` 分类的计数。
    async fn process_team_backlogs(
        &self,
        team_id: crate::domain::id::Id,
        team_backlogs: Vec<TasksBacklog>,
    ) -> BacklogCounts {
        info!(
            "{}",
            tr_log_args(
                "backlog-team-processing",
                &[
                    ("team_id", team_id.to_string()),
                    ("count", team_backlogs.len().to_string()),
                ],
            )
        );

        let mut counts = BacklogCounts::default();
        for backlog in team_backlogs {
            match self.process_single_backlog(backlog).await {
                Ok(BacklogOutcome::Reactivated) => counts.reactivated += 1,
                Ok(BacklogOutcome::Expired) => counts.expired += 1,
                Ok(BacklogOutcome::RetryExhausted) => counts.retry_exhausted += 1,
                Ok(BacklogOutcome::Denied) => counts.denied += 1,
                Ok(BacklogOutcome::Queued) => counts.queued += 1,
                Ok(BacklogOutcome::Skipped) => counts.skipped += 1,
                Err(e) => {
                    error!(
                        "{}",
                        tr_log_args("backlog-processing-failed", &[("error", e.to_string())],)
                    );
                    counts.failed += 1;
                }
            }
        }

        counts
    }

    /// 处理单个积压任务
    async fn process_single_backlog(
        &self,
        backlog: TasksBacklog,
    ) -> Result<BacklogOutcome, WorkerError> {
        if backlog.is_expired() {
            return self.mark_backlog_expired(&backlog).await;
        }

        // 2. 检查是否超过重试次数
        if !backlog.can_retry() {
            return self.mark_backlog_retry_exhausted(&backlog).await;
        }

        // 3. 检查团队的并发限制
        let concurrency = self
            .rate_limiting_service
            .check_team_concurrency(backlog.team_id, backlog.task_id)
            .await;

        self.apply_concurrency_result(&backlog, concurrency).await
    }

    /// 过期积压项:记录日志、标记 Expired 并持久化
    async fn mark_backlog_expired(
        &self,
        backlog: &TasksBacklog,
    ) -> Result<BacklogOutcome, WorkerError> {
        info!(
            "{}",
            tr_log_args(
                "backlog-expired-marked",
                &[("task_id", backlog.id.to_string())],
            )
        );

        let mut expired_backlog = backlog.clone();
        expired_backlog
            .mark_expired()
            .map_err(WorkerError::DomainError)?;

        self.tasks_backlog_repository
            .update(&expired_backlog)
            .await
            .repo_err()?;

        Ok(BacklogOutcome::Expired)
    }

    /// 重试耗尽的积压项:记录日志、标记 Failed 并持久化
    async fn mark_backlog_retry_exhausted(
        &self,
        backlog: &TasksBacklog,
    ) -> Result<BacklogOutcome, WorkerError> {
        warn!(
            "{}",
            tr_log_args(
                "backlog-retry-exhausted-marked",
                &[("task_id", backlog.id.to_string())],
            )
        );

        let mut failed_backlog = backlog.clone();
        failed_backlog
            .mark_failed()
            .map_err(WorkerError::DomainError)?;

        self.tasks_backlog_repository
            .update(&failed_backlog)
            .await
            .repo_err()?;

        Ok(BacklogOutcome::RetryExhausted)
    }

    /// 按并发检查结果分派;放行分支在 [`Self::reactivate_allowed_backlog`]
    async fn apply_concurrency_result(
        &self,
        backlog: &TasksBacklog,
        concurrency: Result<ConcurrencyResult, RateLimitingError>,
    ) -> Result<BacklogOutcome, WorkerError> {
        match concurrency {
            Ok(ConcurrencyResult::Allowed) => self.reactivate_allowed_backlog(backlog).await,
            Ok(ConcurrencyResult::Denied { reason }) => {
                info!(
                    "{}",
                    tr_log_args(
                        "backlog-concurrency-denied",
                        &[
                            ("team_id", backlog.team_id.to_string()),
                            ("reason", reason.to_string()),
                            ("task_id", backlog.id.to_string()),
                        ],
                    )
                );
                Ok(BacklogOutcome::Denied)
            }
            Ok(ConcurrencyResult::Queued { .. }) => {
                // 这种情况不应该发生,因为我们正在处理积压任务
                warn!(
                    "{}",
                    tr_log_args(
                        "backlog-unexpected-requeue",
                        &[("task_id", backlog.id.to_string())],
                    )
                );
                Ok(BacklogOutcome::Queued)
            }
            Err(e) => {
                error!(
                    "{}",
                    tr_log_args(
                        "backlog-concurrency-check-failed",
                        &[("error", e.to_string())],
                    )
                );
                Err(WorkerError::ServiceError(e.to_string()))
            }
        }
    }

    /// 并发放行:Pending → Processing 迁移后重新激活;失败回写重试次数
    async fn reactivate_allowed_backlog(
        &self,
        backlog: &TasksBacklog,
    ) -> Result<BacklogOutcome, WorkerError> {
        log_backlog_concurrency_available(backlog);

        // 4. 前置状态迁移:迁移失败说明该项已非 Pending(被他方处理),跳过该条并继续。
        let Some(processing_backlog) = begin_backlog_processing(backlog) else {
            return Ok(BacklogOutcome::Skipped);
        };

        // 5. 重新激活任务(reactivate_task 内 mark_completed 现从 Processing 迁移,不再恒败)
        match self.reactivate_task(processing_backlog).await {
            Ok(_) => {
                info!(
                    "{}",
                    tr_log_args(
                        "backlog-reactivated",
                        &[("task_id", backlog.id.to_string())],
                    )
                );
                Ok(BacklogOutcome::Reactivated)
            }
            Err(e) => {
                self.persist_retry_after_reactivation_failure(backlog, e)
                    .await
            }
        }
    }

    /// 重新激活失败:记录错误、累加重试次数并持久化 Pending 快照。
    async fn persist_retry_after_reactivation_failure(
        &self,
        backlog: &TasksBacklog,
        e: WorkerError,
    ) -> Result<BacklogOutcome, WorkerError> {
        error!(
            "{}",
            tr_log_args("backlog-reactivation-failed", &[("error", e.to_string())],)
        );

        // 失败重试:在原始 Pending 快照上累加重试次数并持久化,
        // 保持 Pending 以便下一周期重新拉取(不残留 Processing 状态)。
        let mut retry_backlog = backlog.clone();
        retry_backlog.increment_retry_count();

        self.tasks_backlog_repository
            .update(&retry_backlog)
            .await
            .repo_err()?;

        Err(e)
    }

    /// 重新激活任务
    async fn reactivate_task(
        &self,
        backlog: crate::domain::repositories::tasks_backlog_repository::TasksBacklog,
    ) -> Result<(), WorkerError> {
        // 1. 查找原始任务
        let task = self
            .task_repository
            .find_by_id(backlog.task_id)
            .await
            .repo_err()?
            .ok_or_else(|| WorkerError::NotFound(format!("Task {} not found", backlog.task_id)))?;

        if task.status != TaskStatus::Queued {
            return self.complete_inactive_backlog(&task, backlog).await;
        }

        // 3. 更新任务状态为queued,准备重新执行
        let mut updated_task = task.clone();
        updated_task.status = TaskStatus::Queued;
        updated_task.updated_at = Utc::now();

        self.task_repository
            .update(&updated_task)
            .await
            .repo_err()?;

        // 4. 标记积压任务为已完成
        Self::mark_backlog_completed(self.tasks_backlog_repository.as_ref(), backlog).await?;

        info!(
            "{}",
            tr_log_args(
                "backlog-task-reactivated",
                &[("task_id", task.id.to_string())],
            )
        );
        Ok(())
    }

    /// 任务已非 Queued(不可重新激活):记录日志并把积压项标记完成
    /// (自 [`Self::reactivate_task`] 提取)。
    async fn complete_inactive_backlog(
        &self,
        task: &crate::domain::models::Task,
        backlog: crate::domain::repositories::tasks_backlog_repository::TasksBacklog,
    ) -> Result<(), WorkerError> {
        info!(
            "{}",
            tr_log_args(
                "backlog-task-status-not-activatable",
                &[
                    ("task_id", task.id.to_string()),
                    ("status", task.status.to_string()),
                ],
            )
        );

        Self::mark_backlog_completed(self.tasks_backlog_repository.as_ref(), backlog).await
    }

    /// 把积压项标记完成并持久化(自 [`Self::reactivate_task`] 提取)。
    async fn mark_backlog_completed(
        repository: &dyn crate::domain::repositories::tasks_backlog_repository::TasksBacklogRepository,
        mut backlog: crate::domain::repositories::tasks_backlog_repository::TasksBacklog,
    ) -> Result<(), WorkerError> {
        backlog
            .mark_completed()
            .map_err(|e| WorkerError::DomainError(e.to_string()))?;

        repository.update(&backlog).await.repo_err()?;
        Ok(())
    }

    /// 清理过期任务
    async fn cleanup_expired_tasks(&self) -> Result<(), WorkerError> {
        info!("{}", tr_log("backlog-cleanup-started"));

        let expired_backlogs = self
            .tasks_backlog_repository
            .get_expired_tasks(Some(100))
            .await
            .repo_err()?;

        if expired_backlogs.is_empty() {
            info!("{}", tr_log("backlog-cleanup-none"));
            return Ok(());
        }

        let mut cleaned_count = 0;

        for backlog in expired_backlogs {
            match self.process_expired_backlog(backlog).await {
                Ok(_) => cleaned_count += 1,
                Err(e) => {
                    error!(
                        "{}",
                        tr_log_args("backlog-cleanup-failed", &[("error", e.to_string())],)
                    );
                }
            }
        }

        info!(
            "{}",
            tr_log_args(
                "backlog-cleanup-completed",
                &[("count", cleaned_count.to_string())],
            )
        );
        Ok(())
    }

    /// 处理过期积压任务
    async fn process_expired_backlog(
        &self,
        backlog: crate::domain::repositories::tasks_backlog_repository::TasksBacklog,
    ) -> Result<(), WorkerError> {
        info!(
            "{}",
            tr_log_args(
                "backlog-cleanup-processing",
                &[("task_id", backlog.id.to_string())],
            )
        );

        // 1. 标记积压任务为过期
        let mut expired_backlog = backlog.clone();
        expired_backlog
            .mark_expired()
            .map_err(WorkerError::DomainError)?;

        self.tasks_backlog_repository
            .update(&expired_backlog)
            .await
            .repo_err()?;

        // 2. 查找对应的任务
        let task = self
            .task_repository
            .find_by_id(backlog.task_id)
            .await
            .repo_err()?;

        if let Some(task) = task {
            // 3. 如果任务还在pending状态,标记为失败
            if task.status == TaskStatus::Queued {
                let mut failed_task = task.clone();
                failed_task.status = TaskStatus::Failed;
                failed_task.updated_at = Utc::now();

                self.task_repository.update(&failed_task).await.repo_err()?;

                info!(
                    "{}",
                    tr_log_args(
                        "backlog-task-marked-failed-by-expiry",
                        &[("task_id", task.id.to_string())],
                    )
                );
            }
        }

        Ok(())
    }
}

/// 并发额度可用日志。
fn log_backlog_concurrency_available(backlog: &TasksBacklog) {
    info!(
        "{}",
        tr_log_args(
            "backlog-concurrency-available",
            &[
                ("team_id", backlog.team_id.to_string()),
                ("task_id", backlog.id.to_string()),
            ],
        )
    );
}

/// Pending → Processing 状态迁移(域状态机守卫,仅 Pending 可迁移)。
///
/// 这是修复"成功路径 mark_completed 恒败"的关键——mark_completed 要求
/// 积压项处于 Processing。迁移失败说明该项已非 Pending(被他方处理),
/// 返回 None 由调用方跳过该条并继续。
fn begin_backlog_processing(backlog: &TasksBacklog) -> Option<TasksBacklog> {
    let mut processing_backlog = backlog.clone();
    if let Err(e) = processing_backlog.mark_processing() {
        warn!(
            "{}",
            tr_log_args(
                "backlog-state-transition-skipped",
                &[
                    ("task_id", backlog.id.to_string()),
                    ("current", backlog.status.to_string()),
                    ("error", e.to_string()),
                ],
            )
        );
        return None;
    }
    Some(processing_backlog)
}

/// 按团队分组积压项(容量预分配 32)。
fn group_backlogs_by_team(
    pending_backlogs: Vec<TasksBacklog>,
) -> std::collections::HashMap<crate::domain::id::Id, Vec<TasksBacklog>> {
    let mut backlogs_by_team: std::collections::HashMap<crate::domain::id::Id, Vec<TasksBacklog>> =
        std::collections::HashMap::with_capacity(32);
    for backlog in pending_backlogs {
        backlogs_by_team
            .entry(backlog.team_id)
            .or_default()
            .push(backlog);
    }
    backlogs_by_team
}

/// 输出积压处理汇总(各分类计数)。
fn log_backlog_summary(counts: &BacklogCounts) {
    info!(
        "{}",
        tr_log_args(
            "backlog-processing-summary",
            &[
                ("reactivated", counts.reactivated.to_string()),
                ("expired", counts.expired.to_string()),
                ("retry_exhausted", counts.retry_exhausted.to_string()),
                ("denied", counts.denied.to_string()),
                ("queued", counts.queued.to_string()),
                ("skipped", counts.skipped.to_string()),
                ("failed", counts.failed.to_string()),
            ],
        )
    );
}

#[async_trait]
impl WorkerProcess for BacklogWorker {
    fn name(&self) -> &str {
        "backlog-worker"
    }

    async fn process(&self) -> ProcessResult {
        if let Err(e) = self.process_backlog().await {
            return ProcessResult::Error(tr_log_args(
                "backlog-process-error",
                &[("error", e.to_string())],
            ));
        }

        // 定期清理过期任务(每10个周期清理一次)
        let counter = self.cleanup_cycle_counter.fetch_add(1, Ordering::SeqCst);
        if counter.is_multiple_of(10) {
            if let Err(e) = self.cleanup_expired_tasks().await {
                return ProcessResult::Error(tr_log_args(
                    "backlog-cleanup-error",
                    &[("error", e.to_string())],
                ));
            }
        }

        ProcessResult::Completed
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::domain::models::{CreditsTransactionType, Task, TaskType};
    use crate::domain::repositories::task_repository::RepositoryError;
    use crate::domain::repositories::tasks_backlog_repository::TasksBacklog;
    use crate::domain::services::rate_limiting_service::{BacklogService, QuotaService};
    use crate::domain::services::rate_limiting_service::{
        ConcurrencyConfig, ConcurrencyControlService, ConcurrencyResult, RateLimitConfig,
        RateLimitResult, RateLimitService, RateLimitingError,
    };
    use async_trait::async_trait;
    use std::collections::HashSet;
    use std::sync::Mutex;

    // Test Settings factory

    fn make_test_settings(default_team_limit: u64) -> Arc<Settings> {
        use crate::config::settings::*;
        let settings = Settings {
            server: ServerSettings::default(),
            robots: RobotsSettings::default(),
            database: DatabaseSettings::default(),
            cors: CorsSettings::default(),
            rate_limiting: RateLimitingSettings::default(),
            retention: RetentionSettings::default(),
            concurrency: ConcurrencySettings {
                default_team_limit,
                task_lock_duration_seconds: 300,
                mem_pressure_threshold: 0.8,
                mem_critical_threshold: 0.9,
                critical_timeout_seconds: 30,
                adaptive_enabled: false,
            },
            webhook: WebhookSettings::default(),
            bing_search: BingSearchSettings::default(),
            search: SearchSettings::default(),
            llm: LLMSettings::default(),
            rag: RagSettings::default(),
            fluxweir: FluxweirSettings::default(),
            proxy: ProxySettings::default(),
            engines: EngineSettings::default(),
            markdown: Default::default(),
            logging: LoggingSettings::default(),
            workers: WorkerSettings::default(),
            sitemap: SitemapSettings::default(),
            crawl: CrawlSettings::default(),
            timeouts: TimeoutSettings::default(),
            cache: CacheSettings::default(),
            websocket: WebSocketSettings::default(),
            trusted_proxies: TrustedProxySettings::default(),
            observability: ObservabilitySettings::default(),
            auth: AuthSettings::default(),
            i18n: I18nSettings::default(),
            politeness: PolitenessSettings::default(),
            session: SessionSettings::default(),
            content_extraction: ContentExtractionSettings::default(),
            id: IdSettings::default(),
        };
        Arc::new(settings)
    }

    // Mock TasksBacklogRepository

    struct MockBacklogRepo {
        pending: Mutex<Vec<TasksBacklog>>,
        expired: Mutex<Vec<TasksBacklog>>,
        updated: Mutex<Vec<TasksBacklog>>,
        fail_get_pending: bool,
    }

    impl MockBacklogRepo {
        fn new(pending: Vec<TasksBacklog>) -> Self {
            Self {
                pending: Mutex::new(pending),
                expired: Mutex::new(vec![]),
                updated: Mutex::new(vec![]),
                fail_get_pending: false,
            }
        }

        fn new_empty() -> Self {
            Self::new(vec![])
        }

        fn new_failing() -> Self {
            Self {
                pending: Mutex::new(vec![]),
                expired: Mutex::new(vec![]),
                updated: Mutex::new(vec![]),
                fail_get_pending: true,
            }
        }

        fn new_with_expired(expired: Vec<TasksBacklog>) -> Self {
            Self {
                pending: Mutex::new(vec![]),
                expired: Mutex::new(expired),
                updated: Mutex::new(vec![]),
                fail_get_pending: false,
            }
        }

        fn updated(&self) -> Vec<TasksBacklog> {
            self.updated.lock().unwrap().clone()
        }
    }

    #[async_trait]
    impl TasksBacklogRepository for MockBacklogRepo {
        async fn create(&self, backlog: &TasksBacklog) -> Result<TasksBacklog, RepositoryError> {
            Ok(backlog.clone())
        }

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

        async fn find_by_task_id(
            &self,
            _task_id: crate::domain::id::Id,
        ) -> Result<Option<TasksBacklog>, RepositoryError> {
            Ok(None)
        }

        async fn update(&self, backlog: &TasksBacklog) -> Result<TasksBacklog, RepositoryError> {
            self.updated.lock().unwrap().push(backlog.clone());
            Ok(backlog.clone())
        }

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

        async fn get_pending_tasks(
            &self,
            _team_id: Option<crate::domain::id::Id>,
            _limit: Option<u64>,
        ) -> Result<Vec<TasksBacklog>, RepositoryError> {
            if self.fail_get_pending {
                return Err(RepositoryError::Database(anyhow::anyhow!("db error")));
            }
            Ok(self.pending.lock().unwrap().drain(..).collect())
        }

        async fn get_expired_tasks(
            &self,
            _limit: Option<u64>,
        ) -> Result<Vec<TasksBacklog>, RepositoryError> {
            Ok(self.expired.lock().unwrap().drain(..).collect())
        }

        async fn count_by_status(
            &self,
            _team_id: Option<crate::domain::id::Id>,
            _status: crate::domain::repositories::tasks_backlog_repository::TasksBacklogStatus,
        ) -> Result<i64, RepositoryError> {
            Ok(0)
        }

        async fn update_status_batch(
            &self,
            _ids: &[crate::domain::id::Id],
            _status: crate::domain::repositories::tasks_backlog_repository::TasksBacklogStatus,
        ) -> Result<u64, RepositoryError> {
            Ok(0)
        }
    }

    // Mock TaskRepository

    struct MockTaskRepo {
        tasks: Mutex<std::collections::HashMap<crate::domain::id::Id, Task>>,
        updated_tasks: Mutex<Vec<Task>>,
        expire_count: AtomicU64,
    }

    impl MockTaskRepo {
        fn new() -> Self {
            Self {
                tasks: Mutex::new(std::collections::HashMap::new()),
                updated_tasks: Mutex::new(vec![]),
                expire_count: AtomicU64::new(0),
            }
        }

        fn with_task(self, task: Task) -> Self {
            self.tasks.lock().unwrap().insert(task.id, task);
            self
        }

        fn updated_tasks(&self) -> Vec<Task> {
            self.updated_tasks.lock().unwrap().clone()
        }
    }

    #[async_trait]
    impl TaskRepository for MockTaskRepo {
        async fn create(&self, task: &Task) -> Result<Task, RepositoryError> {
            Ok(task.clone())
        }

        async fn find_by_id(
            &self,
            id: crate::domain::id::Id,
        ) -> Result<Option<Task>, RepositoryError> {
            Ok(self.tasks.lock().unwrap().get(&id).cloned())
        }

        async fn update(&self, task: &Task) -> Result<Task, RepositoryError> {
            self.updated_tasks.lock().unwrap().push(task.clone());
            Ok(task.clone())
        }

        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> {
            self.expire_count.fetch_add(1, Ordering::SeqCst);
            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: crate::domain::repositories::task_repository::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)
        }
    }

    // Mock RateLimitingService

    struct MockRateLimitingService {
        concurrency_result: Mutex<ConcurrencyResult>,
        should_error: bool,
    }

    impl MockRateLimitingService {
        fn new_allowed() -> Self {
            Self {
                concurrency_result: Mutex::new(ConcurrencyResult::Allowed),
                should_error: false,
            }
        }

        fn new_denied() -> Self {
            Self {
                concurrency_result: Mutex::new(ConcurrencyResult::Denied {
                    reason: "limit reached".to_string(),
                }),
                should_error: false,
            }
        }

        fn new_queued() -> Self {
            Self {
                concurrency_result: Mutex::new(ConcurrencyResult::Queued {
                    backlog_id: crate::domain::id::Id::generate(),
                }),
                should_error: false,
            }
        }

        fn new_error() -> Self {
            Self {
                concurrency_result: Mutex::new(ConcurrencyResult::Allowed),
                should_error: true,
            }
        }
    }

    #[async_trait]
    impl RateLimitService for MockRateLimitingService {
        async fn check_rate_limit(
            &self,
            _api_key: &str,
            _endpoint: &str,
        ) -> Result<RateLimitResult, RateLimitingError> {
            Ok(RateLimitResult::Allowed)
        }

        async fn get_team_rate_limit_config(
            &self,
            _team_id: crate::domain::id::Id,
        ) -> Result<RateLimitConfig, RateLimitingError> {
            Ok(RateLimitConfig::default())
        }

        async fn update_team_rate_limit_config(
            &self,
            _team_id: crate::domain::id::Id,
            _config: RateLimitConfig,
        ) -> Result<(), RateLimitingError> {
            Ok(())
        }

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

    #[async_trait]
    impl ConcurrencyControlService for MockRateLimitingService {
        async fn check_team_concurrency(
            &self,
            _team_id: crate::domain::id::Id,
            _task_id: crate::domain::id::Id,
        ) -> Result<ConcurrencyResult, RateLimitingError> {
            if self.should_error {
                return Err(RateLimitingError::Other(anyhow::anyhow!(
                    "concurrency check error"
                )));
            }
            Ok(self.concurrency_result.lock().unwrap().clone())
        }

        async fn release_team_concurrency_slot(
            &self,
            _team_id: crate::domain::id::Id,
            _task_id: crate::domain::id::Id,
        ) -> Result<(), RateLimitingError> {
            Ok(())
        }

        async fn get_team_current_concurrency(
            &self,
            _team_id: crate::domain::id::Id,
        ) -> Result<u32, RateLimitingError> {
            Ok(0)
        }

        async fn get_team_concurrency_config(
            &self,
            _team_id: crate::domain::id::Id,
        ) -> Result<ConcurrencyConfig, RateLimitingError> {
            Ok(ConcurrencyConfig::default())
        }

        async fn update_team_concurrency_config(
            &self,
            _team_id: crate::domain::id::Id,
            _config: ConcurrencyConfig,
        ) -> Result<(), RateLimitingError> {
            Ok(())
        }
    }

    #[async_trait]
    impl BacklogService for MockRateLimitingService {
        async fn process_backlog_tasks(
            &self,
            _team_id: crate::domain::id::Id,
        ) -> Result<u32, RateLimitingError> {
            Ok(0)
        }
    }

    #[async_trait]
    impl QuotaService for MockRateLimitingService {
        async fn check_and_deduct_quota(
            &self,
            _team_id: crate::domain::id::Id,
            _amount: i64,
            _transaction_type: CreditsTransactionType,
            _description: String,
            _reference_id: Option<crate::domain::id::Id>,
        ) -> Result<(), RateLimitingError> {
            Ok(())
        }

        async fn get_quota_balance(
            &self,
            _team_id: crate::domain::id::Id,
        ) -> Result<i64, RateLimitingError> {
            Ok(100)
        }

        async fn refund_quota(
            &self,
            _team_id: crate::domain::id::Id,
            _amount: i64,
            _description: String,
            _reference_id: Option<crate::domain::id::Id>,
        ) -> Result<(), RateLimitingError> {
            Ok(())
        }
    }

    #[async_trait]
    impl RateLimitingService for MockRateLimitingService {}

    // Helper functions

    fn make_backlog(
        team_id: crate::domain::id::Id,
        task_id: crate::domain::id::Id,
    ) -> TasksBacklog {
        TasksBacklog::new(
            task_id,
            team_id,
            "scrape".to_string(),
            0,
            serde_json::json!({"url": "http://example.com"}),
            None,
        )
    }

    fn make_expired_backlog(
        team_id: crate::domain::id::Id,
        task_id: crate::domain::id::Id,
    ) -> TasksBacklog {
        let mut backlog = make_backlog(team_id, task_id);
        backlog.expires_at = Some(Utc::now() - chrono::Duration::hours(1));
        backlog
    }

    fn make_max_retry_backlog(
        team_id: crate::domain::id::Id,
        task_id: crate::domain::id::Id,
    ) -> TasksBacklog {
        let mut backlog = make_backlog(team_id, task_id);
        backlog.retry_count = 3;
        backlog.max_retries = 3;
        backlog
    }

    fn make_processing_backlog(
        team_id: crate::domain::id::Id,
        task_id: crate::domain::id::Id,
    ) -> TasksBacklog {
        let mut backlog = make_backlog(team_id, task_id);
        backlog.mark_processing().unwrap();
        backlog
    }

    fn make_task(id: crate::domain::id::Id, status: TaskStatus) -> Task {
        let now = Utc::now();
        Task {
            id,
            task_type: TaskType::Scrape,
            status,
            priority: 0,
            team_id: crate::domain::id::Id::generate(),
            api_key_id: crate::domain::id::Id::generate(),
            url: "http://example.com".to_string(),
            payload: serde_json::json!({}),
            retry_count: 0,
            attempt_count: 0,
            max_retries: 3,
            scheduled_at: None,
            expires_at: None,
            created_at: now,
            started_at: None,
            completed_at: None,
            crawl_id: None,
            updated_at: now,
            lock_token: None,
            lock_expires_at: None,
        }
    }

    fn make_worker(
        backlog_repo: Arc<dyn TasksBacklogRepository>,
        task_repo: Arc<dyn TaskRepository>,
        rate_limiting: Arc<dyn RateLimitingService>,
        settings: Arc<Settings>,
    ) -> BacklogWorker {
        BacklogWorker::new(backlog_repo, task_repo, rate_limiting, settings)
    }

    fn default_settings() -> Arc<Settings> {
        make_test_settings(10)
    }

    // name tests

    #[test]
    fn test_worker_name() {
        let worker = make_worker(
            Arc::new(MockBacklogRepo::new_empty()),
            Arc::new(MockTaskRepo::new()),
            Arc::new(MockRateLimitingService::new_allowed()),
            default_settings(),
        );
        assert_eq!(worker.name(), "backlog-worker");
    }

    // process with empty backlog

    #[tokio::test]
    async fn test_process_empty_backlog_returns_completed() {
        let worker = make_worker(
            Arc::new(MockBacklogRepo::new_empty()),
            Arc::new(MockTaskRepo::new()),
            Arc::new(MockRateLimitingService::new_allowed()),
            default_settings(),
        );
        let result = worker.process().await;
        assert_eq!(result, ProcessResult::Completed);
    }

    // process with repo failure

    #[tokio::test]
    async fn test_process_repo_failure_returns_error() {
        let worker = make_worker(
            Arc::new(MockBacklogRepo::new_failing()),
            Arc::new(MockTaskRepo::new()),
            Arc::new(MockRateLimitingService::new_allowed()),
            default_settings(),
        );
        let result = worker.process().await;
        match result {
            ProcessResult::Error(msg) => {
                assert!(
                msg.contains("backlog-process-error"),
                "tr_log falls back to the key when the startup bundle is not initialized: {msg}"
            );
            }
            _ => panic!("Expected ProcessResult::Error, got {:?}", result),
        }
    }

    // process with expired backlog

    #[tokio::test]
    async fn test_process_expired_backlog_marks_expired() {
        let team_id = crate::domain::id::Id::generate();
        let task_id = crate::domain::id::Id::generate();
        let backlog = make_expired_backlog(team_id, task_id);
        let repo = Arc::new(MockBacklogRepo::new(vec![backlog]));
        let updated_repo = repo.clone();
        let worker = make_worker(
            repo,
            Arc::new(MockTaskRepo::new()),
            Arc::new(MockRateLimitingService::new_allowed()),
            default_settings(),
        );
        let result = worker.process().await;
        assert_eq!(result, ProcessResult::Completed);
        let updated = updated_repo.updated();
        assert_eq!(updated.len(), 1);
        assert_eq!(
            updated[0].status,
            crate::domain::repositories::tasks_backlog_repository::TasksBacklogStatus::Expired
        );
    }

    // process with max retry backlog

    #[tokio::test]
    async fn test_process_max_retry_backlog_marks_failed() {
        let team_id = crate::domain::id::Id::generate();
        let task_id = crate::domain::id::Id::generate();
        let backlog = make_max_retry_backlog(team_id, task_id);
        let repo = Arc::new(MockBacklogRepo::new(vec![backlog]));
        let updated_repo = repo.clone();
        let worker = make_worker(
            repo,
            Arc::new(MockTaskRepo::new()),
            Arc::new(MockRateLimitingService::new_allowed()),
            default_settings(),
        );
        let result = worker.process().await;
        assert_eq!(result, ProcessResult::Completed);
        let updated = updated_repo.updated();
        assert_eq!(updated.len(), 1);
        assert_eq!(
            updated[0].status,
            crate::domain::repositories::tasks_backlog_repository::TasksBacklogStatus::Failed
        );
    }

    // process with concurrency denied

    #[tokio::test]
    async fn test_process_concurrency_denied_keeps_backlog() {
        let team_id = crate::domain::id::Id::generate();
        let task_id = crate::domain::id::Id::generate();
        let backlog = make_backlog(team_id, task_id);
        let repo = Arc::new(MockBacklogRepo::new(vec![backlog]));
        let worker = make_worker(
            repo,
            Arc::new(MockTaskRepo::new()),
            Arc::new(MockRateLimitingService::new_denied()),
            default_settings(),
        );
        let result = worker.process().await;
        assert_eq!(result, ProcessResult::Completed);
        // Denied means no update to the backlog (returns Ok(false) without updating)
    }

    // process with concurrency queued

    #[tokio::test]
    async fn test_process_concurrency_queued_returns_completed() {
        let team_id = crate::domain::id::Id::generate();
        let task_id = crate::domain::id::Id::generate();
        let backlog = make_backlog(team_id, task_id);
        let repo = Arc::new(MockBacklogRepo::new(vec![backlog]));
        let worker = make_worker(
            repo,
            Arc::new(MockTaskRepo::new()),
            Arc::new(MockRateLimitingService::new_queued()),
            default_settings(),
        );
        let result = worker.process().await;
        assert_eq!(result, ProcessResult::Completed);
    }

    // process with concurrency allowed - task not found

    #[tokio::test]
    async fn test_process_allowed_task_not_found_returns_error() {
        let team_id = crate::domain::id::Id::generate();
        let task_id = crate::domain::id::Id::generate();
        let backlog = make_backlog(team_id, task_id);
        let repo = Arc::new(MockBacklogRepo::new(vec![backlog]));
        let worker = make_worker(
            repo,
            Arc::new(MockTaskRepo::new()), // no task with task_id
            Arc::new(MockRateLimitingService::new_allowed()),
            default_settings(),
        );
        let result = worker.process().await;
        // Task not found -> reactivate_task returns Err -> process_single_backlog increments retry and returns Err
        // process_backlog catches the error but the overall result is still Completed (error is logged, not propagated)
        match result {
            ProcessResult::Completed => {}
            ProcessResult::Error(msg) => {
                // The error is caught in process_backlog's inner loop, so process returns Completed
                panic!("Expected Completed but got Error: {}", msg);
            }
            _ => panic!("Unexpected result: {:?}", result),
        }
    }

    // process with concurrency allowed - task already completed

    #[tokio::test]
    async fn test_process_allowed_task_not_queued_marks_completed() {
        let team_id = crate::domain::id::Id::generate();
        let task_id = crate::domain::id::Id::generate();
        let backlog = make_backlog(team_id, task_id);
        // Task is already Completed (not Queued)
        let task = make_task(task_id, TaskStatus::Completed);
        let repo = Arc::new(MockBacklogRepo::new(vec![backlog]));
        let updated_repo = repo.clone();
        let task_repo = Arc::new(MockTaskRepo::new().with_task(task));
        let worker = make_worker(
            repo,
            task_repo,
            Arc::new(MockRateLimitingService::new_allowed()),
            default_settings(),
        );
        let result = worker.process().await;
        assert_eq!(result, ProcessResult::Completed);
        // 前置 mark_processing 迁移后 mark_completed 成功,Pending 积压项
        // 走完激活路径终态为 Completed(不再退化为 Pending + retry_count 递增)。
        let updated = updated_repo.updated();
        assert_eq!(updated.len(), 1);
        assert_eq!(
            updated[0].status,
            crate::domain::repositories::tasks_backlog_repository::TasksBacklogStatus::Completed
        );
        assert_eq!(updated[0].retry_count, 0);
    }

    // process with concurrency allowed - task queued reactivates

    #[tokio::test]
    async fn test_process_allowed_task_queued_reactivates() {
        let team_id = crate::domain::id::Id::generate();
        let task_id = crate::domain::id::Id::generate();
        let backlog = make_backlog(team_id, task_id);
        let task = make_task(task_id, TaskStatus::Queued);
        let repo = Arc::new(MockBacklogRepo::new(vec![backlog]));
        let updated_repo = repo.clone();
        let task_repo = Arc::new(MockTaskRepo::new().with_task(task));
        let worker = make_worker(
            repo,
            task_repo,
            Arc::new(MockRateLimitingService::new_allowed()),
            default_settings(),
        );
        let result = worker.process().await;
        assert_eq!(result, ProcessResult::Completed);
        // 前置 mark_processing 迁移后 mark_completed 成功,Pending 积压项
        // 走完激活路径终态为 Completed(不再退化为 Pending + retry_count 递增)。
        let updated = updated_repo.updated();
        assert_eq!(updated.len(), 1);
        assert_eq!(
            updated[0].status,
            crate::domain::repositories::tasks_backlog_repository::TasksBacklogStatus::Completed
        );
        assert_eq!(updated[0].retry_count, 0);
    }

    // process with multiple teams

    #[tokio::test]
    async fn test_process_multiple_teams() {
        let team1 = crate::domain::id::Id::generate();
        let team2 = crate::domain::id::Id::generate();
        let backlog1 = make_backlog(team1, crate::domain::id::Id::generate());
        let backlog2 = make_backlog(team2, crate::domain::id::Id::generate());
        let repo = Arc::new(MockBacklogRepo::new(vec![backlog1, backlog2]));
        let worker = make_worker(
            repo,
            Arc::new(MockTaskRepo::new()),
            Arc::new(MockRateLimitingService::new_denied()),
            default_settings(),
        );
        let result = worker.process().await;
        assert_eq!(result, ProcessResult::Completed);
    }

    // cleanup cycle counter (every 10th cycle)

    #[tokio::test]
    async fn test_cleanup_runs_on_10th_cycle() {
        // The counter starts at 1, fetch_add returns 1 first, then 2, etc.
        // counter.is_multiple_of(10) is true when counter == 10, 20, ...
        // So cleanup first triggers on the 10th call.
        let worker = make_worker(
            Arc::new(MockBacklogRepo::new_empty()),
            Arc::new(MockTaskRepo::new()),
            Arc::new(MockRateLimitingService::new_allowed()),
            default_settings(),
        );
        // Calls 1-9: counter=1..9, none is multiple of 10 -> no cleanup
        for _ in 0..9 {
            let r = worker.process().await;
            assert_eq!(r, ProcessResult::Completed);
        }
        // 10th call: counter=10, 10.is_multiple_of(10) = true -> cleanup runs
        let result10 = worker.process().await;
        assert_eq!(result10, ProcessResult::Completed);
    }

    #[tokio::test]
    async fn test_cleanup_does_not_run_on_non_10th_cycle() {
        let worker = make_worker(
            Arc::new(MockBacklogRepo::new_empty()),
            Arc::new(MockTaskRepo::new()),
            Arc::new(MockRateLimitingService::new_allowed()),
            default_settings(),
        );
        // Counter starts at 1; calls 1-9 don't trigger cleanup
        let _ = worker.process().await; // counter 1 -> no cleanup
        let _ = worker.process().await; // counter 2 -> no cleanup
        let _ = worker.process().await; // counter 3 -> no cleanup
        let result = worker.process().await; // counter 4 -> no cleanup
        assert_eq!(result, ProcessResult::Completed);
    }

    // cleanup_expired_tasks: process_expired_backlog with task not found

    #[tokio::test]
    async fn test_cleanup_expired_backlog_task_not_found() {
        let team_id = crate::domain::id::Id::generate();
        let task_id = crate::domain::id::Id::generate();
        let expired_backlog = make_expired_backlog(team_id, task_id);
        let repo = Arc::new(MockBacklogRepo::new_with_expired(vec![expired_backlog]));
        let updated_repo = repo.clone();
        let worker = make_worker(
            repo,
            Arc::new(MockTaskRepo::new()), // no task stored
            Arc::new(MockRateLimitingService::new_allowed()),
            default_settings(),
        );
        // 直接调用 cleanup_expired_tasks 测试清理逻辑
        worker.cleanup_expired_tasks().await.unwrap();
        // The expired backlog should be marked as Expired via update
        let updated = updated_repo.updated();
        assert_eq!(updated.len(), 1);
        assert_eq!(
            updated[0].status,
            crate::domain::repositories::tasks_backlog_repository::TasksBacklogStatus::Expired
        );
    }

    // cleanup_expired_tasks: process_expired_backlog marks Queued task as Failed

    #[tokio::test]
    async fn test_cleanup_expired_with_queued_task_marks_failed() {
        let team_id = crate::domain::id::Id::generate();
        let task_id = crate::domain::id::Id::generate();
        let expired_backlog = make_expired_backlog(team_id, task_id);
        let task = make_task(task_id, TaskStatus::Queued);
        let repo = Arc::new(MockBacklogRepo::new_with_expired(vec![expired_backlog]));
        let updated_repo = repo.clone();
        let task_repo = Arc::new(MockTaskRepo::new().with_task(task));
        let task_repo_for_check = task_repo.clone();
        let worker = make_worker(
            repo,
            task_repo,
            Arc::new(MockRateLimitingService::new_allowed()),
            default_settings(),
        );
        // 直接调用 cleanup_expired_tasks 测试清理逻辑
        worker.cleanup_expired_tasks().await.unwrap();
        // The expired backlog should be marked as Expired
        let updated = updated_repo.updated();
        assert_eq!(updated.len(), 1);
        assert_eq!(
            updated[0].status,
            crate::domain::repositories::tasks_backlog_repository::TasksBacklogStatus::Expired
        );
        // The Queued task should have been marked as Failed
        let updated_tasks = task_repo_for_check.updated_tasks();
        assert_eq!(updated_tasks.len(), 1);
        assert_eq!(updated_tasks[0].status, TaskStatus::Failed);
    }

    // cleanup_expired_tasks: process_expired_backlog with non-Queued task

    #[tokio::test]
    async fn test_cleanup_expired_with_non_queued_task_no_task_update() {
        let team_id = crate::domain::id::Id::generate();
        let task_id = crate::domain::id::Id::generate();
        let expired_backlog = make_expired_backlog(team_id, task_id);
        // Task is already Completed, so it should NOT be marked as Failed
        let task = make_task(task_id, TaskStatus::Completed);
        let repo = Arc::new(MockBacklogRepo::new_with_expired(vec![expired_backlog]));
        let updated_repo = repo.clone();
        let worker = make_worker(
            repo,
            Arc::new(MockTaskRepo::new().with_task(task)),
            Arc::new(MockRateLimitingService::new_allowed()),
            default_settings(),
        );
        // 直接调用 cleanup_expired_tasks 测试清理逻辑
        worker.cleanup_expired_tasks().await.unwrap();
        // Only the backlog is updated (marked as Expired), no task update
        let updated = updated_repo.updated();
        assert_eq!(updated.len(), 1);
        assert_eq!(
            updated[0].status,
            crate::domain::repositories::tasks_backlog_repository::TasksBacklogStatus::Expired
        );
    }

    // cleanup_expired_tasks: multiple expired backlogs

    #[tokio::test]
    async fn test_cleanup_multiple_expired_backlogs() {
        let team1 = crate::domain::id::Id::generate();
        let team2 = crate::domain::id::Id::generate();
        let expired1 = make_expired_backlog(team1, crate::domain::id::Id::generate());
        let expired2 = make_expired_backlog(team2, crate::domain::id::Id::generate());
        let repo = Arc::new(MockBacklogRepo::new_with_expired(vec![expired1, expired2]));
        let updated_repo = repo.clone();
        let worker = make_worker(
            repo,
            Arc::new(MockTaskRepo::new()),
            Arc::new(MockRateLimitingService::new_allowed()),
            default_settings(),
        );
        // 直接调用 cleanup_expired_tasks 测试清理逻辑
        worker.cleanup_expired_tasks().await.unwrap();
        let updated = updated_repo.updated();
        assert_eq!(updated.len(), 2);
        for entry in &updated {
            assert_eq!(
                entry.status,
                crate::domain::repositories::tasks_backlog_repository::TasksBacklogStatus::Expired
            );
        }
    }

    // process success path: backlog in Processing, task Queued, Allowed

    #[tokio::test]
    async fn test_process_success_reactivates_queued_task() {
        let team_id = crate::domain::id::Id::generate();
        let task_id = crate::domain::id::Id::generate();
        // seed a Pending backlog (as production get_pending_tasks returns);
        // the worker now transitions Pending → Processing → Completed internally.
        let backlog = make_backlog(team_id, task_id);
        let task = make_task(task_id, TaskStatus::Queued);
        let repo = Arc::new(MockBacklogRepo::new(vec![backlog]));
        let updated_repo = repo.clone();
        let task_repo = Arc::new(MockTaskRepo::new().with_task(task));
        let task_repo_for_check = task_repo.clone();
        let worker = make_worker(
            repo,
            task_repo,
            Arc::new(MockRateLimitingService::new_allowed()),
            default_settings(),
        );
        let result = worker.process().await;
        assert_eq!(result, ProcessResult::Completed);
        // The backlog should be marked as Completed
        let updated = updated_repo.updated();
        assert_eq!(updated.len(), 1);
        assert_eq!(
            updated[0].status,
            crate::domain::repositories::tasks_backlog_repository::TasksBacklogStatus::Completed
        );
        // The task should have been updated (status stays Queued, updated_at refreshed)
        let updated_tasks = task_repo_for_check.updated_tasks();
        assert_eq!(updated_tasks.len(), 1);
        assert_eq!(updated_tasks[0].status, TaskStatus::Queued);
    }

    // process success path: task not Queued marks backlog completed

    #[tokio::test]
    async fn test_process_task_not_queued_marks_backlog_completed() {
        let team_id = crate::domain::id::Id::generate();
        let task_id = crate::domain::id::Id::generate();
        // seed a Pending backlog (as production get_pending_tasks returns);
        // the worker now transitions Pending → Processing → Completed internally.
        let backlog = make_backlog(team_id, task_id);
        // Task is already Completed (not Queued)
        let task = make_task(task_id, TaskStatus::Completed);
        let repo = Arc::new(MockBacklogRepo::new(vec![backlog]));
        let updated_repo = repo.clone();
        let worker = make_worker(
            repo,
            Arc::new(MockTaskRepo::new().with_task(task)),
            Arc::new(MockRateLimitingService::new_allowed()),
            default_settings(),
        );
        let result = worker.process().await;
        assert_eq!(result, ProcessResult::Completed);
        // reactivate_task sees task.status != Queued, marks backlog as Completed
        let updated = updated_repo.updated();
        assert_eq!(updated.len(), 1);
        assert_eq!(
            updated[0].status,
            crate::domain::repositories::tasks_backlog_repository::TasksBacklogStatus::Completed
        );
    }

    // non-Pending backlog is skipped (mark_processing guard)

    #[tokio::test]
    async fn test_process_already_processing_backlog_is_skipped() {
        let team_id = crate::domain::id::Id::generate();
        let task_id = crate::domain::id::Id::generate();
        // Backlog already in Processing: the Pending → Processing guard fails, so the
        // worker skips it (warn) without any repository update — it was already handled
        // by another worker/cycle.
        let backlog = make_processing_backlog(team_id, task_id);
        let task = make_task(task_id, TaskStatus::Queued);
        let repo = Arc::new(MockBacklogRepo::new(vec![backlog]));
        let updated_repo = repo.clone();
        let worker = make_worker(
            repo,
            Arc::new(MockTaskRepo::new().with_task(task)),
            Arc::new(MockRateLimitingService::new_allowed()),
            default_settings(),
        );
        let result = worker.process().await;
        assert_eq!(result, ProcessResult::Completed);
        // Skipped: no backlog update persisted
        let updated = updated_repo.updated();
        assert_eq!(updated.len(), 0, "skipped backlog must not be updated");
    }

    // process with concurrency check error

    #[tokio::test]
    async fn test_process_concurrency_check_error_returns_completed() {
        let team_id = crate::domain::id::Id::generate();
        let task_id = crate::domain::id::Id::generate();
        let backlog = make_backlog(team_id, task_id);
        let repo = Arc::new(MockBacklogRepo::new(vec![backlog]));
        let worker = make_worker(
            repo,
            Arc::new(MockTaskRepo::new()),
            Arc::new(MockRateLimitingService::new_error()),
            default_settings(),
        );
        // The error is caught in process_backlog's inner loop, so process returns Completed
        let result = worker.process().await;
        assert_eq!(result, ProcessResult::Completed);
    }

    // process with mixed backlogs (expired + normal)

    #[tokio::test]
    async fn test_process_mixed_backlogs_expired_and_normal() {
        let team_id = crate::domain::id::Id::generate();
        let task_id1 = crate::domain::id::Id::generate();
        let task_id2 = crate::domain::id::Id::generate();
        // One expired backlog (will be marked Expired)
        let expired = make_expired_backlog(team_id, task_id1);
        // One normal backlog with denied concurrency (will stay as-is)
        let normal = make_backlog(team_id, task_id2);
        let repo = Arc::new(MockBacklogRepo::new(vec![expired, normal]));
        let updated_repo = repo.clone();
        let worker = make_worker(
            repo,
            Arc::new(MockTaskRepo::new()),
            Arc::new(MockRateLimitingService::new_denied()),
            default_settings(),
        );
        let result = worker.process().await;
        assert_eq!(result, ProcessResult::Completed);
        // Only the expired backlog is updated (marked as Expired)
        let updated = updated_repo.updated();
        assert_eq!(updated.len(), 1);
        assert_eq!(
            updated[0].status,
            crate::domain::repositories::tasks_backlog_repository::TasksBacklogStatus::Expired
        );
    }

    // cleanup_expired_tasks: process_expired_backlog error is caught and continues
    // Covers the Err(e) => error!("清理过期积压任务失败: {}", e) branch in cleanup_expired_tasks.
    // When process_expired_backlog returns Err (e.g. backlog update fails), cleanup_expired_tasks
    // must log the error and continue processing remaining backlogs, ultimately returning Ok.

    /// Mock backlog repo whose update always fails, used to trigger the error path
    /// in process_expired_backlog so that cleanup_expired_tasks exercises its catch branch.
    struct FailingUpdateBacklogRepo {
        expired: Mutex<Vec<TasksBacklog>>,
    }

    impl FailingUpdateBacklogRepo {
        fn new_with_expired(expired: Vec<TasksBacklog>) -> Self {
            Self {
                expired: Mutex::new(expired),
            }
        }
    }

    #[async_trait]
    impl TasksBacklogRepository for FailingUpdateBacklogRepo {
        async fn create(&self, backlog: &TasksBacklog) -> Result<TasksBacklog, RepositoryError> {
            Ok(backlog.clone())
        }
        async fn find_by_id(
            &self,
            _id: crate::domain::id::Id,
        ) -> Result<Option<TasksBacklog>, RepositoryError> {
            Ok(None)
        }
        async fn find_by_task_id(
            &self,
            _task_id: crate::domain::id::Id,
        ) -> Result<Option<TasksBacklog>, RepositoryError> {
            Ok(None)
        }
        async fn update(&self, _backlog: &TasksBacklog) -> Result<TasksBacklog, RepositoryError> {
            Err(RepositoryError::Database(anyhow::anyhow!("update failed")))
        }
        async fn delete(&self, _id: crate::domain::id::Id) -> Result<(), RepositoryError> {
            Ok(())
        }
        async fn get_pending_tasks(
            &self,
            _team_id: Option<crate::domain::id::Id>,
            _limit: Option<u64>,
        ) -> Result<Vec<TasksBacklog>, RepositoryError> {
            Ok(vec![])
        }
        async fn get_expired_tasks(
            &self,
            _limit: Option<u64>,
        ) -> Result<Vec<TasksBacklog>, RepositoryError> {
            Ok(self.expired.lock().unwrap().drain(..).collect())
        }
        async fn count_by_status(
            &self,
            _team_id: Option<crate::domain::id::Id>,
            _status: crate::domain::repositories::tasks_backlog_repository::TasksBacklogStatus,
        ) -> Result<i64, RepositoryError> {
            Ok(0)
        }
        async fn update_status_batch(
            &self,
            _ids: &[crate::domain::id::Id],
            _status: crate::domain::repositories::tasks_backlog_repository::TasksBacklogStatus,
        ) -> Result<u64, RepositoryError> {
            Ok(0)
        }
    }

    #[tokio::test]
    async fn test_cleanup_expired_tasks_continues_after_process_error() {
        // When process_expired_backlog returns Err (backlog update fails), cleanup_expired_tasks
        // should log the error and continue, ultimately returning Ok.
        let team_id = crate::domain::id::Id::generate();
        let task_id1 = crate::domain::id::Id::generate();
        let task_id2 = crate::domain::id::Id::generate();
        // Two expired backlogs: both will fail on update, but cleanup must continue past the first
        let expired1 = make_expired_backlog(team_id, task_id1);
        let expired2 = make_expired_backlog(team_id, task_id2);
        let repo = Arc::new(FailingUpdateBacklogRepo::new_with_expired(vec![
            expired1, expired2,
        ]));
        let worker = make_worker(
            repo,
            Arc::new(MockTaskRepo::new()),
            Arc::new(MockRateLimitingService::new_allowed()),
            default_settings(),
        );
        // 直接调用 cleanup_expired_tasks 测试错误继续逻辑
        let result = worker.cleanup_expired_tasks().await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_cleanup_expired_tasks_single_failure_returns_completed() {
        // Single expired backlog whose processing fails: cleanup_expired_tasks should still
        // return Ok (the error is logged, not propagated).
        let team_id = crate::domain::id::Id::generate();
        let task_id = crate::domain::id::Id::generate();
        let expired = make_expired_backlog(team_id, task_id);
        let repo = Arc::new(FailingUpdateBacklogRepo::new_with_expired(vec![expired]));
        let worker = make_worker(
            repo,
            Arc::new(MockTaskRepo::new()),
            Arc::new(MockRateLimitingService::new_allowed()),
            default_settings(),
        );
        // 直接调用 cleanup_expired_tasks 测试错误处理
        let result = worker.cleanup_expired_tasks().await;
        assert!(result.is_ok());
    }

    // cleanup_expired_tasks: empty expired list returns Ok early
    // Covers the early-return Ok path when there are no expired backlogs.

    #[tokio::test]
    async fn test_cleanup_expired_tasks_empty_returns_completed() {
        // No expired backlogs: cleanup_expired_tasks returns Ok immediately after logging
        // "没有过期的积压任务".
        let repo = Arc::new(FailingUpdateBacklogRepo::new_with_expired(vec![]));
        let worker = make_worker(
            repo,
            Arc::new(MockTaskRepo::new()),
            Arc::new(MockRateLimitingService::new_allowed()),
            default_settings(),
        );
        // 直接调用 cleanup_expired_tasks 测试空列表早返回
        let result = worker.cleanup_expired_tasks().await;
        assert!(result.is_ok());
    }
}