claude-sdk-rs 1.0.0

Rust SDK for Claude AI with CLI integration - type-safe async API for Claude Code and direct SDK usage
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
//! Comprehensive unit tests for the cost tracking module
//!
//! This module provides extensive test coverage for cost tracking functionality including:
//! - Cost entry creation and validation
//! - Cost recording with concurrent access
//! - Cost aggregation and analysis
//! - Budget tracking and alerts
//! - Data persistence and storage
//! - Edge cases and error handling

use super::{CostEntry, CostFilter, CostSummary, CostTracker};
use crate::cli::cost::tracker::{
    AdvancedCostTracker, Budget, BudgetScope, BudgetStatus, CostAlert,
};
use crate::cli::session::SessionId;
use chrono::{DateTime, Duration, Utc};
use proptest::prelude::*;
use proptest::strategy::Just;
use std::collections::HashMap;
use std::path::PathBuf;
use tempfile::tempdir;
use uuid::Uuid;

/// Test fixture for creating cost entries with known data
pub struct CostTestFixture {
    pub session_id: SessionId,
    pub entries: Vec<CostEntry>,
    pub temp_dir: tempfile::TempDir,
    pub storage_path: PathBuf,
}

impl CostTestFixture {
    /// Create a new test fixture with sample data
    pub fn new() -> Self {
        let temp_dir = tempdir().expect("Failed to create temp directory");
        let storage_path = temp_dir.path().join("test_costs.json");
        let session_id = Uuid::new_v4();

        let mut entries = Vec::new();

        // Create diverse test entries
        entries.push(CostEntry::new(
            session_id,
            "analyze_code".to_string(),
            0.050,
            150,
            300,
            2500,
            "claude-3-opus".to_string(),
        ));

        entries.push(CostEntry::new(
            session_id,
            "generate_docs".to_string(),
            0.025,
            75,
            150,
            1800,
            "claude-3-sonnet".to_string(),
        ));

        entries.push(CostEntry::new(
            session_id,
            "review_pr".to_string(),
            0.015,
            50,
            100,
            1200,
            "claude-3-haiku".to_string(),
        ));

        entries.push(CostEntry::new(
            session_id,
            "analyze_code".to_string(), // Duplicate command name
            0.040,
            120,
            240,
            2000,
            "claude-3-opus".to_string(),
        ));

        Self {
            session_id,
            entries,
            temp_dir,
            storage_path,
        }
    }

    /// Create fixture with large dataset for performance testing
    pub fn with_large_dataset(entry_count: usize) -> Self {
        let temp_dir = tempdir().expect("Failed to create temp directory");
        let storage_path = temp_dir.path().join("large_test_costs.json");
        let session_id = Uuid::new_v4();

        let mut entries = Vec::new();
        let commands = ["analyze", "generate", "review", "refactor", "test", "debug", "optimize"];
        let models = ["claude-3-opus", "claude-3-sonnet", "claude-3-haiku"];

        for i in 0..entry_count {
            let command_idx = i % commands.len();
            let model_idx = i % models.len();

            entries.push(CostEntry::new(
                session_id,
                format!("{}_{}", commands[command_idx], i),
                0.001 + (i as f64 * 0.001), // Varying costs
                10 + (i as u32 * 5),        // Varying input tokens
                20 + (i as u32 * 10),       // Varying output tokens
                500 + (i as u64 * 100),     // Varying duration
                models[model_idx].to_string(),
            ));
        }

        Self {
            session_id,
            entries,
            temp_dir,
            storage_path,
        }
    }

    /// Create fixture with time-distributed entries for trend analysis
    pub fn with_time_series_data(days: i64) -> Self {
        let temp_dir = tempdir().expect("Failed to create temp directory");
        let storage_path = temp_dir.path().join("timeseries_test_costs.json");
        let session_id = Uuid::new_v4();

        let mut entries = Vec::new();
        let base_time = Utc::now() - Duration::days(days);

        for day in 0..days {
            for hour in [9, 14, 16] {
                // Simulate peak usage hours
                let mut entry = CostEntry::new(
                    session_id,
                    format!("daily_task_{}", day),
                    0.010 + (day as f64 * 0.005), // Increasing cost trend
                    50 + (day as u32 * 2),
                    100 + (day as u32 * 4),
                    1000 + (day as u64 * 50),
                    "claude-3-opus".to_string(),
                );

                // Set specific timestamp
                entry.timestamp = base_time + Duration::days(day) + Duration::hours(hour);
                entries.push(entry);
            }
        }

        Self {
            session_id,
            entries,
            temp_dir,
            storage_path,
        }
    }

    /// Create a cost tracker with the fixture data
    pub async fn create_tracker(&self) -> CostTracker {
        let mut tracker =
            CostTracker::new(self.storage_path.clone()).expect("Failed to create test tracker");

        for entry in &self.entries {
            tracker
                .record_cost(entry.clone())
                .await
                .expect("Failed to record test entry");
        }

        tracker
    }

    /// Generate random cost entry for property-based testing
    pub fn random_entry(session_id: SessionId) -> impl Strategy<Value = CostEntry> {
        (
            any::<String>().prop_filter("Non-empty command", |s| !s.is_empty()),
            0.001f64..1.0f64, // Reasonable cost range
            1u32..10000u32,   // Input tokens
            1u32..20000u32,   // Output tokens
            100u64..60000u64, // Duration ms
            any::<String>().prop_filter("Non-empty model", |s| !s.is_empty()),
        )
            .prop_map(
                move |(command, cost, input_tokens, output_tokens, duration, model)| {
                    CostEntry::new(
                        session_id,
                        command,
                        cost,
                        input_tokens,
                        output_tokens,
                        duration,
                        model,
                    )
                },
            )
    }

    /// Generate cost filter for property-based testing
    pub fn random_filter() -> impl Strategy<Value = CostFilter> {
        (
            prop::option::of(Just(Uuid::new_v4())),
            prop::option::of(any::<String>()),
            prop::option::of(property_strategies::date_range().prop_map(|(start, _)| start)),
            prop::option::of(property_strategies::date_range().prop_map(|(_, end)| end)),
            prop::option::of(0.0f64..1000.0f64),
            prop::option::of(0.0f64..1000.0f64),
            prop::option::of(any::<String>()),
        )
            .prop_map(
                |(session_id, command_pattern, since, until, min_cost, max_cost, model)| {
                    CostFilter {
                        session_id,
                        command_pattern,
                        since,
                        until,
                        min_cost,
                        max_cost,
                        model,
                    }
                },
            )
    }
}

/// Helper functions for test data generation
pub mod test_helpers {
    use super::*;

    /// Create a cost entry with minimal valid data
    pub fn minimal_cost_entry(session_id: SessionId) -> CostEntry {
        CostEntry::new(
            session_id,
            "test_command".to_string(),
            0.001,
            1,
            1,
            100,
            "test_model".to_string(),
        )
    }

    /// Create a cost entry with maximum realistic values
    pub fn maximal_cost_entry(session_id: SessionId) -> CostEntry {
        CostEntry::new(
            session_id,
            "expensive_analysis_command_with_very_long_name".to_string(),
            99.999,
            100000,
            200000,
            3600000, // 1 hour
            "claude-3-opus-premium-ultra".to_string(),
        )
    }

    /// Create entries with edge case values
    pub fn edge_case_entries(session_id: SessionId) -> Vec<CostEntry> {
        vec![
            // Zero cost
            CostEntry::new(
                session_id,
                "free_command".to_string(),
                0.0,
                0,
                0,
                0,
                "free_model".to_string(),
            ),
            // Very small values
            CostEntry::new(
                session_id,
                "tiny".to_string(),
                0.00001,
                1,
                1,
                1,
                "tiny_model".to_string(),
            ),
            // Unicode in command names
            CostEntry::new(
                session_id,
                "分析代码".to_string(),
                0.01,
                50,
                100,
                1000,
                "claude-3-opus".to_string(),
            ),
            // Special characters
            CostEntry::new(
                session_id,
                "cmd-with_special.chars@test!".to_string(),
                0.02,
                60,
                120,
                1500,
                "model-v2.1".to_string(),
            ),
        ]
    }

