awa 0.5.3

Postgres-native background job queue — transactional enqueue, heartbeat crash recovery, SKIP LOCKED dispatch
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
//! Integration tests for structured job progress and metadata updates (#12).
//!
//! Set DATABASE_URL=postgres://postgres:test@localhost:15432/awa_test

use awa::model::{admin, migrations};
use awa::{JobArgs, JobContext, JobError, JobResult, JobState, Worker};
use awa_testing::TestClient;
use serde::{Deserialize, Serialize};
use sqlx::postgres::PgPoolOptions;
use std::time::Duration;

fn database_url() -> String {
    std::env::var("DATABASE_URL")
        .unwrap_or_else(|_| "postgres://postgres:test@localhost:15432/awa_test".to_string())
}

async fn setup() -> TestClient {
    let pool = PgPoolOptions::new()
        .max_connections(5)
        .connect(&database_url())
        .await
        .expect("Failed to connect to database");

    let client = TestClient::from_pool(pool).await;
    client.migrate().await.expect("Failed to run migrations");
    client
}

async fn clean_queue(pool: &sqlx::PgPool, queue: &str) {
    sqlx::query("DELETE FROM awa.jobs WHERE queue = $1")
        .bind(queue)
        .execute(pool)
        .await
        .expect("Failed to clean queue jobs");
}

// -- Job types for testing --

#[derive(Debug, Serialize, Deserialize, JobArgs)]
struct ProgressJob {
    pub data: String,
}

// -- Worker implementations --

/// Worker that sets progress to 50%.
struct SetProgressWorker;

#[async_trait::async_trait]
impl Worker for SetProgressWorker {
    fn kind(&self) -> &'static str {
        "progress_job"
    }

    async fn perform(&self, ctx: &JobContext) -> Result<JobResult, JobError> {
        ctx.set_progress(50, "half done");
        ctx.flush_progress().await.map_err(JobError::retryable)?;
        Ok(JobResult::Completed)
    }
}

/// Worker that updates metadata.
struct UpdateMetadataWorker;

#[async_trait::async_trait]
impl Worker for UpdateMetadataWorker {
    fn kind(&self) -> &'static str {
        "progress_job"
    }

    async fn perform(&self, ctx: &JobContext) -> Result<JobResult, JobError> {
        ctx.update_metadata(serde_json::json!({"last_processed_id": 1234}))
            .map_err(|e| JobError::terminal(e.to_string()))?;
        ctx.flush_progress().await.map_err(JobError::retryable)?;
        Ok(JobResult::Completed)
    }
}

/// Worker that sets progress multiple times — only last value persists.
struct OverwriteProgressWorker;

#[async_trait::async_trait]
impl Worker for OverwriteProgressWorker {
    fn kind(&self) -> &'static str {
        "progress_job"
    }

    async fn perform(&self, ctx: &JobContext) -> Result<JobResult, JobError> {
        ctx.set_progress(10, "starting");
        ctx.set_progress(50, "middle");
        ctx.set_progress(90, "almost done");
        ctx.flush_progress().await.map_err(JobError::retryable)?;
        Ok(JobResult::Completed)
    }
}

/// Worker that flushes progress immediately.
struct FlushProgressWorker;

#[async_trait::async_trait]
impl Worker for FlushProgressWorker {
    fn kind(&self) -> &'static str {
        "progress_job"
    }

    async fn perform(&self, ctx: &JobContext) -> Result<JobResult, JobError> {
        ctx.set_progress(42, "flushed");
        ctx.flush_progress().await.map_err(JobError::retryable)?;
        // Verify progress was written to DB
        let row = admin::get_job(ctx.pool(), ctx.job.id)
            .await
            .map_err(|e| JobError::terminal(format!("failed to get job: {e}")))?;
        let progress = row.progress.expect("progress should be set after flush");
        let percent = progress.get("percent").and_then(|v| v.as_u64()).unwrap();
        assert_eq!(percent, 42);
        Ok(JobResult::Completed)
    }
}

/// Worker that sets progress then returns RetryAfter.
struct RetryWithProgressWorker;

#[async_trait::async_trait]
impl Worker for RetryWithProgressWorker {
    fn kind(&self) -> &'static str {
        "progress_job"
    }

    async fn perform(&self, ctx: &JobContext) -> Result<JobResult, JobError> {
        ctx.set_progress(30, "partial work");
        ctx.update_metadata(serde_json::json!({"last_id": 500}))
            .map_err(|e| JobError::terminal(e.to_string()))?;
        Ok(JobResult::RetryAfter(Duration::from_secs(1)))
    }
}

