graphile_worker 0.11.4

High performance Rust/PostgreSQL job queue (also suitable for getting jobs generated by PostgreSQL triggers/functions out into a different work queue)
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
use graphile_worker::{
    IntoTaskHandlerResult, JobSpec, LocalQueueConfig, RefetchDelayConfig, TaskHandler, Worker,
    WorkerContext,
};
use serde::{Deserialize, Serialize};
use std::sync::Arc;
use std::time::Duration;
use tokio::{
    task::spawn_local,
    time::{sleep, Instant},
};

use crate::helpers::{with_test_db, StaticCounter};

mod helpers;

#[derive(Serialize, Deserialize)]
struct LocalQueueJob {
    id: u32,
}

static LOCAL_QUEUE_JOB_CALL_COUNT: StaticCounter = StaticCounter::new();

impl TaskHandler for LocalQueueJob {
    const IDENTIFIER: &'static str = "local_queue_job";

    async fn run(self, _ctx: WorkerContext) -> impl IntoTaskHandlerResult {
        LOCAL_QUEUE_JOB_CALL_COUNT.increment().await;
    }
}

#[tokio::test]
async fn local_queue_processes_jobs_correctly() {
    with_test_db(|test_db| async move {
        LOCAL_QUEUE_JOB_CALL_COUNT.reset().await;
        let utils = test_db.worker_utils();
        utils.migrate().await.expect("Failed to migrate");

        let worker_fut = spawn_local({
            let test_pool = test_db.test_pool.clone();
            async move {
                Worker::options()
                    .pg_pool(test_pool)
                    .concurrency(3)
                    .local_queue(LocalQueueConfig::builder().size(10).build())
                    .define_job::<LocalQueueJob>()
                    .init()
                    .await
                    .expect("Failed to create worker")
                    .run()
                    .await
                    .expect("Failed to run worker");
            }
        });

        for i in 1..=5 {
            utils
                .add_job(LocalQueueJob { id: i }, JobSpec::default())
                .await
                .expect("Failed to add job");

            let start_time = Instant::now();
            while LOCAL_QUEUE_JOB_CALL_COUNT.get().await < i {
                if start_time.elapsed().as_secs() > 5 {
                    panic!("Job should have been executed by now");
                }
                sleep(Duration::from_millis(100)).await;
            }

            assert_eq!(
                LOCAL_QUEUE_JOB_CALL_COUNT.get().await,
                i,
                "Job should have been executed {} times",
                i
            );
        }

        sleep(Duration::from_secs(1)).await;
        assert_eq!(
            LOCAL_QUEUE_JOB_CALL_COUNT.get().await,
            5,
            "All 5 jobs should have been executed"
        );

        worker_fut.abort();
    })
    .await;
}

#[derive(Serialize, Deserialize)]
struct BatchJob {
    id: u32,
}

static BATCH_CALL_COUNT: StaticCounter = StaticCounter::new();

impl TaskHandler for BatchJob {
    const IDENTIFIER: &'static str = "batch_job";

    async fn run(self, _ctx: WorkerContext) -> impl IntoTaskHandlerResult {
        BATCH_CALL_COUNT.increment().await;
    }
}

#[tokio::test]
async fn local_queue_batch_fetches_jobs() {
    with_test_db(|test_db| async move {
        BATCH_CALL_COUNT.reset().await;
        let utils = test_db.worker_utils();
        utils.migrate().await.expect("Failed to migrate");

        for i in 1..=20 {
            utils
                .add_job(BatchJob { id: i }, JobSpec::default())
                .await
                .expect("Failed to add job");
        }

        let worker_fut = spawn_local({
            let test_pool = test_db.test_pool.clone();
            async move {
                Worker::options()
                    .pg_pool(test_pool)
                    .concurrency(5)
                    .local_queue(LocalQueueConfig::builder().size(50).build())
                    .define_job::<BatchJob>()
                    .init()
                    .await
                    .expect("Failed to create worker")
                    .run()
                    .await
                    .expect("Failed to run worker");
            }
        });

        let start_time = Instant::now();
        while BATCH_CALL_COUNT.get().await < 20 {
            if start_time.elapsed().as_secs() > 10 {
                panic!(
                    "All jobs should have been executed by now, got {}",
                    BATCH_CALL_COUNT.get().await
                );
            }
            sleep(Duration::from_millis(100)).await;
        }

        assert_eq!(
            BATCH_CALL_COUNT.get().await,
            20,
            "All 20 jobs should have been executed"
        );

        worker_fut.abort();
    })
    .await;
}

