aletheiadb 0.1.0

A high-performance bi-temporal graph database for LLM integration
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
//! Strongly-typed ID types for graph elements.
//!
//! This module provides distinct types for different kinds of identifiers to prevent
//! mix-ups at compile time. For example, you cannot accidentally pass a `NodeId` where
//! an `EdgeId` is expected.

use crate::core::error::StorageError;
use std::fmt;
use std::sync::atomic::{AtomicU64, Ordering};

/// Maximum valid ID value. Values above this are reserved.
///
/// This prevents potential DoS attacks where malicious code creates IDs with
/// extreme values (like u64::MAX) that could cause issues in:
/// - Arithmetic operations (addition/subtraction with IDs)
/// - Array indexing or allocation attempts
/// - Serialization buffer sizing
///
/// The reserved range of 1000 values provides a safety margin without meaningfully
/// restricting the ID space (you can still have ~18 quintillion valid IDs).
pub const MAX_VALID_ID: u64 = u64::MAX - 1000;

/// Unique identifier for a node in the graph.
///
/// # The Spark
/// Graph databases run on connections, and every connection needs an anchor.
/// `NodeId` acts as this unique anchor. We strongly type this instead of using a
/// raw `u64` so that you cannot accidentally pass an edge ID to a function
/// expecting a node ID.
///
/// # Examples
/// ```
/// use aletheiadb::core::NodeId;
/// let node_id = NodeId::new(42).unwrap();
/// assert_eq!(node_id.as_u64(), 42);
/// ```
#[derive(
    Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, bytemuck::Pod, bytemuck::Zeroable,
)]
#[repr(transparent)]
pub struct NodeId(u64);

impl NodeId {
    /// Create a new NodeId from a u64 value with validation.
    ///
    /// # The Spark
    /// Graph databases run on connections, and every connection needs an anchor.
    /// `NodeId` acts as this unique anchor. We strongly type this instead of using a
    /// raw `u64` so that you cannot accidentally pass an edge ID to a function
    /// expecting a node ID.
    ///
    /// # The Details
    /// Creating a valid `NodeId` requires validation. The inner `u64` must not exceed
    /// [`MAX_VALID_ID`]. This reserved space prevents potential DoS attacks during
    /// vector resizing or memory allocation.
    ///
    /// # Errors
    /// Returns [`StorageError::InvalidId`] if the provided `id` exceeds [`MAX_VALID_ID`].
    ///
    /// # Examples
    ///
    /// ```
    /// use aletheiadb::core::id::NodeId;
    ///
    /// // Valid ID
    /// let id = NodeId::new(42).unwrap();
    /// assert_eq!(id.as_u64(), 42);
    /// ```
    #[inline]
    pub fn new(id: u64) -> Result<Self, StorageError> {
        if id > MAX_VALID_ID {
            return Err(StorageError::InvalidId {
                id,
                id_type: "node",
            });
        }
        Ok(NodeId(id))
    }

    /// Create a new NodeId without validation (for internal use only).
    ///
    /// # Internal Use Only
    /// This function bypasses validation. Only use when you're certain the ID is valid,
    /// such as when loading from trusted storage or in performance-critical paths where
    /// validation has already occurred.
    #[inline]
    pub(crate) const fn new_unchecked(id: u64) -> Self {
        NodeId(id)
    }

    /// Get the inner u64 value.
    #[inline]
    pub const fn as_u64(self) -> u64 {
        self.0
    }
}

impl fmt::Display for NodeId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Node({})", self.0)
    }
}

/// Unique identifier for an edge in the graph.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[repr(transparent)]
pub struct EdgeId(u64);

impl EdgeId {
    /// Create a new EdgeId from a u64 value with validation.
    ///
    /// # The Spark
    /// Edges are the relationships that give a graph its meaning.
    /// `EdgeId` provides a unique identifier for these relationships. We strongly type
    /// this instead of using a raw `u64` to prevent accidentally mixing up node and
    /// edge identifiers, which would cause silent corruption or mapping failures.
    ///
    /// # The Details
    /// Creating a valid `EdgeId` requires validation. The inner `u64` must not exceed
    /// [`MAX_VALID_ID`]. This reserved space prevents potential DoS attacks during
    /// vector resizing or memory allocation.
    ///
    /// # Errors
    /// Returns [`StorageError::InvalidId`] if the provided `id` exceeds [`MAX_VALID_ID`].
    ///
    /// # Examples
    ///
    /// ```
    /// use aletheiadb::core::id::EdgeId;
    ///
    /// // Valid ID
    /// let id = EdgeId::new(42).unwrap();
    /// assert_eq!(id.as_u64(), 42);
    /// ```
    #[inline]
    pub fn new(id: u64) -> Result<Self, StorageError> {
        if id > MAX_VALID_ID {
            return Err(StorageError::InvalidId {
                id,
                id_type: "edge",
            });
        }
        Ok(EdgeId(id))
    }

    /// Create a new EdgeId without validation (for internal use only).
    ///
    /// # Internal Use Only
    /// This function bypasses validation. Only use when you're certain the ID is valid,
    /// such as when loading from trusted storage or in performance-critical paths where
    /// validation has already occurred.
    #[inline]
    pub(crate) const fn new_unchecked(id: u64) -> Self {
        EdgeId(id)
    }

    /// Get the inner u64 value.
    #[inline]
    pub const fn as_u64(self) -> u64 {
        self.0
    }
}

impl fmt::Display for EdgeId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Edge({})", self.0)
    }
}

/// Unique identifier for a version of a node or edge.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[repr(transparent)]
pub struct VersionId(u64);

impl VersionId {
    /// Create a new VersionId from a u64 value with validation.
    ///
    /// # The Spark
    /// AletheiaDB allows traversing time, not just data.
    /// `VersionId` provides an anchor in this temporal dimension. It's a strongly
    /// typed identifier so that historical snapshots cannot be confused with spatial
    /// entities like nodes or edges.
    ///
    /// # The Details
    /// Creating a valid `VersionId` requires validation. The inner `u64` must not exceed
    /// [`MAX_VALID_ID`]. This reserved space prevents potential DoS attacks during
    /// vector resizing or memory allocation.
    ///
    /// # Errors
    /// Returns [`StorageError::InvalidId`] if the provided `id` exceeds [`MAX_VALID_ID`].
    ///
    /// # Examples
    ///
    /// ```
    /// use aletheiadb::core::id::VersionId;
    ///
    /// // Valid ID
    /// let id = VersionId::new(42).unwrap();
    /// assert_eq!(id.as_u64(), 42);
    /// ```
    #[inline]
    pub fn new(id: u64) -> Result<Self, StorageError> {
        if id > MAX_VALID_ID {
            return Err(StorageError::InvalidId {
                id,
                id_type: "version",
            });
        }
        Ok(VersionId(id))
    }

    /// Create a new VersionId without validation (for internal use only).
    ///
    /// # Internal Use Only
    /// This function bypasses validation. Only use when you're certain the ID is valid,
    /// such as when loading from trusted storage or in performance-critical paths where
    /// validation has already occurred.
    #[inline]
    pub(crate) const fn new_unchecked(id: u64) -> Self {
        VersionId(id)
    }

    /// Get the inner u64 value.
    #[inline]
    pub const fn as_u64(self) -> u64 {
        self.0
    }
}

impl fmt::Display for VersionId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Version({})", self.0)
    }
}

/// Represents either a node or an edge identifier.
///
/// Useful for operations that work with both nodes and edges.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum EntityId {
    /// Node entity variant
    Node(NodeId),
    /// Edge entity variant
    Edge(EdgeId),
}

impl EntityId {
    /// Returns true if this is a node ID.
    #[inline]
    pub const fn is_node(&self) -> bool {
        matches!(self, EntityId::Node(_))
    }

    /// Returns true if this is an edge ID.
    #[inline]
    pub const fn is_edge(&self) -> bool {
        matches!(self, EntityId::Edge(_))
    }