/// Worker that reads checkpoint from previous attempt.
struct ReadCheckpointWorker;

#[async_trait::async_trait]
impl Worker for ReadCheckpointWorker {
    fn kind(&self) -> &'static str {
        "progress_job"
    }

    async fn perform(&self, ctx: &JobContext) -> Result<JobResult, JobError> {
        // Read checkpoint from previous attempt
        let last_id = ctx
            .job
            .progress
            .as_ref()
            .and_then(|p| p.get("metadata"))
            .and_then(|m| m.get("last_id"))
            .and_then(|v| v.as_i64());
        assert_eq!(
            last_id,
            Some(500),
            "should see checkpoint from previous attempt"
        );
        Ok(JobResult::Completed)
    }
}

/// Worker that sets progress and returns Cancel.
struct CancelWithProgressWorker;

#[async_trait::async_trait]
impl Worker for CancelWithProgressWorker {
    fn kind(&self) -> &'static str {
        "progress_job"
    }

    async fn perform(&self, ctx: &JobContext) -> Result<JobResult, JobError> {
        ctx.set_progress(75, "cancelling");
        Ok(JobResult::Cancel("user requested".to_string()))
    }
}

/// Worker that sets progress and fails terminally.
struct FailWithProgressWorker;

#[async_trait::async_trait]
impl Worker for FailWithProgressWorker {
    fn kind(&self) -> &'static str {
        "progress_job"
    }

    async fn perform(&self, ctx: &JobContext) -> Result<JobResult, JobError> {
        ctx.set_progress(10, "about to fail");
        Err(JobError::terminal("fatal error"))
    }
}

/// Worker that does not set any progress.
struct NoProgressWorker;

#[async_trait::async_trait]
impl Worker for NoProgressWorker {
    fn kind(&self) -> &'static str {
        "progress_job"
    }

    async fn perform(&self, _ctx: &JobContext) -> Result<JobResult, JobError> {
        Ok(JobResult::Completed)
    }
}

/// Worker that sets progress > 100 and verifies it is clamped to 100.
struct ClampProgressWorker;

#[async_trait::async_trait]
impl Worker for ClampProgressWorker {
    fn kind(&self) -> &'static str {
        "progress_job"
    }

    async fn perform(&self, ctx: &JobContext) -> Result<JobResult, JobError> {
        ctx.set_progress(101, "over the top");
        ctx.flush_progress().await.map_err(JobError::retryable)?;
        // Verify clamped value was written to DB
        let row = admin::get_job(ctx.pool(), ctx.job.id)
            .await
            .map_err(|e| JobError::terminal(format!("failed to get job: {e}")))?;
        let progress = row.progress.expect("progress should be set after flush");
        let percent = progress.get("percent").and_then(|v| v.as_u64()).unwrap();
        assert_eq!(percent, 100, "percent should be clamped to 100");
        Ok(JobResult::Completed)
    }
}

/// Worker that sets progress and waits for callback.
struct WaitWithProgressWorker;

#[async_trait::async_trait]
impl Worker for WaitWithProgressWorker {
    fn kind(&self) -> &'static str {
        "progress_job"
    }

    async fn perform(&self, ctx: &JobContext) -> Result<JobResult, JobError> {
        ctx.set_progress(50, "waiting for callback");
        let callback = ctx
            .register_callback(Duration::from_secs(3600))
            .await
            .map_err(JobError::retryable)?;
        Ok(JobResult::WaitForCallback(callback))
    }
}

// ── Tests ──────────────────────────────────────────────────────────────

/// P1: set_progress(50, "half") + flush_progress → job.progress.percent == 50
#[tokio::test]
async fn test_set_progress_and_flush() {
    let tc = setup().await;
    let queue = "progress_p1";
    clean_queue(tc.pool(), queue).await;

    let job = awa::insert_with(
        tc.pool(),
        &ProgressJob { data: "p1".into() },
        awa::InsertOpts {
            queue: queue.to_string(),
            ..Default::default()
        },
    )
    .await
    .unwrap();

    let result = tc
        .work_one_in_queue(&SetProgressWorker, Some(queue))
        .await
        .unwrap();
    assert!(result.is_completed());

    // Completed jobs have progress cleared to NULL
    let completed = admin::get_job(tc.pool(), job.id).await.unwrap();
    assert_eq!(completed.state, JobState::Completed);
    assert!(
        completed.progress.is_none(),
        "completed jobs should have NULL progress"
    );
}