#[derive(Serialize, Deserialize)]
struct ShutdownJob {
    id: u32,
}

static SHUTDOWN_CALL_COUNT: StaticCounter = StaticCounter::new();

impl TaskHandler for ShutdownJob {
    const IDENTIFIER: &'static str = "shutdown_job";

    async fn run(self, _ctx: WorkerContext) -> impl IntoTaskHandlerResult {
        sleep(Duration::from_secs(10)).await;
        SHUTDOWN_CALL_COUNT.increment().await;
    }
}

#[tokio::test]
async fn local_queue_returns_jobs_on_shutdown() {
    with_test_db(|test_db| async move {
        SHUTDOWN_CALL_COUNT.reset().await;
        let utils = test_db.worker_utils();
        utils.migrate().await.expect("Failed to migrate");

        for i in 1..=10 {
            utils
                .add_job(ShutdownJob { id: i }, JobSpec::default())
                .await
                .expect("Failed to add job");
        }

        let initial_jobs = test_db.get_jobs().await;
        assert_eq!(initial_jobs.len(), 10, "Should have 10 jobs initially");

        let worker = Arc::new(
            Worker::options()
                .pg_pool(test_db.test_pool.clone())
                .concurrency(2)
                .local_queue(LocalQueueConfig::builder().size(20).build())
                .listen_os_shutdown_signals(false)
                .define_job::<ShutdownJob>()
                .init()
                .await
                .expect("Failed to create worker"),
        );

        let worker_for_run = Arc::clone(&worker);
        let worker_fut = spawn_local(async move {
            let _ = worker_for_run.run().await;
        });

        sleep(Duration::from_millis(500)).await;

        worker.request_shutdown();

        let start_time = Instant::now();
        while !worker_fut.is_finished() {
            if start_time.elapsed().as_secs() > 10 {
                worker_fut.abort();
                panic!("Worker should have shut down by now");
            }
            sleep(Duration::from_millis(100)).await;
        }

        sleep(Duration::from_millis(200)).await;

        let remaining_jobs = test_db.get_jobs().await;
        let unlocked_jobs: Vec<_> = remaining_jobs
            .iter()
            .filter(|j| j.locked_by.is_none())
            .collect();

        assert!(
            unlocked_jobs.len() >= 8,
            "Most jobs should be returned to the queue (got {} unlocked out of {})",
            unlocked_jobs.len(),
            remaining_jobs.len()
        );

        assert_eq!(
            SHUTDOWN_CALL_COUNT.get().await,
            0,
            "No jobs should have completed (they take 10s each)"
        );
    })
    .await;
}

#[derive(Serialize, Deserialize)]
struct FlaggedJob {
    id: u32,
}

static FLAGGED_CALL_COUNT: StaticCounter = StaticCounter::new();

impl TaskHandler for FlaggedJob {
    const IDENTIFIER: &'static str = "flagged_job";

    async fn run(self, _ctx: WorkerContext) -> impl IntoTaskHandlerResult {
        FLAGGED_CALL_COUNT.increment().await;
    }
}

#[tokio::test]
async fn local_queue_with_forbidden_flags_uses_direct_fetch() {
    with_test_db(|test_db| async move {
        FLAGGED_CALL_COUNT.reset().await;
        let utils = test_db.worker_utils();
        utils.migrate().await.expect("Failed to migrate");

        for i in 1..=3 {
            utils
                .add_job(FlaggedJob { id: i }, JobSpec::default())
                .await
                .expect("Failed to add job");
        }

        for i in 4..=6 {
            utils
                .add_job(
                    FlaggedJob { id: i },
                    JobSpec {
                        flags: Some(vec!["special".to_string()]),
                        ..Default::default()
                    },
                )
                .await
                .expect("Failed to add job with flag");
        }

        let worker_fut = spawn_local({
            let test_pool = test_db.test_pool.clone();
            async move {
                Worker::options()
                    .pg_pool(test_pool)
                    .concurrency(3)
                    .local_queue(LocalQueueConfig::builder().size(10).build())
                    .add_forbidden_flag("special")
                    .define_job::<FlaggedJob>()
                    .init()
                    .await
                    .expect("Failed to create worker")
                    .run()
                    .await
                    .expect("Failed to run worker");
            }
        });

        let start_time = Instant::now();
        while FLAGGED_CALL_COUNT.get().await < 3 {
            if start_time.elapsed().as_secs() > 5 {
                panic!("Jobs without flag should have been executed by now");
            }
            sleep(Duration::from_millis(100)).await;
        }

        sleep(Duration::from_millis(500)).await;

        assert_eq!(
            FLAGGED_CALL_COUNT.get().await,
            3,
            "Only 3 jobs without the special flag should have been executed"
        );

        let remaining_jobs = test_db.get_jobs().await;
        assert_eq!(
            remaining_jobs.len(),
            3,
            "3 jobs with the special flag should remain in the queue"
        );

        worker_fut.abort();
    })
    .await;
}

