trypema 2.0.0

High-performance rate limiting primitives in Rust, designed for concurrency safety, low overhead, and predictable latency.
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
//! Redis state inspection tests for the **absolute hybrid** rate limiter.
//!
//! The hybrid limiter accumulates increments locally and commits to Redis only when the
//! local accept budget is exhausted (overflow commit) or on periodic background flushes.
//! These tests verify that Redis state is correct after commits are flushed.
//!
//! # Redis data model (hybrid_absolute, per user-key `K`, prefix `P`)
//!
//! | Redis key                         | Type        | Meaning                                    |
//! |-----------------------------------|-------------|--------------------------------------------|
//! | `P:K:hybrid_absolute:h`           | Hash        | `timestamp_ms → count` buckets             |
//! | `P:K:hybrid_absolute:a`           | Sorted set  | Active bucket timestamps (scores = ts_ms)  |
//! | `P:K:hybrid_absolute:w`           | String      | Stored window limit                        |
//! | `P:K:hybrid_absolute:t`           | String      | Running total count                        |
//! | `P:hybrid_absolute:active_entities` | Sorted set  | All active user-keys (for cleanup)        |
//!
//! **Important:** because the hybrid limiter batches writes, tests must wait for the
//! background committer to flush (`wait_for_hybrid_sync`) before inspecting Redis state.

use std::{collections::HashMap, time::Duration};

use redis::AsyncCommands;

use super::common::{key, key_gen, redis_url, unique_prefix, wait_for_hybrid_sync};
use super::runtime;

use crate::common::RateType;
use crate::{
    BucketSize, HistoryPreservation, RateLimit, RateLimitComparator, RateLimitDecision,
    RateLimiterBuilder, WindowSize,
    hybrid::{HybridRateLimiterProvider, SyncInterval},
    redis::{RedisKey, RedisRateLimiterProvider},
};

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

async fn build_limiter(
    url: &str,
    window_size: u64,
    bucket_size: u64,
    sync_interval: u64,
    prefix: RedisKey,
) -> std::sync::Arc<HybridRateLimiterProvider> {
    let client = redis::Client::open(url).unwrap();
    let cm = client.get_connection_manager().await.unwrap();

    HybridRateLimiterProvider::builder(cm)
        .prefix(prefix)
        .window_size(WindowSize::seconds(window_size).unwrap())
        .bucket_size(BucketSize::milliseconds(bucket_size).unwrap())
        .sync_interval(SyncInterval::milliseconds(sync_interval).unwrap())
        .cleanup_enabled(false)
        .build()
        .unwrap()
}

/// Construct the canonical Redis key for a given suffix using the key generator.
fn redis_key(prefix: &RedisKey, user_key: &RedisKey, suffix: &str) -> String {
    let kg = key_gen(prefix, RateType::HybridAbsolute);
    match suffix {
        "h" => kg.get_hash_key(user_key),
        "a" => kg.get_active_keys(user_key),
        "w" => kg.get_window_limit_key(user_key),
        "t" => kg.get_total_count_key(user_key),
        _ => panic!("unknown suffix for hybrid_absolute rate type: {suffix}"),
    }
}