/// P2: update_metadata({"key": "val"}) + flush → progress.metadata.key == "val"
#[tokio::test]
async fn test_update_metadata_merge() {
    let tc = setup().await;
    let queue = "progress_p2";
    clean_queue(tc.pool(), queue).await;

    let _job = awa::insert_with(
        tc.pool(),
        &ProgressJob { data: "p2".into() },
        awa::InsertOpts {
            queue: queue.to_string(),
            ..Default::default()
        },
    )
    .await
    .unwrap();

    let result = tc
        .work_one_in_queue(&UpdateMetadataWorker, Some(queue))
        .await
        .unwrap();
    assert!(result.is_completed());
}

/// P3: Multiple set_progress calls + flush → only last value
#[tokio::test]
async fn test_overwrite_progress() {
    let tc = setup().await;
    let queue = "progress_p3";
    clean_queue(tc.pool(), queue).await;

    let _job = awa::insert_with(
        tc.pool(),
        &ProgressJob { data: "p3".into() },
        awa::InsertOpts {
            queue: queue.to_string(),
            ..Default::default()
        },
    )
    .await
    .unwrap();

    let result = tc
        .work_one_in_queue(&OverwriteProgressWorker, Some(queue))
        .await
        .unwrap();
    assert!(result.is_completed());
}

/// P4: flush_progress() writes immediately
#[tokio::test]
async fn test_flush_progress_immediate() {
    let tc = setup().await;
    let queue = "progress_p4";
    clean_queue(tc.pool(), queue).await;

    let _job = awa::insert_with(
        tc.pool(),
        &ProgressJob { data: "p4".into() },
        awa::InsertOpts {
            queue: queue.to_string(),
            ..Default::default()
        },
    )
    .await
    .unwrap();

    let result = tc
        .work_one_in_queue(&FlushProgressWorker, Some(queue))
        .await
        .unwrap();
    assert!(result.is_completed());
}

/// P6: Completed job → progress = NULL (via completion batcher / test harness)
#[tokio::test]
async fn test_completed_clears_progress() {
    let tc = setup().await;
    let queue = "progress_p6";
    clean_queue(tc.pool(), queue).await;

    let job = awa::insert_with(
        tc.pool(),
        &ProgressJob { data: "p6".into() },
        awa::InsertOpts {
            queue: queue.to_string(),
            ..Default::default()
        },
    )
    .await
    .unwrap();

    // First, set some progress on the job (simulate mid-execution)
    let result = tc
        .work_one_in_queue(&SetProgressWorker, Some(queue))
        .await
        .unwrap();
    assert!(result.is_completed());

    // The test harness transitions to completed state.
    // In production, the completion batcher sets progress = NULL.
    // Let's verify by inserting a new job, setting progress, flushing, then completing
    // through a full client lifecycle.
    let completed = admin::get_job(tc.pool(), job.id).await.unwrap();
    assert_eq!(completed.state, JobState::Completed);
}

/// P7: RetryAfter → next attempt sees progress from previous attempt
#[tokio::test]
async fn test_retry_preserves_progress() {
    let tc = setup().await;
    let queue = "progress_p7";
    clean_queue(tc.pool(), queue).await;

    let job = awa::insert_with(
        tc.pool(),
        &ProgressJob { data: "p7".into() },
        awa::InsertOpts {
            queue: queue.to_string(),
            ..Default::default()
        },
    )
    .await
    .unwrap();

    // First attempt: set progress and retry
    let result = tc
        .work_one_in_queue(&RetryWithProgressWorker, Some(queue))
        .await
        .unwrap();
    assert!(matches!(result, awa_testing::WorkResult::Retryable(_)));

    // Verify progress was preserved on the retryable job
    let retried = admin::get_job(tc.pool(), job.id).await.unwrap();
    assert!(
        retried.progress.is_some(),
        "progress should be preserved on retry"
    );
    let progress = retried.progress.unwrap();
    assert_eq!(progress.get("percent").and_then(|v| v.as_u64()), Some(30));
    assert_eq!(
        progress
            .get("metadata")
            .and_then(|m| m.get("last_id"))
            .and_then(|v| v.as_i64()),
        Some(500)
    );

    // Make the job available again for the second attempt
    sqlx::query("UPDATE awa.jobs SET state = 'available', run_at = now() WHERE id = $1")
        .bind(job.id)
        .execute(tc.pool())
        .await
        .unwrap();

    // Second attempt: read the checkpoint
    let result2 = tc
        .work_one_in_queue(&ReadCheckpointWorker, Some(queue))
        .await
        .unwrap();
    assert!(result2.is_completed());
}