    /// Generate entries for concurrent testing
    pub fn concurrent_test_entries(session_id: SessionId, count: usize) -> Vec<CostEntry> {
        (0..count)
            .map(|i| {
                CostEntry::new(
                    session_id,
                    format!("concurrent_cmd_{}", i),
                    0.01 * (i + 1) as f64,
                    10 * (i + 1) as u32,
                    20 * (i + 1) as u32,
                    100 * (i + 1) as u64,
                    format!("model_{}", i % 3),
                )
            })
            .collect()
    }

    /// Create entries spanning multiple sessions
    pub fn multi_session_entries() -> (Vec<SessionId>, Vec<CostEntry>) {
        let sessions: Vec<SessionId> = (0..3).map(|_| Uuid::new_v4()).collect();
        let mut entries = Vec::new();

        for (i, &session_id) in sessions.iter().enumerate() {
            for j in 0..5 {
                entries.push(CostEntry::new(
                    session_id,
                    format!("session_{}_cmd_{}", i, j),
                    0.01 * ((i * 5 + j) + 1) as f64,
                    50 + (j * 10) as u32,
                    100 + (j * 20) as u32,
                    1000 + (j * 200) as u64,
                    "claude-3-opus".to_string(),
                ));
            }
        }

        (sessions, entries)
    }

    /// Create temporally distributed entries for date filtering tests
    pub fn time_distributed_entries(session_id: SessionId) -> Vec<CostEntry> {
        let base_time = Utc::now();
        let mut entries = Vec::new();

        // Entries from different time periods
        let time_offsets = [
            Duration::days(-30),    // 30 days ago
            Duration::days(-7),     // 1 week ago
            Duration::days(-1),     // Yesterday
            Duration::hours(-6),    // 6 hours ago
            Duration::hours(-1),    // 1 hour ago
            Duration::minutes(-10), // 10 minutes ago
        ];

        for (i, offset) in time_offsets.iter().enumerate() {
            let mut entry = CostEntry::new(
                session_id,
                format!("time_cmd_{}", i),
                0.01 * (i + 1) as f64,
                50 + (i * 10) as u32,
                100 + (i * 20) as u32,
                1000 + (i * 200) as u64,
                "claude-3-opus".to_string(),
            );
            entry.timestamp = base_time + *offset;
            entries.push(entry);
        }

        entries
    }

    /// Validate cost summary calculations
    pub fn validate_cost_summary(entries: &[CostEntry], summary: &CostSummary) -> bool {
        if entries.is_empty() {
            return summary.total_cost == 0.0
                && summary.command_count == 0
                && summary.average_cost == 0.0
                && summary.total_tokens == 0;
        }

        let expected_total_cost: f64 = entries.iter().map(|e| e.cost_usd).sum();
        let expected_command_count = entries.len();
        let expected_average_cost = expected_total_cost / expected_command_count as f64;
        let expected_total_tokens: u32 = entries
            .iter()
            .map(|e| e.input_tokens + e.output_tokens)
            .sum();

        let cost_match = (summary.total_cost - expected_total_cost).abs() < 0.00001;
        let count_match = summary.command_count == expected_command_count;
        let avg_match = (summary.average_cost - expected_average_cost).abs() < 0.00001;
        let token_match = summary.total_tokens == expected_total_tokens;

        cost_match && count_match && avg_match && token_match
    }

    /// Create performance benchmark entries
    pub fn benchmark_entries(count: usize) -> Vec<CostEntry> {
        let session_id = Uuid::new_v4();
        (0..count)
            .map(|i| {
                CostEntry::new(
                    session_id,
                    format!("benchmark_cmd_{:06}", i),
                    0.001 + (i as f64 / 1000000.0), // Small incremental costs
                    10 + (i % 100) as u32,
                    20 + (i % 200) as u32,
                    100 + (i % 5000) as u64,
                    match i % 3 {
                        0 => "claude-3-opus",
                        1 => "claude-3-sonnet",
                        _ => "claude-3-haiku",
                    }
                    .to_string(),
                )
            })
            .collect()
    }
}

/// Property-based test strategies
pub mod property_strategies {
    use super::*;

    /// Strategy for generating valid cost values
    pub fn valid_cost() -> impl Strategy<Value = f64> {
        (0.0..1000.0f64).prop_filter("Non-negative finite cost", |&cost| {
            cost.is_finite() && cost >= 0.0
        })
    }

    /// Strategy for generating valid token counts
    pub fn valid_tokens() -> impl Strategy<Value = u32> {
        0u32..1000000u32
    }

    /// Strategy for generating valid durations
    pub fn valid_duration() -> impl Strategy<Value = u64> {
        1u64..3600000u64 // 1ms to 1 hour
    }

    /// Strategy for generating realistic command names
    pub fn command_name() -> impl Strategy<Value = String> {
        prop::collection::vec("[a-z_]{1,20}", 1..4).prop_map(|parts| parts.join("_"))
    }

    /// Strategy for generating model names
    pub fn model_name() -> impl Strategy<Value = String> {
        prop_oneof![
            Just("claude-3-opus".to_string()),
            Just("claude-3-sonnet".to_string()),
            Just("claude-3-haiku".to_string()),
            "[a-z0-9-]{5,30}".prop_map(|s| s.to_string()),
        ]
    }

    /// Strategy for generating valid date ranges
    pub fn date_range() -> impl Strategy<Value = (DateTime<Utc>, DateTime<Utc>)> {
        (
            -365i64..0i64, // Days in the past for start
            0i64..365i64,  // Days in the future for end
        )
            .prop_map(|(start_days, end_days)| {
                let base = Utc::now();
                let start = base + Duration::days(start_days);
                let end = base + Duration::days(end_days);
                if start <= end {
                    (start, end)
                } else {
                    (end, start)
                }
            })
    }
}

#[cfg(test)]
mod test_infrastructure_tests {
    use super::*;

    #[test]
    fn test_fixture_creation() {
        let fixture = CostTestFixture::new();

        assert!(!fixture.entries.is_empty());
        assert!(!fixture.storage_path.exists()); // Should not exist yet
        assert_eq!(fixture.entries.len(), 4);

        // Verify entries have the same session ID
        for entry in &fixture.entries {
            assert_eq!(entry.session_id, fixture.session_id);
        }
    }

    #[test]
    fn test_large_dataset_fixture() {
        let fixture = CostTestFixture::with_large_dataset(1000);

        assert_eq!(fixture.entries.len(), 1000);

        // Verify diversity in the dataset
        let mut unique_commands = std::collections::HashSet::new();
        let mut unique_models = std::collections::HashSet::new();

        for entry in &fixture.entries {
            unique_commands.insert(&entry.command_name);
            unique_models.insert(&entry.model);
        }

        assert!(unique_commands.len() > 1);
        assert!(unique_models.len() > 1);
    }

    #[test]
    fn test_time_series_fixture() {
        let fixture = CostTestFixture::with_time_series_data(7);

        assert_eq!(fixture.entries.len(), 7 * 3); // 7 days * 3 entries per day

        // Verify timestamps are distributed over time
        let mut timestamps: Vec<_> = fixture.entries.iter().map(|e| e.timestamp).collect();
        timestamps.sort();

        assert!(timestamps.first().unwrap() < timestamps.last().unwrap());

        // Verify cost trend (should be increasing)
        let costs: Vec<_> = fixture.entries.iter().map(|e| e.cost_usd).collect();
        let first_day_cost = costs[0];
        let last_day_cost = costs[costs.len() - 3]; // Last day, first entry
        assert!(last_day_cost > first_day_cost);
    }

