crdt-lite 0.8.0

A lightweight, column-based CRDT implementation in Rust
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
//! # crdt-lite
//!
//! A lightweight, column-based CRDT (Conflict-free Replicated Data Type) implementation in Rust.
//!
//! This library provides a generic CRDT with last-write-wins semantics, supporting:
//! - Generic key and value types
//! - Logical clock for causality tracking
//! - Tombstone-based deletion
//! - Parent-child CRDT hierarchies
//! - Custom merge rules and comparators
//! - Change compression
//! - Optional serialization support via Serde
//!
//! ## Features
//!
//! This crate provides optional features through feature flags:
//!
//! - `std` - Enables standard library support (enabled by default)
//! - `alloc` - Enables allocator support for no_std environments (pulls in hashbrown for HashMap)
//! - `serde` - Enables Serde support for all CRDT types
//! - `json` - Enables JSON serialization (includes `serde` + `serde_json`)
//! - `binary` - Enables binary serialization (includes `serde` + `bincode`)
//! - `persist` - Enables persistence layer with WAL and hooks (includes `binary` + `std`)
//! - `node-id-u128` - Uses u128 for NodeId instead of u64 (useful for UUID-based node IDs)
//!
//! ### no_std Support
//!
//! For no_std environments, disable default features and enable the `alloc` feature:
//!
//! ```toml
//! [dependencies]
//! crdt-lite = { version = "0.2", default-features = false, features = ["alloc"] }
//! ```
//!
//! ### Usage Example with Serialization
//!
//! ```toml
//! [dependencies]
//! crdt-lite = { version = "0.1", features = ["json", "binary"] }
//! ```
//!
//! ```rust,ignore
//! use crdt_lite::CRDT;
//!
//! // Create and populate a CRDT
//! let mut crdt: CRDT<String, String> = CRDT::new(1, None);
//! let fields = vec![("name".to_string(), "Alice".to_string())];
//! crdt.insert_or_update(&"user1".to_string(), fields);
//!
//! // Serialize to JSON (requires "json" feature)
//! let json = crdt.to_json().unwrap();
//!
//! // Deserialize from JSON
//! let restored: CRDT<String, String> = CRDT::from_json(&json).unwrap();
//!
//! // Serialize to binary (requires "binary" feature)
//! let bytes = crdt.to_bytes().unwrap();
//! let restored: CRDT<String, String> = CRDT::from_bytes(&bytes).unwrap();
//!
//! // Or use generic serde with any format (requires "serde" feature)
//! let json = serde_json::to_string(&crdt).unwrap();
//! let restored: CRDT<String, String> = serde_json::from_str(&json).unwrap();
//! ```
//!
//! **Note on Parent Relationships**: Parent-child CRDT hierarchies are not serialized.
//! After deserialization, the `parent` field will always be `None`. Applications must
//! rebuild parent-child relationships if needed.
//!
//! ## Security and Resource Management
//!
//! ### Logical Clock Overflow
//! The logical clock uses `u64` for version numbers. While overflow is theoretically possible
//! after 2^64 operations (extremely unlikely in practice), applications with extreme longevity
//! should be aware of this limitation.
//!
//! ### DoS Protection and Tombstone Management
//! Tombstones accumulate indefinitely unless manually compacted. To prevent memory exhaustion:
//! - Call `compact_tombstones()` periodically after all nodes have acknowledged a version
//! - Implement application-level rate limiting for operations
//! - Consider setting resource limits on the number of records and tombstones
//!
//! **Important**: Only compact tombstones when ALL participating nodes have acknowledged
//! the minimum version. Compacting too early may cause deleted records to reappear on
//! nodes that haven't received the deletion yet.

#![cfg_attr(not(feature = "std"), no_std)]

// Persistence module (requires any persist-related feature)
#[cfg(any(feature = "persist", feature = "persist-msgpack", feature = "persist-compressed"))]
pub mod persist;

// Ensure valid feature combination: either std or alloc must be enabled
#[cfg(not(any(feature = "std", feature = "alloc")))]
compile_error!("Either 'std' (default) or 'alloc' feature must be enabled. For no_std environments, use: cargo build --no-default-features --features alloc");

#[cfg(not(feature = "std"))]
extern crate alloc;

#[cfg(feature = "std")]
use std::{
  cmp::Ordering,
  collections::{HashMap, HashSet},
  hash::Hash,
  sync::Arc,
};

#[cfg(not(feature = "std"))]
use alloc::{
  string::String,
  sync::Arc,
  vec::Vec,
};
#[cfg(not(feature = "std"))]
use core::{cmp::Ordering, hash::Hash};
#[cfg(all(not(feature = "std"), feature = "alloc"))]
use hashbrown::{HashMap, HashSet};

// Conditional type aliases for sorted vs unsorted storage
#[cfg(all(feature = "sorted-keys", feature = "std"))]
type DataMap<K, V> = std::collections::BTreeMap<K, V>;
#[cfg(all(feature = "sorted-keys", not(feature = "std"), feature = "alloc"))]
type DataMap<K, V> = alloc::collections::BTreeMap<K, V>;
#[cfg(all(not(feature = "sorted-keys"), feature = "std"))]
type DataMap<K, V> = HashMap<K, V>;
#[cfg(all(not(feature = "sorted-keys"), not(feature = "std"), feature = "alloc"))]
type DataMap<K, V> = HashMap<K, V>;

// Conditional Entry type aliases to match DataMap
#[cfg(all(feature = "sorted-keys", feature = "std"))]
type DataMapEntry<'a, K, V> = std::collections::btree_map::Entry<'a, K, V>;
#[cfg(all(feature = "sorted-keys", not(feature = "std"), feature = "alloc"))]
type DataMapEntry<'a, K, V> = alloc::collections::btree_map::Entry<'a, K, V>;
#[cfg(all(not(feature = "sorted-keys"), feature = "std"))]
type DataMapEntry<'a, K, V> = std::collections::hash_map::Entry<'a, K, V>;
#[cfg(all(not(feature = "sorted-keys"), not(feature = "std"), feature = "alloc"))]
type DataMapEntry<'a, K, V> = hashbrown::hash_map::Entry<'a, K, V, hashbrown::DefaultHashBuilder>;

/// Type alias for node IDs
///
/// By default, NodeId is u64. Use the `node-id-u128` feature to enable u128 for UUID-based IDs:
/// ```toml
/// crdt-lite = { version = "0.4", features = ["node-id-u128"] }
/// ```
#[cfg(feature = "node-id-u128")]
pub type NodeId = u128;

#[cfg(not(feature = "node-id-u128"))]
pub type NodeId = u64;

/// Type alias for column keys (field names)
pub type ColumnKey = String;

/// Column version used for tombstone changes
/// Using u64::MAX ensures tombstones are treated as having the highest possible version
const TOMBSTONE_COL_VERSION: u64 = u64::MAX;