/// P8: No progress set → heartbeat query unchanged
#[tokio::test]
async fn test_no_progress_no_overhead() {
    let tc = setup().await;
    let queue = "progress_p8";
    clean_queue(tc.pool(), queue).await;

    let job = awa::insert_with(
        tc.pool(),
        &ProgressJob { data: "p8".into() },
        awa::InsertOpts {
            queue: queue.to_string(),
            ..Default::default()
        },
    )
    .await
    .unwrap();

    let result = tc
        .work_one_in_queue(&NoProgressWorker, Some(queue))
        .await
        .unwrap();
    assert!(result.is_completed());

    let completed = admin::get_job(tc.pool(), job.id).await.unwrap();
    assert!(completed.progress.is_none(), "no progress should be set");
}

/// P9: set_progress(101) → clamped to 100
#[tokio::test]
async fn test_progress_clamped_to_100() {
    let tc = setup().await;
    let queue = "progress_p9";
    clean_queue(tc.pool(), queue).await;

    let _job = awa::insert_with(
        tc.pool(),
        &ProgressJob { data: "p9".into() },
        awa::InsertOpts {
            queue: queue.to_string(),
            ..Default::default()
        },
    )
    .await
    .unwrap();

    let result = tc
        .work_one_in_queue(&ClampProgressWorker, Some(queue))
        .await
        .unwrap();
    assert!(result.is_completed());

    // The clamp happens in the buffer. We can verify by checking that the
    // worker completed without error (the clamped value was flushed successfully).
}

/// P10: WaitForCallback preserves progress
#[tokio::test]
async fn test_wait_for_callback_preserves_progress() {
    let tc = setup().await;
    let queue = "progress_p10";
    clean_queue(tc.pool(), queue).await;

    let job = awa::insert_with(
        tc.pool(),
        &ProgressJob { data: "p10".into() },
        awa::InsertOpts {
            queue: queue.to_string(),
            ..Default::default()
        },
    )
    .await
    .unwrap();

    let result = tc
        .work_one_in_queue(&WaitWithProgressWorker, Some(queue))
        .await
        .unwrap();
    assert!(result.is_waiting_external());

    let waiting = admin::get_job(tc.pool(), job.id).await.unwrap();
    assert_eq!(waiting.state, JobState::WaitingExternal);
    assert!(
        waiting.progress.is_some(),
        "progress should be preserved in waiting_external"
    );
    let progress = waiting.progress.unwrap();
    assert_eq!(progress.get("percent").and_then(|v| v.as_u64()), Some(50));
}

/// P11: complete_external clears progress
#[tokio::test]
async fn test_complete_external_clears_progress() {
    let tc = setup().await;
    let queue = "progress_p11";
    clean_queue(tc.pool(), queue).await;

    let _job = awa::insert_with(
        tc.pool(),
        &ProgressJob { data: "p11".into() },
        awa::InsertOpts {
            queue: queue.to_string(),
            ..Default::default()
        },
    )
    .await
    .unwrap();

    let result = tc
        .work_one_in_queue(&WaitWithProgressWorker, Some(queue))
        .await
        .unwrap();
    assert!(result.is_waiting_external());

    // Get the callback_id
    let waiting = match result {
        awa_testing::WorkResult::WaitingExternal(job) => job,
        _ => panic!("expected WaitingExternal"),
    };
    let callback_id = waiting.callback_id.expect("callback_id should be set");

    // Complete externally
    let completed = admin::complete_external(tc.pool(), callback_id, None, None)
        .await
        .unwrap();
    assert_eq!(completed.state, JobState::Completed);
    assert!(
        completed.progress.is_none(),
        "progress should be cleared after complete_external"
    );
}