    #[tokio::test]
    async fn test_fixture_tracker_creation() {
        let fixture = CostTestFixture::new();
        let tracker = fixture.create_tracker().await;

        // Verify all entries were recorded
        let global_summary = tracker.get_global_summary().await.unwrap();
        assert_eq!(global_summary.command_count, fixture.entries.len());

        // Verify total cost calculation
        let expected_total: f64 = fixture.entries.iter().map(|e| e.cost_usd).sum();
        assert!((global_summary.total_cost - expected_total).abs() < 0.00001);
    }

    #[test]
    fn test_helper_functions() {
        let session_id = Uuid::new_v4();

        // Test minimal entry
        let minimal = test_helpers::minimal_cost_entry(session_id);
        assert_eq!(minimal.session_id, session_id);
        assert!(minimal.cost_usd > 0.0);

        // Test maximal entry
        let maximal = test_helpers::maximal_cost_entry(session_id);
        assert_eq!(maximal.session_id, session_id);
        assert!(maximal.cost_usd > minimal.cost_usd);

        // Test edge cases
        let edge_cases = test_helpers::edge_case_entries(session_id);
        assert!(!edge_cases.is_empty());

        // Test concurrent entries
        let concurrent = test_helpers::concurrent_test_entries(session_id, 10);
        assert_eq!(concurrent.len(), 10);

        // Test multi-session entries
        let (sessions, entries) = test_helpers::multi_session_entries();
        assert_eq!(sessions.len(), 3);
        assert_eq!(entries.len(), 15); // 3 sessions * 5 entries each

        // Test time distributed entries
        let time_entries = test_helpers::time_distributed_entries(session_id);
        assert_eq!(time_entries.len(), 6);
    }

    #[test]
    fn test_summary_validation() {
        let session_id = Uuid::new_v4();
        let entries = vec![
            CostEntry::new(
                session_id,
                "cmd1".to_string(),
                0.10,
                100,
                200,
                1000,
                "model1".to_string(),
            ),
            CostEntry::new(
                session_id,
                "cmd2".to_string(),
                0.20,
                150,
                300,
                1500,
                "model2".to_string(),
            ),
        ];

        let summary = CostSummary {
            total_cost: 0.30,
            command_count: 2,
            average_cost: 0.15,
            total_tokens: 750, // 100+200+150+300
            date_range: (Utc::now(), Utc::now()),
            by_command: HashMap::new(),
            by_model: HashMap::new(),
        };

        assert!(test_helpers::validate_cost_summary(&entries, &summary));

        // Test with invalid summary
        let invalid_summary = CostSummary {
            total_cost: 999.99, // Wrong total
            ..summary.clone()
        };

        assert!(!test_helpers::validate_cost_summary(
            &entries,
            &invalid_summary
        ));
    }

    #[test]
    fn test_benchmark_entries() {
        let entries = test_helpers::benchmark_entries(10000);
        assert_eq!(entries.len(), 10000);

        // Verify performance characteristics
        let start = std::time::Instant::now();
        let _total_cost: f64 = entries.iter().map(|e| e.cost_usd).sum();
        let duration = start.elapsed();

        // Should be able to sum 10k entries quickly
        assert!(duration.as_millis() < 10);
    }

    proptest! {
        #[test]
        fn property_cost_entry_creation(
            cost in property_strategies::valid_cost(),
            input_tokens in property_strategies::valid_tokens(),
            output_tokens in property_strategies::valid_tokens(),
            duration in property_strategies::valid_duration(),
            command in property_strategies::command_name(),
            model in property_strategies::model_name(),
        ) {
            let session_id = Uuid::new_v4();
            let entry = CostEntry::new(
                session_id,
                command,
                cost,
                input_tokens,
                output_tokens,
                duration,
                model.clone(),
            );

            // Verify properties
            prop_assert_eq!(entry.session_id, session_id);
            prop_assert_eq!(entry.cost_usd, cost);
            prop_assert_eq!(entry.input_tokens, input_tokens);
            prop_assert_eq!(entry.output_tokens, output_tokens);
            prop_assert_eq!(entry.duration_ms, duration);
            prop_assert_eq!(entry.model, model);
            prop_assert!(!entry.id.is_empty());
        }

        #[test]
        fn property_cost_filter_behavior(
            filter in CostTestFixture::random_filter(),
            entry in CostTestFixture::random_entry(Uuid::new_v4()),
        ) {
            // This test verifies that filter logic doesn't panic
            // and behaves consistently
            let temp_dir = tempdir().unwrap();
            let storage_path = temp_dir.path().join("prop_test.json");
            let tracker = CostTracker::new(storage_path).unwrap();

            // The filter logic should not panic regardless of input
            let matches = tracker.matches_filter(&entry, &filter);
            prop_assert!(matches == true || matches == false); // Just checking no panic
        }

        #[test]
        fn property_summary_calculation_consistency(
            entries in prop::collection::vec(
                CostTestFixture::random_entry(Uuid::new_v4()),
                0..100
            )
        ) {
            // Test that summary calculations are consistent
            if !entries.is_empty() {
                let total_cost: f64 = entries.iter().map(|e| e.cost_usd).sum();
                let command_count = entries.len();
                let average_cost = total_cost / command_count as f64;

                prop_assert!(total_cost >= 0.0);
                prop_assert!(average_cost >= 0.0);
                prop_assert!(command_count > 0);

                // If all entries have positive cost, average should be positive
                if entries.iter().all(|e| e.cost_usd > 0.0) {
                    prop_assert!(average_cost > 0.0);
                }
            }
        }
    }
}

/// Tests for core cost recording functionality (Task 1.2)
#[cfg(test)]
mod core_recording_tests {
    use super::*;
    use std::sync::Arc;
    use tokio::sync::Mutex;

    #[tokio::test]
    async fn test_record_cost_valid_data() {
        let fixture = CostTestFixture::new();
        let mut tracker = CostTracker::new(fixture.storage_path.clone()).unwrap();

        let session_id = Uuid::new_v4();
        let entry = CostEntry::new(
            session_id,
            "test_command".to_string(),
            0.025,
            100,
            200,
            1500,
            "claude-3-opus".to_string(),
        );

        let initial_count = tracker.entries.len();
        tracker.record_cost(entry.clone()).await.unwrap();

        assert_eq!(tracker.entries.len(), initial_count + 1);
        let recorded_entry = &tracker.entries[tracker.entries.len() - 1];
        assert_eq!(recorded_entry.session_id, entry.session_id);
        assert_eq!(recorded_entry.command_name, entry.command_name);
        assert_eq!(recorded_entry.cost_usd, entry.cost_usd);
        assert_eq!(recorded_entry.input_tokens, entry.input_tokens);
        assert_eq!(recorded_entry.output_tokens, entry.output_tokens);
        assert_eq!(recorded_entry.duration_ms, entry.duration_ms);
        assert_eq!(recorded_entry.model, entry.model);
    }

    #[tokio::test]
    async fn test_record_cost_zero_values() {
        let fixture = CostTestFixture::new();
        let mut tracker = CostTracker::new(fixture.storage_path.clone()).unwrap();

        let session_id = Uuid::new_v4();
        let zero_cost_entry = CostEntry::new(
            session_id,
            "free_command".to_string(),
            0.0, // Zero cost
            0,   // Zero input tokens
            0,   // Zero output tokens
            0,   // Zero duration
            "free_model".to_string(),
        );

        // Should succeed even with zero values
        tracker.record_cost(zero_cost_entry.clone()).await.unwrap();

        let summary = tracker.get_session_summary(session_id).await.unwrap();
        assert_eq!(summary.total_cost, 0.0);
        assert_eq!(summary.command_count, 1);
        assert_eq!(summary.total_tokens, 0);
    }

    #[tokio::test]
    async fn test_record_cost_negative_values() {
        let fixture = CostTestFixture::new();
        let mut tracker = CostTracker::new(fixture.storage_path.clone()).unwrap();

        let session_id = Uuid::new_v4();
        let negative_cost_entry = CostEntry::new(
            session_id,
            "refund_command".to_string(),
            -0.05, // Negative cost (refund scenario)
            100,
            200,
            1000,
            "claude-3-opus".to_string(),
        );

        // Should handle negative costs (e.g., for refunds)
        tracker
            .record_cost(negative_cost_entry.clone())
            .await
            .unwrap();

        let summary = tracker.get_session_summary(session_id).await.unwrap();
        assert_eq!(summary.total_cost, -0.05);
        assert_eq!(summary.command_count, 1);
        assert!(summary.average_cost < 0.0);
    }