#[derive(Serialize, Deserialize)]
struct RunOnceJob {
    id: u32,
}

static RUN_ONCE_CALL_COUNT: StaticCounter = StaticCounter::new();

impl TaskHandler for RunOnceJob {
    const IDENTIFIER: &'static str = "run_once_job";

    async fn run(self, _ctx: WorkerContext) -> impl IntoTaskHandlerResult {
        RUN_ONCE_CALL_COUNT.increment().await;
    }
}

#[tokio::test]
async fn local_queue_works_with_run_once() {
    with_test_db(|test_db| async move {
        RUN_ONCE_CALL_COUNT.reset().await;
        let utils = test_db.worker_utils();
        utils.migrate().await.expect("Failed to migrate");

        for i in 1..=5 {
            utils
                .add_job(RunOnceJob { id: i }, JobSpec::default())
                .await
                .expect("Failed to add job");
        }

        let worker = Worker::options()
            .pg_pool(test_db.test_pool.clone())
            .concurrency(3)
            .define_job::<RunOnceJob>()
            .init()
            .await
            .expect("Failed to create worker");

        worker.run_once().await.expect("Failed to run_once");

        assert_eq!(
            RUN_ONCE_CALL_COUNT.get().await,
            5,
            "All 5 jobs should have been executed with run_once"
        );

        let remaining_jobs = test_db.get_jobs().await;
        assert_eq!(
            remaining_jobs.len(),
            0,
            "No jobs should remain after run_once"
        );
    })
    .await;
}

#[derive(Serialize, Deserialize)]
struct TtlExpiryJob {
    id: u32,
}

static TTL_CALL_COUNT: StaticCounter = StaticCounter::new();

impl TaskHandler for TtlExpiryJob {
    const IDENTIFIER: &'static str = "ttl_expiry_job";

    async fn run(self, _ctx: WorkerContext) -> impl IntoTaskHandlerResult {
        sleep(Duration::from_secs(30)).await;
        TTL_CALL_COUNT.increment().await;
    }
}

#[tokio::test]
async fn local_queue_returns_jobs_on_ttl_expiry() {
    with_test_db(|test_db| async move {
        TTL_CALL_COUNT.reset().await;
        let utils = test_db.worker_utils();
        utils.migrate().await.expect("Failed to migrate");

        for i in 1..=10 {
            utils
                .add_job(TtlExpiryJob { id: i }, JobSpec::default())
                .await
                .expect("Failed to add job");
        }

        let initial_jobs = test_db.get_jobs().await;
        assert_eq!(initial_jobs.len(), 10, "Should have 10 jobs initially");

        let worker = Arc::new(
            Worker::options()
                .pg_pool(test_db.test_pool.clone())
                .concurrency(1)
                .local_queue(
                    LocalQueueConfig::builder()
                        .size(20)
                        .ttl(Duration::from_millis(500))
                        .build(),
                )
                .listen_os_shutdown_signals(false)
                .define_job::<TtlExpiryJob>()
                .init()
                .await
                .expect("Failed to create worker"),
        );

        let worker_for_run = Arc::clone(&worker);
        let worker_fut = spawn_local(async move {
            let _ = worker_for_run.run().await;
        });

        sleep(Duration::from_millis(200)).await;

        let jobs_during_processing = test_db.get_jobs().await;
        let locked_jobs: Vec<_> = jobs_during_processing
            .iter()
            .filter(|j| j.locked_by.is_some())
            .collect();
        assert!(
            !locked_jobs.is_empty(),
            "At least one job should be locked by worker"
        );

        sleep(Duration::from_millis(800)).await;

        let jobs_after_ttl = test_db.get_jobs().await;
        let unlocked_jobs: Vec<_> = jobs_after_ttl
            .iter()
            .filter(|j| j.locked_by.is_none())
            .collect();

        assert!(
            unlocked_jobs.len() >= 8,
            "Most jobs should be returned after TTL expiry (got {} unlocked out of {})",
            unlocked_jobs.len(),
            jobs_after_ttl.len()
        );

        worker.request_shutdown();
        worker_fut.abort();
    })
    .await;
}