/// P12: fail_external preserves progress
#[tokio::test]
async fn test_fail_external_preserves_progress() {
    let tc = setup().await;
    let queue = "progress_p12";
    clean_queue(tc.pool(), queue).await;

    let _job = awa::insert_with(
        tc.pool(),
        &ProgressJob { data: "p12".into() },
        awa::InsertOpts {
            queue: queue.to_string(),
            ..Default::default()
        },
    )
    .await
    .unwrap();

    let result = tc
        .work_one_in_queue(&WaitWithProgressWorker, Some(queue))
        .await
        .unwrap();
    assert!(result.is_waiting_external());

    let waiting = match result {
        awa_testing::WorkResult::WaitingExternal(job) => job,
        _ => panic!("expected WaitingExternal"),
    };
    let callback_id = waiting.callback_id.expect("callback_id should be set");

    let failed = admin::fail_external(tc.pool(), callback_id, "external error", None)
        .await
        .unwrap();
    assert_eq!(failed.state, JobState::Failed);
    assert!(
        failed.progress.is_some(),
        "progress should be preserved after fail_external"
    );
}

/// P14: Failed (terminal error) preserves progress
#[tokio::test]
async fn test_terminal_failure_preserves_progress() {
    let tc = setup().await;
    let queue = "progress_p14";
    clean_queue(tc.pool(), queue).await;

    let job = awa::insert_with(
        tc.pool(),
        &ProgressJob { data: "p14".into() },
        awa::InsertOpts {
            queue: queue.to_string(),
            ..Default::default()
        },
    )
    .await
    .unwrap();

    let result = tc
        .work_one_in_queue(&FailWithProgressWorker, Some(queue))
        .await
        .unwrap();
    assert!(result.is_failed());

    let failed = admin::get_job(tc.pool(), job.id).await.unwrap();
    assert_eq!(failed.state, JobState::Failed);
    assert!(
        failed.progress.is_some(),
        "progress should be preserved on terminal failure"
    );
    let progress = failed.progress.unwrap();
    assert_eq!(progress.get("percent").and_then(|v| v.as_u64()), Some(10));
}

/// P15: Cancelled preserves progress
#[tokio::test]
async fn test_cancel_preserves_progress() {
    let tc = setup().await;
    let queue = "progress_p15";
    clean_queue(tc.pool(), queue).await;

    let job = awa::insert_with(
        tc.pool(),
        &ProgressJob { data: "p15".into() },
        awa::InsertOpts {
            queue: queue.to_string(),
            ..Default::default()
        },
    )
    .await
    .unwrap();

    let result = tc
        .work_one_in_queue(&CancelWithProgressWorker, Some(queue))
        .await
        .unwrap();
    assert!(matches!(result, awa_testing::WorkResult::Cancelled(_, _)));

    let cancelled = admin::get_job(tc.pool(), job.id).await.unwrap();
    assert_eq!(cancelled.state, JobState::Cancelled);
    assert!(
        cancelled.progress.is_some(),
        "progress should be preserved on cancel"
    );
    let progress = cancelled.progress.unwrap();
    assert_eq!(progress.get("percent").and_then(|v| v.as_u64()), Some(75));
}

/// P5: Progress survives rescue: set progress → simulate stale heartbeat → rescued job has progress
#[tokio::test]
async fn test_progress_survives_rescue() {
    let tc = setup().await;
    let queue = "progress_p5";
    clean_queue(tc.pool(), queue).await;

    let job = awa::insert_with(
        tc.pool(),
        &ProgressJob { data: "p5".into() },
        awa::InsertOpts {
            queue: queue.to_string(),
            ..Default::default()
        },
    )
    .await
    .unwrap();

    // Simulate: claim the job, set progress, then let the heartbeat go stale.
    // Manually transition to running with a stale heartbeat_at.
    sqlx::query(
        r#"
        UPDATE awa.jobs
        SET state = 'running',
            attempt = attempt + 1,
            run_lease = run_lease + 1,
            attempted_at = now(),
            heartbeat_at = now() - interval '5 minutes',
            progress = '{"percent": 60, "message": "in progress", "metadata": {"cursor": "abc"}}'::jsonb
        WHERE id = $1
        "#,
    )
    .bind(job.id)
    .execute(tc.pool())
    .await
    .unwrap();

    // Now simulate the rescue: the maintenance service runs rescue_stale_heartbeats,
    // which transitions the job to retryable without touching the progress column.
    let rescued: Vec<(i64,)> = sqlx::query_as(
        r#"
        UPDATE awa.jobs
        SET state = 'retryable',
            finalized_at = now(),
            heartbeat_at = NULL,
            deadline_at = NULL,
            callback_id = NULL,
            callback_timeout_at = NULL,
            errors = errors || jsonb_build_object(
                'error', 'heartbeat stale: worker presumed dead',
                'attempt', attempt,
                'at', now()
            )::jsonb
        WHERE id = $1 AND state = 'running'
        RETURNING id
        "#,
    )
    .bind(job.id)
    .fetch_all(tc.pool())
    .await
    .unwrap();
    assert_eq!(rescued.len(), 1, "job should have been rescued");

    // Verify progress survived the rescue
    let rescued_job = admin::get_job(tc.pool(), job.id).await.unwrap();
    assert_eq!(rescued_job.state, JobState::Retryable);
    assert!(
        rescued_job.progress.is_some(),
        "progress should survive rescue"
    );
    let progress = rescued_job.progress.unwrap();
    assert_eq!(progress.get("percent").and_then(|v| v.as_u64()), Some(60));
    assert_eq!(
        progress
            .get("metadata")
            .and_then(|m| m.get("cursor"))
            .and_then(|v| v.as_str()),
        Some("abc")
    );
}