    /// Returns the inner NodeId if this is a node, None otherwise.
    #[inline]
    pub const fn as_node(&self) -> Option<NodeId> {
        match self {
            EntityId::Node(id) => Some(*id),
            EntityId::Edge(_) => None,
        }
    }

    /// Returns the inner EdgeId if this is an edge, None otherwise.
    #[inline]
    pub const fn as_edge(&self) -> Option<EdgeId> {
        match self {
            EntityId::Node(_) => None,
            EntityId::Edge(id) => Some(*id),
        }
    }
}

impl fmt::Display for EntityId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            EntityId::Node(id) => write!(f, "{}", id),
            EntityId::Edge(id) => write!(f, "{}", id),
        }
    }
}

impl From<NodeId> for EntityId {
    fn from(id: NodeId) -> Self {
        EntityId::Node(id)
    }
}

impl From<EdgeId> for EntityId {
    fn from(id: EdgeId) -> Self {
        EntityId::Edge(id)
    }
}

/// Atomic ID generator for creating unique IDs.
///
/// This is thread-safe and can be used concurrently without external synchronization.
/// A thread-safe generator for strictly increasing element IDs (nodes/edges).
///
/// # The Spark
/// When creating new nodes or edges, we need a way to assign them unique identifiers
/// safely across multiple threads. `IdGenerator` handles this via atomic counters.
///
/// # Examples
/// ```
/// use aletheiadb::core::IdGenerator;
/// let generator = IdGenerator::new();
/// let first_id = generator.next().unwrap();
/// let second_id = generator.next().unwrap();
/// assert_eq!(first_id, 0);
/// assert_eq!(second_id, 1);
/// ```
pub struct IdGenerator {
    next_id: AtomicU64,
}

impl IdGenerator {
    /// Create a new ID generator starting from 0.
    pub const fn new() -> Self {
        IdGenerator {
            next_id: AtomicU64::new(0),
        }
    }

    /// Create a new ID generator starting from a specific value.
    pub const fn with_start(start: u64) -> Self {
        IdGenerator {
            next_id: AtomicU64::new(start),
        }
    }

    /// Generate the next unique ID.
    ///
    /// This method is thread-safe and lock-free.
    ///
    /// Returns an error if the generator would exceed `MAX_VALID_ID`. In practice, this requires
    /// ~18 quintillion operations and is unrealistic for a single database instance.
    ///
    /// # Memory Ordering
    ///
    /// Uses `Ordering::SeqCst` (sequentially consistent) to ensure:
    /// - **Cross-thread visibility**: All threads observe ID operations in a globally consistent order
    /// - **Uniqueness guarantee**: No two threads can receive the same ID value
    /// - **Monotonicity**: IDs are strictly increasing across all threads
    ///
    /// While `Ordering::AcqRel` could provide atomicity, `SeqCst` offers the strongest correctness
    /// guarantees for ID generation. The ~5-10% performance overhead is acceptable because:
    /// 1. ID generation is infrequent compared to ID lookups (not a hot path)
    /// 2. Correctness is prioritized over micro-optimizations in ID allocation
    /// 3. The cost is per-ID, not per-operation on the graph
    ///
    /// See [issue #21](https://github.com/madmax983/AletheiaDB/issues/21) for context.
    #[inline]
    pub fn next(&self) -> Result<u64, StorageError> {
        let id = self.next_id.fetch_add(1, Ordering::SeqCst);
        if id > MAX_VALID_ID {
            return Err(StorageError::InvalidId {
                id,
                id_type: "generated",
            });
        }
        Ok(id)
    }

    /// Get the current value without incrementing.
    ///
    /// # Memory Ordering
    ///
    /// Uses `Ordering::SeqCst` to maintain consistency with `next()`, ensuring all threads
    /// observe the same global order of ID operations. This provides a consistent snapshot
    /// of the next ID that will be allocated.
    #[inline]
    pub fn current(&self) -> u64 {
        self.next_id.load(Ordering::SeqCst)
    }

    /// Get an approximate current value without incrementing, optimized for non-critical use cases.
    ///
    /// This method provides a **relaxed** view of the current ID counter, trading strict
    /// consistency for ~10x better performance (~1ns vs ~10ns per call). The returned value
    /// may be slightly stale due to relaxed memory ordering.
    ///
    /// # Memory Ordering
    ///
    /// Uses `Ordering::Relaxed` which provides:
    /// - **No cross-thread synchronization**: Different threads may observe updates in different orders
    /// - **No happens-before guarantees**: The value may not reflect recent writes from other threads
    /// - **Atomicity only**: Reads are atomic but may see stale values
    ///
    /// This is **significantly faster** than `current()` because it avoids the cross-core
    /// synchronization overhead of sequential consistency. On modern hardware:
    /// - `current_approximate()`: ~1ns (relaxed load)
    /// - `current()`: ~5-10ns (SeqCst load with full memory barrier)
    ///
    /// # When to Use
    ///
    /// **✓ Safe and appropriate for:**
    /// - **Metrics collection**: Counting operations, tracking rates (`operations_per_second`)
    /// - **Progress indicators**: Displaying approximate progress (`"Processed ~1.2M items..."`)
    /// - **Debugging/logging**: Non-critical diagnostics (`debug!("Current ID: ~{}", id)`)
    /// - **Approximate counts**: Where exact accuracy isn't required (`"~500 items remaining"`)
    /// - **Performance monitoring**: Low-overhead instrumentation
    ///
    /// **✗ DO NOT use for:**
    /// - **Snapshot isolation decisions**: Use `current()` for MVCC/transaction visibility
    /// - **Transaction visibility**: Determining what data a transaction can see
    /// - **Correctness-critical paths**: Where stale values could cause incorrect behavior
    /// - **Consistency guarantees**: Where you need a globally consistent view across threads
    /// - **Synchronization**: Coordinating between threads (use proper synchronization primitives)
    ///
    /// # Example: Metrics Collection
    ///
    /// ```rust
    /// # use aletheiadb::core::id::IdGenerator;
    /// let generator = IdGenerator::new();
    ///
    /// // In a metrics reporting loop (runs every second)
    /// fn report_metrics(generator: &IdGenerator) {
    ///     // Using approximate is fine here - we don't need exact precision
    ///     let approx_count = generator.current_approximate();
    ///     println!("Approximate ID count: ~{}", approx_count);
    ///     // Metrics don't need perfect accuracy, and this is 10x faster
    /// }
    /// ```
    ///
    /// # Example: When NOT to Use
    ///
    /// ```rust
    /// # use aletheiadb::core::id::IdGenerator;
    /// let generator = IdGenerator::new();
    ///
    /// // ❌ WRONG: Using approximate for snapshot isolation
    /// // let snapshot_id = generator.current_approximate(); // DON'T DO THIS
    ///
    /// // ✓ CORRECT: Use current() for snapshot isolation
    /// let snapshot_id = generator.current();
    /// // Snapshot isolation requires a consistent view across all threads
    /// ```
    ///
    /// # Performance Characteristics
    ///
    /// Benchmark results (1M operations):
    /// - `current_approximate()`: ~1ns/op (relaxed load)
    /// - `current()`: ~5-10ns/op (SeqCst load)
    /// - **Speedup**: ~5-10x faster
    ///
    /// The performance advantage comes from avoiding CPU cache coherence overhead.
    /// Relaxed loads can be satisfied from the CPU's local cache without waiting for
    /// cache line synchronization across cores.
    ///
    /// # Cross-Reference
    ///
    /// See [ADR-0009](https://github.com/madmax983/AletheiaDB/blob/main/docs/adr/0009-strong-id-types.md)
    /// for discussion of memory ordering in ID generation and
    /// [issue #198](https://github.com/madmax983/AletheiaDB/issues/198) for the
    /// motivation behind this method.
    #[inline]
    pub fn current_approximate(&self) -> u64 {
        self.next_id.load(Ordering::Relaxed)
    }