/// Represents a single change in the CRDT.
///
/// A change can represent:
/// - An insertion or update of a column value (when `col_name` is `Some`)
/// - A deletion of a specific column (when `col_name` is `Some` and `value` is `None`)
/// - A deletion of an entire record (when `col_name` is `None`)
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(bound(serialize = "K: serde::Serialize, C: serde::Serialize, V: serde::Serialize")))]
#[cfg_attr(feature = "serde", serde(bound(deserialize = "K: serde::de::DeserializeOwned, C: serde::de::DeserializeOwned, V: serde::de::DeserializeOwned")))]
pub struct Change<K, C, V> {
  pub record_id: K,
  /// `None` represents tombstone of the record
  pub col_name: Option<C>,
  /// `None` represents deletion of the column (not the record)
  pub value: Option<V>,
  pub col_version: u64,
  pub db_version: u64,
  pub node_id: NodeId,
  /// Local db_version when the change was created (useful for `get_changes_since`)
  pub local_db_version: u64,
  /// Optional flags to indicate the type of change (ephemeral, not stored)
  pub flags: u32,
}

impl<K: Eq, C: Eq, V: Eq> Eq for Change<K, C, V> {}

impl<K, C, V> Change<K, C, V> {
  /// Creates a new Change with all parameters
  #[allow(clippy::too_many_arguments)]
  pub fn new(
    record_id: K,
    col_name: Option<C>,
    value: Option<V>,
    col_version: u64,
    db_version: u64,
    node_id: NodeId,
    local_db_version: u64,
    flags: u32,
  ) -> Self {
    Self {
      record_id,
      col_name,
      value,
      col_version,
      db_version,
      node_id,
      local_db_version,
      flags,
    }
  }
}

/// Represents version information for a column.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct ColumnVersion {
  pub col_version: u64,
  pub db_version: u64,
  pub node_id: NodeId,
  /// Local db_version when the change was created
  pub local_db_version: u64,
}

impl ColumnVersion {
  pub fn new(col_version: u64, db_version: u64, node_id: NodeId, local_db_version: u64) -> Self {
    Self {
      col_version,
      db_version,
      node_id,
      local_db_version,
    }
  }
}

/// Minimal version information for tombstones.
///
/// Stores essential data: db_version for conflict resolution, node_id for sync exclusion,
/// and local_db_version for sync.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct TombstoneInfo {
  pub db_version: u64,
  pub node_id: NodeId,
  pub local_db_version: u64,
}

impl TombstoneInfo {
  pub fn new(db_version: u64, node_id: NodeId, local_db_version: u64) -> Self {
    Self {
      db_version,
      node_id,
      local_db_version,
    }
  }

  /// Helper to create a ColumnVersion for comparison with regular columns
  pub fn as_column_version(&self) -> ColumnVersion {
    ColumnVersion::new(
      TOMBSTONE_COL_VERSION,
      self.db_version,
      self.node_id,
      self.local_db_version,
    )
  }
}

/// Represents a logical clock for maintaining causality.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct LogicalClock {
  time: u64,
}

impl LogicalClock {
  /// Creates a new logical clock starting at 0
  pub fn new() -> Self {
    Self { time: 0 }
  }

  /// Increments the clock for a local event and returns the new time
  pub fn tick(&mut self) -> u64 {
    self.time += 1;
    self.time
  }

  /// Updates the clock based on a received time and returns the new time
  pub fn update(&mut self, received_time: u64) -> u64 {
    self.time = self.time.max(received_time);
    self.time += 1;
    self.time
  }

  /// Sets the logical clock to a specific time
  pub fn set_time(&mut self, time: u64) {
    self.time = time;
  }

  /// Retrieves the current time
  pub fn current_time(&self) -> u64 {
    self.time
  }
}

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

/// Storage for tombstones (deleted records).
///
/// Uses a HashMap for efficient lookups and supports compaction.
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct TombstoneStorage<K: Hash + Eq> {
  entries: HashMap<K, TombstoneInfo>,
}

impl<K: Hash + Eq> TombstoneStorage<K> {
  pub fn new() -> Self {
    Self {
      entries: HashMap::new(),
    }
  }

  pub fn insert_or_assign(&mut self, key: K, info: TombstoneInfo) {
    self.entries.insert(key, info);
  }

  pub fn find(&self, key: &K) -> Option<TombstoneInfo> {
    self.entries.get(key).copied()
  }

  pub fn erase(&mut self, key: &K) -> bool {
    self.entries.remove(key).is_some()
  }

  pub fn clear(&mut self) {
    self.entries.clear();
  }

  pub fn iter(&self) -> impl Iterator<Item = (&K, &TombstoneInfo)> {
    self.entries.iter()
  }

  pub fn len(&self) -> usize {
    self.entries.len()
  }

  pub fn is_empty(&self) -> bool {
    self.entries.is_empty()
  }

  /// Compact tombstones older than the specified version.
  ///
  /// Returns the number of tombstones removed.
  pub fn compact(&mut self, min_acknowledged_version: u64) -> usize {
    let initial_len = self.entries.len();
    self
      .entries
      .retain(|_, info| info.db_version >= min_acknowledged_version);
    initial_len - self.entries.len()
  }
}

impl<K: Hash + Eq> Default for TombstoneStorage<K> {
  fn default() -> Self {
    Self::new()
  }
}

/// Represents a record in the CRDT.
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(bound(serialize = "C: serde::Serialize + Hash + Eq, V: serde::Serialize")))]
#[cfg_attr(feature = "serde", serde(bound(deserialize = "C: serde::de::DeserializeOwned + Hash + Eq, V: serde::de::DeserializeOwned")))]
pub struct Record<C, V> {
  pub fields: HashMap<C, V>,
  pub column_versions: HashMap<C, ColumnVersion>,
  /// Track version boundaries for efficient filtering
  pub lowest_local_db_version: u64,
  pub highest_local_db_version: u64,
}

impl<C: Hash + Eq, V> Record<C, V> {
  pub fn new() -> Self {
    Self {
      fields: HashMap::new(),
      column_versions: HashMap::new(),
      lowest_local_db_version: u64::MAX,
      highest_local_db_version: 0,
    }
  }

  /// Creates a record from existing fields and column versions
  pub fn from_parts(
    fields: HashMap<C, V>,
    column_versions: HashMap<C, ColumnVersion>,
  ) -> Self {
    let mut lowest = u64::MAX;
    let mut highest = 0;

    for ver in column_versions.values() {
      if ver.local_db_version < lowest {
        lowest = ver.local_db_version;
      }
      if ver.local_db_version > highest {
        highest = ver.local_db_version;
      }
    }

    Self {
      fields,
      column_versions,
      lowest_local_db_version: lowest,
      highest_local_db_version: highest,
    }
  }
}

impl<C: Hash + Eq + PartialEq, V: PartialEq> PartialEq for Record<C, V> {
  fn eq(&self, other: &Self) -> bool {
    // Compare only fields, not column_versions (those will differ per node)
    self.fields == other.fields
  }
}

impl<C: Hash + Eq, V> Default for Record<C, V> {
  fn default() -> Self {
    Self::new()
  }
}

/// Trait for merge rules that determine conflict resolution.
///
/// Implementations should return `true` if the remote change should be accepted,
/// `false` otherwise.
pub trait MergeRule<K, C, V> {
  /// Determines whether to accept a remote change over a local one
  fn should_accept(
    &self,
    local_col: u64,
    local_db: u64,
    local_node: NodeId,
    remote_col: u64,
    remote_db: u64,
    remote_node: NodeId,
  ) -> bool;

  /// Convenience method for Change objects
  fn should_accept_change(&self, local: &Change<K, C, V>, remote: &Change<K, C, V>) -> bool {
    self.should_accept(
      local.col_version,
      local.db_version,
      local.node_id,
      remote.col_version,
      remote.db_version,
      remote.node_id,
    )
  }
}