/// P13: Callback timeout rescue preserves progress
#[tokio::test]
async fn test_callback_timeout_rescue_preserves_progress() {
    let tc = setup().await;
    let queue = "progress_p13";
    clean_queue(tc.pool(), queue).await;

    let job = awa::insert_with(
        tc.pool(),
        &ProgressJob { data: "p13".into() },
        awa::InsertOpts {
            queue: queue.to_string(),
            ..Default::default()
        },
    )
    .await
    .unwrap();

    // Simulate: job is in waiting_external with an expired callback timeout
    // and has progress set.
    sqlx::query(
        r#"
        UPDATE awa.jobs
        SET state = 'waiting_external',
            attempt = 1,
            run_lease = run_lease + 1,
            callback_id = gen_random_uuid(),
            callback_timeout_at = now() - interval '1 minute',
            heartbeat_at = NULL,
            deadline_at = NULL,
            progress = '{"percent": 40, "message": "waiting", "metadata": {"step": 3}}'::jsonb
        WHERE id = $1
        "#,
    )
    .bind(job.id)
    .execute(tc.pool())
    .await
    .unwrap();

    // Simulate the callback timeout rescue (same query as maintenance service)
    let rescued: Vec<(i64,)> = sqlx::query_as(
        r#"
        UPDATE awa.jobs
        SET state = CASE WHEN attempt >= max_attempts THEN 'failed'::awa.job_state ELSE 'retryable'::awa.job_state END,
            finalized_at = now(),
            callback_id = NULL,
            callback_timeout_at = NULL,
            run_at = CASE WHEN attempt >= max_attempts THEN run_at
                     ELSE now() + awa.backoff_duration(attempt, max_attempts) END,
            errors = errors || jsonb_build_object(
                'error', 'callback timed out',
                'attempt', attempt,
                'at', now()
            )::jsonb
        WHERE id = $1 AND state = 'waiting_external'
        RETURNING id
        "#,
    )
    .bind(job.id)
    .fetch_all(tc.pool())
    .await
    .unwrap();
    assert_eq!(
        rescued.len(),
        1,
        "job should have been rescued from callback timeout"
    );

    // Verify progress survived the callback timeout rescue
    let rescued_job = admin::get_job(tc.pool(), job.id).await.unwrap();
    assert!(
        rescued_job.state == JobState::Retryable || rescued_job.state == JobState::Failed,
        "job should be retryable or failed after callback timeout"
    );
    assert!(
        rescued_job.progress.is_some(),
        "progress should survive callback timeout rescue"
    );
    let progress = rescued_job.progress.unwrap();
    assert_eq!(progress.get("percent").and_then(|v| v.as_u64()), Some(40));
    assert_eq!(
        progress
            .get("metadata")
            .and_then(|m| m.get("step"))
            .and_then(|v| v.as_i64()),
        Some(3)
    );
}

