posthog-rs 0.7.0

The official Rust client for Posthog (https://posthog.com/).
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
// Some tests in this file exercise the deprecated single-flag methods
// alongside the local-evaluation cache; tolerate the deprecation warnings
// during the transition window.
#![allow(deprecated)]

use httpmock::prelude::*;
#[cfg(feature = "async-client")]
use posthog_rs::AsyncFlagPoller;
use posthog_rs::{
    ClientOptionsBuilder, FeatureFlag, FeatureFlagCondition, FeatureFlagFilters, FlagCache,
    FlagPoller, FlagValue, LocalEvaluationConfig, LocalEvaluationResponse, LocalEvaluator,
    Property,
};
use serde_json::json;
use std::collections::HashMap;
use std::time::Duration;

#[test]
fn test_local_evaluation_basic() {
    // Create a cache and evaluator
    let cache = FlagCache::new();
    let evaluator = LocalEvaluator::new(cache.clone());

    // Create a simple flag
    let flag = FeatureFlag {
        key: "test-flag".to_string(),
        active: true,
        filters: FeatureFlagFilters {
            groups: vec![FeatureFlagCondition {
                properties: vec![],
                rollout_percentage: Some(100.0),
                variant: None,
                aggregation_group_type_index: None,
            }],
            multivariate: None,
            payloads: HashMap::new(),
            aggregation_group_type_index: None,
        },
    };

    // Update cache with the flag
    let response = LocalEvaluationResponse {
        flags: vec![flag],
        group_type_mapping: HashMap::new(),
        cohorts: HashMap::new(),
    };
    cache.update(response);

    // Test evaluation
    let properties = HashMap::new();
    let result = evaluator.evaluate_flag(
        "test-flag",
        "user-123",
        &properties,
        &HashMap::new(),
        &HashMap::new(),
    );

    assert!(result.is_ok());
    assert_eq!(result.unwrap(), Some(FlagValue::Boolean(true)));
}

#[test]
fn test_local_evaluation_with_properties() {
    let cache = FlagCache::new();
    let evaluator = LocalEvaluator::new(cache.clone());

    // Create a flag with property conditions
    let flag = FeatureFlag {
        key: "premium-feature".to_string(),
        active: true,
        filters: FeatureFlagFilters {
            groups: vec![FeatureFlagCondition {
                properties: vec![Property {
                    key: "plan".to_string(),
                    value: json!("premium"),
                    operator: "exact".to_string(),
                    property_type: None,
                }],
                rollout_percentage: Some(100.0),
                variant: None,
                aggregation_group_type_index: None,
            }],
            multivariate: None,
            payloads: HashMap::new(),
            aggregation_group_type_index: None,
        },
    };

    // Update cache
    let response = LocalEvaluationResponse {
        flags: vec![flag],
        group_type_mapping: HashMap::new(),
        cohorts: HashMap::new(),
    };
    cache.update(response);

    // Test with matching properties
    let mut properties = HashMap::new();
    properties.insert("plan".to_string(), json!("premium"));

    let result = evaluator.evaluate_flag(
        "premium-feature",
        "user-123",
        &properties,
        &HashMap::new(),
        &HashMap::new(),
    );
    assert!(result.is_ok());
    assert_eq!(result.unwrap(), Some(FlagValue::Boolean(true)));

    // Test with non-matching properties
    let mut properties = HashMap::new();
    properties.insert("plan".to_string(), json!("free"));

    let result = evaluator.evaluate_flag(
        "premium-feature",
        "user-456",
        &properties,
        &HashMap::new(),
        &HashMap::new(),
    );
    assert!(result.is_ok());
    assert_eq!(result.unwrap(), Some(FlagValue::Boolean(false)));
}

#[test]
fn test_local_evaluation_missing_flag() {
    let cache = FlagCache::new();
    let evaluator = LocalEvaluator::new(cache);

    let properties = HashMap::new();
    let result = evaluator.evaluate_flag(
        "non-existent",
        "user-123",
        &properties,
        &HashMap::new(),
        &HashMap::new(),
    );

    assert!(result.is_ok());
    assert_eq!(result.unwrap(), None);
}

#[cfg(feature = "async-client")]
#[tokio::test]
async fn test_local_evaluation_with_mock_server() {
    let server = MockServer::start();

    // Mock the local evaluation endpoint
    let mock_flags = json!({
        "flags": [
            {
                "key": "feature-a",
                "active": true,
                "filters": {
                    "groups": [
                        {
                            "properties": [],
                            "rollout_percentage": 50.0,
                            "variant": null
                        }
                    ],
                    "multivariate": null,
                    "payloads": {}
                }
            },
            {
                "key": "feature-b",
                "active": true,
                "filters": {
                    "groups": [
                        {
                            "properties": [
                                {
                                    "key": "email",
                                    "value": "@company.com",
                                    "operator": "icontains"
                                }
                            ],
                            "rollout_percentage": 100.0,
                            "variant": null
                        }
                    ],
                    "multivariate": null,
                    "payloads": {}
                }
            }
        ],
        "group_type_mapping": {},
        "cohorts": {}
    });

    let eval_mock = server.mock(|when, then| {
        when.method(GET)
            .path("/flags/definitions/")
            .header("Authorization", "Bearer test_personal_key")
            .header("X-PostHog-Project-Api-Key", "test_project_key")
            .query_param("send_cohorts", "");
        then.status(200).json_body(mock_flags);
    });

    // Create client with local evaluation enabled
    let options = ClientOptionsBuilder::default()
        .host(server.base_url())
        .api_key("test_project_key".to_string())
        .personal_api_key("test_personal_key".to_string())
        .enable_local_evaluation(true)
        .poll_interval_seconds(60)
        .build()
        .unwrap();

    let client = posthog_rs::client(options).await;

    // Give it a moment to load initial flags
    tokio::time::sleep(Duration::from_millis(100)).await;

    // Test local evaluation
    let mut properties = HashMap::new();
    properties.insert("email".to_string(), json!("test@company.com"));

    let result = client
        .get_feature_flag("feature-b", "user-123", None, Some(properties), None)
        .await;

    assert!(result.unwrap() == Some(FlagValue::Boolean(true)));

    eval_mock.assert();
}

#[test]
fn test_cache_operations() {
    let cache = FlagCache::new();

    // Create multiple flags
    let flags = vec![
        FeatureFlag {
            key: "flag1".to_string(),
            active: true,
            filters: FeatureFlagFilters {
                groups: vec![],
                multivariate: None,
                payloads: HashMap::new(),
                aggregation_group_type_index: None,
            },
        },
        FeatureFlag {
            key: "flag2".to_string(),
            active: true,
            filters: FeatureFlagFilters {
                groups: vec![],
                multivariate: None,
                payloads: HashMap::new(),
                aggregation_group_type_index: None,
            },
        },
    ];

    let response = LocalEvaluationResponse {
        flags: flags.clone(),
        group_type_mapping: HashMap::new(),
        cohorts: HashMap::new(),
    };

    cache.update(response);

    // Test get_flag
    assert!(cache.get_flag("flag1").is_some());
    assert!(cache.get_flag("flag2").is_some());
    assert!(cache.get_flag("flag3").is_none());

    // Test get_all_flags
    let all_flags = cache.get_all_flags();
    assert_eq!(all_flags.len(), 2);

    // Test clear
    cache.clear();
    assert!(cache.get_flag("flag1").is_none());
    assert_eq!(cache.get_all_flags().len(), 0);
}

#[cfg(feature = "async-client")]
#[tokio::test]
async fn test_etag_sent_on_second_poll() {
    let server = MockServer::start();

    let mock_flags = json!({
        "flags": [{
            "key": "test-flag",
            "active": true,
            "filters": {
                "groups": [{"properties": [], "rollout_percentage": 100.0, "variant": null}],
                "multivariate": null,
                "payloads": {}
            }
        }],
        "group_type_mapping": {},
        "cohorts": {}
    });

    // Mock for requests WITH If-None-Match header (subsequent polls) -> 304
    // Registered FIRST but uses matches() to only match when header is present with correct value
    let etag_mock = server.mock(|when, then| {
        when.method(GET)
            .path("/flags/definitions/")
            .query_param("send_cohorts", "")
            .matches(|req| {
                // Match only if If-None-Match header exists with the correct value
                req.headers.as_ref().is_some_and(|headers| {
                    headers.iter().any(|(name, value)| {
                        name.to_lowercase() == "if-none-match" && value == "\"abc123\""
                    })
                })
            });
        then.status(304);
    });

    // Mock for requests WITHOUT If-None-Match (initial load + first poll) -> 200 with ETag
    // Registered SECOND - will be tried first but etag_mock's matches() will fail if no header
    let no_etag_mock = server.mock(|when, then| {
        when.method(GET)
            .path("/flags/definitions/")
            .query_param("send_cohorts", "");
        then.status(200)
            .header("ETag", "\"abc123\"")
            .json_body(mock_flags.clone());
    });

    let cache = FlagCache::new();
    let config = LocalEvaluationConfig {
        personal_api_key: "test_personal_key".to_string(),
        project_api_key: "test_project_key".to_string(),
        api_host: server.base_url(),
        poll_interval: Duration::from_millis(100),
        request_timeout: Duration::from_secs(5),
    };

    let mut poller = AsyncFlagPoller::new(config, cache.clone());
    poller.start().await;

    // Wait for:
    // - Initial load (immediate) -> gets 200 with ETag (load_flags doesn't set last_etag)
    // - First poll tick (after 100ms) -> gets 200, sets last_etag in the polling loop
    // - Second poll tick (after 200ms) -> sends If-None-Match, gets 304
    tokio::time::sleep(Duration::from_millis(350)).await;

    poller.stop().await;

    // Verify requests without If-None-Match were made (initial load + first poll)
    assert!(
        no_etag_mock.hits() >= 2,
        "Should have at least 2 requests without If-None-Match (initial + first poll), got {}",
        no_etag_mock.hits()
    );

    // Verify at least one request WITH If-None-Match was made (second+ poll)
    assert!(
        etag_mock.hits() >= 1,
        "Should have at least 1 request with If-None-Match header, got {}",
        etag_mock.hits()
    );

    // Verify cache has the flag (preserved after 304)
    assert!(
        cache.get_flag("test-flag").is_some(),
        "Flag should be in cache"
    );
}

#[cfg(feature = "async-client")]
#[tokio::test]
async fn test_304_preserves_cache() {
    let server = MockServer::start();

    let mock_flags = json!({
        "flags": [{
            "key": "preserved-flag",
            "active": true,
            "filters": {
                "groups": [{"properties": [], "rollout_percentage": 100.0, "variant": null}],
                "multivariate": null,
                "payloads": {}
            }
        }],
        "group_type_mapping": {},
        "cohorts": {}
    });

    // Mock for requests WITH If-None-Match -> returns 304
    // Registered FIRST but uses matches() to only match when header is present with correct value
    let etag_mock = server.mock(|when, then| {
        when.method(GET)
            .path("/flags/definitions/")
            .query_param("send_cohorts", "")
            .matches(|req| {
                // Match only if If-None-Match header exists with the correct value
                req.headers.as_ref().is_some_and(|headers| {
                    headers.iter().any(|(name, value)| {
                        name.to_lowercase() == "if-none-match" && value == "\"v1\""
                    })
                })
            });
        then.status(304);
    });

    // Mock for requests WITHOUT If-None-Match -> returns 200 with ETag
    // Registered SECOND - will be tried first but etag_mock's matches() will fail if no header
    server.mock(|when, then| {
        when.method(GET)
            .path("/flags/definitions/")
            .query_param("send_cohorts", "");
        then.status(200)
            .header("ETag", "\"v1\"")
            .json_body(mock_flags);
    });

    let cache = FlagCache::new();
    let config = LocalEvaluationConfig {
        personal_api_key: "test_personal_key".to_string(),
        project_api_key: "test_project_key".to_string(),
        api_host: server.base_url(),
        poll_interval: Duration::from_millis(100),
        request_timeout: Duration::from_secs(5),
    };

    let mut poller = AsyncFlagPoller::new(config, cache.clone());
    poller.start().await;

    // Wait for initial load
    tokio::time::sleep(Duration::from_millis(50)).await;

    // Verify flag is in cache after initial load
    assert!(
        cache.get_flag("preserved-flag").is_some(),
        "Flag should be loaded initially"
    );

    // Wait for multiple poll cycles (enough for at least one 304 response)
    tokio::time::sleep(Duration::from_millis(350)).await;

    poller.stop().await;

    // Verify 304 mock was hit (proves If-None-Match was sent and 304 was received)
    assert!(
        etag_mock.hits() >= 1,
        "Should have received at least one 304 response, got {} hits",
        etag_mock.hits()
    );

    // Flag should still be present after 304 response (cache preserved)
    assert!(
        cache.get_flag("preserved-flag").is_some(),
        "Flag should remain in cache after 304 response"
    );
}

#[cfg(feature = "async-client")]
#[tokio::test]
async fn test_no_etag_from_server() {
    let server = MockServer::start();

    let mock_flags = json!({
        "flags": [{
            "key": "no-etag-flag",
            "active": true,
            "filters": {
                "groups": [{"properties": [], "rollout_percentage": 100.0, "variant": null}],
                "multivariate": null,
                "payloads": {}
            }
        }],
        "group_type_mapping": {},
        "cohorts": {}
    });

    // Server returns 200 without ETag header
    let mock = server.mock(|when, then| {
        when.method(GET).path("/flags/definitions/");
        then.status(200).json_body(mock_flags);
    });

    let cache = FlagCache::new();
    let config = LocalEvaluationConfig {
        personal_api_key: "test_personal_key".to_string(),
        project_api_key: "test_project_key".to_string(),
        api_host: server.base_url(),
        poll_interval: Duration::from_millis(50),
        request_timeout: Duration::from_secs(5),
    };

    let mut poller = AsyncFlagPoller::new(config, cache.clone());
    poller.start().await;

    // Wait for initial load + a couple poll cycles
    tokio::time::sleep(Duration::from_millis(150)).await;

    poller.stop().await;

    // Should have made multiple requests (initial + polls), all without If-None-Match
    assert!(
        mock.hits() >= 2,
        "Should have made multiple requests without ETag"
    );

    // Cache should have the flag
    assert!(
        cache.get_flag("no-etag-flag").is_some(),
        "Flag should be in cache"
    );
}

// Sync FlagPoller tests

#[test]
fn test_sync_etag_sent_on_second_poll() {
    let server = MockServer::start();

    let mock_flags = json!({
        "flags": [{
            "key": "test-flag",
            "active": true,
            "filters": {
                "groups": [{"properties": [], "rollout_percentage": 100.0, "variant": null}],
                "multivariate": null,
                "payloads": {}
            }
        }],
        "group_type_mapping": {},
        "cohorts": {}
    });

    // Mock for requests WITH If-None-Match header (subsequent polls) -> 304
    let etag_mock = server.mock(|when, then| {
        when.method(GET)
            .path("/flags/definitions/")
            .query_param("send_cohorts", "")
            .matches(|req| {
                // Match only if If-None-Match header exists with the correct value
                req.headers.as_ref().is_some_and(|headers| {
                    headers.iter().any(|(name, value)| {
                        name.to_lowercase() == "if-none-match" && value == "\"sync-abc123\""
                    })
                })
            });
        then.status(304);
    });

    // Mock for requests WITHOUT If-None-Match -> 200 with ETag
    let no_etag_mock = server.mock(|when, then| {
        when.method(GET)
            .path("/flags/definitions/")
            .query_param("send_cohorts", "");
        then.status(200)
            .header("ETag", "\"sync-abc123\"")
            .json_body(mock_flags.clone());
    });

    let cache = FlagCache::new();
    let config = LocalEvaluationConfig {
        personal_api_key: "test_personal_key".to_string(),
        project_api_key: "test_project_key".to_string(),
        api_host: server.base_url(),
        poll_interval: Duration::from_millis(100),
        request_timeout: Duration::from_secs(5),
    };

    let mut poller = FlagPoller::new(config, cache.clone());
    poller.start();

    // Wait for:
    // - Initial load (immediate) -> gets 200 with ETag (load_flags doesn't set last_etag)
    // - First poll tick (after 100ms) -> gets 200, sets last_etag
    // - Second poll tick (after 200ms) -> sends If-None-Match, gets 304
    std::thread::sleep(Duration::from_millis(350));

    poller.stop();

    // Verify requests without If-None-Match were made (initial load + first poll)
    assert!(
        no_etag_mock.hits() >= 2,
        "Should have at least 2 requests without If-None-Match (initial + first poll), got {}",
        no_etag_mock.hits()
    );

    // Verify at least one request WITH If-None-Match was made (second+ poll)
    assert!(
        etag_mock.hits() >= 1,
        "Should have at least 1 request with If-None-Match header, got {}",
        etag_mock.hits()
    );

    // Verify cache has the flag (preserved after 304)
    assert!(
        cache.get_flag("test-flag").is_some(),
        "Flag should be in cache"
    );
}

#[test]
fn test_sync_304_preserves_cache() {
    let server = MockServer::start();

    let mock_flags = json!({
        "flags": [{
            "key": "preserved-flag",
            "active": true,
            "filters": {
                "groups": [{"properties": [], "rollout_percentage": 100.0, "variant": null}],
                "multivariate": null,
                "payloads": {}
            }
        }],
        "group_type_mapping": {},
        "cohorts": {}
    });

    // Mock for requests WITH If-None-Match -> returns 304
    let etag_mock = server.mock(|when, then| {
        when.method(GET)
            .path("/flags/definitions/")
            .query_param("send_cohorts", "")
            .matches(|req| {
                // Match only if If-None-Match header exists with the correct value
                req.headers.as_ref().is_some_and(|headers| {
                    headers.iter().any(|(name, value)| {
                        name.to_lowercase() == "if-none-match" && value == "\"sync-v1\""
                    })
                })
            });
        then.status(304);
    });

    // Mock for requests WITHOUT If-None-Match -> returns 200 with ETag
    server.mock(|when, then| {
        when.method(GET)
            .path("/flags/definitions/")
            .query_param("send_cohorts", "");
        then.status(200)
            .header("ETag", "\"sync-v1\"")
            .json_body(mock_flags);
    });

    let cache = FlagCache::new();
    let config = LocalEvaluationConfig {
        personal_api_key: "test_personal_key".to_string(),
        project_api_key: "test_project_key".to_string(),
        api_host: server.base_url(),
        poll_interval: Duration::from_millis(100),
        request_timeout: Duration::from_secs(5),
    };

    let mut poller = FlagPoller::new(config, cache.clone());
    poller.start();

    // Wait for initial load
    std::thread::sleep(Duration::from_millis(50));

    // Verify flag is in cache after initial load
    assert!(
        cache.get_flag("preserved-flag").is_some(),
        "Flag should be loaded initially"
    );

    // Wait for multiple poll cycles (enough for at least one 304 response)
    std::thread::sleep(Duration::from_millis(350));

    poller.stop();

    // Verify 304 mock was hit (proves If-None-Match was sent and 304 was received)
    assert!(
        etag_mock.hits() >= 1,
        "Should have received at least one 304 response, got {} hits",
        etag_mock.hits()
    );

    // Flag should still be present after 304 response (cache preserved)
    assert!(
        cache.get_flag("preserved-flag").is_some(),
        "Flag should remain in cache after 304 response"
    );
}

#[test]
fn test_sync_no_etag_from_server() {
    let server = MockServer::start();

    let mock_flags = json!({
        "flags": [{
            "key": "no-etag-flag",
            "active": true,
            "filters": {
                "groups": [{"properties": [], "rollout_percentage": 100.0, "variant": null}],
                "multivariate": null,
                "payloads": {}
            }
        }],
        "group_type_mapping": {},
        "cohorts": {}
    });

    // Server returns 200 without ETag header
    let mock = server.mock(|when, then| {
        when.method(GET).path("/flags/definitions/");
        then.status(200).json_body(mock_flags);
    });

    let cache = FlagCache::new();
    let config = LocalEvaluationConfig {
        personal_api_key: "test_personal_key".to_string(),
        project_api_key: "test_project_key".to_string(),
        api_host: server.base_url(),
        poll_interval: Duration::from_millis(50),
        request_timeout: Duration::from_secs(5),
    };

    let mut poller = FlagPoller::new(config, cache.clone());
    poller.start();

    // Wait for initial load + a couple poll cycles
    std::thread::sleep(Duration::from_millis(150));

    poller.stop();

    // Should have made multiple requests (initial + polls), all without If-None-Match
    assert!(
        mock.hits() >= 2,
        "Should have made multiple requests without ETag"
    );

    // Cache should have the flag
    assert!(
        cache.get_flag("no-etag-flag").is_some(),
        "Flag should be in cache"
    );
}

// ---- Group-targeted and mixed-targeting tests ----

fn mixed_flag() -> FeatureFlag {
    FeatureFlag {
        key: "mixed-flag".to_string(),
        active: true,
        filters: FeatureFlagFilters {
            groups: vec![
                // Group condition: company plan == enterprise
                FeatureFlagCondition {
                    properties: vec![Property {
                        key: "plan".to_string(),
                        value: json!("enterprise"),
                        operator: "exact".to_string(),
                        property_type: Some("group".to_string()),
                    }],
                    rollout_percentage: Some(100.0),
                    variant: None,
                    aggregation_group_type_index: Some(0),
                },
                // Person condition: email == test@example.com
                FeatureFlagCondition {
                    properties: vec![Property {
                        key: "email".to_string(),
                        value: json!("test@example.com"),
                        operator: "exact".to_string(),
                        property_type: Some("person".to_string()),
                    }],
                    rollout_percentage: Some(100.0),
                    variant: None,
                    aggregation_group_type_index: None,
                },
            ],
            multivariate: None,
            payloads: HashMap::new(),
            aggregation_group_type_index: None, // null = mixed
        },
    }
}

fn only_group_flag() -> FeatureFlag {
    FeatureFlag {
        key: "only-group-flag".to_string(),
        active: true,
        filters: FeatureFlagFilters {
            groups: vec![FeatureFlagCondition {
                properties: vec![Property {
                    key: "plan".to_string(),
                    value: json!("enterprise"),
                    operator: "exact".to_string(),
                    property_type: Some("group".to_string()),
                }],
                rollout_percentage: Some(100.0),
                variant: None,
                aggregation_group_type_index: None,
            }],
            multivariate: None,
            payloads: HashMap::new(),
            // Pure group flag at the flag level
            aggregation_group_type_index: Some(0),
        },
    }
}

fn cache_with(flag: FeatureFlag) -> FlagCache {
    let cache = FlagCache::new();
    let mut group_type_mapping = HashMap::new();
    group_type_mapping.insert("0".to_string(), "company".to_string());
    cache.update(LocalEvaluationResponse {
        flags: vec![flag],
        group_type_mapping,
        cohorts: HashMap::new(),
    });
    cache
}

#[test]
fn test_pure_group_flag_matches_with_group_passed_in() {
    let evaluator = LocalEvaluator::new(cache_with(only_group_flag()));
    let mut groups = HashMap::new();
    groups.insert("company".to_string(), "acme".to_string());
    let mut group_props = HashMap::new();
    let mut acme_props = HashMap::new();
    acme_props.insert("plan".to_string(), json!("enterprise"));
    group_props.insert("company".to_string(), acme_props);

    let result = evaluator
        .evaluate_flag(
            "only-group-flag",
            "any-distinct-id",
            &HashMap::new(),
            &groups,
            &group_props,
        )
        .unwrap();
    assert_eq!(result, Some(FlagValue::Boolean(true)));
}

#[test]
fn test_pure_group_flag_returns_false_when_groups_not_passed() {
    // Pure group flag with no groups passed in: skip the condition, return false.
    let evaluator = LocalEvaluator::new(cache_with(only_group_flag()));
    let result = evaluator
        .evaluate_flag(
            "only-group-flag",
            "any-distinct-id",
            &HashMap::new(),
            &HashMap::new(),
            &HashMap::new(),
        )
        .unwrap();
    assert_eq!(result, Some(FlagValue::Boolean(false)));
}

#[test]
fn test_mixed_flag_person_condition_matches_when_no_groups() {
    let evaluator = LocalEvaluator::new(cache_with(mixed_flag()));
    let mut person = HashMap::new();
    person.insert("email".to_string(), json!("test@example.com"));

    let result = evaluator
        .evaluate_flag(
            "mixed-flag",
            "user-1",
            &person,
            &HashMap::new(),
            &HashMap::new(),
        )
        .unwrap();
    assert_eq!(result, Some(FlagValue::Boolean(true)));
}

#[test]
fn test_mixed_flag_group_condition_matches_with_group_props() {
    let evaluator = LocalEvaluator::new(cache_with(mixed_flag()));
    let mut groups = HashMap::new();
    groups.insert("company".to_string(), "acme".to_string());
    let mut group_props = HashMap::new();
    let mut acme = HashMap::new();
    acme.insert("plan".to_string(), json!("enterprise"));
    group_props.insert("company".to_string(), acme);
    let mut person = HashMap::new();
    person.insert("email".to_string(), json!("nope@example.com"));

    let result = evaluator
        .evaluate_flag("mixed-flag", "user-2", &person, &groups, &group_props)
        .unwrap();
    assert_eq!(result, Some(FlagValue::Boolean(true)));
}

#[test]
fn test_mixed_flag_no_match_when_both_fail() {
    let evaluator = LocalEvaluator::new(cache_with(mixed_flag()));
    let mut groups = HashMap::new();
    groups.insert("company".to_string(), "acme".to_string());
    let mut group_props = HashMap::new();
    let mut acme = HashMap::new();
    acme.insert("plan".to_string(), json!("free"));
    group_props.insert("company".to_string(), acme);
    let mut person = HashMap::new();
    person.insert("email".to_string(), json!("nope@example.com"));

    let result = evaluator
        .evaluate_flag("mixed-flag", "user-3", &person, &groups, &group_props)
        .unwrap();
    assert_eq!(result, Some(FlagValue::Boolean(false)));
}

#[test]
fn test_mixed_flag_only_group_condition_no_groups_returns_false() {
    // Mixed flag with only group conditions and no groups passed: skip, return false.
    let flag = FeatureFlag {
        key: "mixed-only-group".to_string(),
        active: true,
        filters: FeatureFlagFilters {
            groups: vec![FeatureFlagCondition {
                properties: vec![Property {
                    key: "plan".to_string(),
                    value: json!("enterprise"),
                    operator: "exact".to_string(),
                    property_type: Some("group".to_string()),
                }],
                rollout_percentage: Some(100.0),
                variant: None,
                aggregation_group_type_index: Some(0),
            }],
            multivariate: None,
            payloads: HashMap::new(),
            aggregation_group_type_index: None,
        },
    };
    let evaluator = LocalEvaluator::new(cache_with(flag));
    let result = evaluator
        .evaluate_flag(
            "mixed-only-group",
            "user-1",
            &HashMap::new(),
            &HashMap::new(),
            &HashMap::new(),
        )
        .unwrap();
    assert_eq!(result, Some(FlagValue::Boolean(false)));
}

#[test]
fn test_group_condition_uses_group_key_for_bucketing() {
    // Group condition at 50% rollout. Use two groups whose hash on
    // ("rollout-flag", group_key) straddles 0.5, with a distinct_id whose hash
    // is also out-of-bucket. If the matcher regressed to bucketing on
    // distinct_id, the in-bucket assertion would fail.
    let flag = FeatureFlag {
        key: "rollout-flag".to_string(),
        active: true,
        filters: FeatureFlagFilters {
            groups: vec![FeatureFlagCondition {
                properties: vec![],
                rollout_percentage: Some(50.0),
                variant: None,
                aggregation_group_type_index: None,
            }],
            multivariate: None,
            payloads: HashMap::new(),
            aggregation_group_type_index: Some(0),
        },
    };
    let evaluator = LocalEvaluator::new(cache_with(flag));
    let distinct_id = "user-0"; // hash > 0.5 against "rollout-flag"

    // Pre-computed: hash("rollout-flag.company-7") ~ 0.118 → in bucket
    let mut groups_in = HashMap::new();
    groups_in.insert("company".to_string(), "company-7".to_string());
    let mut group_props = HashMap::new();
    group_props.insert("company".to_string(), HashMap::new());
    let result = evaluator
        .evaluate_flag(
            "rollout-flag",
            distinct_id,
            &HashMap::new(),
            &groups_in,
            &group_props,
        )
        .unwrap();
    assert_eq!(result, Some(FlagValue::Boolean(true)));

    // Pre-computed: hash("rollout-flag.company-2") ~ 0.803 → out of bucket
    let mut groups_out = HashMap::new();
    groups_out.insert("company".to_string(), "company-2".to_string());
    let result = evaluator
        .evaluate_flag(
            "rollout-flag",
            distinct_id,
            &HashMap::new(),
            &groups_out,
            &group_props,
        )
        .unwrap();
    assert_eq!(result, Some(FlagValue::Boolean(false)));
}