fn assert_allowed(decision: RateLimitDecision, context: &str) {
    assert!(
        matches!(decision, RateLimitDecision::Allowed),
        "{context}: expected allowed decision, got {decision:?}"
    );
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

/// Before the local accept budget is exhausted, no hybrid_absolute Redis keys should exist
/// because the hybrid limiter has not yet committed any state.
#[test]
fn redis_state_hybrid_absolute_no_redis_keys_before_overflow() {
    let url = redis_url();

    runtime::block_on(async {
        let prefix = unique_prefix();
        let window_size = 1_u64;
        let sync_interval = 2000_u64; // very slow tick so no background flush occurs

        let rl = build_limiter(&url, window_size, 1000, sync_interval, prefix.clone()).await;
        let k = key("k");
        let rate_limit = RateLimit::per_second(5f64).unwrap();
        // capacity = 1 * 5 = 5; fill all 5 slots locally.
        for _ in 0..5 {
            let d = rl.absolute().inc(&k, &rate_limit, 1).await.unwrap();
            assert!(matches!(d, RateLimitDecision::Allowed), "d: {d:?}");
        }

        let mut conn = redis::Client::open(url.as_str())
            .unwrap()
            .get_multiplexed_async_connection()
            .await
            .unwrap();

        // No commit should have happened yet.
        let key_generator = key_gen(&prefix, RateType::HybridAbsolute);
        for entity_key in key_generator.get_all_entity_keys(&k) {
            let exists: bool = conn.exists(&entity_key).await.unwrap();
            assert!(!exists, "local-only usage created {entity_key}");
        }
        let active_score: Option<f64> = conn
            .zscore(key_generator.get_active_entities_key(), k.as_str())
            .await
            .unwrap();
        assert!(
            active_score.is_none(),
            "local-only usage marked the key active"
        );
    });
}

/// After the local budget overflows (triggering a commit), the committed count must be
/// visible in Redis once the background committer flushes.
#[test]
fn redis_state_hybrid_absolute_commit_writes_total_count_after_overflow() {
    let url = redis_url();

    runtime::block_on(async {
        let prefix = unique_prefix();
        let window_size = 1_u64;
        let sync_interval = 25_u64;

        let rl = build_limiter(&url, window_size, 1000, sync_interval, prefix.clone()).await;
        let k = key("k");
        let rate_limit = RateLimit::per_second(5f64).unwrap();
        let cap = (window_size as f64 * rate_limit.as_per_second()) as u64; // 5

        // Fill the local budget.
        for _ in 0..cap {
            let d = rl.absolute().inc(&k, &rate_limit, 1).await.unwrap();
            assert!(matches!(d, RateLimitDecision::Allowed), "d: {d:?}");
        }

        // Trigger overflow — the accepted capacity is committed synchronously.
        let d_overflow = rl.absolute().inc(&k, &rate_limit, 1).await.unwrap();
        assert!(
            matches!(d_overflow, RateLimitDecision::Rejected { .. }),
            "d_overflow: {d_overflow:?}"
        );

        // Wait for the committer to flush.
        wait_for_hybrid_sync(sync_interval).await;

        let mut conn = redis::Client::open(url.as_str())
            .unwrap()
            .get_multiplexed_async_connection()
            .await
            .unwrap();

        let total: u64 = conn.get(redis_key(&prefix, &k, "t")).await.unwrap();
        assert_eq!(total, cap, "the rejected overflow must not be committed");

        // The hash must have at least one bucket.
        let hash: HashMap<String, u64> = conn.hgetall(redis_key(&prefix, &k, "h")).await.unwrap();
        assert_eq!(hash.values().sum::<u64>(), cap);

        // The active sorted set must have at least one member.
        let active_count: u64 = conn.zcard(redis_key(&prefix, &k, "a")).await.unwrap();
        assert_eq!(active_count, 1, "one grouped commit must create one bucket");
    });
}

/// After a commit, the window limit key must be set and reflect the correct capacity.
#[test]
fn redis_state_hybrid_absolute_window_limit_key_is_set_after_commit() {
    let url = redis_url();

    runtime::block_on(async {
        let prefix = unique_prefix();
        let window_size = 2_u64;
        let sync_interval = 25_u64;

        let rl = build_limiter(&url, window_size, 1000, sync_interval, prefix.clone()).await;
        let k = key("k");
        let rate_limit = RateLimit::per_second(3f64).unwrap();
        // capacity = 2 * 3 = 6
        let expected_window_limit = 6_u64;

        for _ in 0..expected_window_limit {
            assert_allowed(
                rl.absolute().inc(&k, &rate_limit, 1).await.unwrap(),
                "window-limit setup increment",
            );
        }
        // Overflow to trigger commit.
        let overflow = rl.absolute().inc(&k, &rate_limit, 1).await.unwrap();
        assert!(matches!(overflow, RateLimitDecision::Rejected { .. }));
        wait_for_hybrid_sync(sync_interval).await;

        let mut conn = redis::Client::open(url.as_str())
            .unwrap()
            .get_multiplexed_async_connection()
            .await
            .unwrap();

        let stored_limit: u64 = conn.get(redis_key(&prefix, &k, "w")).await.unwrap();
        assert_eq!(
            stored_limit, expected_window_limit,
            "stored window limit should equal capacity"
        );
    });
}

/// Two limiters sharing the same prefix should observe each other's committed state.
/// Once limiter A overflows and commits, limiter B must see a non-zero total in Redis.
#[test]
fn redis_state_hybrid_absolute_committed_state_is_visible_to_another_instance() {
    let url = redis_url();

    runtime::block_on(async {
        let prefix = unique_prefix();
        let window_size = 1_u64;
        let sync_interval = 25_u64;

        let rl_a = build_limiter(&url, window_size, 1000, sync_interval, prefix.clone()).await;
        let k = key("k");
        let rate_limit = RateLimit::per_second(5f64).unwrap();
        let cap = (window_size as f64 * rate_limit.as_per_second()) as u64;

        // A fills and overflows.
        for _ in 0..cap {
            assert_allowed(
                rl_a.absolute().inc(&k, &rate_limit, 1).await.unwrap(),
                "shared-prefix setup increment",
            );
        }
        let overflow = rl_a.absolute().inc(&k, &rate_limit, 1).await.unwrap();
        assert!(matches!(overflow, RateLimitDecision::Rejected { .. }));
        wait_for_hybrid_sync(sync_interval).await;

        let mut conn = redis::Client::open(url.as_str())
            .unwrap()
            .get_multiplexed_async_connection()
            .await
            .unwrap();

        let total: u64 = conn.get(redis_key(&prefix, &k, "t")).await.unwrap();
        assert_eq!(total, cap, "the complete accepted volume must be visible");
    });
}

/// The hash bucket sum must always equal the total count key after a commit.
#[test]
fn redis_state_hybrid_absolute_hash_sum_matches_total_count_after_commit() {
    let url = redis_url();

    runtime::block_on(async {
        let prefix = unique_prefix();
        let window_size = 1_u64;
        let sync_interval = 25_u64;

        let rl = build_limiter(&url, window_size, 1000, sync_interval, prefix.clone()).await;
        let k = key("k");
        let rate_limit = RateLimit::per_second(5f64).unwrap();
        let cap = (window_size as f64 * rate_limit.as_per_second()) as u64;

        for _ in 0..cap {
            assert_allowed(
                rl.absolute().inc(&k, &rate_limit, 1).await.unwrap(),
                "hash-total setup increment",
            );
        }
        let overflow = rl.absolute().inc(&k, &rate_limit, 1).await.unwrap();
        assert!(matches!(overflow, RateLimitDecision::Rejected { .. }));
        wait_for_hybrid_sync(sync_interval).await;

        let mut conn = redis::Client::open(url.as_str())
            .unwrap()
            .get_multiplexed_async_connection()
            .await
            .unwrap();

        let total: u64 = conn.get(redis_key(&prefix, &k, "t")).await.unwrap();
        let hash: HashMap<String, u64> = conn.hgetall(redis_key(&prefix, &k, "h")).await.unwrap();
        let hash_sum: u64 = hash.values().sum();

        assert_eq!(
            total, cap,
            "the rejected overflow must not change the total"
        );
        assert_eq!(
            hash_sum, total,
            "hash sum ({hash_sum}) must equal total count ({total}) after commit"
        );
    });
}

/// After the window expires and a new commit is made, stale buckets must be evicted so
/// the total count reflects only the fresh increment.
#[test]
fn redis_state_hybrid_absolute_evicts_expired_buckets_on_next_commit() {
    let url = redis_url();

    runtime::block_on(async {
        let prefix = unique_prefix();
        let window_size = 1_u64;
        let sync_interval = 25_u64;

        let rl = build_limiter(&url, window_size, 1000, sync_interval, prefix.clone()).await;
        let k = key("k");
        let rate_limit = RateLimit::per_second(5f64).unwrap();
        let cap = (window_size as f64 * rate_limit.as_per_second()) as u64;

        // First burst: fill and overflow to commit.
        for _ in 0..cap {
            assert_allowed(
                rl.absolute().inc(&k, &rate_limit, 1).await.unwrap(),
                "expiry setup increment",
            );
        }
        let overflow = rl.absolute().inc(&k, &rate_limit, 1).await.unwrap();
        assert!(matches!(overflow, RateLimitDecision::Rejected { .. }));
        wait_for_hybrid_sync(sync_interval).await;

        // Wait for the window to expire.
        runtime::async_sleep(Duration::from_millis(window_size * 1000 + 100)).await;

        // Second burst: this read_state call in the hybrid limiter triggers Redis eviction.
        let d = rl.absolute().inc(&k, &rate_limit, 1).await.unwrap();
        assert!(
            matches!(d, RateLimitDecision::Allowed),
            "d after expiry: {d:?}"
        );
        // Let the new commit flush if needed.
        wait_for_hybrid_sync(sync_interval).await;

        let mut conn = redis::Client::open(url.as_str())
            .unwrap()
            .get_multiplexed_async_connection()
            .await
            .unwrap();

        let total: u64 = conn.get(redis_key(&prefix, &k, "t")).await.unwrap();
        assert_eq!(total, 1, "expired usage must be fully evicted");
    });
}

/// Two separate prefixes must maintain independent Redis namespaces.  Usage committed
/// under prefix A must not appear under prefix B.
#[test]
fn redis_state_hybrid_absolute_different_prefixes_are_isolated() {
    let url = redis_url();

    runtime::block_on(async {
        let prefix_a = unique_prefix();
        let prefix_b = unique_prefix();
        let window_size = 1_u64;
        let sync_interval = 25_u64;

        let rl_a = build_limiter(&url, window_size, 1000, sync_interval, prefix_a.clone()).await;
        let rl_b = build_limiter(&url, window_size, 1000, sync_interval, prefix_b.clone()).await;

        let k = key("k");
        let rate_limit = RateLimit::per_second(5f64).unwrap();
        let cap = (window_size as f64 * rate_limit.as_per_second()) as u64;

        // Overflow A to trigger commit.
        for _ in 0..cap {
            assert_allowed(
                rl_a.absolute().inc(&k, &rate_limit, 1).await.unwrap(),
                "prefix A setup increment",
            );
        }
        let overflow = rl_a.absolute().inc(&k, &rate_limit, 1).await.unwrap();
        assert!(matches!(overflow, RateLimitDecision::Rejected { .. }));
        wait_for_hybrid_sync(sync_interval).await;

        let mut conn = redis::Client::open(url.as_str())
            .unwrap()
            .get_multiplexed_async_connection()
            .await
            .unwrap();

        // B's namespace must be empty.
        let total_b: Option<u64> = conn.get(redis_key(&prefix_b, &k, "t")).await.unwrap();
        assert!(
            total_b.is_none(),
            "prefix B should not have a total count after prefix A's commit"
        );

        // Sanity: B can still operate independently.
        let d_b = rl_b.absolute().inc(&k, &rate_limit, 1).await.unwrap();
        assert!(matches!(d_b, RateLimitDecision::Allowed), "d_b: {d_b:?}");
    });
}

/// The active sorted set scores (bucket timestamps) must be monotonically non-decreasing
/// after multiple overflow-and-commit cycles within the same window.
#[test]
fn redis_state_hybrid_absolute_active_sorted_set_scores_are_ordered() {
    let url = redis_url();

    runtime::block_on(async {
        let prefix = unique_prefix();
        let window_size = 10_u64;
        // Small group size so each commit lands in a new bucket.
        let bucket_size = 100_u64;
        let sync_interval = 50_u64;

        let rl = build_limiter(
            &url,
            window_size,
            bucket_size,
            sync_interval,
            prefix.clone(),
        )
        .await;
        let k = key("k");
        let rate_limit = RateLimit::per_second(10f64).unwrap();

        // Trigger two separate periodic commit cycles with a gap between them.
        for _ in 0..10 {
            assert_allowed(
                rl.absolute().inc(&k, &rate_limit, 1).await.unwrap(),
                "first ordered-bucket setup increment",
            );
        }
        assert_allowed(
            rl.absolute().inc(&k, &rate_limit, 1).await.unwrap(),
            "first ordered-bucket final increment",
        );
        wait_for_hybrid_sync(sync_interval).await;

        // A brief pause ensures the next commit lands in a later ms bucket.
        runtime::async_sleep(Duration::from_millis(200)).await;

        // Reset local state so we can accumulate more.
        let rl2 = build_limiter(
            &url,
            window_size,
            bucket_size,
            sync_interval,
            prefix.clone(),
        )
        .await;
        for _ in 0..10 {
            assert_allowed(
                rl2.absolute().inc(&k, &rate_limit, 1).await.unwrap(),
                "second ordered-bucket setup increment",
            );
        }
        assert_allowed(
            rl2.absolute().inc(&k, &rate_limit, 1).await.unwrap(),
            "second ordered-bucket final increment",
        );
        wait_for_hybrid_sync(sync_interval).await;

        let mut conn = redis::Client::open(url.as_str())
            .unwrap()
            .get_multiplexed_async_connection()
            .await
            .unwrap();

        let members_with_scores: Vec<(String, f64)> = conn
            .zrange_withscores(redis_key(&prefix, &k, "a"), 0isize, -1isize)
            .await
            .unwrap();

        assert_eq!(
            members_with_scores.len(),
            2,
            "the two separated commits must create two ordered buckets"
        );

        let scores: Vec<f64> = members_with_scores.iter().map(|(_, s)| *s).collect();
        for i in 1..scores.len() {
            assert!(
                scores[i] > scores[i - 1],
                "separated bucket scores must be strictly increasing: {scores:?}"
            );
        }
    });
}

// ---------------------------------------------------------------------------
// Cleanup tests
// ---------------------------------------------------------------------------

/// After cleanup with a stale threshold the entity has exceeded, all per-entity Redis keys
/// must be deleted and the entity must be removed from the `active_entities` sorted set.
#[test]
fn redis_state_hybrid_absolute_cleanup_removes_all_redis_keys_for_stale_entity() {
    let url = redis_url();

    runtime::block_on(async {
        let prefix = unique_prefix();
        let window_size = 5_u64;
        let sync_interval = 25_u64;
        let stale_after_ms = 150_u64;

        let rl = build_limiter(&url, window_size, 1000, sync_interval, prefix.clone()).await;
        let k = key("k");
        let rate_limit = RateLimit::per_second(5f64).unwrap();
        let cap = (window_size as f64 * rate_limit.as_per_second()) as u64;

        // Overflow to trigger a Redis commit.
        for _ in 0..cap {
            assert_allowed(
                rl.absolute().inc(&k, &rate_limit, 1).await.unwrap(),
                "stale cleanup setup increment",
            );
        }
        let overflow = rl.absolute().inc(&k, &rate_limit, 1).await.unwrap();
        assert!(matches!(overflow, RateLimitDecision::Rejected { .. }));
        wait_for_hybrid_sync(sync_interval).await;

        let active_entities_key =
            key_gen(&prefix, RateType::HybridAbsolute).get_active_entities_key();

        let mut conn = redis::Client::open(url.as_str())
            .unwrap()
            .get_multiplexed_async_connection()
            .await
            .unwrap();

        let kg = key_gen(&prefix, RateType::HybridAbsolute);

        // Verify all keys exist before cleanup.
        for entity_key in kg.get_all_entity_keys(&k) {
            // Absolute limiter only writes h, a, w, t — others are trivially absent.
            // We check only the ones that must exist.
            if entity_key == kg.get_hash_key(&k)
                || entity_key == kg.get_active_keys(&k)
                || entity_key == kg.get_window_limit_key(&k)
                || entity_key == kg.get_total_count_key(&k)
            {
                let exists: bool = conn.exists(&entity_key).await.unwrap();
                assert!(exists, "key {entity_key} must exist before cleanup");
            }
        }
        let score: Option<f64> = conn.zscore(&active_entities_key, k.as_str()).await.unwrap();
        assert!(
            score.is_some(),
            "entity must be in active_entities before cleanup"
        );

        // Wait until the entity is stale.
        runtime::async_sleep(Duration::from_millis(stale_after_ms + 50)).await;

        rl.absolute().cleanup(stale_after_ms).await.unwrap();

        // All per-entity keys must be deleted.
        for entity_key in kg.get_all_entity_keys(&k) {
            let exists: bool = conn.exists(&entity_key).await.unwrap();
            assert!(!exists, "key {entity_key} must be deleted after cleanup");
        }

        // Entity must be removed from active_entities.
        let score_after: Option<f64> = conn.zscore(&active_entities_key, k.as_str()).await.unwrap();
        assert!(
            score_after.is_none(),
            "entity must be removed from active_entities after cleanup"
        );
    });
}

/// An entity whose last-commit timestamp is within `stale_after_ms` must survive cleanup.
#[test]
fn redis_state_hybrid_absolute_cleanup_does_not_remove_active_entity() {
    let url = redis_url();

    runtime::block_on(async {
        let prefix = unique_prefix();
        let window_size = 5_u64;
        let sync_interval = 25_u64;
        let stale_after_ms = 5_000_u64; // very long — entity will not be stale yet

        let rl = build_limiter(&url, window_size, 1000, sync_interval, prefix.clone()).await;
        let k = key("k");
        let rate_limit = RateLimit::per_second(5f64).unwrap();
        let cap = (window_size as f64 * rate_limit.as_per_second()) as u64;

        // Overflow and sync — entity is recent.
        for _ in 0..cap {
            assert_allowed(
                rl.absolute().inc(&k, &rate_limit, 1).await.unwrap(),
                "active cleanup setup increment",
            );
        }
        let overflow = rl.absolute().inc(&k, &rate_limit, 1).await.unwrap();
        assert!(matches!(overflow, RateLimitDecision::Rejected { .. }));
        wait_for_hybrid_sync(sync_interval).await;

        // Immediately cleanup with a long threshold — nothing should be removed.
        rl.absolute().cleanup(stale_after_ms).await.unwrap();

        let active_entities_key =
            key_gen(&prefix, RateType::HybridAbsolute).get_active_entities_key();

        let mut conn = redis::Client::open(url.as_str())
            .unwrap()
            .get_multiplexed_async_connection()
            .await
            .unwrap();

        let t_exists: bool = conn.exists(redis_key(&prefix, &k, "t")).await.unwrap();
        assert!(
            t_exists,
            "total count key must still exist for active entity"
        );
        let score: Option<f64> = conn.zscore(&active_entities_key, k.as_str()).await.unwrap();
        assert!(
            score.is_some(),
            "active entity must remain in active_entities after cleanup"
        );
    });
}

/// After cleanup removes Redis state, a subsequent `inc` for the same key must be allowed
/// (the in-memory state must also be cleared so the limiter starts fresh from Redis).
#[test]
fn redis_state_hybrid_absolute_cleanup_allows_fresh_requests_after_cleanup() {
    let url = redis_url();

    runtime::block_on(async {
        let prefix = unique_prefix();
        let window_size = 1_u64;
        let sync_interval = 25_u64;
        let stale_after_ms = 150_u64;

        let rl = build_limiter(&url, window_size, 1000, sync_interval, prefix.clone()).await;
        let k = key("k");
        let rate_limit = RateLimit::per_second(2f64).unwrap();
        let cap = (window_size as f64 * rate_limit.as_per_second()) as u64;

        // Fill capacity then overflow — entity ends up in Rejecting state.
        for _ in 0..cap {
            assert_allowed(
                rl.absolute().inc(&k, &rate_limit, 1).await.unwrap(),
                "cleanup reset setup increment",
            );
        }
        let rejected = rl.absolute().inc(&k, &rate_limit, 1).await.unwrap();
        assert!(
            matches!(rejected, RateLimitDecision::Rejected { .. }),
            "expected Rejected after overflow, got {rejected:?}"
        );
        wait_for_hybrid_sync(sync_interval).await;

        // Wait until the retry TTL and its following stale horizon have elapsed.
        runtime::async_sleep(Duration::from_millis(
            window_size * 1000 + stale_after_ms + 100,
        ))
        .await;
        rl.absolute().cleanup(stale_after_ms).await.unwrap();

        let mut conn = redis::Client::open(url.as_str())
            .unwrap()
            .get_multiplexed_async_connection()
            .await
            .unwrap();

        let t_exists: bool = conn.exists(redis_key(&prefix, &k, "t")).await.unwrap();
        assert!(!t_exists, "total count key must be deleted after cleanup");

        // The next request must be allowed after the post-TTL stale horizon has elapsed.
        let decision = rl.absolute().inc(&k, &rate_limit, 1).await.unwrap();
        assert!(
            matches!(decision, RateLimitDecision::Allowed),
            "expected Allowed after cleanup but got {decision:?}"
        );
    });
}

/// When multiple entities exist under the same prefix, cleanup must only remove stale ones
/// and leave recently-active entities intact.
#[test]
fn redis_state_hybrid_absolute_cleanup_multiple_entities_mixed() {
    let url = redis_url();

    runtime::block_on(async {
        let prefix = unique_prefix();
        let window_size = 5_u64;
        let sync_interval = 25_u64;
        let stale_after_ms = 150_u64;

        let rl = build_limiter(&url, window_size, 1000, sync_interval, prefix.clone()).await;
        let stale = key("stale_user");
        let active = key("active_user");
        let rate_limit = RateLimit::per_second(2f64).unwrap();
        let cap = (window_size as f64 * rate_limit.as_per_second()) as u64;

        // Overflow stale_user and sync.
        for _ in 0..cap {
            assert_allowed(
                rl.absolute().inc(&stale, &rate_limit, 1).await.unwrap(),
                "stale entity setup increment",
            );
        }
        let stale_overflow = rl.absolute().inc(&stale, &rate_limit, 1).await.unwrap();
        assert!(matches!(stale_overflow, RateLimitDecision::Rejected { .. }));
        wait_for_hybrid_sync(sync_interval).await;

        // Wait for stale_user to become stale.
        runtime::async_sleep(Duration::from_millis(stale_after_ms + 50)).await;

        // Now overflow active_user — its commit timestamp is recent.
        let rl2 = build_limiter(&url, window_size, 1000, sync_interval, prefix.clone()).await;
        for _ in 0..cap {
            assert_allowed(
                rl2.absolute().inc(&active, &rate_limit, 1).await.unwrap(),
                "active entity setup increment",
            );
        }
        let active_overflow = rl2.absolute().inc(&active, &rate_limit, 1).await.unwrap();
        assert!(matches!(
            active_overflow,
            RateLimitDecision::Rejected { .. }
        ));
        wait_for_hybrid_sync(sync_interval).await;

        rl2.absolute().cleanup(stale_after_ms).await.unwrap();

        let active_entities_key =
            key_gen(&prefix, RateType::HybridAbsolute).get_active_entities_key();

        let mut conn = redis::Client::open(url.as_str())
            .unwrap()
            .get_multiplexed_async_connection()
            .await
            .unwrap();

        // stale_user keys must be gone.
        let stale_t: bool = conn.exists(redis_key(&prefix, &stale, "t")).await.unwrap();
        assert!(!stale_t, "stale_user total count key must be deleted");
        let stale_score: Option<f64> = conn
            .zscore(&active_entities_key, stale.as_str())
            .await
            .unwrap();
        assert!(
            stale_score.is_none(),
            "stale_user must be removed from active_entities"
        );

        // active_user keys must still exist.
        let active_t: bool = conn.exists(redis_key(&prefix, &active, "t")).await.unwrap();
        assert!(active_t, "active_user total count key must still exist");
        let active_score: Option<f64> = conn
            .zscore(&active_entities_key, active.as_str())
            .await
            .unwrap();
        assert!(
            active_score.is_some(),
            "active_user must remain in active_entities"
        );
    });
}

/// A limiter that has not yet overflowed writes nothing to the hybrid_absolute keyspace,
/// while another limiter using the same prefix (but different rate type, e.g. redis absolute)
/// A matched `set_if` replaces the window contents with exactly one bucket holding the
/// written count, sets the running total to that count, and (re)defines the window limit.
#[test]
fn redis_state_hybrid_absolute_set_if_writes_single_bucket_total_and_window_limit() {
    let url = redis_url();

    runtime::block_on(async {
        let prefix = unique_prefix();
        let window_size = 6_u64;

        let rl = build_limiter(&url, window_size, 1000, 25, prefix.clone()).await;
        let k = key("k");
        let rate_limit = RateLimit::per_second(10f64).unwrap();

        let outcome = rl
            .absolute()
            .set_if(&k, &rate_limit, RateLimitComparator::Lt(40), 40)
            .await
            .unwrap();
        let (new_total, old_total) = (outcome.current_total, outcome.previous_total);
        assert_eq!((new_total, old_total), (40, 0));

        let mut conn = redis::Client::open(url.as_str())
            .unwrap()
            .get_multiplexed_async_connection()
            .await
            .unwrap();

        let total: u64 = conn.get(redis_key(&prefix, &k, "t")).await.unwrap();
        assert_eq!(total, 40, "running total must equal the written count");

        let window_limit: u64 = conn.get(redis_key(&prefix, &k, "w")).await.unwrap();
        assert_eq!(
            window_limit, 60,
            "window limit must be window_size * rate (6 * 10)"
        );

        let buckets: HashMap<String, u64> =
            conn.hgetall(redis_key(&prefix, &k, "h")).await.unwrap();
        assert_eq!(buckets.len(), 1, "exactly one bucket expected: {buckets:?}");
        assert_eq!(
            buckets.values().sum::<u64>(),
            40,
            "the single bucket must hold the written count"
        );

        let ordering_key = redis_key(&prefix, &k, "a");
        let ordering: Vec<String> = conn.zrange(&ordering_key, 0, -1).await.unwrap();
        assert_eq!(ordering.len(), 1, "exactly one active bucket expected");
        assert!(
            buckets.contains_key(&ordering[0]),
            "ordering member must reference the history bucket: {ordering:?} {buckets:?}"
        );

        let limit_ttl_ms: i64 = conn.pttl(redis_key(&prefix, &k, "w")).await.unwrap();
        assert!(
            limit_ttl_ms > 0 && limit_ttl_ms <= window_size as i64 * 1_000,
            "window-limit TTL must be live and bounded by the window: {limit_ttl_ms}"
        );

        let active_score: Option<f64> = conn
            .zscore(
                key_gen(&prefix, RateType::HybridAbsolute).get_active_entities_key(),
                k.as_str(),
            )
            .await
            .unwrap();
        assert!(active_score.is_some(), "entity must be marked active");
    });
}

#[test]
fn redis_state_hybrid_absolute_preserves_requested_history_edge() {
    let url = redis_url();

    runtime::block_on(async {
        let prefix = unique_prefix();
        let sync_interval = 25_u64;
        let rl = build_limiter(&url, 60, 1, sync_interval, prefix.clone()).await;
        let rate = RateLimit::per_second(100f64).unwrap();

        for (name, preservation, expected_reduced, expected_increased) in [
            (
                "newest",
                HistoryPreservation::PreserveNewest,
                vec![2_u64, 6],
                vec![2_u64, 9],
            ),
            (
                "oldest",
                HistoryPreservation::PreserveOldest,
                vec![4_u64, 4],
                vec![7_u64, 4],
            ),
        ] {
            let k = key(name);
            assert_eq!(
                rl.absolute()
                    .set_if(&k, &rate, RateLimitComparator::Always, 4)
                    .await
                    .unwrap(),
                (4, 0)
            );
            runtime::async_sleep(Duration::from_millis(3)).await;
            assert!(matches!(
                rl.absolute().inc(&k, &rate, 5).await.unwrap(),
                RateLimitDecision::Allowed
            ));
            assert_eq!(
                rl
                    .absolute()
                    .set_if_preserve_history(
                        &k,
                        &rate,
                        RateLimitComparator::Eq(9),
                        9,
                        preservation,
                    )
                    .await
                    .unwrap(),
                (9, 9)
            );
            runtime::async_sleep(Duration::from_millis(3)).await;
            assert!(matches!(
                rl.absolute().inc(&k, &rate, 6).await.unwrap(),
                RateLimitDecision::Allowed
            ));
            assert_eq!(
                rl.absolute()
                    .set_if_preserve_history(
                        &k,
                        &rate,
                        RateLimitComparator::Eq(15),
                        15,
                        preservation,
                    )
                    .await
                    .unwrap(),
                (15, 15)
            );
            assert_eq!(rl.absolute().get(&k).await.unwrap(), 15);

            assert_eq!(
                rl.absolute()
                    .set_if_preserve_history(
                        &k,
                        &rate,
                        RateLimitComparator::Eq(15),
                        8,
                        preservation,
                    )
                    .await
                    .unwrap(),
                (8, 15)
            );

            let mut conn = redis::Client::open(url.as_str())
                .unwrap()
                .get_multiplexed_async_connection()
                .await
                .unwrap();
            let ordering_key = redis_key(&prefix, &k, "a");
            let history_key = redis_key(&prefix, &k, "h");
            let fields: Vec<String> = conn.zrange(&ordering_key, 0, -1).await.unwrap();
            let counts: Vec<u64> = redis::cmd("HMGET")
                .arg(&history_key)
                .arg(&fields)
                .query_async(&mut conn)
                .await
                .unwrap();
            assert_eq!(counts, expected_reduced);

            assert_eq!(
                rl.absolute()
                    .set_if_preserve_history(
                        &k,
                        &rate,
                        RateLimitComparator::Eq(8),
                        11,
                        preservation,
                    )
                    .await
                    .unwrap(),
                (11, 8)
            );
            let fields: Vec<String> = conn.zrange(&ordering_key, 0, -1).await.unwrap();
            let counts: Vec<u64> = redis::cmd("HMGET")
                .arg(&history_key)
                .arg(&fields)
                .query_async(&mut conn)
                .await
                .unwrap();
            assert_eq!(counts, expected_increased);
            let total: u64 = conn.get(redis_key(&prefix, &k, "t")).await.unwrap();
            assert_eq!(total, 11);
        }
    });
}

/// An unmatched `set_if` must leave buckets, totals, and the stored limit untouched.
#[test]
fn redis_state_hybrid_absolute_set_if_no_match_leaves_buckets_and_total_untouched() {
    let url = redis_url();

    runtime::block_on(async {
        let prefix = unique_prefix();
        let window_size = 6_u64;

        let rl = build_limiter(&url, window_size, 1000, 25, prefix.clone()).await;
        let k = key("k");

        // Seed exact state through set_if itself (single bucket of 17, window limit 6*10=60).
        let rate_seed = RateLimit::per_second(10f64).unwrap();
        assert_eq!(
            rl.absolute()
                .set_if(&k, &rate_seed, RateLimitComparator::Always, 17)
                .await
                .unwrap(),
            (17, 0)
        );

        let mut conn = redis::Client::open(url.as_str())
            .unwrap()
            .get_multiplexed_async_connection()
            .await
            .unwrap();
        let key_generator = key_gen(&prefix, RateType::HybridAbsolute);
        let history_key = redis_key(&prefix, &k, "h");
        let ordering_key = redis_key(&prefix, &k, "a");
        let total_key = redis_key(&prefix, &k, "t");
        let limit_key = redis_key(&prefix, &k, "w");
        let history_before: HashMap<String, u64> = conn.hgetall(&history_key).await.unwrap();
        let ordering_before: Vec<(String, f64)> =
            conn.zrange_withscores(&ordering_key, 0, -1).await.unwrap();
        let total_before: u64 = conn.get(&total_key).await.unwrap();
        let limit_before: u64 = conn.get(&limit_key).await.unwrap();
        let limit_ttl_before: i64 = conn.pttl(&limit_key).await.unwrap();
        let active_score_before: Option<f64> = conn
            .zscore(key_generator.get_active_entities_key(), k.to_string())
            .await
            .unwrap();

        runtime::async_sleep(Duration::from_millis(50)).await;

        // Guard cannot match (17 is not > 1000); a different rate is ignored.
        let rate_new = RateLimit::per_second(20f64).unwrap();
        let outcome = rl
            .absolute()
            .set_if(&k, &rate_new, RateLimitComparator::Gt(1000), 5)
            .await
            .unwrap();
        let (new_total, old_total) = (outcome.current_total, outcome.previous_total);
        assert_eq!((new_total, old_total), (17, 17));

        let history_after: HashMap<String, u64> = conn.hgetall(&history_key).await.unwrap();
        let ordering_after: Vec<(String, f64)> =
            conn.zrange_withscores(&ordering_key, 0, -1).await.unwrap();
        let total_after: u64 = conn.get(&total_key).await.unwrap();
        let limit_after: u64 = conn.get(&limit_key).await.unwrap();
        let limit_ttl_after: i64 = conn.pttl(&limit_key).await.unwrap();
        let active_score_after: Option<f64> = conn
            .zscore(key_generator.get_active_entities_key(), k.to_string())
            .await
            .unwrap();

        assert_eq!(history_after, history_before, "history changed on no-match");
        assert_eq!(
            ordering_after, ordering_before,
            "ordering changed on no-match"
        );
        assert_eq!(total_after, total_before, "total changed on no-match");
        assert_eq!(limit_after, limit_before, "limit changed on no-match");
        assert_eq!(
            active_score_after, active_score_before,
            "active-entity score changed on no-match"
        );
        assert!(
            limit_ttl_after > 0 && limit_ttl_after <= limit_ttl_before - 20,
            "limit TTL was refreshed on no-match: before={limit_ttl_before}, after={limit_ttl_after}"
        );
    });
}

#[test]
fn redis_state_hybrid_absolute_conditional_set_uses_live_history_before_mutating() {
    let url = redis_url();

    runtime::block_on(async {
        let prefix = unique_prefix();
        let window_size = 2_u64;
        let sync_interval = 25_u64;
        let rl = build_limiter(&url, window_size, 1, sync_interval, prefix.clone()).await;
        let k = key("k");
        let rate = RateLimit::per_second(100f64).unwrap();

        assert_eq!(
            rl.absolute()
                .set_if(&k, &rate, RateLimitComparator::Always, 4)
                .await
                .unwrap(),
            (4, 0)
        );
        runtime::async_sleep(Duration::from_millis(1_000)).await;
        assert_allowed(
            rl.absolute().inc(&k, &rate, 6).await.unwrap(),
            "fresh bucket setup increment",
        );
        wait_for_hybrid_sync(sync_interval).await;
        runtime::async_sleep(Duration::from_millis(1_050)).await;

        let mut conn = redis::Client::open(url.as_str())
            .unwrap()
            .get_multiplexed_async_connection()
            .await
            .unwrap();
        let key_generator = key_gen(&prefix, RateType::HybridAbsolute);
        let history_key = key_generator.get_hash_key(&k);
        let ordering_key = key_generator.get_active_keys(&k);
        let total_key = key_generator.get_total_count_key(&k);
        let limit_key = key_generator.get_window_limit_key(&k);
        let active_entities_key = key_generator.get_active_entities_key();

        let history_before: HashMap<String, u64> = conn.hgetall(&history_key).await.unwrap();
        let ordering_before: Vec<(String, f64)> =
            conn.zrange_withscores(&ordering_key, 0, -1).await.unwrap();
        let total_before: u64 = conn.get(&total_key).await.unwrap();
        let limit_before: u64 = conn.get(&limit_key).await.unwrap();
        let limit_ttl_before: i64 = conn.pttl(&limit_key).await.unwrap();
        let active_score_before: Option<f64> =
            conn.zscore(&active_entities_key, k.as_str()).await.unwrap();
        assert_eq!(history_before.len(), 2, "setup must create two buckets");
        assert_eq!(ordering_before.len(), 2, "setup must order two buckets");
        assert_eq!(
            total_before, 10,
            "stored total still includes expired history"
        );

        assert_eq!(
            rl.absolute()
                .set_if(&k, &rate, RateLimitComparator::Gt(100), 5)
                .await
                .unwrap(),
            (6, 6),
            "the comparator must see only the fresh six-unit bucket"
        );

        let history_after_miss: HashMap<String, u64> = conn.hgetall(&history_key).await.unwrap();
        let ordering_after_miss: Vec<(String, f64)> =
            conn.zrange_withscores(&ordering_key, 0, -1).await.unwrap();
        let total_after_miss: u64 = conn.get(&total_key).await.unwrap();
        let limit_after_miss: u64 = conn.get(&limit_key).await.unwrap();
        let limit_ttl_after_miss: i64 = conn.pttl(&limit_key).await.unwrap();
        let active_score_after_miss: Option<f64> =
            conn.zscore(&active_entities_key, k.as_str()).await.unwrap();
        assert_eq!(history_after_miss, history_before);
        assert_eq!(ordering_after_miss, ordering_before);
        assert_eq!(total_after_miss, total_before);
        assert_eq!(limit_after_miss, limit_before);
        assert_eq!(active_score_after_miss, active_score_before);
        assert!(
            limit_ttl_after_miss > 0 && limit_ttl_after_miss <= limit_ttl_before,
            "a guard miss must not refresh the limit TTL: before={limit_ttl_before}, after={limit_ttl_after_miss}"
        );

        assert_eq!(
            rl.absolute()
                .set_if_preserve_history(
                    &k,
                    &rate,
                    RateLimitComparator::Eq(6),
                    4,
                    HistoryPreservation::PreserveNewest,
                )
                .await
                .unwrap(),
            (4, 6)
        );

        let history_after_match: HashMap<String, u64> = conn.hgetall(&history_key).await.unwrap();
        let ordering_after_match: Vec<String> = conn.zrange(&ordering_key, 0, -1).await.unwrap();
        let total_after_match: u64 = conn.get(&total_key).await.unwrap();
        assert_eq!(history_after_match.len(), 1);
        assert_eq!(ordering_after_match.len(), 1);
        assert_eq!(history_after_match.get(&ordering_after_match[0]), Some(&4));
        assert_eq!(total_after_match, 4);
    });
}

/// must not contaminate the hybrid_absolute namespace.
#[test]
fn redis_state_hybrid_absolute_redis_absolute_keys_do_not_contaminate_hybrid_keyspace() {
    let url = redis_url();

    runtime::block_on(async {
        let prefix = unique_prefix();
        let window_size = 1_u64;
        let sync_interval = 2000_u64; // slow tick

        let hybrid = build_limiter(&url, window_size, 1000, sync_interval, prefix.clone()).await;
        let connection = redis::Client::open(url.as_str())
            .unwrap()
            .get_connection_manager()
            .await
            .unwrap();
        let redis = RedisRateLimiterProvider::builder(connection)
            .prefix(prefix.clone())
            .window_size(WindowSize::seconds_or_panic(window_size))
            .bucket_size(BucketSize::milliseconds_or_panic(1_000))
            .cleanup_enabled(false)
            .build()
            .unwrap();
        let k = key("k");
        let rate_limit = RateLimit::per_second(5f64).unwrap();

        // Use only the redis (non-hybrid) absolute limiter — this writes to `absolute:*` keys.
        for _ in 0..5 {
            assert_allowed(
                redis.absolute().inc(&k, &rate_limit, 1).await.unwrap(),
                "pure Redis namespace setup increment",
            );
        }
        assert_eq!(hybrid.absolute().get(&k).await.unwrap(), 0);

        let mut conn = redis::Client::open(url.as_str())
            .unwrap()
            .get_multiplexed_async_connection()
            .await
            .unwrap();

        // The hybrid_absolute keyspace must still be empty.
        let hybrid_total: Option<u64> = conn.get(redis_key(&prefix, &k, "t")).await.unwrap();
        assert!(
            hybrid_total.is_none(),
            "hybrid_absolute keyspace must not be contaminated by redis absolute writes"
        );
    });
}

#[test]
fn redis_state_hybrid_absolute_zero_target_removes_all_entity_state() {
    let url = redis_url();

    runtime::block_on(async {
        let prefix = unique_prefix();
        let rl = build_limiter(&url, 6, 1000, 25, prefix.clone()).await;
        let rate = RateLimit::per_second(10f64).unwrap();
        let key_generator = key_gen(&prefix, RateType::HybridAbsolute);

        for (name, preservation) in [
            ("replace", None),
            ("preserve", Some(HistoryPreservation::PreserveNewest)),
        ] {
            let k = key(name);
            let missing_result = match preservation {
                Some(preservation) => rl
                    .absolute()
                    .set_if_preserve_history(&k, &rate, RateLimitComparator::Eq(0), 0, preservation)
                    .await
                    .unwrap(),
                None => rl
                    .absolute()
                    .set_if(&k, &rate, RateLimitComparator::Eq(0), 0)
                    .await
                    .unwrap(),
            };
            assert_eq!(missing_result, (0, 0));

            let mut conn = redis::Client::open(url.as_str())
                .unwrap()
                .get_multiplexed_async_connection()
                .await
                .unwrap();
            for entity_key in key_generator.get_all_entity_keys(&k) {
                let exists: bool = conn.exists(&entity_key).await.unwrap();
                assert!(
                    !exists,
                    "missing zero target unexpectedly created {entity_key}"
                );
            }
            let score: Option<f64> = conn
                .zscore(key_generator.get_active_entities_key(), k.as_str())
                .await
                .unwrap();
            assert!(score.is_none(), "missing zero target marked {name} active");

            assert_eq!(
                rl.absolute()
                    .set_if(&k, &rate, RateLimitComparator::Always, 17)
                    .await
                    .unwrap(),
                (17, 0)
            );

            let result = match preservation {
                Some(preservation) => rl
                    .absolute()
                    .set_if_preserve_history(
                        &k,
                        &rate,
                        RateLimitComparator::Always,
                        0,
                        preservation,
                    )
                    .await
                    .unwrap(),
                None => rl
                    .absolute()
                    .set_if(&k, &rate, RateLimitComparator::Always, 0)
                    .await
                    .unwrap(),
            };
            assert_eq!(result, (0, 17));

            for entity_key in key_generator.get_all_entity_keys(&k) {
                let exists: bool = conn.exists(&entity_key).await.unwrap();
                assert!(!exists, "unexpected entity key: {entity_key}");
            }
            let score: Option<f64> = conn
                .zscore(key_generator.get_active_entities_key(), k.as_str())
                .await
                .unwrap();
            assert!(score.is_none(), "unexpected active membership for {name}");
        }
    });
}

#[test]
fn redis_state_hybrid_absolute_get_keeps_unknown_entity_absent() {
    let url = redis_url();

    runtime::block_on(async {
        let prefix = unique_prefix();
        let rl = build_limiter(&url, 6, 1000, 25, prefix.clone()).await;
        let k = key("k");
        let rate = RateLimit::per_second(10f64).unwrap();
        let key_generator = key_gen(&prefix, RateType::HybridAbsolute);

        assert_eq!(rl.absolute().get_estimate(&k).await.unwrap(), 0);
        assert_eq!(rl.absolute().get(&k).await.unwrap(), 0);
        let mut conn = redis::Client::open(url.as_str())
            .unwrap()
            .get_multiplexed_async_connection()
            .await
            .unwrap();
        for entity_key in key_generator.get_all_entity_keys(&k) {
            let exists: bool = conn.exists(&entity_key).await.unwrap();
            assert!(!exists, "unknown get created {entity_key}");
        }
        let score: Option<f64> = conn
            .zscore(key_generator.get_active_entities_key(), k.as_str())
            .await
            .unwrap();
        assert!(score.is_none());

        rl.absolute()
            .set_if(&k, &rate, RateLimitComparator::Always, 3)
            .await
            .unwrap();
        let _: u64 = conn
            .zrem(key_generator.get_active_entities_key(), k.as_str())
            .await
            .unwrap();

        assert_eq!(rl.absolute().get_estimate(&k).await.unwrap(), 3);
        let score: Option<f64> = conn
            .zscore(key_generator.get_active_entities_key(), k.as_str())
            .await
            .unwrap();
        assert!(
            score.is_some(),
            "state refresh must restore active membership"
        );

        let _: u64 = conn
            .zrem(key_generator.get_active_entities_key(), k.as_str())
            .await
            .unwrap();
        assert_eq!(rl.absolute().get_estimate(&k).await.unwrap(), 3);
        let score: Option<f64> = conn
            .zscore(key_generator.get_active_entities_key(), k.as_str())
            .await
            .unwrap();
        assert!(
            score.is_none(),
            "local inference fast path must not read or mutate Redis"
        );

        assert_eq!(rl.absolute().get(&k).await.unwrap(), 3);
        let score: Option<f64> = conn
            .zscore(key_generator.get_active_entities_key(), k.as_str())
            .await
            .unwrap();
        assert!(score.is_some(), "known get must refresh active membership");
    });
}