/// Default merge rule implementing last-write-wins semantics.
///
/// Comparison priority:
/// 1. Column version (higher wins)
/// 2. DB version (higher wins)
/// 3. Node ID (higher wins as tiebreaker)
#[derive(Debug, Clone, Copy, Default)]
pub struct DefaultMergeRule;

impl<K, C, V> MergeRule<K, C, V> for DefaultMergeRule {
  fn should_accept(
    &self,
    local_col: u64,
    local_db: u64,
    local_node: NodeId,
    remote_col: u64,
    remote_db: u64,
    remote_node: NodeId,
  ) -> bool {
    match remote_col.cmp(&local_col) {
      Ordering::Greater => true,
      Ordering::Less => false,
      Ordering::Equal => match remote_db.cmp(&local_db) {
        Ordering::Greater => true,
        Ordering::Less => false,
        Ordering::Equal => remote_node > local_node,
      },
    }
  }
}

/// Trait for change comparators used in sorting and compression.
pub trait ChangeComparator<K, C, V> {
  fn compare(&self, a: &Change<K, C, V>, b: &Change<K, C, V>) -> Ordering;
}

/// Default change comparator.
///
/// Sorts by:
/// 1. Record ID (ascending)
/// 2. Column name presence (deletions/tombstones last)
/// 3. Column name (ascending)
/// 4. Column version (descending - most recent first)
/// 5. DB version (descending)
/// 6. Node ID (descending)
#[derive(Debug, Clone, Copy, Default)]
pub struct DefaultChangeComparator;

impl<K: Ord, C: Ord, V> ChangeComparator<K, C, V> for DefaultChangeComparator {
  fn compare(&self, a: &Change<K, C, V>, b: &Change<K, C, V>) -> Ordering {
    // Compare record IDs
    match a.record_id.cmp(&b.record_id) {
      Ordering::Equal => {}
      ord => return ord,
    }

    // Deletions (None) come last for each record
    match (a.col_name.as_ref(), b.col_name.as_ref()) {
      (None, None) => {}
      (None, Some(_)) => return Ordering::Greater,
      (Some(_), None) => return Ordering::Less,
      (Some(a_col), Some(b_col)) => match a_col.cmp(b_col) {
        Ordering::Equal => {}
        ord => return ord,
      },
    }

    // Compare versions (descending - most recent first)
    match b.col_version.cmp(&a.col_version) {
      Ordering::Equal => {}
      ord => return ord,
    }

    match b.db_version.cmp(&a.db_version) {
      Ordering::Equal => {}
      ord => return ord,
    }

    b.node_id.cmp(&a.node_id)
  }
}

/// Main CRDT structure, generic over key (K), column (C), and value (V) types.
///
/// This implements a column-based CRDT with last-write-wins semantics.
///
/// # Sorted Keys Feature
///
/// When the `sorted-keys` feature is enabled, the internal storage uses `BTreeMap`
/// instead of `HashMap`, enabling ordered iteration and range queries at the cost
/// of O(log n) operations instead of O(1).
///
/// # Type Requirements
///
/// K (record key) must implement `Ord + Hash + Eq + Clone`:
/// - `Ord` is required for potential use with sorted-keys feature (BTreeMap)
/// - Even without sorted-keys, requiring `Ord` keeps the API consistent and enables
///   seamless feature toggling. Most common types (String, u64, etc.) already implement Ord.
/// - This is consistent with PersistedCRDT which also requires K: Ord for serialization.
#[derive(Debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(bound(serialize = "K: serde::Serialize, C: serde::Serialize, V: serde::Serialize")))]
#[cfg_attr(feature = "serde", serde(bound(deserialize = "K: serde::de::DeserializeOwned + Ord + Hash + Eq + Clone, C: serde::de::DeserializeOwned + Hash + Eq + Clone, V: serde::de::DeserializeOwned + Clone")))]
pub struct CRDT<K: Ord + Hash + Eq + Clone, C: Hash + Eq + Clone, V: Clone> {
  node_id: NodeId,
  clock: LogicalClock,
  data: DataMap<K, Record<C, V>>,
  tombstones: TombstoneStorage<K>,
  #[cfg_attr(feature = "serde", serde(skip, default))]
  parent: Option<Arc<CRDT<K, C, V>>>,
  #[allow(dead_code)]
  base_version: u64,
}

// Main implementation (works with both HashMap and BTreeMap via DataMap alias)
impl<K: Ord + Hash + Eq + Clone, C: Hash + Eq + Clone, V: Clone> CRDT<K, C, V> {
  /// Creates a new empty CRDT.
  ///
  /// # Arguments
  ///
  /// * `node_id` - Unique identifier for this CRDT node
  /// * `parent` - Optional parent CRDT for hierarchical structures
  pub fn new(node_id: NodeId, parent: Option<Arc<CRDT<K, C, V>>>) -> Self {
    let (clock, base_version) = if let Some(ref p) = parent {
      let parent_clock = p.clock;
      let base = parent_clock.current_time();
      (parent_clock, base)
    } else {
      (LogicalClock::new(), 0)
    };

    Self {
      node_id,
      clock,
      data: DataMap::new(),
      tombstones: TombstoneStorage::new(),
      parent,
      base_version,
    }
  }

  /// Creates a CRDT from a list of changes (e.g., loaded from disk).
  ///
  /// # Arguments
  ///
  /// * `node_id` - The unique identifier for this CRDT node
  /// * `changes` - A list of changes to apply to reconstruct the CRDT state
  pub fn from_changes(node_id: NodeId, changes: Vec<Change<K, C, V>>) -> Self {
    let mut crdt = Self::new(node_id, None);
    crdt.apply_changes(changes);
    crdt
  }

  /// Resets the CRDT to a state as if it was constructed with the given changes.
  ///
  /// # Arguments
  ///
  /// * `changes` - A list of changes to apply to reconstruct the CRDT state
  pub fn reset(&mut self, changes: Vec<Change<K, C, V>>) {
    self.data.clear();
    self.tombstones.clear();
    self.clock = LogicalClock::new();
    self.apply_changes(changes);
  }

  /// Applies a list of changes to reconstruct the CRDT state.
  fn apply_changes(&mut self, changes: Vec<Change<K, C, V>>) {
    // Determine the maximum db_version from the changes
    let max_db_version = changes
      .iter()
      .map(|c| c.db_version.max(c.local_db_version))
      .max()
      .unwrap_or(0);

    // Set the logical clock to the maximum db_version
    self.clock.set_time(max_db_version);

    // Apply each change to reconstruct the CRDT state
    for change in changes {
      let record_id = change.record_id.clone();
      let col_name = change.col_name.clone();
      let remote_col_version = change.col_version;
      let remote_db_version = change.db_version;
      let remote_node_id = change.node_id;
      let remote_local_db_version = change.local_db_version;
      let remote_value = change.value;

      if col_name.is_none() {
        // Handle deletion
        self.data.remove(&record_id);

        // Store deletion information in tombstones
        self.tombstones.insert_or_assign(
          record_id,
          TombstoneInfo::new(remote_db_version, remote_node_id, remote_local_db_version),
        );
      } else if let Some(col_key) = col_name {
        // Handle insertion or update
        if !self.is_record_tombstoned(&record_id, false) {
          let record = self.get_or_create_record_unchecked(&record_id, false);

          // Insert or update the field value
          if let Some(value) = remote_value {
            record.fields.insert(col_key.clone(), value);
          }

          // Update the column version info
          let col_ver = ColumnVersion::new(
            remote_col_version,
            remote_db_version,
            remote_node_id,
            remote_local_db_version,
          );
          record.column_versions.insert(col_key, col_ver);

          // Update version boundaries
          if remote_local_db_version < record.lowest_local_db_version {
            record.lowest_local_db_version = remote_local_db_version;
          }
          if remote_local_db_version > record.highest_local_db_version {
            record.highest_local_db_version = remote_local_db_version;
          }
        }
      }
    }
  }