    /// Reset the generator to a specific value.
    ///
    /// This is used during recovery to initialize the ID generator from the maximum ID
    /// found in the WAL, ensuring continued ID generation without conflicts.
    ///
    /// # Arguments
    ///
    /// * `value` - The next ID to generate (typically max_id + 1)
    ///
    /// # Memory Ordering
    ///
    /// Uses `Ordering::SeqCst` to ensure all threads observe the reset consistently.
    /// This is critical during recovery when re-initializing generators.
    #[inline]
    pub(crate) fn reset_to(&self, value: u64) {
        self.next_id.store(value, Ordering::SeqCst);
    }

    /// Ensure the generator's next value is at least the specified minimum.
    ///
    /// This is used during recovery when we need to account for IDs from multiple
    /// sources (e.g., current storage and historical storage) without overwriting
    /// a higher value that was already set.
    ///
    /// # Thread Safety
    ///
    /// This method uses compare-and-swap (CAS) in a loop to atomically ensure
    /// the value is at least `min_value`, avoiding check-then-act race conditions
    /// that could occur with separate load/store operations.
    ///
    /// # Arguments
    ///
    /// * `min_value` - The minimum next ID to generate
    ///
    /// # Memory Ordering
    ///
    /// Uses `Ordering::SeqCst` for compare_exchange to ensure all threads observe
    /// a globally consistent order of operations.
    #[inline]
    pub(crate) fn ensure_at_least(&self, min_value: u64) {
        let mut current = self.next_id.load(Ordering::SeqCst);
        while min_value > current {
            match self.next_id.compare_exchange(
                current,
                min_value,
                Ordering::SeqCst,
                Ordering::SeqCst,
            ) {
                Ok(_) => break,                  // Successfully updated
                Err(actual) => current = actual, // Retry with actual current value
            }
        }
    }
}