#[derive(Serialize, Deserialize)]
struct RefetchDelayJob {
    id: u32,
}

static REFETCH_DELAY_CALL_COUNT: StaticCounter = StaticCounter::new();

impl TaskHandler for RefetchDelayJob {
    const IDENTIFIER: &'static str = "refetch_delay_job";

    async fn run(self, _ctx: WorkerContext) -> impl IntoTaskHandlerResult {
        REFETCH_DELAY_CALL_COUNT.increment().await;
    }
}

#[tokio::test]
async fn local_queue_refetch_delay_triggers_when_below_threshold() {
    with_test_db(|test_db| async move {
        REFETCH_DELAY_CALL_COUNT.reset().await;
        let utils = test_db.worker_utils();
        utils.migrate().await.expect("Failed to migrate");

        for i in 1..=3 {
            utils
                .add_job(RefetchDelayJob { id: i }, JobSpec::default())
                .await
                .expect("Failed to add job");
        }

        let worker_fut = spawn_local({
            let test_pool = test_db.test_pool.clone();
            async move {
                Worker::options()
                    .pg_pool(test_pool)
                    .concurrency(2)
                    .poll_interval(Duration::from_secs(10))
                    .local_queue(
                        LocalQueueConfig::builder()
                            .size(10)
                            .refetch_delay(
                                RefetchDelayConfig::builder()
                                    .duration(Duration::from_millis(200))
                                    .threshold(5)
                                    .build(),
                            )
                            .build(),
                    )
                    .define_job::<RefetchDelayJob>()
                    .init()
                    .await
                    .expect("Failed to create worker")
                    .run()
                    .await
                    .expect("Failed to run worker");
            }
        });

        let start_time = Instant::now();
        while REFETCH_DELAY_CALL_COUNT.get().await < 3 {
            if start_time.elapsed().as_secs() > 5 {
                panic!(
                    "Jobs should have been executed by now, got {}",
                    REFETCH_DELAY_CALL_COUNT.get().await
                );
            }
            sleep(Duration::from_millis(50)).await;
        }

        assert_eq!(
            REFETCH_DELAY_CALL_COUNT.get().await,
            3,
            "All 3 jobs should have been executed"
        );

        worker_fut.abort();
    })
    .await;
}

#[derive(Serialize, Deserialize)]
struct SmallQueueJob {
    id: u32,
}

static SMALL_QUEUE_CALL_COUNT: StaticCounter = StaticCounter::new();

impl TaskHandler for SmallQueueJob {
    const IDENTIFIER: &'static str = "small_queue_job";

    async fn run(self, _ctx: WorkerContext) -> impl IntoTaskHandlerResult {
        SMALL_QUEUE_CALL_COUNT.increment().await;
    }
}

#[tokio::test]
async fn local_queue_with_size_one() {
    with_test_db(|test_db| async move {
        SMALL_QUEUE_CALL_COUNT.reset().await;
        let utils = test_db.worker_utils();
        utils.migrate().await.expect("Failed to migrate");

        for i in 1..=5 {
            utils
                .add_job(SmallQueueJob { id: i }, JobSpec::default())
                .await
                .expect("Failed to add job");
        }

        let worker_fut = spawn_local({
            let test_pool = test_db.test_pool.clone();
            async move {
                Worker::options()
                    .pg_pool(test_pool)
                    .concurrency(1)
                    .local_queue(LocalQueueConfig::builder().size(1).build())
                    .define_job::<SmallQueueJob>()
                    .init()
                    .await
                    .expect("Failed to create worker")
                    .run()
                    .await
                    .expect("Failed to run worker");
            }
        });

        let start_time = Instant::now();
        while SMALL_QUEUE_CALL_COUNT.get().await < 5 {
            if start_time.elapsed().as_secs() > 10 {
                panic!(
                    "All jobs should have been executed by now, got {}",
                    SMALL_QUEUE_CALL_COUNT.get().await
                );
            }
            sleep(Duration::from_millis(100)).await;
        }

        assert_eq!(
            SMALL_QUEUE_CALL_COUNT.get().await,
            5,
            "All 5 jobs should have been executed even with queue size 1"
        );

        worker_fut.abort();
    })
    .await;
}

#[derive(Serialize, Deserialize)]
struct ConcurrentDistributionJob {
    id: u32,
}

static CONCURRENT_CALL_COUNT: StaticCounter = StaticCounter::new();

impl TaskHandler for ConcurrentDistributionJob {
    const IDENTIFIER: &'static str = "concurrent_distribution_job";