  /// Inserts a new record or updates an existing record in the CRDT.
  ///
  /// # Arguments
  ///
  /// * `record_id` - The unique identifier for the record
  /// * `fields` - An iterator of (column_name, value) pairs
  ///
  /// # Returns
  ///
  /// A vector of changes created by this operation
  #[must_use = "changes should be propagated to other nodes"]
  pub fn insert_or_update<I>(&mut self, record_id: &K, fields: I) -> Vec<Change<K, C, V>>
  where
    I: IntoIterator<Item = (C, V)>,
  {
    self.insert_or_update_with_flags(record_id, 0, fields)
  }

  /// Inserts a new record or updates an existing record with flags.
  ///
  /// # Arguments
  ///
  /// * `record_id` - The unique identifier for the record
  /// * `flags` - Flags to indicate the type of change
  /// * `fields` - An iterator of (column_name, value) pairs
  ///
  /// # Returns
  ///
  /// A vector of changes created by this operation
  #[must_use = "changes should be propagated to other nodes"]
  pub fn insert_or_update_with_flags<I>(
    &mut self,
    record_id: &K,
    flags: u32,
    fields: I,
  ) -> Vec<Change<K, C, V>>
  where
    I: IntoIterator<Item = (C, V)>,
  {
    let db_version = self.clock.tick();

    // Check if the record is tombstoned
    if self.is_record_tombstoned(record_id, false) {
      return Vec::new();
    }

    let mut changes = Vec::new();
    let node_id = self.node_id; // Store node_id before mutable borrow
    let record = self.get_or_create_record_unchecked(record_id, false);

    for (col_name, value) in fields {
      let col_version = if let Some(col_info) = record.column_versions.get_mut(&col_name) {
        col_info.col_version += 1;
        col_info.db_version = db_version;
        col_info.node_id = node_id;
        col_info.local_db_version = db_version;
        col_info.col_version
      } else {
        record.column_versions.insert(
          col_name.clone(),
          ColumnVersion::new(1, db_version, node_id, db_version),
        );
        1
      };

      // Update record version boundaries
      if db_version < record.lowest_local_db_version {
        record.lowest_local_db_version = db_version;
      }
      if db_version > record.highest_local_db_version {
        record.highest_local_db_version = db_version;
      }

      record.fields.insert(col_name.clone(), value.clone());
      changes.push(Change::new(
        record_id.clone(),
        Some(col_name),
        Some(value),
        col_version,
        db_version,
        node_id,
        db_version,
        flags,
      ));
    }

    changes
  }

  /// Deletes a record by marking it as tombstoned.
  ///
  /// # Arguments
  ///
  /// * `record_id` - The unique identifier for the record
  ///
  /// # Returns
  ///
  /// An optional Change representing the deletion
  #[must_use = "changes should be propagated to other nodes"]
  pub fn delete_record(&mut self, record_id: &K) -> Option<Change<K, C, V>> {
    self.delete_record_with_flags(record_id, 0)
  }

  /// Deletes a record with flags.
  ///
  /// # Arguments
  ///
  /// * `record_id` - The unique identifier for the record
  /// * `flags` - Flags to indicate the type of change
  ///
  /// # Returns
  ///
  /// An optional Change representing the deletion
  #[must_use = "changes should be propagated to other nodes"]
  pub fn delete_record_with_flags(&mut self, record_id: &K, flags: u32) -> Option<Change<K, C, V>> {
    if self.is_record_tombstoned(record_id, false) {
      return None;
    }

    let db_version = self.clock.tick();

    // Mark as tombstone and remove data
    self.data.remove(record_id);

    // Store deletion information in tombstones
    self.tombstones.insert_or_assign(
      record_id.clone(),
      TombstoneInfo::new(db_version, self.node_id, db_version),
    );

    Some(Change::new(
      record_id.clone(),
      None,
      None,
      TOMBSTONE_COL_VERSION,
      db_version,
      self.node_id,
      db_version,
      flags,
    ))
  }

  /// Deletes a specific field from a record.
  ///
  /// # Arguments
  ///
  /// * `record_id` - The unique identifier for the record
  /// * `field_name` - The name of the field to delete
  ///
  /// # Returns
  ///
  /// An optional Change representing the field deletion. Returns None if:
  /// - The record is tombstoned
  /// - The record doesn't exist
  /// - The field doesn't exist in the record
  #[must_use = "changes should be propagated to other nodes"]
  pub fn delete_field(&mut self, record_id: &K, field_name: &C) -> Option<Change<K, C, V>> {
    self.delete_field_with_flags(record_id, field_name, 0)
  }

  /// Deletes a specific field from a record with flags.
  ///
  /// # Arguments
  ///
  /// * `record_id` - The unique identifier for the record
  /// * `field_name` - The name of the field to delete
  /// * `flags` - Flags to indicate the type of change
  ///
  /// # Returns
  ///
  /// An optional Change representing the field deletion. Returns None if:
  /// - The record is tombstoned
  /// - The record doesn't exist
  /// - The field doesn't exist in the record
  #[must_use = "changes should be propagated to other nodes"]
  pub fn delete_field_with_flags(
    &mut self,
    record_id: &K,
    field_name: &C,
    flags: u32,
  ) -> Option<Change<K, C, V>> {
    // Check if the record is tombstoned
    if self.is_record_tombstoned(record_id, false) {
      return None;
    }

    // Get the record (return None if it doesn't exist)
    let record = self.data.get_mut(record_id)?;

    // Check if the field exists
    if !record.fields.contains_key(field_name) {
      return None;
    }

    let db_version = self.clock.tick();

    // Get or create column version and increment it
    let col_version = if let Some(col_info) = record.column_versions.get_mut(field_name) {
      col_info.col_version += 1;
      col_info.db_version = db_version;
      col_info.node_id = self.node_id;
      col_info.local_db_version = db_version;
      col_info.col_version
    } else {
      // This shouldn't happen if the field exists, but handle it gracefully
      record.column_versions.insert(
        field_name.clone(),
        ColumnVersion::new(1, db_version, self.node_id, db_version),
      );
      1
    };

    // Update record version boundaries
    if db_version < record.lowest_local_db_version {
      record.lowest_local_db_version = db_version;
    }
    if db_version > record.highest_local_db_version {
      record.highest_local_db_version = db_version;
    }

    // Remove the field from the record (but keep the ColumnVersion as field tombstone)
    record.fields.remove(field_name);

    Some(Change::new(
      record_id.clone(),
      Some(field_name.clone()),
      None, // None value indicates field deletion
      col_version,
      db_version,
      self.node_id,
      db_version,
      flags,
    ))
  }