    #[tokio::test]
    async fn test_record_cost_different_types() {
        let fixture = CostTestFixture::new();
        let mut tracker = CostTracker::new(fixture.storage_path.clone()).unwrap();

        let session_id = Uuid::new_v4();

        // Different cost types and models
        let entries = vec![
            CostEntry::new(
                session_id,
                "input_heavy".to_string(),
                0.10,
                1000,
                100,
                2000,
                "claude-3-opus".to_string(),
            ),
            CostEntry::new(
                session_id,
                "output_heavy".to_string(),
                0.15,
                100,
                1000,
                3000,
                "claude-3-opus".to_string(),
            ),
            CostEntry::new(
                session_id,
                "balanced".to_string(),
                0.08,
                500,
                500,
                1500,
                "claude-3-sonnet".to_string(),
            ),
            CostEntry::new(
                session_id,
                "quick_task".to_string(),
                0.01,
                50,
                50,
                200,
                "claude-3-haiku".to_string(),
            ),
        ];

        for entry in entries {
            tracker.record_cost(entry).await.unwrap();
        }

        let summary = tracker.get_session_summary(session_id).await.unwrap();
        assert_eq!(summary.command_count, 4);
        assert_eq!(summary.by_model.len(), 3); // Three different models

        // Verify input-heavy vs output-heavy distinction
        let total_input_tokens: u32 = tracker
            .entries
            .iter()
            .filter(|e| e.session_id == session_id)
            .map(|e| e.input_tokens)
            .sum();
        let total_output_tokens: u32 = tracker
            .entries
            .iter()
            .filter(|e| e.session_id == session_id)
            .map(|e| e.output_tokens)
            .sum();

        assert_eq!(total_input_tokens, 1650);
        assert_eq!(total_output_tokens, 1650);
        assert_eq!(summary.total_tokens, 3300);
    }

    #[tokio::test]
    async fn test_concurrent_cost_recording() {
        let fixture = CostTestFixture::new();
        let tracker = Arc::new(Mutex::new(
            CostTracker::new(fixture.storage_path.clone()).unwrap(),
        ));
        let session_id = Uuid::new_v4();

        // Create multiple concurrent tasks
        let mut handles = vec![];

        for i in 0..50 {
            let tracker_clone = Arc::clone(&tracker);
            let handle = tokio::spawn(async move {
                let entry = CostEntry::new(
                    session_id,
                    format!("concurrent_cmd_{}", i),
                    0.01 * (i + 1) as f64,
                    10 + i as u32,
                    20 + i as u32,
                    100 + i as u64,
                    format!("model_{}", i % 3),
                );

                let mut tracker_lock = tracker_clone.lock().await;
                tracker_lock.record_cost(entry).await.unwrap();
            });
            handles.push(handle);
        }

        // Wait for all tasks to complete
        for handle in handles {
            handle.await.unwrap();
        }

        let tracker_lock = tracker.lock().await;
        let summary = tracker_lock.get_session_summary(session_id).await.unwrap();

        assert_eq!(summary.command_count, 50);

        // Verify total cost calculation
        let expected_total: f64 = (1..=50).map(|i| 0.01 * i as f64).sum();
        assert!((summary.total_cost - expected_total).abs() < 0.00001);
    }

    #[tokio::test]
    async fn test_cost_recording_persistence() {
        let fixture = CostTestFixture::new();
        let session_id = Uuid::new_v4();

        // Create first tracker and add entries
        {
            let mut tracker = CostTracker::new(fixture.storage_path.clone()).unwrap();

            for i in 0..5 {
                let entry = CostEntry::new(
                    session_id,
                    format!("persistent_cmd_{}", i),
                    0.01 * (i + 1) as f64,
                    50 + i as u32 * 10,
                    100 + i as u32 * 20,
                    1000 + i as u64 * 200,
                    "claude-3-opus".to_string(),
                );
                tracker.record_cost(entry).await.unwrap();
            }
        } // tracker goes out of scope

        // Create new tracker instance and verify persistence
        let tracker = CostTracker::new(fixture.storage_path.clone()).unwrap();
        let summary = tracker.get_session_summary(session_id).await.unwrap();

        assert_eq!(summary.command_count, 5);

        let expected_total: f64 = (1..=5).map(|i| 0.01 * i as f64).sum();
        assert!((summary.total_cost - expected_total).abs() < 0.00001);
    }

    #[tokio::test]
    async fn test_record_cost_storage_failure_handling() {
        // Create a tracker with an invalid storage path (read-only directory)
        let temp_dir = tempdir().unwrap();
        let readonly_path = temp_dir.path().join("readonly");
        std::fs::create_dir(&readonly_path).unwrap();

        // Make directory read-only (this test might behave differently on different platforms)
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let mut perms = std::fs::metadata(&readonly_path).unwrap().permissions();
            perms.set_mode(0o444); // Read-only
            std::fs::set_permissions(&readonly_path, perms).unwrap();
        }

        let storage_path = readonly_path.join("costs.json");
        let mut tracker = CostTracker::new(storage_path).unwrap();

        let session_id = Uuid::new_v4();
        let entry = CostEntry::new(
            session_id,
            "test_command".to_string(),
            0.025,
            100,
            200,
            1500,
            "claude-3-opus".to_string(),
        );

        // This should fail due to permission issues on Unix systems
        #[cfg(unix)]
        {
            let result = tracker.record_cost(entry).await;
            assert!(result.is_err());
        }