impl Default for IdGenerator {
    fn default() -> Self {
        Self::new()
    }
}

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

    #[test]
    fn test_id_generator_reset_to() {
        let generator = IdGenerator::new();
        // Generate a few IDs
        assert_eq!(generator.next(), Ok(0));
        assert_eq!(generator.next(), Ok(1));

        // Reset to a higher value (simulating recovery)
        generator.reset_to(100);
        assert_eq!(generator.current(), 100);

        // Next ID should be 100
        assert_eq!(generator.next(), Ok(100));
        assert_eq!(generator.next(), Ok(101));
    }

    #[test]
    fn test_id_generator_ensure_at_least() {
        let generator = IdGenerator::with_start(50);

        // Ensure at least 40 (less than current 50) - should do nothing
        generator.ensure_at_least(40);
        assert_eq!(generator.current(), 50);

        // Ensure at least 50 (equal to current) - should do nothing
        generator.ensure_at_least(50);
        assert_eq!(generator.current(), 50);

        // Ensure at least 60 (greater than current) - should update
        generator.ensure_at_least(60);
        assert_eq!(generator.current(), 60);
        assert_eq!(generator.next(), Ok(60));
    }

    #[test]
    fn test_id_generator_ensure_at_least_concurrent() {
        use std::sync::Arc;
        use std::thread;

        let generator = Arc::new(IdGenerator::new());
        let num_threads = 10;

        // Each thread tries to ensure at least its thread_id * 100
        // The final value should be the maximum of all inputs
        let handles: Vec<_> = (0..num_threads)
            .map(|i| {
                let generator_clone = Arc::clone(&generator);
                thread::spawn(move || {
                    generator_clone.ensure_at_least((i as u64) * 100);
                })
            })
            .collect();

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

        // The max input was (9 * 100) = 900
        // ensure_at_least(X) sets current to max(current, X).
        // So the final value must be >= max(inputs) = 900.

        assert!(generator.current() >= 900);

        // It should be exactly 900 unless we called next() somewhere (we didn't).
        assert_eq!(generator.current(), 900);
    }

    #[test]
    fn test_tx_id_generator_basics() {
        let tx_gen = TxIdGenerator::new();

        // Initial state: starts at 1
        // current() returns counter - 1. So initially 1 - 1 = 0.
        // This means "last generated ID was 0" (reserved).
        assert_eq!(tx_gen.current(), TxId(0));

        // First generation
        let id1 = tx_gen.next();
        assert_eq!(id1, TxId(1));
        assert_eq!(tx_gen.current(), TxId(1));

        // Second generation
        let id2 = tx_gen.next();
        assert_eq!(id2, TxId(2));
        assert_eq!(tx_gen.current(), TxId(2));

        // Verify strict ordering
        assert!(id2 > id1);
    }

    #[test]
    fn test_tx_id_generator_default() {
        let tx_gen: TxIdGenerator = Default::default();
        assert_eq!(tx_gen.current(), TxId(0));
    }

    #[test]
    fn test_tx_id_display() {
        let tx_id = TxId::new(12345);
        assert_eq!(format!("{}", tx_id), "TxId(12345)");
        assert_ne!(format!("{}", tx_id), "TxId(0)");
        assert_ne!(format!("{}", tx_id), "");
    }

    #[test]
    fn test_entity_id_conversion_negative() {
        let node_id = NodeId::new(1).unwrap();
        let entity_node: EntityId = node_id.into();

        // Should be Node, not Edge
        assert!(entity_node.is_node());
        assert!(!entity_node.is_edge());
        assert_eq!(entity_node.as_node(), Some(node_id));
        assert_eq!(entity_node.as_edge(), None);

        let edge_id = EdgeId::new(2).unwrap();
        let entity_edge: EntityId = edge_id.into();

        // Should be Edge, not Node
        assert!(!entity_edge.is_node());
        assert!(entity_edge.is_edge());
        assert_eq!(entity_edge.as_node(), None);
        assert_eq!(entity_edge.as_edge(), Some(edge_id));
    }
}

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

    #[test]
    fn test_node_id_creation() {
        let id = NodeId::new(42).unwrap();
        assert_eq!(id.as_u64(), 42);
    }

    #[test]
    fn test_edge_id_creation() {
        let id = EdgeId::new(100).unwrap();
        assert_eq!(id.as_u64(), 100);
    }

    #[test]
    fn test_version_id_creation() {
        let id = VersionId::new(1000).unwrap();
        assert_eq!(id.as_u64(), 1000);
    }

    #[test]
    fn test_entity_id_from_node() {
        let node_id = NodeId::new(1).unwrap();
        let entity_id: EntityId = node_id.into();
        assert!(entity_id.is_node());
        assert!(!entity_id.is_edge());
        assert_eq!(entity_id.as_node(), Some(node_id));
        assert_eq!(entity_id.as_edge(), None);
    }

    #[test]
    fn test_entity_id_from_edge() {
        let edge_id = EdgeId::new(2).unwrap();
        let entity_id: EntityId = edge_id.into();
        assert!(!entity_id.is_node());
        assert!(entity_id.is_edge());
        assert_eq!(entity_id.as_edge(), Some(edge_id));
        assert_eq!(entity_id.as_node(), None);
    }
    #[test]
    fn test_id_generator() {
        let generator = IdGenerator::new();
        assert_eq!(generator.next(), Ok(0));
        assert_eq!(generator.next(), Ok(1));
        assert_eq!(generator.next(), Ok(2));
        assert_eq!(generator.current(), 3);
    }

    #[test]
    fn test_id_generator_with_start() {
        let generator = IdGenerator::with_start(100);
        assert_eq!(generator.next(), Ok(100));
        assert_eq!(generator.next(), Ok(101));
    }

    #[test]
    fn test_id_display() {
        let node = NodeId::new(42).unwrap();
        let edge = EdgeId::new(100).unwrap();
        let version = VersionId::new(1000).unwrap();

        assert_eq!(format!("{}", node), "Node(42)");
        assert_eq!(format!("{}", edge), "Edge(100)");
        assert_eq!(format!("{}", version), "Version(1000)");
    }

    #[test]
    fn test_ids_are_distinct_types() {
        // This test ensures that you cannot accidentally use one type where another is expected.
        // This is enforced by the type system, so we just verify we can create different types.
        // Use new_unchecked since we're just testing the type system, not validation.
        let _node = NodeId::new_unchecked(1);
        let _edge = EdgeId::new_unchecked(1);
        let _version = VersionId::new_unchecked(1);

        // The following would fail to compile (which is what we want):
        // fn takes_node_id(_id: NodeId) {}
        // takes_node_id(_edge); // Type error!
    }

    #[test]
    fn test_id_validation_accepts_valid_ids() {
        // Valid IDs should be accepted
        assert!(NodeId::new(0).is_ok());
        assert!(NodeId::new(42).is_ok());
        assert!(NodeId::new(MAX_VALID_ID).is_ok());

        assert!(EdgeId::new(0).is_ok());
        assert!(EdgeId::new(100).is_ok());
        assert!(EdgeId::new(MAX_VALID_ID).is_ok());

        assert!(VersionId::new(0).is_ok());
        assert!(VersionId::new(1000).is_ok());
        assert!(VersionId::new(MAX_VALID_ID).is_ok());
    }

    #[test]
    fn test_id_validation_rejects_out_of_range() {
        // IDs exceeding MAX_VALID_ID should be rejected
        let node_result = NodeId::new(MAX_VALID_ID + 1);
        assert!(node_result.is_err());
        if let Err(StorageError::InvalidId { id, id_type }) = node_result {
            assert_eq!(id, MAX_VALID_ID + 1);
            assert_eq!(id_type, "node");
        } else {
            panic!("Expected InvalidId error");
        }

        let edge_result = EdgeId::new(u64::MAX);
        assert!(edge_result.is_err());
        if let Err(StorageError::InvalidId { id, id_type }) = edge_result {
            assert_eq!(id, u64::MAX);
            assert_eq!(id_type, "edge");
        } else {
            panic!("Expected InvalidId error");
        }

        let version_result = VersionId::new(MAX_VALID_ID + 1000);
        assert!(version_result.is_err());
        if let Err(StorageError::InvalidId { id, id_type }) = version_result {
            assert_eq!(id, MAX_VALID_ID + 1000);
            assert_eq!(id_type, "version");
        } else {
            panic!("Expected InvalidId error");
        }
    }

    #[test]
    fn test_new_unchecked_bypasses_validation() {
        // new_unchecked should create IDs without validation
        // This is for internal use where we know the ID is safe
        let node = NodeId::new_unchecked(42);
        assert_eq!(node.as_u64(), 42);

        let edge = EdgeId::new_unchecked(100);
        assert_eq!(edge.as_u64(), 100);

        let version = VersionId::new_unchecked(1000);
        assert_eq!(version.as_u64(), 1000);

        // Even out-of-range values work with new_unchecked (though they shouldn't be used)
        let _risky_node = NodeId::new_unchecked(u64::MAX);
        let _risky_edge = EdgeId::new_unchecked(u64::MAX);
        let _risky_version = VersionId::new_unchecked(u64::MAX);
    }

    #[test]
    fn test_max_valid_id_constant() {
        // Verify the MAX_VALID_ID constant is set correctly
        assert_eq!(MAX_VALID_ID, u64::MAX - 1000);

        // Verify it leaves room for reserved values
        const { assert!(MAX_VALID_ID < u64::MAX) };
        const { assert!(u64::MAX - MAX_VALID_ID >= 1000) };
    }

    #[test]
    fn test_id_validation_boundary_cases() {
        // Test values around MAX_VALID_ID boundary
        assert!(NodeId::new(MAX_VALID_ID - 1).is_ok());
        assert!(NodeId::new(MAX_VALID_ID).is_ok());
        assert!(NodeId::new(MAX_VALID_ID + 1).is_err());
        assert!(NodeId::new(MAX_VALID_ID + 2).is_err());

        // Same for other ID types
        assert!(EdgeId::new(MAX_VALID_ID - 1).is_ok());
        assert!(EdgeId::new(MAX_VALID_ID).is_ok());
        assert!(EdgeId::new(MAX_VALID_ID + 1).is_err());

        assert!(VersionId::new(MAX_VALID_ID - 1).is_ok());
        assert!(VersionId::new(MAX_VALID_ID).is_ok());
        assert!(VersionId::new(MAX_VALID_ID + 1).is_err());
    }

    #[test]
    fn test_error_message_content() {
        // Verify error messages are properly formatted
        let err = NodeId::new(MAX_VALID_ID + 1).unwrap_err();
        let msg = format!("{}", err);
        assert!(msg.contains("Invalid"));
        assert!(msg.contains("node"));
        assert!(msg.contains("ID"));
        assert!(msg.contains(&(MAX_VALID_ID + 1).to_string()));
        assert!(msg.contains("exceeds maximum"));
        assert!(msg.contains(&MAX_VALID_ID.to_string()));
        assert!(msg.contains("reserved range for internal use"));
    }

    #[test]
    fn test_id_generator_respects_max_valid_id() {
        // Verify ID generators produce valid IDs
        let generator = IdGenerator::new();
        for _ in 0..100 {
            let id = generator.next().expect("Generator should produce valid ID");
            assert!(
                NodeId::new(id).is_ok(),
                "Generator produced invalid ID: {}",
                id
            );
        }

        // Test generator starting near the limit
        let generator = IdGenerator::with_start(MAX_VALID_ID - 10);
        for _ in 0..10 {
            let id = generator
                .next()
                .expect("Generator near limit should produce valid ID");
            assert!(
                NodeId::new(id).is_ok(),
                "Generator near limit produced invalid ID: {}",
                id
            );
        }

        // Note: After MAX_VALID_ID, generator would produce invalid IDs.
        // In practice, this would require ~18 quintillion operations,
        // which is unrealistic for a single database instance.
    }

    #[test]
    fn test_id_generator_returns_error_on_overflow() {
        // Verify generator returns error when exceeding MAX_VALID_ID
        let generator = IdGenerator::with_start(MAX_VALID_ID);
        assert!(generator.next().is_ok()); // This should be OK (at MAX_VALID_ID)
        assert!(generator.next().is_err()); // This should error (exceeds MAX_VALID_ID)

        // Verify error type
        let err = generator.next().unwrap_err();
        assert!(matches!(
            err,
            StorageError::InvalidId {
                id_type: "generated",
                ..
            }
        ));
    }

    #[test]
    fn test_id_validation_performance() {
        // Verify validation overhead is negligible
        // This is a simple smoke test - proper benchmarking should use criterion
        use std::time::Instant;

        let iterations = 1_000_000;

        // Time validated creation
        let start = Instant::now();
        for i in 0..iterations {
            let _ = NodeId::new(i);
        }
        let validated_duration = start.elapsed();

        // Time unchecked creation (for comparison)
        let start = Instant::now();
        for i in 0..iterations {
            let _ = NodeId::new_unchecked(i);
        }
        let unchecked_duration = start.elapsed();

        // Print results for manual inspection (not asserted in test)
        println!("\nID Validation Performance (1M iterations):");
        println!(
            "  Validated:  {:?} ({} ns/op)",
            validated_duration,
            validated_duration.as_nanos() / iterations as u128
        );
        println!(
            "  Unchecked:  {:?} ({} ns/op)",
            unchecked_duration,
            unchecked_duration.as_nanos() / iterations as u128
        );
        println!(
            "  Overhead:   {:?}",
            validated_duration.saturating_sub(unchecked_duration)
        );

        // Validation should add minimal overhead (< 2ns per operation on modern hardware)
        // We don't assert this in the test since it's hardware-dependent
    }

    #[test]
    fn test_id_generator_concurrent_near_limit() {
        use std::collections::HashSet;
        use std::sync::Arc;
        use std::thread;

        // Start generator 20 IDs before the limit
        let ids_before_limit = 20u64;
        let generator = Arc::new(IdGenerator::with_start(MAX_VALID_ID - ids_before_limit + 1));

        // Spawn 10 threads, each trying to generate 5 IDs
        let num_threads = 10;
        let ids_per_thread = 5;
        let total_attempts = num_threads * ids_per_thread;

        let handles: Vec<_> = (0..num_threads)
            .map(|_| {
                let gen_clone = Arc::clone(&generator);
                thread::spawn(move || {
                    let mut results = Vec::new();
                    for _ in 0..ids_per_thread {
                        results.push(gen_clone.next());
                    }
                    results
                })
            })
            .collect();

        // Collect all results
        let mut all_results = Vec::new();
        for handle in handles {
            let thread_results = handle.join().expect("Thread panicked");
            all_results.extend(thread_results);
        }

        // Verify results
        let mut successful_ids = HashSet::new();
        let mut error_count = 0;

        for result in all_results {
            match result {
                Ok(id) => {
                    // Verify ID is valid
                    assert!(
                        id <= MAX_VALID_ID,
                        "Generated ID {} exceeds MAX_VALID_ID",
                        id
                    );
                    // Verify no duplicates (critical for concurrency correctness)
                    assert!(successful_ids.insert(id), "Duplicate ID generated: {}", id);
                }
                Err(e) => {
                    // Verify error is the expected overflow error
                    assert!(
                        matches!(
                            e,
                            StorageError::InvalidId {
                                id_type: "generated",
                                ..
                            }
                        ),
                        "Unexpected error type: {:?}",
                        e
                    );
                    error_count += 1;
                }
            }
        }

        // We started with 20 IDs available (MAX_VALID_ID - start + 1 = 20)
        // So exactly 20 should succeed and the rest should fail
        assert_eq!(
            successful_ids.len(),
            ids_before_limit as usize,
            "Expected exactly {} successful ID generations",
            ids_before_limit
        );
        assert_eq!(
            error_count,
            total_attempts - ids_before_limit as usize,
            "Expected {} errors when exceeding limit",
            total_attempts - ids_before_limit as usize
        );

        // Verify all successful IDs are in the expected range
        for id in &successful_ids {
            assert!(
                *id > MAX_VALID_ID - ids_before_limit && *id <= MAX_VALID_ID,
                "ID {} outside expected range [{}, {}]",
                id,
                MAX_VALID_ID - ids_before_limit + 1,
                MAX_VALID_ID
            );
        }

        println!("\nConcurrent ID Generation Test Results:");
        println!("  Threads: {}", num_threads);
        println!("  Attempts per thread: {}", ids_per_thread);
        println!("  Total attempts: {}", total_attempts);
        println!("  Successful: {} (no duplicates)", successful_ids.len());
        println!("  Errors: {}", error_count);
        println!(
            "  ID range: {} - {}",
            successful_ids.iter().min().unwrap(),
            successful_ids.iter().max().unwrap()
        );
    }

    #[test]
    fn test_id_generator_concurrent_uniqueness() {
        use std::collections::HashSet;
        use std::sync::Arc;
        use std::thread;

        // Create a shared ID generator
        let generator = Arc::new(IdGenerator::new());

        // Spawn many threads to generate IDs concurrently
        let num_threads = 20;
        let ids_per_thread = 1000;
        let total_ids = num_threads * ids_per_thread;

        let handles: Vec<_> = (0..num_threads)
            .map(|thread_id| {
                let gen_clone = Arc::clone(&generator);
                thread::spawn(move || {
                    let mut thread_ids = Vec::with_capacity(ids_per_thread);
                    for _ in 0..ids_per_thread {
                        match gen_clone.next() {
                            Ok(id) => thread_ids.push(id),
                            Err(e) => panic!("Thread {} failed to generate ID: {:?}", thread_id, e),
                        }
                    }
                    thread_ids
                })
            })
            .collect();

        // Collect all IDs from all threads
        let mut all_ids = Vec::with_capacity(total_ids);
        for handle in handles {
            let thread_ids = handle.join().expect("Thread panicked");
            all_ids.extend(thread_ids);
        }

        // Verify we got the expected number of IDs
        assert_eq!(
            all_ids.len(),
            total_ids,
            "Expected {} IDs but got {}",
            total_ids,
            all_ids.len()
        );

        // CRITICAL: Verify all IDs are unique (no duplicates)
        let unique_ids: HashSet<_> = all_ids.iter().copied().collect();
        assert_eq!(
            unique_ids.len(),
            all_ids.len(),
            "Found {} duplicate IDs! All IDs must be unique.",
            all_ids.len() - unique_ids.len()
        );

        // Verify IDs are in valid range
        for id in &all_ids {
            assert!(
                *id < total_ids as u64,
                "ID {} is unexpectedly large (expected < {})",
                id,
                total_ids
            );
        }

        // Verify IDs form a contiguous sequence from 0 to total_ids-1
        let mut sorted_ids = all_ids.clone();
        sorted_ids.sort_unstable();
        for (i, id) in sorted_ids.iter().enumerate() {
            assert_eq!(
                *id, i as u64,
                "Expected ID {} at position {} but found {}",
                i, i, id
            );
        }

        println!("\nConcurrent ID Uniqueness Test Results:");
        println!("  Threads: {}", num_threads);
        println!("  IDs per thread: {}", ids_per_thread);
        println!("  Total IDs generated: {}", all_ids.len());
        println!("  Unique IDs: {}", unique_ids.len());
        println!("  Duplicates: 0 ✓");
        println!("  ID range: 0 - {}", sorted_ids.last().unwrap());
    }

    #[test]
    fn test_current_approximate_basic() {
        // Test basic functionality of current_approximate()
        let generator = IdGenerator::new();

        // Initial value should be 0
        assert_eq!(generator.current_approximate(), 0);

        // Generate some IDs
        assert_eq!(generator.next(), Ok(0));
        assert_eq!(generator.next(), Ok(1));
        assert_eq!(generator.next(), Ok(2));

        // current_approximate() should return a value close to current()
        let approximate = generator.current_approximate();
        let exact = generator.current();

        // Approximate should be close to exact (within reasonable bounds)
        // Due to relaxed ordering, it might be slightly behind
        assert!(
            approximate <= exact,
            "Approximate {} should be <= exact {}",
            approximate,
            exact
        );
    }

    #[test]
    fn test_current_approximate_with_start() {
        // Test current_approximate() with non-zero start value
        let generator = IdGenerator::with_start(100);

        assert_eq!(generator.current_approximate(), 100);
        assert_eq!(generator.next(), Ok(100));
        assert_eq!(generator.next(), Ok(101));

        let approximate = generator.current_approximate();
        assert!(approximate >= 100, "Should be at least the start value");
        assert!(approximate <= 102, "Should not exceed current value");
    }

    #[test]
    fn test_current_approximate_is_non_blocking() {
        use std::sync::Arc;
        use std::thread;

        // Verify current_approximate() can be called concurrently without blocking
        let generator = Arc::new(IdGenerator::new());
        let num_threads = 10;
        let reads_per_thread = 10000;

        let handles: Vec<_> = (0..num_threads)
            .map(|_| {
                let gen_clone = Arc::clone(&generator);
                thread::spawn(move || {
                    // Rapidly call current_approximate() - should never block
                    for _ in 0..reads_per_thread {
                        let _ = gen_clone.current_approximate();
                    }
                })
            })
            .collect();

        // All threads should complete without blocking
        for handle in handles {
            handle.join().expect("Thread should not panic");
        }
    }

    #[test]
    fn test_current_approximate_concurrent_with_writes() {
        use std::sync::Arc;
        use std::thread;
        use std::time::Duration;

        // Test that current_approximate() works correctly when IDs are being generated
        let generator = Arc::new(IdGenerator::new());

        // Spawn writer threads
        let writer_handles: Vec<_> = (0..5)
            .map(|_| {
                let gen_clone = Arc::clone(&generator);
                thread::spawn(move || {
                    for _ in 0..1000 {
                        let _ = gen_clone.next();
                        thread::sleep(Duration::from_micros(1));
                    }
                })
            })
            .collect();

        // Spawn reader threads using current_approximate()
        let reader_handles: Vec<_> = (0..5)
            .map(|_| {
                let gen_clone = Arc::clone(&generator);
                thread::spawn(move || {
                    let mut readings = Vec::new();
                    for _ in 0..1000 {
                        readings.push(gen_clone.current_approximate());
                        thread::sleep(Duration::from_micros(1));
                    }
                    readings
                })
            })
            .collect();

        // Wait for all threads
        for handle in writer_handles {
            handle.join().expect("Writer thread should not panic");
        }

        let mut all_readings = Vec::new();
        for handle in reader_handles {
            let readings = handle.join().expect("Reader thread should not panic");
            all_readings.extend(readings);
        }

        // Verify all readings are reasonable (non-decreasing trend overall)
        // Note: Individual readings might not be monotonic due to relaxed ordering,
        // but the general trend should be increasing
        let first_reading = all_readings[0];
        let last_reading = all_readings[all_readings.len() - 1];
        assert!(
            last_reading >= first_reading,
            "Last reading {} should be >= first reading {}",
            last_reading,
            first_reading
        );
    }

    #[test]
    fn test_current_approximate_vs_current_consistency() {
        // Test that current_approximate() and current() return related values
        let generator = IdGenerator::new();

        for i in 0..100 {
            let _ = generator.next();

            let approximate = generator.current_approximate();
            let exact = generator.current();

            // Approximate should never exceed exact
            assert!(
                approximate <= exact,
                "At iteration {}: approximate {} should be <= exact {}",
                i,
                approximate,
                exact
            );

            // In a single-threaded context, `approximate` should always equal `exact` because
            // the call to `next()` is sequenced-before `current_approximate()`.
            // Relaxed ordering only affects cross-thread visibility, not same-thread ordering.
            assert_eq!(
                approximate, exact,
                "At iteration {}: approximate {} should be equal to exact {}",
                i, approximate, exact
            );
        }
    }

    #[test]
    fn test_current_approximate_performance_characteristic() {
        use std::hint::black_box;
        use std::time::Instant;

        let generator = IdGenerator::new();
        let iterations = 1_000_000;

        // Warm up
        for _ in 0..1000 {
            black_box(generator.current_approximate());
            black_box(generator.current());
        }

        // Benchmark current_approximate()
        let start = Instant::now();
        for _ in 0..iterations {
            black_box(generator.current_approximate());
        }
        let approximate_duration = start.elapsed();

        // Benchmark current()
        let start = Instant::now();
        for _ in 0..iterations {
            black_box(generator.current());
        }
        let current_duration = start.elapsed();

        let approx_ns = approximate_duration.as_nanos() / iterations as u128;
        let current_ns = current_duration.as_nanos() / iterations as u128;

        println!("\nPerformance Comparison ({} iterations):", iterations);
        println!("  current_approximate(): {} ns/op", approx_ns);
        println!("  current():             {} ns/op", current_ns);
        if current_ns > 0 && approx_ns > 0 {
            println!(
                "  Speedup:               {:.2}x",
                current_ns as f64 / approx_ns as f64
            );
        }

        // Note: Precise performance testing should be done with criterion benchmarks,
        // not unit tests. This test just verifies the method works and prints timing info.
        // On most hardware, current_approximate() should be comparable or faster due to
        // relaxed ordering, but we don't assert this here due to timing variance in tests.
    }
}