  /// Merges incoming changes into the CRDT.
  ///
  /// # Arguments
  ///
  /// * `changes` - Vector of changes to merge
  /// * `merge_rule` - The merge rule to use for conflict resolution
  ///
  /// # Returns
  ///
  /// Vector of accepted changes (if requested)
  pub fn merge_changes<R: MergeRule<K, C, V>>(
    &mut self,
    changes: Vec<Change<K, C, V>>,
    merge_rule: &R,
  ) -> Vec<Change<K, C, V>> {
    self.merge_changes_impl(changes, false, merge_rule)
  }

  fn merge_changes_impl<R: MergeRule<K, C, V>>(
    &mut self,
    changes: Vec<Change<K, C, V>>,
    ignore_parent: bool,
    merge_rule: &R,
  ) -> Vec<Change<K, C, V>> {
    let mut accepted_changes = Vec::new();

    if changes.is_empty() {
      return accepted_changes;
    }

    for change in changes {
      // Move values from change to avoid unnecessary clones
      let Change {
        record_id,
        col_name,
        value: remote_value,
        col_version: remote_col_version,
        db_version: remote_db_version,
        node_id: remote_node_id,
        flags,
        ..
      } = change;

      // Always update the logical clock to maintain causal consistency
      let new_local_db_version = self.clock.update(remote_db_version);

      // Skip all changes for tombstoned records
      if self.is_record_tombstoned(&record_id, ignore_parent) {
        continue;
      }

      // Retrieve local column version information
      let local_col_info = if col_name.is_none() {
        // For deletions, check tombstones
        self
          .tombstones
          .find(&record_id)
          .map(|info| info.as_column_version())
      } else if let Some(ref col) = col_name {
        // For column updates, check the record
        self
          .get_record_ptr(&record_id, ignore_parent)
          .and_then(|record| record.column_versions.get(col).copied())
      } else {
        None
      };

      // Determine whether to accept the remote change
      let should_accept = if let Some(local_info) = local_col_info {
        merge_rule.should_accept(
          local_info.col_version,
          local_info.db_version,
          local_info.node_id,
          remote_col_version,
          remote_db_version,
          remote_node_id,
        )
      } else {
        true
      };

      if should_accept {
        if let Some(col_key) = col_name {
          // Handle insertion or update
          let record = self.get_or_create_record_unchecked(&record_id, ignore_parent);

          // Update field value
          if let Some(value) = remote_value.clone() {
            record.fields.insert(col_key.clone(), value);
          } else {
            // If remote_value is None, remove the field
            record.fields.remove(&col_key);
          }

          // Update the column version info and record version boundaries
          record.column_versions.insert(
            col_key.clone(),
            ColumnVersion::new(
              remote_col_version,
              remote_db_version,
              remote_node_id,
              new_local_db_version,
            ),
          );

          // Update version boundaries
          if new_local_db_version < record.lowest_local_db_version {
            record.lowest_local_db_version = new_local_db_version;
          }
          if new_local_db_version > record.highest_local_db_version {
            record.highest_local_db_version = new_local_db_version;
          }

          accepted_changes.push(Change::new(
            record_id,
            Some(col_key),
            remote_value,
            remote_col_version,
            remote_db_version,
            remote_node_id,
            new_local_db_version,
            flags,
          ));
        } else {
          // Handle deletion
          self.data.remove(&record_id);

          // Store deletion information in tombstones
          self.tombstones.insert_or_assign(
            record_id.clone(),
            TombstoneInfo::new(remote_db_version, remote_node_id, new_local_db_version),
          );

          accepted_changes.push(Change::new(
            record_id,
            None,
            None,
            remote_col_version,
            remote_db_version,
            remote_node_id,
            new_local_db_version,
            flags,
          ));
        }
      }
    }

    accepted_changes
  }

  /// Retrieves all changes since a given `last_db_version`.
  ///
  /// # Arguments
  ///
  /// * `last_db_version` - The database version to retrieve changes since
  ///
  /// # Returns
  ///
  /// A vector of changes
  #[must_use]
  pub fn get_changes_since(&self, last_db_version: u64) -> Vec<Change<K, C, V>>
  where
    K: Ord,
    C: Ord,
  {
    self.get_changes_since_excluding(last_db_version, &HashSet::new())
  }

  /// Retrieves all changes since a given `last_db_version`, excluding specific nodes.
  pub fn get_changes_since_excluding(
    &self,
    last_db_version: u64,
    excluding: &HashSet<NodeId>,
  ) -> Vec<Change<K, C, V>>
  where
    K: Ord,
    C: Ord,
  {
    let mut changes = Vec::new();

    // Get changes from parent
    if let Some(ref parent) = self.parent {
      let parent_changes = parent.get_changes_since_excluding(last_db_version, excluding);
      changes.extend(parent_changes);
    }

    // Get changes from regular records
    for (record_id, record) in &self.data {
      // Skip records that haven't changed since last_db_version
      if record.highest_local_db_version <= last_db_version {
        continue;
      }

      for (col_name, clock_info) in &record.column_versions {
        if clock_info.local_db_version > last_db_version && !excluding.contains(&clock_info.node_id)
        {
          let value = record.fields.get(col_name).cloned();

          changes.push(Change::new(
            record_id.clone(),
            Some(col_name.clone()),
            value,
            clock_info.col_version,
            clock_info.db_version,
            clock_info.node_id,
            clock_info.local_db_version,
            0,
          ));
        }
      }
    }

    // Get deletion changes from tombstones
    for (record_id, tombstone_info) in self.tombstones.iter() {
      if tombstone_info.local_db_version > last_db_version
        && !excluding.contains(&tombstone_info.node_id)
      {
        changes.push(Change::new(
          record_id.clone(),
          None,
          None,
          TOMBSTONE_COL_VERSION,
          tombstone_info.db_version,
          tombstone_info.node_id,
          tombstone_info.local_db_version,
          0,
        ));
      }
    }

    if self.parent.is_some() {
      // Compress changes to remove redundant operations
      Self::compress_changes(&mut changes);
    }

    changes
  }

  /// Compresses a vector of changes in-place by removing redundant changes.
  ///
  /// Changes are sorted and then compressed using a two-pointer technique.
  ///
  /// # Performance
  ///
  /// This method uses `sort_unstable_by` which provides O(n log n) average time complexity
  /// but does not preserve the relative order of equal elements. Since the comparator
  /// provides a total ordering, stability is not required.
  pub fn compress_changes(changes: &mut Vec<Change<K, C, V>>)
  where
    K: Ord,
    C: Ord,
  {
    if changes.is_empty() {
      return;
    }

    // Sort changes using the DefaultChangeComparator
    // Use sort_unstable for better performance since we don't need stable sorting
    let comparator = DefaultChangeComparator;
    changes.sort_unstable_by(|a, b| comparator.compare(a, b));

    // Use two-pointer technique to compress in-place
    let mut write = 0;
    for read in 1..changes.len() {
      if changes[read].record_id != changes[write].record_id {
        // New record, always keep it
        write += 1;
        if write != read {
          changes[write] = changes[read].clone();
        }
      } else if changes[read].col_name.is_none() && changes[write].col_name.is_some() {
        // Current read is a deletion, backtrack to first change for this record
        // and replace it with the deletion, effectively discarding all field updates
        let mut first_pos = write;
        while first_pos > 0 && changes[first_pos - 1].record_id == changes[read].record_id {
          first_pos -= 1;
        }
        changes[first_pos] = changes[read].clone();
        write = first_pos;
      } else if changes[read].col_name != changes[write].col_name
        && changes[write].col_name.is_some()
      {
        // New column for the same record
        write += 1;
        if write != read {
          changes[write] = changes[read].clone();
        }
      }
      // Else: same record and column, keep the existing one (most recent due to sorting)
    }

    changes.truncate(write + 1);
  }