    async fn run(self, _ctx: WorkerContext) -> impl IntoTaskHandlerResult {
        sleep(Duration::from_millis(100)).await;
        CONCURRENT_CALL_COUNT.increment().await;
    }
}

#[tokio::test]
async fn local_queue_distributes_jobs_to_concurrent_workers() {
    with_test_db(|test_db| async move {
        CONCURRENT_CALL_COUNT.reset().await;
        let utils = test_db.worker_utils();
        utils.migrate().await.expect("Failed to migrate");

        for i in 1..=10 {
            utils
                .add_job(ConcurrentDistributionJob { id: i }, JobSpec::default())
                .await
                .expect("Failed to add job");
        }

        let start = Instant::now();

        let worker_fut = spawn_local({
            let test_pool = test_db.test_pool.clone();
            async move {
                Worker::options()
                    .pg_pool(test_pool)
                    .concurrency(5)
                    .local_queue(LocalQueueConfig::builder().size(20).build())
                    .define_job::<ConcurrentDistributionJob>()
                    .init()
                    .await
                    .expect("Failed to create worker")
                    .run()
                    .await
                    .expect("Failed to run worker");
            }
        });

        while CONCURRENT_CALL_COUNT.get().await < 10 {
            if start.elapsed().as_secs() > 10 {
                panic!(
                    "All jobs should have been executed by now, got {}",
                    CONCURRENT_CALL_COUNT.get().await
                );
            }
            sleep(Duration::from_millis(50)).await;
        }

        let elapsed = start.elapsed();

        assert!(
            elapsed < Duration::from_secs(3),
            "With concurrency 5, 10 jobs at 100ms each should complete faster than sequential (10s), took {:?}",
            elapsed
        );

        worker_fut.abort();
    })
    .await;
}

#[derive(Serialize, Deserialize)]
struct ModeTransitionJob {
    id: u32,
}

static MODE_TRANSITION_CALL_COUNT: StaticCounter = StaticCounter::new();

impl TaskHandler for ModeTransitionJob {
    const IDENTIFIER: &'static str = "mode_transition_job";

    async fn run(self, _ctx: WorkerContext) -> impl IntoTaskHandlerResult {
        sleep(Duration::from_millis(50)).await;
        MODE_TRANSITION_CALL_COUNT.increment().await;
    }
}

#[tokio::test]
async fn local_queue_transitions_modes_correctly() {
    with_test_db(|test_db| async move {
        MODE_TRANSITION_CALL_COUNT.reset().await;
        let utils = test_db.worker_utils();
        utils.migrate().await.expect("Failed to migrate");

        let worker = Arc::new(
            Worker::options()
                .pg_pool(test_db.test_pool.clone())
                .concurrency(1)
                .poll_interval(Duration::from_millis(100))
                .local_queue(LocalQueueConfig::builder().size(5).build())
                .listen_os_shutdown_signals(false)
                .define_job::<ModeTransitionJob>()
                .init()
                .await
                .expect("Failed to create worker"),
        );

        let worker_for_run = Arc::clone(&worker);
        let worker_fut = spawn_local(async move {
            let _ = worker_for_run.run().await;
        });

        sleep(Duration::from_millis(50)).await;

        for i in 1..=3 {
            utils
                .add_job(ModeTransitionJob { id: i }, JobSpec::default())
                .await
                .expect("Failed to add job");
        }

        let start_time = Instant::now();
        while MODE_TRANSITION_CALL_COUNT.get().await < 3 {
            if start_time.elapsed().as_secs() > 5 {
                panic!("First batch should have been executed");
            }
            sleep(Duration::from_millis(50)).await;
        }

        sleep(Duration::from_millis(200)).await;

        for i in 4..=6 {
            utils
                .add_job(ModeTransitionJob { id: i }, JobSpec::default())
                .await
                .expect("Failed to add job");
        }

        let start_time = Instant::now();
        while MODE_TRANSITION_CALL_COUNT.get().await < 6 {
            if start_time.elapsed().as_secs() > 5 {
                panic!("Second batch should have been executed");
            }
            sleep(Duration::from_millis(50)).await;
        }

        assert_eq!(
            MODE_TRANSITION_CALL_COUNT.get().await,
            6,
            "All 6 jobs should have been executed across mode transitions"
        );

        worker.request_shutdown();
        worker_fut.abort();
    })
    .await;
}

#[derive(Serialize, Deserialize)]
struct EmptyQueueJob {
    id: u32,
}