#[cfg(test)]
mod proptests {
    use super::*;
    use proptest::prelude::*;

    // Generate valid IDs (0..=MAX_VALID_ID)
    fn valid_id_strategy() -> impl Strategy<Value = u64> {
        0..=MAX_VALID_ID
    }

    // Generate any u64 value
    fn any_u64_strategy() -> impl Strategy<Value = u64> {
        any::<u64>()
    }

    proptest! {
        /// Property: Any ID that passes validation must be <= MAX_VALID_ID
        #[test]
        fn prop_validated_ids_within_bounds(raw_id in valid_id_strategy()) {
            // All valid IDs should successfully create NodeId
            let node_id = NodeId::new(raw_id).expect("Valid ID should not fail");
            prop_assert!(node_id.as_u64() <= MAX_VALID_ID);

            // Same for EdgeId and VersionId
            let edge_id = EdgeId::new(raw_id).expect("Valid ID should not fail");
            prop_assert!(edge_id.as_u64() <= MAX_VALID_ID);

            let version_id = VersionId::new(raw_id).expect("Valid ID should not fail");
            prop_assert!(version_id.as_u64() <= MAX_VALID_ID);
        }

        /// Property: Any ID > MAX_VALID_ID must be rejected
        #[test]
        fn prop_invalid_ids_rejected(offset in 1u64..=1000) {
            let invalid_id = MAX_VALID_ID + offset;

            // All invalid IDs should fail validation
            prop_assert!(NodeId::new(invalid_id).is_err());
            prop_assert!(EdgeId::new(invalid_id).is_err());
            prop_assert!(VersionId::new(invalid_id).is_err());
        }

        /// Property: ID roundtrip (ID -> u64 -> ID) preserves value
        #[test]
        fn prop_id_roundtrip_preserves_value(raw_id in valid_id_strategy()) {
            // NodeId roundtrip
            let node_id = NodeId::new(raw_id).unwrap();
            let roundtrip_node = NodeId::new(node_id.as_u64()).unwrap();
            prop_assert_eq!(node_id, roundtrip_node);

            // EdgeId roundtrip
            let edge_id = EdgeId::new(raw_id).unwrap();
            let roundtrip_edge = EdgeId::new(edge_id.as_u64()).unwrap();
            prop_assert_eq!(edge_id, roundtrip_edge);

            // VersionId roundtrip
            let version_id = VersionId::new(raw_id).unwrap();
            let roundtrip_version = VersionId::new(version_id.as_u64()).unwrap();
            prop_assert_eq!(version_id, roundtrip_version);
        }

        /// Property: ID ordering is consistent with u64 ordering
        #[test]
        fn prop_id_ordering_consistent(a in valid_id_strategy(), b in valid_id_strategy()) {
            let node_a = NodeId::new(a).unwrap();
            let node_b = NodeId::new(b).unwrap();

            // Ordering should match raw u64 ordering
            prop_assert_eq!(node_a.cmp(&node_b), a.cmp(&b));
            prop_assert_eq!(node_a == node_b, a == b);
            prop_assert_eq!(node_a < node_b, a < b);
            prop_assert_eq!(node_a > node_b, a > b);
        }

        /// Property: ID generator produces strictly increasing sequence
        #[test]
        fn prop_generator_monotonic_increasing(start in 0u64..MAX_VALID_ID-100, count in 1usize..100) {
            let generator = IdGenerator::with_start(start);
            let mut prev_id: Option<u64> = None;

            for _ in 0..count {
                match generator.next() {
                    Ok(id) => {
                        // Verify ID is within bounds
                        prop_assert!(id <= MAX_VALID_ID, "Generator must respect MAX_VALID_ID");

                        // Verify strictly increasing (if not first ID)
                        if let Some(prev) = prev_id {
                            prop_assert!(id > prev, "Generator must produce strictly increasing IDs");
                        }

                        prev_id = Some(id);
                    }
                    Err(_) => {
                        // Once we hit an error, all future calls should also error
                        if let Some(prev) = prev_id {
                            prop_assert!(prev >= MAX_VALID_ID, "Generator should only error after MAX_VALID_ID");
                        }
                        break;
                    }
                }
            }
        }

        /// Property: ID generator never produces duplicates
        #[test]
        fn prop_generator_no_duplicates(start in 0u64..MAX_VALID_ID-1000, count in 1usize..1000) {
            let generator = IdGenerator::with_start(start);
            let mut seen = std::collections::HashSet::new();

            for _ in 0..count {
                match generator.next() {
                    Ok(id) => {
                        prop_assert!(seen.insert(id), "Generator produced duplicate ID: {}", id);
                    }
                    Err(_) => break, // Hit the limit
                }
            }
        }

        /// Property: new_unchecked accepts any value (for internal use)
        #[test]
        fn prop_new_unchecked_accepts_all(raw_id in any_u64_strategy()) {
            // new_unchecked should work with any value, even invalid ones
            let node = NodeId::new_unchecked(raw_id);
            prop_assert_eq!(node.as_u64(), raw_id);

            let edge = EdgeId::new_unchecked(raw_id);
            prop_assert_eq!(edge.as_u64(), raw_id);

            let version = VersionId::new_unchecked(raw_id);
            prop_assert_eq!(version.as_u64(), raw_id);
        }

        /// Property: ID ordering is transitive: if a < b and b < c then a < c
        #[test]
        fn prop_id_ordering_is_transitive(
            a in valid_id_strategy(),
            b in valid_id_strategy(),
            c in valid_id_strategy(),
        ) {
            let node_a = NodeId::new(a).unwrap();
            let node_b = NodeId::new(b).unwrap();
            let node_c = NodeId::new(c).unwrap();

            if node_a < node_b && node_b < node_c {
                prop_assert!(node_a < node_c,
                    "Ordering transitivity violated: {:?} < {:?} < {:?} but a >= c",
                    node_a, node_b, node_c);
            }

            // Also verify for EdgeId
            let edge_a = EdgeId::new(a).unwrap();
            let edge_b = EdgeId::new(b).unwrap();
            let edge_c = EdgeId::new(c).unwrap();

            if edge_a < edge_b && edge_b < edge_c {
                prop_assert!(edge_a < edge_c,
                    "EdgeId ordering transitivity violated");
            }
        }

        /// Property: IDs from a generator never exceed MAX_VALID_ID
        #[test]
        fn prop_generator_ids_within_max_valid_id(start in 0u64..MAX_VALID_ID-50, count in 1usize..50) {
            let generator = IdGenerator::with_start(start);

            for _ in 0..count {
                match generator.next() {
                    Ok(id) => {
                        prop_assert!(id <= MAX_VALID_ID,
                            "Generator produced ID {} exceeding MAX_VALID_ID {}", id, MAX_VALID_ID);
                    }
                    Err(_) => break,
                }
            }
        }

        /// Property: TxIdGenerator produces strictly increasing transaction IDs
        #[test]
        fn prop_tx_id_generator_monotonic(_dummy in 0..50usize) {
            let tx_gen = TxIdGenerator::new();
            let mut prev = tx_gen.next();

            for _ in 0..10 {
                let curr = tx_gen.next();
                prop_assert!(curr > prev,
                    "TxId should be strictly increasing: {:?} vs {:?}", prev, curr);
                prev = curr;
            }
        }

        /// Property: Validation is consistent (always returns same result for same input)
        #[test]
        fn prop_validation_is_deterministic(raw_id in any_u64_strategy()) {
            // Call validation twice with same input
            let result1 = NodeId::new(raw_id);
            let result2 = NodeId::new(raw_id);

            // Results should be identical
            match (result1, result2) {
                (Ok(id1), Ok(id2)) => prop_assert_eq!(id1, id2),
                (Err(_), Err(_)) => {
                    // Both should reject invalid IDs
                    prop_assert!(raw_id > MAX_VALID_ID);
                }
                _ => prop_assert!(false, "Validation must be deterministic"),
            }
        }
    }
}