  /// Retrieves a reference to a record if it exists.
  pub fn get_record(&self, record_id: &K) -> Option<&Record<C, V>> {
    self.get_record_ptr(record_id, false)
  }

  /// Checks if a record is tombstoned.
  pub fn is_tombstoned(&self, record_id: &K) -> bool {
    self.is_record_tombstoned(record_id, false)
  }

  /// Gets tombstone information for a record.
  pub fn get_tombstone(&self, record_id: &K) -> Option<TombstoneInfo> {
    if let Some(info) = self.tombstones.find(record_id) {
      return Some(info);
    }

    if let Some(ref parent) = self.parent {
      return parent.get_tombstone(record_id);
    }

    None
  }

  /// Removes tombstones older than the specified version.
  ///
  /// # Safety and DoS Mitigation
  ///
  /// **IMPORTANT**: Only call this method when ALL participating nodes have acknowledged
  /// the `min_acknowledged_version`. Compacting too early may cause deleted records to
  /// reappear on nodes that haven't received the deletion yet.
  ///
  /// To prevent DoS via tombstone accumulation:
  /// - Call this method periodically as part of your sync protocol
  /// - Track which versions have been acknowledged by all nodes
  /// - Consider implementing a tombstone limit and rejecting operations when exceeded
  ///
  /// # Arguments
  ///
  /// * `min_acknowledged_version` - Tombstones with db_version < this value will be removed
  ///
  /// # Returns
  ///
  /// The number of tombstones removed
  pub fn compact_tombstones(&mut self, min_acknowledged_version: u64) -> usize {
    self.tombstones.compact(min_acknowledged_version)
  }

  /// Gets the number of tombstones currently stored.
  pub fn tombstone_count(&self) -> usize {
    self.tombstones.len()
  }

  /// Gets the current logical clock.
  pub fn get_clock(&self) -> &LogicalClock {
    &self.clock
  }

  /// Gets a reference to the internal data map.
  pub fn get_data(&self) -> &DataMap<K, Record<C, V>> {
    &self.data
  }

  /// Serializes the CRDT to a JSON string.
  ///
  /// Note: The parent relationship is not serialized and must be rebuilt after deserialization.
  ///
  /// # Errors
  ///
  /// Returns an error if serialization fails.
  #[cfg(feature = "json")]
  pub fn to_json(&self) -> Result<String, serde_json::Error>
  where
    K: serde::Serialize,
    C: serde::Serialize,
    V: serde::Serialize,
  {
    serde_json::to_string(self)
  }

  /// Deserializes a CRDT from a JSON string.
  ///
  /// Note: The parent relationship is not deserialized and will be `None`.
  /// Applications must rebuild parent-child relationships if needed.
  ///
  /// # Errors
  ///
  /// Returns an error if deserialization fails.
  #[cfg(feature = "json")]
  pub fn from_json(json: &str) -> Result<Self, serde_json::Error>
  where
    K: serde::de::DeserializeOwned + Hash + Eq + Clone,
    C: serde::de::DeserializeOwned + Hash + Eq + Clone,
    V: serde::de::DeserializeOwned + Clone,
  {
    serde_json::from_str(json)
  }

  /// Serializes the CRDT to bytes using bincode.
  ///
  /// Note: The parent relationship is not serialized and must be rebuilt after deserialization.
  ///
  /// # Errors
  ///
  /// Returns an error if serialization fails.
  #[cfg(feature = "binary")]
  pub fn to_bytes(&self) -> Result<Vec<u8>, bincode::error::EncodeError>
  where
    K: serde::Serialize,
    C: serde::Serialize,
    V: serde::Serialize,
  {
    bincode::serde::encode_to_vec(self, bincode::config::standard())
  }

  /// Deserializes a CRDT from bytes using bincode.
  ///
  /// Note: The parent relationship is not deserialized and will be `None`.
  /// Applications must rebuild parent-child relationships if needed.
  ///
  /// # Errors
  ///
  /// Returns an error if deserialization fails.
  #[cfg(feature = "binary")]
  pub fn from_bytes(bytes: &[u8]) -> Result<Self, bincode::error::DecodeError>
  where
    K: serde::de::DeserializeOwned + Hash + Eq + Clone,
    C: serde::de::DeserializeOwned + Hash + Eq + Clone,
    V: serde::de::DeserializeOwned + Clone,
  {
    let (result, _len) = bincode::serde::decode_from_slice(bytes, bincode::config::standard())?;
    Ok(result)
  }

  /// Serializes the CRDT to bytes using MessagePack.
  ///
  /// MessagePack supports schema evolution - fields can be added with `#[serde(default)]`
  /// without breaking compatibility with older snapshots.
  ///
  /// Note: The parent relationship is not serialized and must be rebuilt after deserialization.
  ///
  /// # Errors
  ///
  /// Returns an error if serialization fails.
  #[cfg(feature = "msgpack")]
  pub fn to_msgpack_bytes(&self) -> Result<Vec<u8>, rmp_serde::encode::Error>
  where
    K: serde::Serialize,
    C: serde::Serialize,
    V: serde::Serialize,
  {
    rmp_serde::to_vec(self)
  }

  /// Deserializes a CRDT from MessagePack bytes.
  ///
  /// MessagePack supports schema evolution - older snapshots can be loaded even if
  /// the CRDT structure has new fields with `#[serde(default)]`.
  ///
  /// Note: The parent relationship is not deserialized and will be `None`.
  /// Applications must rebuild parent-child relationships if needed.
  ///
  /// # Errors
  ///
  /// Returns an error if deserialization fails.
  #[cfg(feature = "msgpack")]
  pub fn from_msgpack_bytes(bytes: &[u8]) -> Result<Self, rmp_serde::decode::Error>
  where
    K: serde::de::DeserializeOwned + Hash + Eq + Clone,
    C: serde::de::DeserializeOwned + Hash + Eq + Clone,
    V: serde::de::DeserializeOwned + Clone,
  {
    rmp_serde::from_slice(bytes)
  }

  /// Gets records and tombstones that have changed since a specific version.
  ///
  /// This is used for creating incremental snapshots, which only contain
  /// records that have been modified since the base snapshot.
  ///
  /// # Arguments
  ///
  /// * `since_version` - Only return changes after this db_version
  ///
  /// # Returns
  ///
  /// Tuple of (changed_records, new_tombstones)
  ///
  /// # Example
  ///
  /// ```ignore
  /// // Get all changes since version 1000
  /// let (records, tombstones) = crdt.get_changed_since(1000);
  /// // records contains only records modified after version 1000
  /// // tombstones contains only records deleted after version 1000
  /// ```
  #[cfg(feature = "std")]
  pub fn get_changed_since(&self, since_version: u64) -> (
    DataMap<K, Record<C, V>>,
    HashMap<K, TombstoneInfo>,
  ) {
    let records = self.data
      .iter()
      .filter(|(_, record)| record.highest_local_db_version > since_version)
      .map(|(k, v)| (k.clone(), v.clone()))
      .collect();

    let tombstones = self.tombstones
      .iter()
      .filter(|(_, info)| info.local_db_version > since_version)
      .map(|(k, v)| (k.clone(), *v))
      .collect();

    (records, tombstones)
  }