static EMPTY_QUEUE_CALL_COUNT: StaticCounter = StaticCounter::new();

impl TaskHandler for EmptyQueueJob {
    const IDENTIFIER: &'static str = "empty_queue_job";

    async fn run(self, _ctx: WorkerContext) -> impl IntoTaskHandlerResult {
        EMPTY_QUEUE_CALL_COUNT.increment().await;
    }
}

#[tokio::test]
async fn local_queue_handles_empty_queue_gracefully() {
    with_test_db(|test_db| async move {
        EMPTY_QUEUE_CALL_COUNT.reset().await;
        let utils = test_db.worker_utils();
        utils.migrate().await.expect("Failed to migrate");

        let worker = Arc::new(
            Worker::options()
                .pg_pool(test_db.test_pool.clone())
                .concurrency(2)
                .poll_interval(Duration::from_millis(100))
                .local_queue(LocalQueueConfig::builder().size(10).build())
                .listen_os_shutdown_signals(false)
                .define_job::<EmptyQueueJob>()
                .init()
                .await
                .expect("Failed to create worker"),
        );

        let worker_for_run = Arc::clone(&worker);
        let worker_fut = spawn_local(async move {
            let _ = worker_for_run.run().await;
        });

        sleep(Duration::from_millis(300)).await;

        assert_eq!(
            EMPTY_QUEUE_CALL_COUNT.get().await,
            0,
            "No jobs should have been executed on empty queue"
        );

        utils
            .add_job(EmptyQueueJob { id: 1 }, JobSpec::default())
            .await
            .expect("Failed to add job");

        let start_time = Instant::now();
        while EMPTY_QUEUE_CALL_COUNT.get().await < 1 {
            if start_time.elapsed().as_secs() > 5 {
                panic!("Job should have been executed");
            }
            sleep(Duration::from_millis(50)).await;
        }

        assert_eq!(
            EMPTY_QUEUE_CALL_COUNT.get().await,
            1,
            "Job should have been executed after being added to empty queue"
        );

        worker.request_shutdown();
        worker_fut.abort();
    })
    .await;
}

#[derive(Serialize, Deserialize)]
struct LargeBatchJob {
    id: u32,
}

static LARGE_BATCH_CALL_COUNT: StaticCounter = StaticCounter::new();

impl TaskHandler for LargeBatchJob {
    const IDENTIFIER: &'static str = "large_batch_job";

    async fn run(self, _ctx: WorkerContext) -> impl IntoTaskHandlerResult {
        LARGE_BATCH_CALL_COUNT.increment().await;
    }
}

#[tokio::test]
async fn local_queue_handles_large_batch() {
    with_test_db(|test_db| async move {
        LARGE_BATCH_CALL_COUNT.reset().await;
        let utils = test_db.worker_utils();
        utils.migrate().await.expect("Failed to migrate");

        for i in 1..=100 {
            utils
                .add_job(LargeBatchJob { id: i }, JobSpec::default())
                .await
                .expect("Failed to add job");
        }

        let worker_fut = spawn_local({
            let test_pool = test_db.test_pool.clone();
            async move {
                Worker::options()
                    .pg_pool(test_pool)
                    .concurrency(10)
                    .local_queue(LocalQueueConfig::builder().size(50).build())
                    .define_job::<LargeBatchJob>()
                    .init()
                    .await
                    .expect("Failed to create worker")
                    .run()
                    .await
                    .expect("Failed to run worker");
            }
        });

        let start_time = Instant::now();
        while LARGE_BATCH_CALL_COUNT.get().await < 100 {
            if start_time.elapsed().as_secs() > 30 {
                panic!(
                    "All jobs should have been executed by now, got {}",
                    LARGE_BATCH_CALL_COUNT.get().await
                );
            }
            sleep(Duration::from_millis(100)).await;
        }

        assert_eq!(
            LARGE_BATCH_CALL_COUNT.get().await,
            100,
            "All 100 jobs should have been executed"
        );

        worker_fut.abort();
    })
    .await;
}

#[derive(Serialize, Deserialize)]
struct RefetchDelayWithJobsJob {
    id: u32,
}

static REFETCH_WITH_JOBS_CALL_COUNT: StaticCounter = StaticCounter::new();

impl TaskHandler for RefetchDelayWithJobsJob {
    const IDENTIFIER: &'static str = "refetch_delay_with_jobs_job";

    async fn run(self, _ctx: WorkerContext) -> impl IntoTaskHandlerResult {
        REFETCH_WITH_JOBS_CALL_COUNT.increment().await;
    }
}