/// Transaction ID - globally unique identifier for transactions
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(transparent)]
/// Unique identifier for a transaction in the database.
///
/// # The Spark
/// To track bi-temporal state correctly, AletheiaDB needs to know not only *when*
/// a change occurred, but *who* made it. The `TxId` provides this context, linking
/// specific versions of graph elements back to the logical transaction that created them.
///
/// # Examples
/// ```
/// use aletheiadb::TxId;
/// let tx_id = TxId::new(100);
/// assert_eq!(tx_id.as_u64(), 100);
/// ```
pub struct TxId(u64);

impl TxId {
    /// Create a new transaction ID
    pub fn new(id: u64) -> Self {
        TxId(id)
    }

    /// Get the inner ID value
    pub fn as_u64(&self) -> u64 {
        self.0
    }
}

impl std::fmt::Display for TxId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "TxId({})", self.0)
    }
}

/// Global transaction ID generator
///
/// Generates monotonically increasing transaction IDs using atomic operations.
/// A thread-safe generator for strictly increasing transaction IDs.
///
/// # The Spark
/// Multiple concurrent writers need unique transaction IDs. The `TxIdGenerator` uses
/// atomic operations to ensure that every transaction receives a unique, monotonically
/// increasing ID without requiring locks.
///
/// # Examples
/// ```
/// use aletheiadb::core::id::TxIdGenerator;
/// let generator = TxIdGenerator::new();
/// let first_tx = generator.next();
/// let second_tx = generator.next();
/// assert_eq!(first_tx.as_u64(), 1);
/// assert_eq!(second_tx.as_u64(), 2);
/// ```
pub struct TxIdGenerator {
    counter: AtomicU64,
}