        // On other platforms, we just ensure it doesn't panic
        #[cfg(not(unix))]
        {
            let _result = tracker.record_cost(entry).await;
        }
    }

    #[tokio::test]
    async fn test_record_cost_with_unicode_content() {
        let fixture = CostTestFixture::new();
        let mut tracker = CostTracker::new(fixture.storage_path.clone()).unwrap();

        let session_id = Uuid::new_v4();
        let entries = vec![
            CostEntry::new(
                session_id,
                "分析代码".to_string(),
                0.025,
                100,
                200,
                1500,
                "claude-3-opus".to_string(),
            ),
            CostEntry::new(
                session_id,
                "анализ_кода".to_string(),
                0.030,
                150,
                250,
                2000,
                "claude-3-sonnet".to_string(),
            ),
            CostEntry::new(
                session_id,
                "コード解析".to_string(),
                0.020,
                80,
                180,
                1200,
                "claude-3-haiku".to_string(),
            ),
            CostEntry::new(
                session_id,
                "🔍analyze🚀".to_string(),
                0.035,
                200,
                300,
                2500,
                "claude-3-opus".to_string(),
            ),
        ];

        for entry in entries {
            tracker.record_cost(entry).await.unwrap();
        }

        let summary = tracker.get_session_summary(session_id).await.unwrap();
        assert_eq!(summary.command_count, 4);

        // Verify unicode commands are stored correctly
        let global_summary = tracker.get_global_summary().await.unwrap();
        assert!(global_summary.by_command.contains_key("分析代码"));
        assert!(global_summary.by_command.contains_key("анализ_кода"));
        assert!(global_summary.by_command.contains_key("コード解析"));
        assert!(global_summary.by_command.contains_key("🔍analyze🚀"));
    }

    #[tokio::test]
    async fn test_record_cost_large_values() {
        let fixture = CostTestFixture::new();
        let mut tracker = CostTracker::new(fixture.storage_path.clone()).unwrap();

        let session_id = Uuid::new_v4();
        let large_entry = CostEntry::new(
            session_id,
            "extremely_expensive_analysis".to_string(),
            999.999, // Very large cost
            1000000, // 1M input tokens
            2000000, // 2M output tokens
            3600000, // 1 hour duration
            "claude-3-opus-premium".to_string(),
        );

        tracker.record_cost(large_entry).await.unwrap();

        let summary = tracker.get_session_summary(session_id).await.unwrap();
        assert_eq!(summary.command_count, 1);
        assert!((summary.total_cost - 999.999).abs() < 0.00001);
        assert_eq!(summary.total_tokens, 3000000);
        assert!((summary.average_cost - 999.999).abs() < 0.00001);
    }

    #[tokio::test]
    async fn test_record_cost_precision() {
        let fixture = CostTestFixture::new();
        let mut tracker = CostTracker::new(fixture.storage_path.clone()).unwrap();

        let session_id = Uuid::new_v4();

        // Test with very small precise values
        let precise_entries = vec![0.00001, 0.00002, 0.00003, 0.00004, 0.00005];

        for (i, cost) in precise_entries.iter().enumerate() {
            let entry = CostEntry::new(
                session_id,
                format!("precise_cmd_{}", i),
                *cost,
                1,
                1,
                100,
                "claude-3-haiku".to_string(),
            );
            tracker.record_cost(entry).await.unwrap();
        }

        let summary = tracker.get_session_summary(session_id).await.unwrap();
        let expected_total: f64 = precise_entries.iter().sum();

        // Verify precision is maintained
        assert!((summary.total_cost - expected_total).abs() < 0.0000001);
        assert_eq!(summary.command_count, 5);
    }

    #[tokio::test]
    async fn test_record_cost_non_deduplication() {
        let fixture = CostTestFixture::new();
        let mut tracker = CostTracker::new(fixture.storage_path.clone()).unwrap();

        let session_id = Uuid::new_v4();

        // Record the same command multiple times (each with new ID)
        for _ in 0..3 {
            let entry = CostEntry::new(
                session_id,
                "test_command".to_string(),
                0.025,
                100,
                200,
                1500,
                "claude-3-opus".to_string(),
            );
            tracker.record_cost(entry).await.unwrap();
        }

        let summary = tracker.get_session_summary(session_id).await.unwrap();

        // Should have 3 separate entries (not deduplicated)
        assert_eq!(summary.command_count, 3);
        assert!((summary.total_cost - 0.075).abs() < 0.00001); // 3 * 0.025

        // Verify all entries have different IDs
        let session_entries: Vec<_> = tracker
            .entries
            .iter()
            .filter(|e| e.session_id == session_id)
            .collect();

        let entry_count = session_entries.len();
        let mut ids: std::collections::HashSet<String> = std::collections::HashSet::new();
        for entry in session_entries {
            ids.insert(entry.id.clone());
        }
        // Each entry should have a unique ID
        assert_eq!(ids.len(), entry_count);
        assert_eq!(ids.len(), 3);
    }

    proptest! {
        #[test]
        fn property_record_cost_maintains_invariants(
            cost in property_strategies::valid_cost(),
            input_tokens in property_strategies::valid_tokens(),
            output_tokens in property_strategies::valid_tokens(),
            duration in property_strategies::valid_duration(),
            command in property_strategies::command_name(),
            model in property_strategies::model_name(),
        ) {
            tokio_test::block_on(async {
                let fixture = CostTestFixture::new();
                let mut tracker = CostTracker::new(fixture.storage_path.clone()).unwrap();
                let session_id = Uuid::new_v4();

                let initial_count = tracker.entries.len();

                let entry = CostEntry::new(
                    session_id,
                    command,
                    cost,
                    input_tokens,
                    output_tokens,
                    duration,
                    model,
                );

                tracker.record_cost(entry.clone()).await.unwrap();

                // Invariants that should always hold after recording
                prop_assert_eq!(tracker.entries.len(), initial_count + 1);

                let summary = tracker.get_session_summary(session_id).await.unwrap();
                prop_assert_eq!(summary.command_count, 1);
                prop_assert!((summary.total_cost - cost).abs() < 0.00001);
                prop_assert_eq!(summary.total_tokens, input_tokens + output_tokens);

                if cost > 0.0 {
                    prop_assert!(summary.average_cost > 0.0);
                }

                Ok(())
            });
        }

        #[test]
        fn property_concurrent_recording_consistency(
            entries in prop::collection::vec(
                (
                    property_strategies::valid_cost(),
                    property_strategies::valid_tokens(),
                    property_strategies::valid_tokens(),
                    property_strategies::valid_duration(),
                    property_strategies::command_name(),
                    property_strategies::model_name(),
                ),
                1..20
            )
        ) {
            tokio_test::block_on(async {
                let fixture = CostTestFixture::new();
                let tracker = Arc::new(Mutex::new(CostTracker::new(fixture.storage_path.clone()).unwrap()));
                let session_id = Uuid::new_v4();

                let mut handles = vec![];
                let expected_total: f64 = entries.iter().map(|(cost, _, _, _, _, _)| cost).sum();

                for (i, (cost, input_tokens, output_tokens, duration, command, model)) in entries.into_iter().enumerate() {
                    let tracker_clone = Arc::clone(&tracker);
                    let handle = tokio::spawn(async move {
                        let entry = CostEntry::new(
                            session_id,
                            format!("{}_{}", command, i),
                            cost,
                            input_tokens,
                            output_tokens,
                            duration,
                            model,
                        );

                        let mut tracker_lock = tracker_clone.lock().await;
                        tracker_lock.record_cost(entry).await.unwrap();
                    });
                    handles.push(handle);
                }

                for handle in handles {
                    handle.await.unwrap();
                }

                let tracker_lock = tracker.lock().await;
                let summary = tracker_lock.get_session_summary(session_id).await.unwrap();

                prop_assert!((summary.total_cost - expected_total).abs() < 0.0001);

                Ok(())
            });
        }
    }
}

/// Tests for cost aggregation and analysis functionality (Task 1.3)
#[cfg(test)]
mod aggregation_analysis_tests {
    use super::*;
    use approx::assert_relative_eq;

    #[tokio::test]
    async fn test_cost_aggregation_by_session_multiple_entries() {
        let fixture = CostTestFixture::new();
        let mut tracker = CostTracker::new(fixture.storage_path.clone()).unwrap();

        let session1 = Uuid::new_v4();
        let session2 = Uuid::new_v4();

        // Add multiple entries for session1
        let session1_entries = vec![
            CostEntry::new(
                session1,
                "analyze".to_string(),
                0.10,
                100,
                200,
                1000,
                "claude-3-opus".to_string(),
            ),
            CostEntry::new(
                session1,
                "generate".to_string(),
                0.05,
                50,
                100,
                500,
                "claude-3-sonnet".to_string(),
            ),
            CostEntry::new(
                session1,
                "review".to_string(),
                0.03,
                30,
                60,
                300,
                "claude-3-haiku".to_string(),
            ),
        ];

        // Add entries for session2
        let session2_entries = vec![
            CostEntry::new(
                session2,
                "debug".to_string(),
                0.08,
                80,
                160,
                800,
                "claude-3-opus".to_string(),
            ),
            CostEntry::new(
                session2,
                "optimize".to_string(),
                0.12,
                120,
                240,
                1200,
                "claude-3-sonnet".to_string(),
            ),
        ];

        // Record all entries
        for entry in session1_entries.iter().chain(session2_entries.iter()) {
            tracker.record_cost(entry.clone()).await.unwrap();
        }

        // Test session1 aggregation
        let summary1 = tracker.get_session_summary(session1).await.unwrap();
        assert_eq!(summary1.command_count, 3);
        assert_relative_eq!(summary1.total_cost, 0.18, epsilon = 0.00001); // 0.10 + 0.05 + 0.03
        assert_relative_eq!(summary1.average_cost, 0.06, epsilon = 0.00001); // 0.18 / 3
        assert_eq!(summary1.total_tokens, 540); // (100+200) + (50+100) + (30+60)
        assert_eq!(summary1.by_command.len(), 3);
        assert_eq!(summary1.by_model.len(), 3);

        // Test session2 aggregation
        let summary2 = tracker.get_session_summary(session2).await.unwrap();
        assert_eq!(summary2.command_count, 2);
        assert_relative_eq!(summary2.total_cost, 0.20, epsilon = 0.00001); // 0.08 + 0.12
        assert_relative_eq!(summary2.average_cost, 0.10, epsilon = 0.00001); // 0.20 / 2
        assert_eq!(summary2.total_tokens, 600); // (80+160) + (120+240)
        assert_eq!(summary2.by_command.len(), 2);
        assert_eq!(summary2.by_model.len(), 2);

        // Verify command breakdowns
        assert_relative_eq!(summary1.by_command["analyze"], 0.10, epsilon = 0.00001);
        assert_relative_eq!(summary1.by_command["generate"], 0.05, epsilon = 0.00001);
        assert_relative_eq!(summary1.by_command["review"], 0.03, epsilon = 0.00001);

        assert_relative_eq!(summary2.by_command["debug"], 0.08, epsilon = 0.00001);
        assert_relative_eq!(summary2.by_command["optimize"], 0.12, epsilon = 0.00001);
    }