#[tokio::test]
async fn local_queue_processes_jobs_with_refetch_delay() {
    with_test_db(|test_db| async move {
        REFETCH_WITH_JOBS_CALL_COUNT.reset().await;
        let utils = test_db.worker_utils();
        utils.migrate().await.expect("Failed to migrate");

        for i in 1..=5 {
            utils
                .add_job(RefetchDelayWithJobsJob { id: i }, JobSpec::default())
                .await
                .expect("Failed to add job");
        }

        let worker_fut = spawn_local({
            let test_pool = test_db.test_pool.clone();
            async move {
                Worker::options()
                    .pg_pool(test_pool)
                    .concurrency(2)
                    .poll_interval(Duration::from_millis(200))
                    .local_queue(
                        LocalQueueConfig::default()
                            .with_size(10)
                            .with_refetch_delay(
                                RefetchDelayConfig::default()
                                    .with_duration(Duration::from_millis(100))
                                    .with_threshold(3)
                                    .with_max_abort_threshold(10),
                            ),
                    )
                    .define_job::<RefetchDelayWithJobsJob>()
                    .init()
                    .await
                    .expect("Failed to create worker")
                    .run()
                    .await
                    .expect("Failed to run worker");
            }
        });

        let start_time = Instant::now();
        while REFETCH_WITH_JOBS_CALL_COUNT.get().await < 5 {
            if start_time.elapsed().as_secs() > 10 {
                panic!(
                    "Jobs should have been executed, got {}",
                    REFETCH_WITH_JOBS_CALL_COUNT.get().await
                );
            }
            sleep(Duration::from_millis(100)).await;
        }

        assert_eq!(
            REFETCH_WITH_JOBS_CALL_COUNT.get().await,
            5,
            "All 5 jobs should have been executed with refetch delay configured"
        );

        worker_fut.abort();
    })
    .await;
}

#[derive(Serialize, Deserialize)]
struct PulseImmediateFetchJob {
    id: u32,
}

static PULSE_IMMEDIATE_CALL_COUNT: StaticCounter = StaticCounter::new();

impl TaskHandler for PulseImmediateFetchJob {
    const IDENTIFIER: &'static str = "pulse_immediate_fetch_job";

    async fn run(self, _ctx: WorkerContext) -> impl IntoTaskHandlerResult {
        PULSE_IMMEDIATE_CALL_COUNT.increment().await;
    }
}

#[tokio::test]
async fn local_queue_pulse_triggers_immediate_fetch() {
    with_test_db(|test_db| async move {
        PULSE_IMMEDIATE_CALL_COUNT.reset().await;
        let utils = test_db.worker_utils();
        utils.migrate().await.expect("Failed to migrate");

        let worker = Arc::new(
            Worker::options()
                .pg_pool(test_db.test_pool.clone())
                .concurrency(1)
                .poll_interval(Duration::from_secs(30))
                .local_queue(LocalQueueConfig::builder().size(10).build())
                .listen_os_shutdown_signals(false)
                .define_job::<PulseImmediateFetchJob>()
                .init()
                .await
                .expect("Failed to create worker"),
        );

        let worker_for_run = Arc::clone(&worker);
        let worker_fut = spawn_local(async move {
            let _ = worker_for_run.run().await;
        });

        sleep(Duration::from_millis(500)).await;

        let start = Instant::now();
        utils
            .add_job(PulseImmediateFetchJob { id: 1 }, JobSpec::default())
            .await
            .expect("Failed to add job");

        while PULSE_IMMEDIATE_CALL_COUNT.get().await < 1 {
            if start.elapsed().as_secs() > 5 {
                panic!("Job should have been processed immediately via pulse, not after 30s poll");
            }
            sleep(Duration::from_millis(50)).await;
        }

        let elapsed = start.elapsed();
        assert!(
            elapsed < Duration::from_secs(3),
            "Job should be processed quickly via pulse (took {:?}), not waiting for 30s poll_interval",
            elapsed
        );

        worker.request_shutdown();
        worker_fut.abort();
    })
    .await;
}

#[derive(Serialize, Deserialize)]
struct ReleaseWaitsJob {
    id: u32,
}

static RELEASE_WAITS_CALL_COUNT: StaticCounter = StaticCounter::new();
static RELEASE_WAITS_COMPLETED: StaticCounter = StaticCounter::new();

impl TaskHandler for ReleaseWaitsJob {
    const IDENTIFIER: &'static str = "release_waits_job";