  /// Gets records and tombstones that have changed since a specific version (no_std version).
  #[cfg(not(feature = "std"))]
  pub fn get_changed_since(&self, since_version: u64) -> (
    DataMap<K, Record<C, V>>,
    HashMap<K, TombstoneInfo>,
  ) {
    let records = self.data
      .iter()
      .filter(|(_, record)| record.highest_local_db_version > since_version)
      .map(|(k, v)| (k.clone(), v.clone()))
      .collect();

    let tombstones = self.tombstones
      .iter()
      .filter(|(_, info)| info.local_db_version > since_version)
      .map(|(k, v)| (k.clone(), *v))
      .collect();

    (records, tombstones)
  }

  // Helper methods

  fn is_record_tombstoned(&self, record_id: &K, ignore_parent: bool) -> bool {
    if self.tombstones.find(record_id).is_some() {
      return true;
    }

    if !ignore_parent {
      if let Some(ref parent) = self.parent {
        return parent.is_record_tombstoned(record_id, false);
      }
    }

    false
  }

  fn get_or_create_record_unchecked(
    &mut self,
    record_id: &K,
    ignore_parent: bool,
  ) -> &mut Record<C, V> {
    match self.data.entry(record_id.clone()) {
      DataMapEntry::Occupied(e) => e.into_mut(),
      DataMapEntry::Vacant(e) => {
        let record = if !ignore_parent {
          self
            .parent
            .as_ref()
            .and_then(|p| p.get_record_ptr(record_id, false))
            .cloned()
            .unwrap_or_else(Record::new)
        } else {
          Record::new()
        };
        e.insert(record)
      }
    }
  }

  fn get_record_ptr(&self, record_id: &K, ignore_parent: bool) -> Option<&Record<C, V>> {
    if let Some(record) = self.data.get(record_id) {
      return Some(record);
    }

    if !ignore_parent {
      if let Some(ref parent) = self.parent {
        return parent.get_record_ptr(record_id, false);
      }
    }

    None
  }
}