    #[tokio::test]
    async fn test_cost_aggregation_by_time_periods() {
        let fixture = CostTestFixture::with_time_series_data(30); // 30 days of data
        let tracker = fixture.create_tracker().await;

        let now = Utc::now();

        // Test daily aggregation (last 24 hours)
        let daily_filter = CostFilter {
            since: Some(now - Duration::days(1)),
            until: Some(now),
            ..Default::default()
        };
        let daily_summary = tracker.get_filtered_summary(&daily_filter).await.unwrap();

        // Test weekly aggregation (last 7 days)
        let weekly_filter = CostFilter {
            since: Some(now - Duration::days(7)),
            until: Some(now),
            ..Default::default()
        };
        let weekly_summary = tracker.get_filtered_summary(&weekly_filter).await.unwrap();

        // Test monthly aggregation (last 30 days)
        let monthly_filter = CostFilter {
            since: Some(now - Duration::days(30)),
            until: Some(now),
            ..Default::default()
        };
        let monthly_summary = tracker.get_filtered_summary(&monthly_filter).await.unwrap();

        // Verify hierarchical relationship: daily <= weekly <= monthly
        assert!(daily_summary.command_count <= weekly_summary.command_count);
        assert!(weekly_summary.command_count <= monthly_summary.command_count);

        assert!(daily_summary.total_cost <= weekly_summary.total_cost);
        assert!(weekly_summary.total_cost <= monthly_summary.total_cost);

        // Monthly should have all 90 entries (30 days * 3 entries per day)
        assert_eq!(monthly_summary.command_count, 90);

        // Verify weekly has entries from last 7 days (21 entries)
        assert_eq!(weekly_summary.command_count, 21);

        // Daily should have entries from today (3 entries if today is included)
        assert!(daily_summary.command_count <= 3);
    }

    #[tokio::test]
    async fn test_cost_filtering_by_date_ranges() {
        let fixture = CostTestFixture::new();
        let mut tracker = CostTracker::new(fixture.storage_path.clone()).unwrap();

        let session_id = Uuid::new_v4();
        let base_time = Utc::now() - Duration::days(10);

        // Create entries with specific timestamps
        let mut entries = vec![];
        for i in 0..10 {
            let mut entry = CostEntry::new(
                session_id,
                format!("day_{}_cmd", i),
                0.01 * (i + 1) as f64,
                10 * (i + 1) as u32,
                20 * (i + 1) as u32,
                100 * (i + 1) as u64,
                "claude-3-opus".to_string(),
            );
            entry.timestamp = base_time + Duration::days(i as i64);
            entries.push(entry);
        }

        for entry in entries {
            tracker.record_cost(entry).await.unwrap();
        }

        // Test filtering middle range (days 3-7)
        let mid_start = base_time + Duration::days(3);
        let mid_end = base_time + Duration::days(7);
        let mid_filter = CostFilter {
            since: Some(mid_start),
            until: Some(mid_end),
            ..Default::default()
        };
        let mid_summary = tracker.get_filtered_summary(&mid_filter).await.unwrap();

        assert_eq!(mid_summary.command_count, 5); // Days 3, 4, 5, 6, 7
        let expected_mid_cost: f64 = (4..=8).map(|i| 0.01 * i as f64).sum(); // 0.04 + 0.05 + 0.06 + 0.07 + 0.08
        assert_relative_eq!(mid_summary.total_cost, expected_mid_cost, epsilon = 0.00001);

        // Test filtering exact day
        let exact_day_start = base_time + Duration::days(5);
        let exact_day_end = exact_day_start + Duration::hours(23) + Duration::minutes(59);
        let exact_filter = CostFilter {
            since: Some(exact_day_start),
            until: Some(exact_day_end),
            ..Default::default()
        };
        let exact_summary = tracker.get_filtered_summary(&exact_filter).await.unwrap();

        assert_eq!(exact_summary.command_count, 1);
        assert_relative_eq!(exact_summary.total_cost, 0.06, epsilon = 0.00001);

        // Test filtering with inclusive boundaries
        let inclusive_filter = CostFilter {
            since: Some(base_time),
            until: Some(base_time + Duration::days(9)),
            ..Default::default()
        };
        let inclusive_summary = tracker
            .get_filtered_summary(&inclusive_filter)
            .await
            .unwrap();

        assert_eq!(inclusive_summary.command_count, 10); // All entries
        let expected_total: f64 = (1..=10).map(|i| 0.01 * i as f64).sum();
        assert_relative_eq!(
            inclusive_summary.total_cost,
            expected_total,
            epsilon = 0.00001
        );
    }

    #[tokio::test]
    async fn test_cost_filtering_edge_cases() {
        let fixture = CostTestFixture::new();
        let mut tracker = CostTracker::new(fixture.storage_path.clone()).unwrap();

        let session_id = Uuid::new_v4();
        let now = Utc::now();

        // Add some test entries
        for i in 0..5 {
            let mut entry = CostEntry::new(
                session_id,
                format!("test_cmd_{}", i),
                0.01 * (i + 1) as f64,
                10 * (i + 1) as u32,
                20 * (i + 1) as u32,
                100 * (i + 1) as u64,
                "claude-3-opus".to_string(),
            );
            entry.timestamp = now - Duration::hours(i as i64);
            tracker.record_cost(entry).await.unwrap();
        }

        // Test empty date range (since > until)
        let invalid_filter = CostFilter {
            since: Some(now),
            until: Some(now - Duration::hours(1)),
            ..Default::default()
        };
        let invalid_summary = tracker.get_filtered_summary(&invalid_filter).await.unwrap();
        assert_eq!(invalid_summary.command_count, 0);
        assert_eq!(invalid_summary.total_cost, 0.0);

        // Test future date range
        let future_filter = CostFilter {
            since: Some(now + Duration::hours(1)),
            until: Some(now + Duration::hours(2)),
            ..Default::default()
        };
        let future_summary = tracker.get_filtered_summary(&future_filter).await.unwrap();
        assert_eq!(future_summary.command_count, 0);

        // Test very old date range
        let old_filter = CostFilter {
            since: Some(now - Duration::days(365)),
            until: Some(now - Duration::days(364)),
            ..Default::default()
        };
        let old_summary = tracker.get_filtered_summary(&old_filter).await.unwrap();
        assert_eq!(old_summary.command_count, 0);

        // Test exact timestamp boundary
        let first_entry_time = now;
        let boundary_filter = CostFilter {
            since: Some(first_entry_time),
            until: Some(first_entry_time),
            ..Default::default()
        };
        let boundary_summary = tracker
            .get_filtered_summary(&boundary_filter)
            .await
            .unwrap();
        assert_eq!(boundary_summary.command_count, 1); // Should include exact match

        // Test microsecond precision
        let precise_start = now - Duration::microseconds(1);
        let precise_end = now + Duration::microseconds(1);
        let precise_filter = CostFilter {
            since: Some(precise_start),
            until: Some(precise_end),
            ..Default::default()
        };
        let precise_summary = tracker.get_filtered_summary(&precise_filter).await.unwrap();
        assert_eq!(precise_summary.command_count, 1);
    }