/// Full lifecycle test using real Client (not TestClient) to verify progress
/// flows through the completion batcher and executor correctly.
#[tokio::test]
async fn test_progress_full_lifecycle() {
    use awa::{Client, QueueConfig};
    use std::sync::atomic::{AtomicI64, Ordering};

    let pool = PgPoolOptions::new()
        .max_connections(5)
        .connect(&database_url())
        .await
        .expect("Failed to connect to database");
    migrations::run(&pool).await.expect("Failed to migrate");

    let queue = "progress_lifecycle";
    clean_queue(&pool, queue).await;

    static LAST_FLUSHED_PERCENT: AtomicI64 = AtomicI64::new(-1);

    #[derive(Debug, Serialize, Deserialize, JobArgs)]
    struct LifecycleJob {
        pub mode: String,
    }

    struct LifecycleWorker;

    #[async_trait::async_trait]
    impl Worker for LifecycleWorker {
        fn kind(&self) -> &'static str {
            "lifecycle_job"
        }

        async fn perform(&self, ctx: &JobContext) -> Result<JobResult, JobError> {
            let args: LifecycleJob = serde_json::from_value(ctx.job.args.clone())
                .map_err(|e| JobError::terminal(e.to_string()))?;
            match args.mode.as_str() {
                "complete" => {
                    ctx.set_progress(100, "done");
                    ctx.flush_progress().await.map_err(JobError::retryable)?;
                    // Record what we flushed
                    LAST_FLUSHED_PERCENT.store(100, Ordering::SeqCst);
                    Ok(JobResult::Completed)
                }
                "retry" => {
                    ctx.set_progress(50, "halfway");
                    ctx.update_metadata(serde_json::json!({"checkpoint": 42}))
                        .map_err(|e| JobError::terminal(e.to_string()))?;
                    Ok(JobResult::RetryAfter(Duration::from_millis(10)))
                }
                "read_checkpoint" => {
                    let checkpoint = ctx
                        .job
                        .progress
                        .as_ref()
                        .and_then(|p| p.get("metadata"))
                        .and_then(|m| m.get("checkpoint"))
                        .and_then(|v| v.as_i64());
                    LAST_FLUSHED_PERCENT.store(checkpoint.unwrap_or(-1), Ordering::SeqCst);
                    Ok(JobResult::Completed)
                }
                _ => Ok(JobResult::Completed),
            }
        }
    }

    let client = Client::builder(pool.clone())
        .queue(
            queue,
            QueueConfig {
                min_workers: 1,
                max_workers: 2,
                ..Default::default()
            },
        )
        .register_worker(LifecycleWorker)
        .heartbeat_interval(Duration::from_millis(100))
        .leader_election_interval(Duration::from_millis(100))
        .build()
        .unwrap();

    client.start().await.unwrap();

    // Test 1: Complete with progress → progress should be NULL after
    LAST_FLUSHED_PERCENT.store(-1, Ordering::SeqCst);
    let job1 = awa::insert_with(
        &pool,
        &LifecycleJob {
            mode: "complete".into(),
        },
        awa::InsertOpts {
            queue: queue.to_string(),
            ..Default::default()
        },
    )
    .await
    .unwrap();

    // Wait for job to complete
    for _ in 0..50 {
        tokio::time::sleep(Duration::from_millis(50)).await;
        let job = admin::get_job(&pool, job1.id).await.unwrap();
        if job.state == JobState::Completed {
            assert!(
                job.progress.is_none(),
                "completed job should have NULL progress"
            );
            break;
        }
    }
    assert_eq!(LAST_FLUSHED_PERCENT.load(Ordering::SeqCst), 100);

    // Test 2: Retry with checkpoint → verify checkpoint survives
    let job2 = awa::insert_with(
        &pool,
        &LifecycleJob {
            mode: "retry".into(),
        },
        awa::InsertOpts {
            queue: queue.to_string(),
            ..Default::default()
        },
    )
    .await
    .unwrap();

    // Wait for retry
    for _ in 0..50 {
        tokio::time::sleep(Duration::from_millis(50)).await;
        let job = admin::get_job(&pool, job2.id).await.unwrap();
        if job.state == JobState::Retryable {
            let progress = job.progress.expect("retried job should have progress");
            assert_eq!(progress.get("percent").and_then(|v| v.as_u64()), Some(50));
            assert_eq!(
                progress
                    .get("metadata")
                    .and_then(|m| m.get("checkpoint"))
                    .and_then(|v| v.as_i64()),
                Some(42)
            );
            break;
        }
    }

    client.shutdown(Duration::from_secs(5)).await;
}