// Additional methods requiring Ord (sorted-keys feature only)
#[cfg(feature = "sorted-keys")]
impl<K: Ord + Hash + Eq + Clone, C: Hash + Eq + Clone, V: Clone> CRDT<K, C, V> {
  /// Query records within a specific key range (only available with sorted-keys feature).
  ///
  /// This method leverages BTreeMap's range query capability to efficiently retrieve
  /// all records whose keys fall within the specified range.
  ///
  /// **IMPORTANT**: This method only queries the local CRDT's data. If this CRDT has a parent,
  /// parent records are NOT included in the range query results. For parent-aware queries,
  /// iterate over the full range and use `get_record()` for each key.
  ///
  /// # Arguments
  ///
  /// * `range` - A range of keys to query (e.g., `"session-abc-".."session-abd-"`)
  ///
  /// # Returns
  ///
  /// An iterator over key-value pairs within the range (local records only)
  ///
  /// # Example
  ///
  /// ```ignore
  /// // Get all records for a specific session
  /// for (key, record) in crdt.range("session-abc-".."session-abd-") {
  ///     println!("Found record: {:?}", record);
  /// }
  ///
  /// // Get all records with a specific prefix
  /// for (key, record) in crdt.range("user-".."user/") {
  ///     // Keys starting with "user-" (using "user/" as exclusive upper bound)
  /// }
  /// ```
  pub fn range<R>(&self, range: R) -> impl Iterator<Item = (&K, &Record<C, V>)>
  where
    R: core::ops::RangeBounds<K>,
  {
    self.data.range(range)
  }
}

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

  #[cfg(not(feature = "std"))]
  use alloc::{string::ToString, vec};

  #[test]
  fn test_logical_clock() {
    let mut clock = LogicalClock::new();
    assert_eq!(clock.current_time(), 0);

    let t1 = clock.tick();
    assert_eq!(t1, 1);
    assert_eq!(clock.current_time(), 1);

    let t2 = clock.update(5);
    assert_eq!(t2, 6);
    assert_eq!(clock.current_time(), 6);
  }

  #[test]
  fn test_tombstone_storage() {
    let mut storage = TombstoneStorage::new();
    let info = TombstoneInfo::new(10, 1, 10);

    storage.insert_or_assign("key1".to_string(), info);
    assert_eq!(storage.len(), 1);

    assert_eq!(storage.find(&"key1".to_string()), Some(info));
    assert_eq!(storage.find(&"key2".to_string()), None);

    let removed = storage.compact(15);
    assert_eq!(removed, 1);
    assert_eq!(storage.len(), 0);
  }

  #[test]
  fn test_basic_insert() {
    let mut crdt: CRDT<String, String, String> = CRDT::new(1, None);

    let fields = vec![
      ("name".to_string(), "Alice".to_string()),
      ("age".to_string(), "30".to_string()),
    ];

    let changes = crdt.insert_or_update(&"user1".to_string(), fields);

    assert_eq!(changes.len(), 2);
    assert_eq!(crdt.get_data().len(), 1);

    let record = crdt.get_record(&"user1".to_string()).unwrap();
    assert_eq!(record.fields.get("name").unwrap(), "Alice");
    assert_eq!(record.fields.get("age").unwrap(), "30");
  }

  #[test]
  fn test_delete_record() {
    let mut crdt: CRDT<String, String, String> = CRDT::new(1, None);

    let fields = vec![("name".to_string(), "Bob".to_string())];
    let _ = crdt.insert_or_update(&"user2".to_string(), fields);

    let delete_change = crdt.delete_record(&"user2".to_string());
    assert!(delete_change.is_some());
    assert!(crdt.is_tombstoned(&"user2".to_string()));
    assert_eq!(crdt.get_data().len(), 0);
  }

  #[test]
  fn test_merge_changes() {
    let mut crdt1: CRDT<String, String, String> = CRDT::new(1, None);
    let mut crdt2: CRDT<String, String, String> = CRDT::new(2, None);

    let fields1 = vec![("tag".to_string(), "Node1".to_string())];
    let changes1 = crdt1.insert_or_update(&"record1".to_string(), fields1);

    let fields2 = vec![("tag".to_string(), "Node2".to_string())];
    let changes2 = crdt2.insert_or_update(&"record1".to_string(), fields2);

    let merge_rule = DefaultMergeRule;
    crdt1.merge_changes(changes2, &merge_rule);
    crdt2.merge_changes(changes1, &merge_rule);

    // Node2 has higher node_id, so its value should win
    assert_eq!(
      crdt1
        .get_record(&"record1".to_string())
        .unwrap()
        .fields
        .get("tag")
        .unwrap(),
      "Node2"
    );
    assert_eq!(crdt1.get_data(), crdt2.get_data());
  }

  #[test]
  #[cfg(feature = "serde")]
  fn test_change_serialization() {
    #[allow(unused_variables)]
    let change = Change::new(
      "record1".to_string(),
      Some("name".to_string()),
      Some("Alice".to_string()),
      1,
      10,
      1,
      10,
      0,
    );

    // Test JSON serialization
    #[cfg(feature = "json")]
    {
      let json = serde_json::to_string(&change).unwrap();
      let deserialized: Change<String, String, String> = serde_json::from_str(&json).unwrap();
      assert_eq!(change, deserialized);
    }

    // Test binary serialization
    #[cfg(feature = "binary")]
    {
      let bytes = bincode::serde::encode_to_vec(&change, bincode::config::standard()).unwrap();
      let (deserialized, _): (Change<String, String, String>, _) =
        bincode::serde::decode_from_slice(&bytes, bincode::config::standard()).unwrap();
      assert_eq!(change, deserialized);
    }
  }

  #[test]
  #[cfg(feature = "serde")]
  fn test_record_serialization() {
    let mut fields = HashMap::new();
    fields.insert("name".to_string(), "Bob".to_string());
    fields.insert("age".to_string(), "25".to_string());

    let mut column_versions = HashMap::new();
    column_versions.insert("name".to_string(), ColumnVersion::new(1, 10, 1, 10));
    column_versions.insert("age".to_string(), ColumnVersion::new(1, 11, 1, 11));

    #[allow(unused_variables)]
    let record = Record::from_parts(fields, column_versions);

    // Test JSON serialization
    #[cfg(feature = "json")]
    {
      let json = serde_json::to_string(&record).unwrap();
      let deserialized: Record<String, String> = serde_json::from_str(&json).unwrap();
      assert_eq!(record, deserialized);
    }

    // Test binary serialization
    #[cfg(feature = "binary")]
    {
      let bytes = bincode::serde::encode_to_vec(&record, bincode::config::standard()).unwrap();
      let (deserialized, _): (Record<String, String>, _) =
        bincode::serde::decode_from_slice(&bytes, bincode::config::standard()).unwrap();
      assert_eq!(record, deserialized);
    }
  }

  #[test]
  #[cfg(feature = "json")]
  fn test_crdt_json_serialization() {
    let mut crdt: CRDT<String, String, String> = CRDT::new(1, None);

    // Add some data
    let fields = vec![
      ("name".to_string(), "Alice".to_string()),
      ("age".to_string(), "30".to_string()),
    ];
    let _ = crdt.insert_or_update(&"user1".to_string(), fields);

    let fields2 = vec![("name".to_string(), "Bob".to_string())];
    let _ = crdt.insert_or_update(&"user2".to_string(), fields2);

    // Delete one record
    let _ = crdt.delete_record(&"user2".to_string());

    // Serialize to JSON
    let json = crdt.to_json().unwrap();

    // Deserialize
    let deserialized: CRDT<String, String, String> = CRDT::from_json(&json).unwrap();

    // Verify data is preserved
    assert_eq!(crdt.get_data().len(), deserialized.get_data().len());
    assert_eq!(
      crdt.get_record(&"user1".to_string()).unwrap().fields,
      deserialized.get_record(&"user1".to_string()).unwrap().fields
    );

    // Verify tombstones are preserved
    assert_eq!(crdt.tombstone_count(), deserialized.tombstone_count());
    assert!(deserialized.is_tombstoned(&"user2".to_string()));

    // Verify clock is preserved
    assert_eq!(
      crdt.get_clock().current_time(),
      deserialized.get_clock().current_time()
    );

    // Verify parent is None after deserialization
    let has_parent = deserialized.parent.is_some();
    assert!(!has_parent);
  }

  #[test]
  #[cfg(feature = "binary")]
  fn test_crdt_binary_serialization() {
    let mut crdt: CRDT<String, String, String> = CRDT::new(1, None);

    // Add some data
    let fields = vec![
      ("name".to_string(), "Alice".to_string()),
      ("age".to_string(), "30".to_string()),
    ];
    let _ = crdt.insert_or_update(&"user1".to_string(), fields);

    // Serialize to bytes
    let bytes = crdt.to_bytes().unwrap();

    // Deserialize
    let deserialized: CRDT<String, String, String> = CRDT::from_bytes(&bytes).unwrap();

    // Verify data is preserved
    assert_eq!(crdt.get_data().len(), deserialized.get_data().len());
    assert_eq!(
      crdt.get_record(&"user1".to_string()).unwrap().fields,
      deserialized.get_record(&"user1".to_string()).unwrap().fields
    );

    // Verify clock is preserved
    assert_eq!(
      crdt.get_clock().current_time(),
      deserialized.get_clock().current_time()
    );
  }

  #[test]
  #[cfg(feature = "serde")]
  fn test_parent_not_serialized() {
    // Create a parent CRDT
    let mut parent: CRDT<String, String, String> = CRDT::new(1, None);
    let fields = vec![("parent_field".to_string(), "parent_value".to_string())];
    let _ = parent.insert_or_update(&"parent_record".to_string(), fields);

    // Create a child CRDT with parent
    let parent_arc = Arc::new(parent);
    let mut child = CRDT::new(2, Some(parent_arc.clone()));
    let child_fields = vec![("child_field".to_string(), "child_value".to_string())];
    let _ = child.insert_or_update(&"child_record".to_string(), child_fields);

    // Serialize and deserialize the child
    #[cfg(feature = "json")]
    {
      let json = serde_json::to_string(&child).unwrap();
      let deserialized: CRDT<String, String, String> = serde_json::from_str(&json).unwrap();

      // Verify parent is None
      assert!(deserialized.parent.is_none());

      // Verify child's own data is preserved
      assert!(deserialized.get_record(&"child_record".to_string()).is_some());

      // Verify parent's data is NOT in deserialized child
      assert!(deserialized.get_record(&"parent_record".to_string()).is_none());
    }
  }

  #[test]
  #[cfg(feature = "sorted-keys")]
  fn test_sorted_keys_range_queries() {
    let mut crdt: CRDT<String, String, String> = CRDT::new(1, None);

    // Insert records with composite keys
    let _ = crdt.insert_or_update(
      &String::from("session-abc-001"),
      vec![(String::from("data"), String::from("first"))],
    );
    let _ = crdt.insert_or_update(
      &String::from("session-abc-002"),
      vec![(String::from("data"), String::from("second"))],
    );
    let _ = crdt.insert_or_update(
      &String::from("session-abc-003"),
      vec![(String::from("data"), String::from("third"))],
    );
    let _ = crdt.insert_or_update(
      &String::from("session-xyz-001"),
      vec![(String::from("data"), String::from("other"))],
    );
    let _ = crdt.insert_or_update(
      &String::from("user-001"),
      vec![(String::from("name"), String::from("Alice"))],
    );

    // Test range query for session-abc records
    let session_abc_records: Vec<_> = crdt
      .range(String::from("session-abc-")..String::from("session-abd-"))
      .collect();

    assert_eq!(session_abc_records.len(), 3);
    assert!(session_abc_records
      .iter()
      .all(|(k, _)| k.starts_with("session-abc-")));

    // Test that we can iterate in sorted order
    let all_keys: Vec<String> = crdt.get_data().keys().cloned().collect();
    let mut sorted_keys = all_keys.clone();
    sorted_keys.sort();
    assert_eq!(all_keys, sorted_keys, "Keys should be in sorted order");

    // Test range query boundaries
    let range_from_user: Vec<_> = crdt.range(String::from("user-")..).collect();
    assert_eq!(range_from_user.len(), 1);
    assert_eq!(range_from_user[0].0, "user-001");
  }
}