    #[tokio::test]
    async fn test_cost_aggregation_by_command_name() {
        let fixture = CostTestFixture::new();
        let mut tracker = CostTracker::new(fixture.storage_path.clone()).unwrap();

        let session_id = Uuid::new_v4();

        // Add multiple entries for same commands
        let entries = vec![
            // Multiple "analyze" commands
            CostEntry::new(
                session_id,
                "analyze".to_string(),
                0.10,
                100,
                200,
                1000,
                "claude-3-opus".to_string(),
            ),
            CostEntry::new(
                session_id,
                "analyze".to_string(),
                0.15,
                150,
                300,
                1500,
                "claude-3-opus".to_string(),
            ),
            CostEntry::new(
                session_id,
                "analyze".to_string(),
                0.08,
                80,
                160,
                800,
                "claude-3-sonnet".to_string(),
            ),
            // Multiple "generate" commands
            CostEntry::new(
                session_id,
                "generate".to_string(),
                0.05,
                50,
                100,
                500,
                "claude-3-haiku".to_string(),
            ),
            CostEntry::new(
                session_id,
                "generate".to_string(),
                0.07,
                70,
                140,
                700,
                "claude-3-sonnet".to_string(),
            ),
            // Single "review" command
            CostEntry::new(
                session_id,
                "review".to_string(),
                0.03,
                30,
                60,
                300,
                "claude-3-haiku".to_string(),
            ),
        ];

        for entry in entries {
            tracker.record_cost(entry).await.unwrap();
        }

        let summary = tracker.get_session_summary(session_id).await.unwrap();

        // Verify command aggregation
        assert_eq!(summary.by_command.len(), 3);
        assert_relative_eq!(summary.by_command["analyze"], 0.33, epsilon = 0.00001); // 0.10 + 0.15 + 0.08
        assert_relative_eq!(summary.by_command["generate"], 0.12, epsilon = 0.00001); // 0.05 + 0.07
        assert_relative_eq!(summary.by_command["review"], 0.03, epsilon = 0.00001);

        // Verify model aggregation
        assert_eq!(summary.by_model.len(), 3);
        assert_relative_eq!(summary.by_model["claude-3-opus"], 0.25, epsilon = 0.00001); // 0.10 + 0.15
        assert_relative_eq!(summary.by_model["claude-3-sonnet"], 0.15, epsilon = 0.00001); // 0.08 + 0.07
        assert_relative_eq!(summary.by_model["claude-3-haiku"], 0.08, epsilon = 0.00001); // 0.05 + 0.03

        // Test top commands functionality
        let top_commands = tracker.get_top_commands(5).await.unwrap();
        assert_eq!(top_commands.len(), 3);
        assert_eq!(top_commands[0].0, "analyze"); // Most expensive
        assert_relative_eq!(top_commands[0].1, 0.33, epsilon = 0.00001);
        assert_eq!(top_commands[1].0, "generate");
        assert_relative_eq!(top_commands[1].1, 0.12, epsilon = 0.00001);
        assert_eq!(top_commands[2].0, "review"); // Least expensive
        assert_relative_eq!(top_commands[2].1, 0.03, epsilon = 0.00001);
    }

    #[tokio::test]
    async fn test_cost_aggregation_by_model_types() {
        let fixture = CostTestFixture::new();
        let mut tracker = CostTracker::new(fixture.storage_path.clone()).unwrap();

        let session_id = Uuid::new_v4();

        // Create entries with different model costs to reflect realistic pricing
        let entries = vec![
            // Opus entries (highest cost)
            CostEntry::new(
                session_id,
                "complex_analysis".to_string(),
                0.50,
                500,
                1000,
                5000,
                "claude-3-opus".to_string(),
            ),
            CostEntry::new(
                session_id,
                "deep_review".to_string(),
                0.60,
                600,
                1200,
                6000,
                "claude-3-opus".to_string(),
            ),
            // Sonnet entries (medium cost)
            CostEntry::new(
                session_id,
                "standard_task".to_string(),
                0.20,
                200,
                400,
                2000,
                "claude-3-sonnet".to_string(),
            ),
            CostEntry::new(
                session_id,
                "balanced_work".to_string(),
                0.25,
                250,
                500,
                2500,
                "claude-3-sonnet".to_string(),
            ),
            CostEntry::new(
                session_id,
                "routine_check".to_string(),
                0.15,
                150,
                300,
                1500,
                "claude-3-sonnet".to_string(),
            ),
            // Haiku entries (lowest cost)
            CostEntry::new(
                session_id,
                "quick_task".to_string(),
                0.05,
                50,
                100,
                500,
                "claude-3-haiku".to_string(),
            ),
            CostEntry::new(
                session_id,
                "simple_query".to_string(),
                0.03,
                30,
                60,
                300,
                "claude-3-haiku".to_string(),
            ),
            CostEntry::new(
                session_id,
                "fast_check".to_string(),
                0.04,
                40,
                80,
                400,
                "claude-3-haiku".to_string(),
            ),
            CostEntry::new(
                session_id,
                "basic_task".to_string(),
                0.02,
                20,
                40,
                200,
                "claude-3-haiku".to_string(),
            ),
        ];

        for entry in entries {
            tracker.record_cost(entry).await.unwrap();
        }

        let summary = tracker.get_session_summary(session_id).await.unwrap();

        // Verify model cost aggregation
        assert_eq!(summary.by_model.len(), 3);
        assert_relative_eq!(summary.by_model["claude-3-opus"], 1.10, epsilon = 0.00001); // 0.50 + 0.60
        assert_relative_eq!(summary.by_model["claude-3-sonnet"], 0.60, epsilon = 0.00001); // 0.20 + 0.25 + 0.15
        assert_relative_eq!(summary.by_model["claude-3-haiku"], 0.14, epsilon = 0.00001); // 0.05 + 0.03 + 0.04 + 0.02

        // Verify total cost
        assert_relative_eq!(summary.total_cost, 1.84, epsilon = 0.00001); // 1.10 + 0.60 + 0.14

        // Verify command count distribution
        assert_eq!(summary.command_count, 9);

        // Test cost ratio analysis
        let opus_ratio = summary.by_model["claude-3-opus"] / summary.total_cost;
        let sonnet_ratio = summary.by_model["claude-3-sonnet"] / summary.total_cost;
        let haiku_ratio = summary.by_model["claude-3-haiku"] / summary.total_cost;

        assert!(opus_ratio > sonnet_ratio); // Opus should be most expensive
        assert!(sonnet_ratio > haiku_ratio); // Sonnet should be medium cost
        assert_relative_eq!(
            opus_ratio + sonnet_ratio + haiku_ratio,
            1.0,
            epsilon = 0.00001
        );
    }