impl TxIdGenerator {
    /// Create a new transaction ID generator starting from 1
    pub fn new() -> Self {
        TxIdGenerator {
            counter: AtomicU64::new(1),
        }
    }

    /// Generate the next transaction ID
    ///
    /// This operation is atomic and thread-safe.
    pub fn next(&self) -> TxId {
        let mut current = self.counter.load(Ordering::SeqCst);
        loop {
            if current == u64::MAX {
                panic!("Transaction ID overflow! Database requires restart/migration.");
            }
            match self.counter.compare_exchange(
                current,
                current + 1,
                Ordering::SeqCst,
                Ordering::SeqCst,
            ) {
                Ok(_) => return TxId(current),
                Err(v) => current = v,
            }
        }
    }

    /// Get the current transaction ID (last generated)
    pub fn current(&self) -> TxId {
        TxId(self.counter.load(Ordering::SeqCst).saturating_sub(1))
    }

    #[cfg(test)]
    /// Set the internal counter for testing overflow conditions.
    pub fn set_counter(&self, val: u64) {
        self.counter.store(val, Ordering::SeqCst);
    }
}

impl Default for TxIdGenerator {
    fn default() -> Self {
        Self::new()
    }
}

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

    #[test]
    #[should_panic(expected = "Transaction ID overflow")]
    fn test_tx_id_overflow_panic() {
        let generator = TxIdGenerator::new();
        // Force counter to max to simulate exhaustion
        generator.set_counter(u64::MAX);
        // This should panic to prevent wrapping to 0
        let _ = generator.next();
    }
}

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

    #[test]
    fn test_id_generator_current_approximate_exhaustive() {
        let generator = IdGenerator::with_start(42);

        let current = generator.current_approximate();
        assert_eq!(current, 42);

        generator.next().unwrap();
        let current2 = generator.current_approximate();
        assert_eq!(current2, 43);
    }

    #[test]
    fn test_id_generator_ensure_at_least_exhaustive() {
        let generator = IdGenerator::with_start(42);

        // This fails if `>` was replaced with `==` (since 50 != 42, it wouldn't update)
        generator.ensure_at_least(50);
        assert_eq!(generator.current(), 50);

        // This fails if `>` was replaced with `<` (since 40 < 50 is true, it would update)
        generator.ensure_at_least(40);
        assert_eq!(generator.current(), 50);
    }

    #[test]
    fn test_tx_id_generator_next_exhaustive() {
        let generator = TxIdGenerator::new(); // Starts at 1

        // Kill "replace TxIdGenerator::next -> TxId with Default::default()"
        let first = generator.next();
        assert_eq!(first, TxId::new(1));

        // Kill "replace + with -" or "*"
        let second = generator.next();
        assert_eq!(second, TxId::new(2));

        // Kill "replace == with !=" for u64::MAX check
        // If it were `!=`, it would panic immediately because 1 != u64::MAX

        // Ensure returning default current doesn't pass
        let generator_current = generator.current();
        assert_eq!(generator_current, TxId::new(2));
    }

    #[test]
    fn test_id_generator_next_boundaries() {
        // Kill "> with == / < / >="
        // We set generator right to MAX_VALID_ID
        let generator = IdGenerator::with_start(MAX_VALID_ID);

        // This will fetch_add MAX_VALID_ID and return MAX_VALID_ID, incrementing to MAX_VALID_ID+1
        let first = generator.next();
        assert_eq!(first, Ok(MAX_VALID_ID));

        // The next attempt will return the incremented MAX_VALID_ID+1 and fail the limit check
        let second = generator.next();
        assert!(second.is_err());

        if let Err(crate::core::error::StorageError::InvalidId { id, .. }) = second {
            assert_eq!(id, MAX_VALID_ID + 1);
        } else {
            panic!("Expected InvalidId error");
        }
    }

    #[test]
    fn test_max_valid_id_math() {
        // Kill `replace - with +` or `/` in `pub const MAX_VALID_ID: u64 = u64::MAX - 1000;`
        let id_plus = u64::MAX.wrapping_add(1000);
        let id_div = u64::MAX / 1000;
        assert_ne!(MAX_VALID_ID, id_plus);
        assert_ne!(MAX_VALID_ID, id_div);
        assert_eq!(MAX_VALID_ID, u64::MAX - 1000);
    }

    #[test]
    fn test_id_generator_reset_to_exhaustive() {
        let generator = IdGenerator::new();
        generator.reset_to(42);
        assert_eq!(generator.current(), 42);

        // This fails if reset_to returned early / was empty body
        let id = generator.next().unwrap();
        assert_eq!(id, 42);
    }

    #[test]
    fn test_id_generator_default() {
        let generator: IdGenerator = Default::default();
        assert_eq!(generator.current(), 0);
    }

    #[test]
    fn test_node_id_new_unchecked_exhaustive() {
        let unchecked = NodeId::new_unchecked(42);
        assert_eq!(unchecked.as_u64(), 42);
        assert_ne!(unchecked.as_u64(), 0);
    }

    #[test]
    fn test_edge_id_new_unchecked_exhaustive() {
        let unchecked = EdgeId::new_unchecked(42);
        assert_eq!(unchecked.as_u64(), 42);
        assert_ne!(unchecked.as_u64(), 0);
    }

    #[test]
    fn test_version_id_new_unchecked_exhaustive() {
        let unchecked = VersionId::new_unchecked(42);
        assert_eq!(unchecked.as_u64(), 42);
        assert_ne!(unchecked.as_u64(), 0);
    }
}