    async fn run(self, _ctx: WorkerContext) -> impl IntoTaskHandlerResult {
        RELEASE_WAITS_CALL_COUNT.increment().await;
        sleep(Duration::from_millis(200)).await;
        RELEASE_WAITS_COMPLETED.increment().await;
    }
}

#[tokio::test]
async fn local_queue_release_waits_for_run_loop() {
    with_test_db(|test_db| async move {
        RELEASE_WAITS_CALL_COUNT.reset().await;
        RELEASE_WAITS_COMPLETED.reset().await;
        let utils = test_db.worker_utils();
        utils.migrate().await.expect("Failed to migrate");

        for i in 1..=3 {
            utils
                .add_job(ReleaseWaitsJob { id: i }, JobSpec::default())
                .await
                .expect("Failed to add job");
        }

        let worker = Arc::new(
            Worker::options()
                .pg_pool(test_db.test_pool.clone())
                .concurrency(2)
                .local_queue(LocalQueueConfig::builder().size(10).build())
                .listen_os_shutdown_signals(false)
                .define_job::<ReleaseWaitsJob>()
                .init()
                .await
                .expect("Failed to create worker"),
        );

        let worker_for_run = Arc::clone(&worker);
        let worker_fut = spawn_local(async move {
            let _ = worker_for_run.run().await;
        });

        sleep(Duration::from_millis(500)).await;

        assert!(
            RELEASE_WAITS_CALL_COUNT.get().await > 0,
            "At least one job should have started"
        );

        worker.request_shutdown();

        let start = Instant::now();
        while !worker_fut.is_finished() {
            if start.elapsed().as_secs() > 10 {
                worker_fut.abort();
                panic!("Worker should have finished shutdown by now");
            }
            sleep(Duration::from_millis(50)).await;
        }

        assert!(
            worker_fut.is_finished(),
            "Worker future should be finished after shutdown"
        );
    })
    .await;
}

#[derive(Serialize, Deserialize)]
struct RefetchAbortJob {
    id: u32,
}

static REFETCH_ABORT_CALL_COUNT: StaticCounter = StaticCounter::new();

impl TaskHandler for RefetchAbortJob {
    const IDENTIFIER: &'static str = "refetch_abort_job";

    async fn run(self, _ctx: WorkerContext) -> impl IntoTaskHandlerResult {
        REFETCH_ABORT_CALL_COUNT.increment().await;
    }
}

#[tokio::test]
async fn local_queue_refetch_delay_abort_with_low_concurrency() {
    with_test_db(|test_db| async move {
        REFETCH_ABORT_CALL_COUNT.reset().await;
        let utils = test_db.worker_utils();
        utils.migrate().await.expect("Failed to migrate");

        let worker = Arc::new(
            Worker::options()
                .pg_pool(test_db.test_pool.clone())
                .concurrency(2)
                .poll_interval(Duration::from_secs(30))
                .local_queue(
                    LocalQueueConfig::default()
                        .with_size(10)
                        .with_refetch_delay(
                            RefetchDelayConfig::default()
                                .with_duration(Duration::from_secs(30))
                                .with_threshold(0)
                                .with_max_abort_threshold(3),
                        ),
                )
                .listen_os_shutdown_signals(false)
                .define_job::<RefetchAbortJob>()
                .init()
                .await
                .expect("Failed to create worker"),
        );

        let worker_for_run = Arc::clone(&worker);
        let worker_fut = spawn_local(async move {
            let _ = worker_for_run.run().await;
        });

        sleep(Duration::from_millis(300)).await;

        for i in 1..=5 {
            utils
                .add_job(RefetchAbortJob { id: i }, JobSpec::default())
                .await
                .expect("Failed to add job");
            sleep(Duration::from_millis(50)).await;
        }

        let start_time = Instant::now();
        while REFETCH_ABORT_CALL_COUNT.get().await < 5 {
            if start_time.elapsed().as_secs() > 10 {
                worker_fut.abort();
                panic!(
                    "Jobs should have been executed (got {}). This would deadlock without the fix: \
                    with concurrency=2 and abort_threshold=3, handlers would block on oneshot \
                    channels before enough pulses could trigger the abort.",
                    REFETCH_ABORT_CALL_COUNT.get().await
                );
            }
            sleep(Duration::from_millis(100)).await;
        }

        assert_eq!(
            REFETCH_ABORT_CALL_COUNT.get().await,
            5,
            "All 5 jobs should have been executed after refetch delay abort"
        );

        worker.request_shutdown();
        worker_fut.abort();
    })
    .await;
}