    #[tokio::test]
    async fn test_global_vs_session_aggregation() {
        let fixture = CostTestFixture::new();
        let mut tracker = CostTracker::new(fixture.storage_path.clone()).unwrap();

        // Create multiple sessions
        let sessions = vec![Uuid::new_v4(), Uuid::new_v4(), Uuid::new_v4()];

        let mut total_expected_cost = 0.0;
        let mut total_expected_commands = 0;

        // Add entries for each session
        for (session_index, &session_id) in sessions.iter().enumerate() {
            for cmd_index in 0..5 {
                let cost = 0.01 * ((session_index * 5 + cmd_index) + 1) as f64;
                let entry = CostEntry::new(
                    session_id,
                    format!("s{}_cmd_{}", session_index, cmd_index),
                    cost,
                    10 * (cmd_index + 1) as u32,
                    20 * (cmd_index + 1) as u32,
                    100 * (cmd_index + 1) as u64,
                    format!("model_{}", cmd_index % 3),
                );
                tracker.record_cost(entry).await.unwrap();
                total_expected_cost += cost;
                total_expected_commands += 1;
            }
        }

        // Test global aggregation
        let global_summary = tracker.get_global_summary().await.unwrap();
        assert_eq!(global_summary.command_count, total_expected_commands);
        assert_relative_eq!(
            global_summary.total_cost,
            total_expected_cost,
            epsilon = 0.00001
        );
        assert_relative_eq!(
            global_summary.average_cost,
            total_expected_cost / total_expected_commands as f64,
            epsilon = 0.00001
        );

        // Test individual session aggregations
        let mut sum_of_session_costs = 0.0;
        let mut sum_of_session_commands = 0;

        for (session_index, &session_id) in sessions.iter().enumerate() {
            let session_summary = tracker.get_session_summary(session_id).await.unwrap();
            assert_eq!(session_summary.command_count, 5);

            // Verify session cost calculation
            let session_expected_cost: f64 = (0..5)
                .map(|cmd_index| 0.01 * ((session_index * 5 + cmd_index) + 1) as f64)
                .sum();
            assert_relative_eq!(
                session_summary.total_cost,
                session_expected_cost,
                epsilon = 0.00001
            );

            sum_of_session_costs += session_summary.total_cost;
            sum_of_session_commands += session_summary.command_count;
        }

        // Verify that sum of sessions equals global
        assert_relative_eq!(
            sum_of_session_costs,
            global_summary.total_cost,
            epsilon = 0.00001
        );
        assert_eq!(sum_of_session_commands, global_summary.command_count);

        // Verify global command breakdown includes all sessions
        assert_eq!(global_summary.by_command.len(), 15); // 3 sessions * 5 commands each
    }

    #[tokio::test]
    async fn test_cost_aggregation_with_empty_results() {
        let fixture = CostTestFixture::new();
        let tracker = CostTracker::new(fixture.storage_path.clone()).unwrap();

        let empty_session_id = Uuid::new_v4();

        // Test aggregation on empty session
        let empty_summary = tracker.get_session_summary(empty_session_id).await.unwrap();
        assert_eq!(empty_summary.command_count, 0);
        assert_eq!(empty_summary.total_cost, 0.0);
        assert_eq!(empty_summary.average_cost, 0.0);
        assert_eq!(empty_summary.total_tokens, 0);
        assert!(empty_summary.by_command.is_empty());
        assert!(empty_summary.by_model.is_empty());

        // Test global aggregation on empty tracker
        let global_empty = tracker.get_global_summary().await.unwrap();
        assert_eq!(global_empty.command_count, 0);
        assert_eq!(global_empty.total_cost, 0.0);
        assert_eq!(global_empty.average_cost, 0.0);
        assert_eq!(global_empty.total_tokens, 0);

        // Test filtered aggregation with no matches
        let no_match_filter = CostFilter {
            command_pattern: Some("nonexistent_command".to_string()),
            ..Default::default()
        };
        let no_match_summary = tracker
            .get_filtered_summary(&no_match_filter)
            .await
            .unwrap();
        assert_eq!(no_match_summary.command_count, 0);
        assert_eq!(no_match_summary.total_cost, 0.0);

        // Test top commands on empty tracker
        let top_commands = tracker.get_top_commands(10).await.unwrap();
        assert!(top_commands.is_empty());
    }

    #[tokio::test]
    async fn test_cost_aggregation_precision_with_large_datasets() {
        let fixture = CostTestFixture::with_large_dataset(1000);
        let tracker = fixture.create_tracker().await;

        let global_summary = tracker.get_global_summary().await.unwrap();

        // Verify aggregation consistency with large dataset
        assert_eq!(global_summary.command_count, 1000);

        // Calculate expected total manually
        let expected_total: f64 = (0..1000).map(|i| 0.001 + (i as f64 * 0.001)).sum();
        assert_relative_eq!(global_summary.total_cost, expected_total, epsilon = 0.001);

        // Verify average calculation
        let expected_average = expected_total / 1000.0;
        assert_relative_eq!(
            global_summary.average_cost,
            expected_average,
            epsilon = 0.001
        );

        // Verify token calculation
        let expected_tokens: u32 = (0..1000)
            .map(|i| (10 + (i as u32 * 5)) + (20 + (i as u32 * 10)))
            .sum();
        assert_eq!(global_summary.total_tokens, expected_tokens);

        // Test that aggregation performs well with large dataset
        let start = std::time::Instant::now();
        let _summary = tracker.get_global_summary().await.unwrap();
        let duration = start.elapsed();

        // Should complete aggregation quickly
        assert!(duration.as_millis() < 100);
    }

    proptest! {
        #[test]
        fn property_aggregation_consistency(
            entries in prop::collection::vec(
                (
                    property_strategies::valid_cost(),
                    property_strategies::valid_tokens(),
                    property_strategies::valid_tokens(),
                    property_strategies::command_name(),
                    property_strategies::model_name(),
                ),
                1..50
            )
        ) {
            let _ = tokio_test::block_on(async {
                let fixture = CostTestFixture::new();
                let mut tracker = CostTracker::new(fixture.storage_path.clone()).unwrap();
                let session_id = Uuid::new_v4();

                let mut expected_total_cost = 0.0;
                let mut expected_total_tokens = 0u32;

                for (i, (cost, input_tokens, output_tokens, command, model)) in entries.into_iter().enumerate() {
                    let entry = CostEntry::new(
                        session_id,
                        format!("{}_{}", command, i),
                        cost,
                        input_tokens,
                        output_tokens,
                        1000,
                        model,
                    );

                    tracker.record_cost(entry).await.unwrap();
                    expected_total_cost += cost;
                    expected_total_tokens += input_tokens + output_tokens;
                }

                let summary = tracker.get_session_summary(session_id).await.unwrap();

                // Verify aggregation properties
                prop_assert!((summary.total_cost - expected_total_cost).abs() < 0.001);
                prop_assert_eq!(summary.total_tokens, expected_total_tokens);

                if summary.command_count > 0 {
                    prop_assert!((summary.average_cost - (expected_total_cost / summary.command_count as f64)).abs() < 0.001);
                }

                // Verify that by_command total equals session total
                let command_total: f64 = summary.by_command.values().sum();
                prop_assert!((command_total - summary.total_cost).abs() < 0.001);

                // Verify that by_model total equals session total
                let model_total: f64 = summary.by_model.values().sum();
                prop_assert!((model_total - summary.total_cost).abs() < 0.001);

                Ok(())
            });
        }

        #[test]
        fn property_filtering_subset_consistency(
            cost_filter in 0.001f64..1.0f64,
            token_filter in 1u32..1000u32,
        ) {
            let _ = tokio_test::block_on(async {
                let fixture = CostTestFixture::new();
                let mut tracker = CostTracker::new(fixture.storage_path.clone()).unwrap();
                let session_id = Uuid::new_v4();

                // Add test entries with varying costs and tokens
                for i in 0..20 {
                    let entry = CostEntry::new(
                        session_id,
                        format!("cmd_{}", i),
                        0.01 * (i + 1) as f64,
                        10 * (i + 1) as u32,
                        20 * (i + 1) as u32,
                        1000,
                        "claude-3-opus".to_string(),
                    );
                    tracker.record_cost(entry).await.unwrap();
                }

                // Get global summary
                let global_summary = tracker.get_global_summary().await.unwrap();

                // Apply cost filter
                let cost_filtered = CostFilter {
                    min_cost: Some(cost_filter),
                    ..Default::default()
                };
                let filtered_summary = tracker.get_filtered_summary(&cost_filtered).await.unwrap();

                // Filtered results should be subset of global
                prop_assert!(filtered_summary.command_count <= global_summary.command_count);
                prop_assert!(filtered_summary.total_cost <= global_summary.total_cost);
                prop_assert!(filtered_summary.total_tokens <= global_summary.total_tokens);

                // All filtered costs should meet minimum threshold
                for entry in tracker.get_entries(&cost_filtered).await.unwrap() {
                    prop_assert!(entry.cost_usd >= cost_filter);
                }

                Ok(())
            });
        }
    }
}