use std::str::FromStr;

impl TryFrom<u64> for NodeId {
    type Error = StorageError;

    fn try_from(value: u64) -> Result<Self, Self::Error> {
        NodeId::new(value)
    }
}

impl FromStr for NodeId {
    type Err = StorageError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let value = s.parse::<u64>().map_err(|_| StorageError::InvalidId {
            id: u64::MAX,
            id_type: "NodeId",
        })?;
        NodeId::new(value)
    }
}

impl TryFrom<u64> for EdgeId {
    type Error = StorageError;

    fn try_from(value: u64) -> Result<Self, Self::Error> {
        EdgeId::new(value)
    }
}

impl FromStr for EdgeId {
    type Err = StorageError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let value = s.parse::<u64>().map_err(|_| StorageError::InvalidId {
            id: u64::MAX,
            id_type: "EdgeId",
        })?;
        EdgeId::new(value)
    }
}

impl TryFrom<u64> for VersionId {
    type Error = StorageError;

    fn try_from(value: u64) -> Result<Self, Self::Error> {
        VersionId::new(value)
    }
}

impl FromStr for VersionId {
    type Err = StorageError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let value = s.parse::<u64>().map_err(|_| StorageError::InvalidId {
            id: u64::MAX,
            id_type: "VersionId",
        })?;
        VersionId::new(value)
    }
}

impl TryFrom<u64> for TxId {
    type Error = StorageError;

    fn try_from(value: u64) -> Result<Self, Self::Error> {
        Ok(TxId::new(value))
    }
}

impl FromStr for TxId {
    type Err = StorageError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let value = s.parse::<u64>().map_err(|_| StorageError::InvalidId {
            id: u64::MAX,
            id_type: "TxId",
        })?;
        Ok(TxId::new(value))
    }
}

#[cfg(test)]
mod tests_conversions {
    use super::*;
    use std::str::FromStr;

    #[test]
    fn test_node_id_conversions() {
        let n = NodeId::try_from(42).unwrap();
        assert_eq!(n, NodeId::new(42).unwrap());

        let err = NodeId::try_from(u64::MAX).unwrap_err();
        assert!(matches!(err, StorageError::InvalidId { .. }));

        let n2 = NodeId::from_str("42").unwrap();
        assert_eq!(n2, n);

        let err = NodeId::from_str("invalid").unwrap_err();
        assert!(matches!(err, StorageError::InvalidId { .. }));

        let err2 = NodeId::from_str("-1").unwrap_err();
        assert!(matches!(err2, StorageError::InvalidId { .. }));

        let err3 = NodeId::from_str(&u64::MAX.to_string()).unwrap_err();
        assert!(matches!(err3, StorageError::InvalidId { .. }));
    }

    #[test]
    fn test_edge_id_conversions() {
        let e = EdgeId::try_from(42).unwrap();
        assert_eq!(e, EdgeId::new(42).unwrap());

        let err = EdgeId::try_from(u64::MAX).unwrap_err();
        assert!(matches!(err, StorageError::InvalidId { .. }));

        let e2 = EdgeId::from_str("42").unwrap();
        assert_eq!(e2, e);

        let err = EdgeId::from_str("invalid").unwrap_err();
        assert!(matches!(err, StorageError::InvalidId { .. }));

        let err2 = EdgeId::from_str(&u64::MAX.to_string()).unwrap_err();
        assert!(matches!(err2, StorageError::InvalidId { .. }));
    }

    #[test]
    fn test_version_id_conversions() {
        let v = VersionId::try_from(42).unwrap();
        assert_eq!(v, VersionId::new(42).unwrap());

        let err = VersionId::try_from(u64::MAX).unwrap_err();
        assert!(matches!(err, StorageError::InvalidId { .. }));

        let v2 = VersionId::from_str("42").unwrap();
        assert_eq!(v2, v);

        let err = VersionId::from_str("invalid").unwrap_err();
        assert!(matches!(err, StorageError::InvalidId { .. }));

        let err2 = VersionId::from_str(&u64::MAX.to_string()).unwrap_err();
        assert!(matches!(err2, StorageError::InvalidId { .. }));
    }

    #[test]
    fn test_tx_id_conversions() {
        let t = TxId::try_from(42).unwrap();
        assert_eq!(t, TxId::new(42));

        let t2 = TxId::from_str("42").unwrap();
        assert_eq!(t2, t);

        let err = TxId::from_str("invalid").unwrap_err();
        assert!(matches!(err, StorageError::InvalidId { .. }));

        let err2 = TxId::from_str("-1").unwrap_err();
        assert!(matches!(err2, StorageError::InvalidId { .. }));
    }

    #[test]
    fn test_id_conversions_exhaustive() {
        let n_try = NodeId::try_from(42).unwrap();
        assert_eq!(n_try.as_u64(), 42);

        let n_str = NodeId::from_str("42").unwrap();
        assert_eq!(n_str.as_u64(), 42);

        let e_try = EdgeId::try_from(42).unwrap();
        assert_eq!(e_try.as_u64(), 42);

        let e_str = EdgeId::from_str("42").unwrap();
        assert_eq!(e_str.as_u64(), 42);

        let v_try = VersionId::try_from(42).unwrap();
        assert_eq!(v_try.as_u64(), 42);

        let v_str = VersionId::from_str("42").unwrap();
        assert_eq!(v_str.as_u64(), 42);

        let t_try = TxId::try_from(42).unwrap();
        assert_eq!(t_try.as_u64(), 42);

        let t_str = TxId::from_str("42").unwrap();
        assert_eq!(t_str.as_u64(), 42);
    }
}