leptos-sync-core 0.9.0

Core synchronization library for Leptos applications
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
//! Custom CRDT Builder Framework
//!
//! This module provides a framework for users to define their own CRDT types
//! using declarative macros and trait implementations.

use crate::crdt::{CRDT, Mergeable, ReplicaId};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::error::Error;
use std::fmt;

/// Error types for CRDT builder operations
#[derive(Debug, Clone, PartialEq)]
pub enum BuilderError {
    /// Invalid field configuration
    InvalidFieldConfig(String),
    /// Missing required field
    MissingField(String),
    /// Type mismatch in field
    TypeMismatch(String),
    /// Strategy not supported
    UnsupportedStrategy(String),
    /// Serialization error
    SerializationError(String),
    /// Merge operation failed
    MergeError(String),
}

impl fmt::Display for BuilderError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            BuilderError::InvalidFieldConfig(msg) => write!(f, "Invalid field config: {}", msg),
            BuilderError::MissingField(field) => write!(f, "Missing required field: {}", field),
            BuilderError::TypeMismatch(msg) => write!(f, "Type mismatch: {}", msg),
            BuilderError::UnsupportedStrategy(strategy) => write!(f, "Unsupported strategy: {}", strategy),
            BuilderError::SerializationError(msg) => write!(f, "Serialization error: {}", msg),
            BuilderError::MergeError(msg) => write!(f, "Merge error: {}", msg),
        }
    }
}

impl Error for BuilderError {}

/// CRDT field strategies
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum CrdtStrategy {
    /// Last-Write-Wins strategy
    Lww,
    /// Add-Wins strategy
    AddWins,
    /// Remove-Wins strategy
    RemoveWins,
    /// Grow-Only Counter
    GCounter,
    /// Multi-Value Register
    MvRegister,
    /// Replicated Growable Array
    Rga,
    /// Logoot Sequence
    Lseq,
    /// Yjs-style tree
    YjsTree,
    /// Directed Acyclic Graph
    Dag,
}

/// Field configuration for CRDT builder
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct FieldConfig {
    /// Field name
    pub name: String,
    /// CRDT strategy to use
    pub strategy: CrdtStrategy,
    /// Whether the field is optional
    pub optional: bool,
    /// Default value for optional fields
    pub default: Option<serde_json::Value>,
}

/// CRDT builder configuration
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CrdtBuilderConfig {
    /// CRDT type name
    pub type_name: String,
    /// Field configurations
    pub fields: Vec<FieldConfig>,
    /// Replica ID field name (optional, defaults to auto-generated)
    pub replica_id_field: Option<String>,
}

/// Trait for CRDT field operations
pub trait CrdtField: Clone + Send + Sync {
    /// Get the field value
    fn get_value(&self) -> serde_json::Value;
    
    /// Set the field value
    fn set_value(&mut self, value: serde_json::Value) -> Result<(), BuilderError>;
    
    /// Merge with another field
    fn merge(&mut self, other: &Self) -> Result<(), BuilderError>;
    
    /// Check if there's a conflict with another field
    fn has_conflict(&self, other: &Self) -> bool;
    
    /// Get the field strategy
    fn strategy(&self) -> CrdtStrategy;
}

/// Generic CRDT field implementation
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct GenericCrdtField {
    /// Field name
    pub name: String,
    /// Field value
    pub value: serde_json::Value,
    /// CRDT strategy
    pub strategy: CrdtStrategy,
    /// Field metadata (timestamps, replica IDs, etc.)
    pub metadata: HashMap<String, serde_json::Value>,
}

impl CrdtField for GenericCrdtField {
    fn get_value(&self) -> serde_json::Value {
        self.value.clone()
    }
    
    fn set_value(&mut self, value: serde_json::Value) -> Result<(), BuilderError> {
        self.value = value;
        Ok(())
    }
    
    fn merge(&mut self, other: &Self) -> Result<(), BuilderError> {
        if self.strategy != other.strategy {
            return Err(BuilderError::TypeMismatch(
                format!("Cannot merge fields with different strategies: {:?} vs {:?}", 
                        self.strategy, other.strategy)
            ));
        }
        
        match self.strategy {
            CrdtStrategy::Lww => self.merge_lww(other),
            CrdtStrategy::AddWins => self.merge_add_wins(other),
            CrdtStrategy::RemoveWins => self.merge_remove_wins(other),
            CrdtStrategy::GCounter => self.merge_gcounter(other),
            CrdtStrategy::MvRegister => self.merge_mv_register(other),
            CrdtStrategy::Rga => self.merge_rga(other),
            CrdtStrategy::Lseq => self.merge_lseq(other),
            CrdtStrategy::YjsTree => self.merge_yjs_tree(other),
            CrdtStrategy::Dag => self.merge_dag(other),
        }
    }
    
    fn has_conflict(&self, other: &Self) -> bool {
        if self.strategy != other.strategy {
            return true;
        }
        
        match self.strategy {
            CrdtStrategy::Lww => self.has_lww_conflict(other),
            CrdtStrategy::AddWins => self.has_add_wins_conflict(other),
            CrdtStrategy::RemoveWins => self.has_remove_wins_conflict(other),
            CrdtStrategy::GCounter => false, // G-Counters never conflict
            CrdtStrategy::MvRegister => self.has_mv_register_conflict(other),
            CrdtStrategy::Rga => self.has_rga_conflict(other),
            CrdtStrategy::Lseq => self.has_lseq_conflict(other),
            CrdtStrategy::YjsTree => self.has_yjs_tree_conflict(other),
            CrdtStrategy::Dag => self.has_dag_conflict(other),
        }
    }
    
    fn strategy(&self) -> CrdtStrategy {
        self.strategy.clone()
    }
}

impl GenericCrdtField {
    /// Create a new generic CRDT field
    pub fn new(name: String, value: serde_json::Value, strategy: CrdtStrategy) -> Self {
        Self {
            name,
            value,
            strategy,
            metadata: HashMap::new(),
        }
    }
    
    /// Merge using Last-Write-Wins strategy
    fn merge_lww(&mut self, other: &Self) -> Result<(), BuilderError> {
        let self_timestamp = self.metadata.get("timestamp")
            .and_then(|v| v.as_u64())
            .unwrap_or(0);
        let other_timestamp = other.metadata.get("timestamp")
            .and_then(|v| v.as_u64())
            .unwrap_or(0);
        
        if other_timestamp >= self_timestamp {
            self.value = other.value.clone();
            self.metadata = other.metadata.clone();
        }
        
        Ok(())
    }
    
    /// Merge using Add-Wins strategy
    fn merge_add_wins(&mut self, other: &Self) -> Result<(), BuilderError> {
        // For add-wins, we keep all values that were added
        if let (Some(self_set), Some(other_set)) = (
            self.value.as_array(),
            other.value.as_array()
        ) {
            let mut combined: Vec<serde_json::Value> = self_set.clone();
            for item in other_set {
                if !combined.contains(item) {
                    combined.push(item.clone());
                }
            }
            self.value = serde_json::Value::Array(combined);
        } else {
            // For non-array values, use LWW as fallback
            self.merge_lww(other)?;
        }
        
        Ok(())
    }
    
    /// Merge using Remove-Wins strategy
    fn merge_remove_wins(&mut self, other: &Self) -> Result<(), BuilderError> {
        // For remove-wins, we remove items that were explicitly removed
        if let (Some(self_set), Some(other_set)) = (
            self.value.as_array(),
            other.value.as_array()
        ) {
            let mut combined: Vec<serde_json::Value> = self_set.clone();
            for item in other_set {
                if !combined.contains(item) {
                    combined.push(item.clone());
                }
            }
            
            // Remove items marked as removed
            combined.retain(|item| {
                !other.metadata.get("removed")
                    .and_then(|v| v.as_array())
                    .map(|removed| removed.contains(item))
                    .unwrap_or(false)
            });
            
            self.value = serde_json::Value::Array(combined);
        } else {
            // For non-array values, use LWW as fallback
            self.merge_lww(other)?;
        }
        
        Ok(())
    }
    
    /// Merge using G-Counter strategy
    fn merge_gcounter(&mut self, other: &Self) -> Result<(), BuilderError> {
        if let (Some(self_count), Some(other_count)) = (
            self.value.as_u64(),
            other.value.as_u64()
        ) {
            self.value = serde_json::Value::Number(serde_json::Number::from(
                self_count.max(other_count)
            ));
        }
        
        Ok(())
    }
    
    /// Merge using Multi-Value Register strategy
    fn merge_mv_register(&mut self, other: &Self) -> Result<(), BuilderError> {
        // For MV-Register, we keep all concurrent values
        if let (Some(self_values), Some(other_values)) = (
            self.value.as_array(),
            other.value.as_array()
        ) {
            let mut combined: Vec<serde_json::Value> = self_values.clone();
            for value in other_values {
                if !combined.contains(value) {
                    combined.push(value.clone());
                }
            }
            self.value = serde_json::Value::Array(combined);
        } else {
            // For non-array values, use LWW as fallback
            self.merge_lww(other)?;
        }
        
        Ok(())
    }
    
    /// Merge using RGA strategy (simplified)
    fn merge_rga(&mut self, other: &Self) -> Result<(), BuilderError> {
        // Simplified RGA merge - in practice, this would be much more complex
        self.merge_add_wins(other)
    }
    
    /// Merge using LSEQ strategy (simplified)
    fn merge_lseq(&mut self, other: &Self) -> Result<(), BuilderError> {
        // Simplified LSEQ merge - in practice, this would be much more complex
        self.merge_add_wins(other)
    }
    
    /// Merge using Yjs-style tree strategy (simplified)
    fn merge_yjs_tree(&mut self, other: &Self) -> Result<(), BuilderError> {
        // Simplified Yjs tree merge - in practice, this would be much more complex
        self.merge_add_wins(other)
    }
    
    /// Merge using DAG strategy (simplified)
    fn merge_dag(&mut self, other: &Self) -> Result<(), BuilderError> {
        // Simplified DAG merge - in practice, this would be much more complex
        self.merge_add_wins(other)
    }
    
    // Conflict detection methods
    fn has_lww_conflict(&self, other: &Self) -> bool {
        let self_timestamp = self.metadata.get("timestamp")
            .and_then(|v| v.as_u64())
            .unwrap_or(0);
        let other_timestamp = other.metadata.get("timestamp")
            .and_then(|v| v.as_u64())
            .unwrap_or(0);
        
        self.value != other.value && self_timestamp == other_timestamp
    }
    
    fn has_add_wins_conflict(&self, _other: &Self) -> bool {
        false // Add-wins never conflicts
    }
    
    fn has_remove_wins_conflict(&self, _other: &Self) -> bool {
        false // Remove-wins never conflicts
    }
    
    fn has_mv_register_conflict(&self, other: &Self) -> bool {
        self.value != other.value
    }
    
    fn has_rga_conflict(&self, other: &Self) -> bool {
        self.value != other.value
    }
    
    fn has_lseq_conflict(&self, other: &Self) -> bool {
        self.value != other.value
    }
    
    fn has_yjs_tree_conflict(&self, other: &Self) -> bool {
        self.value != other.value
    }
    
    fn has_dag_conflict(&self, other: &Self) -> bool {
        self.value != other.value
    }
}

/// Custom CRDT built using the builder framework
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CustomCrdt {
    /// CRDT configuration
    pub config: CrdtBuilderConfig,
    /// Field values
    pub fields: HashMap<String, GenericCrdtField>,
    /// Replica ID
    pub replica_id: ReplicaId,
}

impl CRDT for CustomCrdt {
    fn replica_id(&self) -> &ReplicaId {
        &self.replica_id
    }
}

impl Mergeable for CustomCrdt {
    type Error = BuilderError;
    
    fn merge(&mut self, other: &Self) -> Result<(), Self::Error> {
        if self.config.type_name != other.config.type_name {
            return Err(BuilderError::TypeMismatch(
                format!("Cannot merge CRDTs of different types: {} vs {}", 
                        self.config.type_name, other.config.type_name)
            ));
        }
        
        // Merge each field
        for (field_name, other_field) in &other.fields {
            if let Some(self_field) = self.fields.get_mut(field_name) {
                self_field.merge(other_field)?;
            } else {
                // Add new field from other CRDT
                self.fields.insert(field_name.clone(), other_field.clone());
            }
        }
        
        Ok(())
    }
    
    fn has_conflict(&self, other: &Self) -> bool {
        if self.config.type_name != other.config.type_name {
            return true;
        }
        
        // Check for conflicts in each field
        for (field_name, self_field) in &self.fields {
            if let Some(other_field) = other.fields.get(field_name) {
                if self_field.has_conflict(other_field) {
                    return true;
                }
            }
        }
        
        false
    }
}

impl CustomCrdt {
    /// Create a new custom CRDT
    pub fn new(config: CrdtBuilderConfig, replica_id: ReplicaId) -> Self {
        let mut fields = HashMap::new();
        
        // Initialize fields with default values
        for field_config in &config.fields {
            let default_value = field_config.default.clone()
                .unwrap_or_else(|| serde_json::Value::Null);
            
            let field = GenericCrdtField::new(
                field_config.name.clone(),
                default_value,
                field_config.strategy.clone(),
            );
            
            fields.insert(field_config.name.clone(), field);
        }
        
        Self {
            config,
            fields,
            replica_id,
        }
    }
    
    /// Get a field value
    pub fn get_field(&self, field_name: &str) -> Option<&serde_json::Value> {
        self.fields.get(field_name).map(|f| &f.value)
    }
    
    /// Set a field value
    pub fn set_field(&mut self, field_name: &str, value: serde_json::Value) -> Result<(), BuilderError> {
        if let Some(field) = self.fields.get_mut(field_name) {
            field.set_value(value)?;
            // Update timestamp for LWW fields
            if field.strategy == CrdtStrategy::Lww {
                field.metadata.insert("timestamp".to_string(), 
                    serde_json::Value::Number(serde_json::Number::from(
                        std::time::SystemTime::now()
                            .duration_since(std::time::UNIX_EPOCH)
                            .unwrap_or_default()
                            .as_millis() as u64
                    )));
            }
            Ok(())
        } else {
            Err(BuilderError::MissingField(field_name.to_string()))
        }
    }
    
    /// Get all field names
    pub fn field_names(&self) -> Vec<String> {
        self.fields.keys().cloned().collect()
    }
    
    /// Get field configuration
    pub fn get_field_config(&self, field_name: &str) -> Option<&FieldConfig> {
        self.config.fields.iter().find(|f| f.name == field_name)
    }
}

/// CRDT Builder for creating custom CRDT types
pub struct CrdtBuilder {
    config: CrdtBuilderConfig,
}

impl CrdtBuilder {
    /// Create a new CRDT builder
    pub fn new(type_name: String) -> Self {
        Self {
            config: CrdtBuilderConfig {
                type_name,
                fields: Vec::new(),
                replica_id_field: None,
            },
        }
    }
    
    /// Add a field to the CRDT
    pub fn add_field(mut self, name: String, strategy: CrdtStrategy) -> Self {
        self.config.fields.push(FieldConfig {
            name,
            strategy,
            optional: false,
            default: None,
        });
        self
    }
    
    /// Add an optional field with default value
    pub fn add_optional_field(mut self, name: String, strategy: CrdtStrategy, default: serde_json::Value) -> Self {
        self.config.fields.push(FieldConfig {
            name,
            strategy,
            optional: true,
            default: Some(default),
        });
        self
    }
    
    /// Set the replica ID field name
    pub fn replica_id_field(mut self, field_name: String) -> Self {
        self.config.replica_id_field = Some(field_name);
        self
    }
    
    /// Build the CRDT configuration
    pub fn build(self) -> CrdtBuilderConfig {
        self.config
    }
    
    /// Create a new CRDT instance
    pub fn create_crdt(self, replica_id: ReplicaId) -> CustomCrdt {
        CustomCrdt::new(self.config, replica_id)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::crdt::ReplicaId;
    use uuid::Uuid;
    
    #[test]
    fn test_crdt_builder_creation() {
        let config = CrdtBuilder::new("TestCRDT".to_string())
            .add_field("name".to_string(), CrdtStrategy::Lww)
            .add_field("count".to_string(), CrdtStrategy::GCounter)
            .add_optional_field("tags".to_string(), CrdtStrategy::AddWins, 
                serde_json::Value::Array(vec![]))
            .build();
        
        assert_eq!(config.type_name, "TestCRDT");
        assert_eq!(config.fields.len(), 3);
        assert_eq!(config.fields[0].name, "name");
        assert_eq!(config.fields[0].strategy, CrdtStrategy::Lww);
        assert_eq!(config.fields[1].name, "count");
        assert_eq!(config.fields[1].strategy, CrdtStrategy::GCounter);
        assert_eq!(config.fields[2].name, "tags");
        assert_eq!(config.fields[2].strategy, CrdtStrategy::AddWins);
        assert!(config.fields[2].optional);
    }
    
    #[test]
    fn test_custom_crdt_creation() {
        let replica_id = ReplicaId::from(Uuid::new_v4());
        let config = CrdtBuilder::new("TestCRDT".to_string())
            .add_field("name".to_string(), CrdtStrategy::Lww)
            .add_field("count".to_string(), CrdtStrategy::GCounter)
            .build();
        
        let crdt = CustomCrdt::new(config, replica_id.clone());
        
        assert_eq!(crdt.replica_id(), &replica_id);
        assert_eq!(crdt.field_names().len(), 2);
        assert!(crdt.get_field("name").is_some());
        assert!(crdt.get_field("count").is_some());
    }
    
    #[test]
    fn test_custom_crdt_field_operations() {
        let replica_id = ReplicaId::from(Uuid::new_v4());
        let config = CrdtBuilder::new("TestCRDT".to_string())
            .add_field("name".to_string(), CrdtStrategy::Lww)
            .add_field("count".to_string(), CrdtStrategy::GCounter)
            .build();
        
        let mut crdt = CustomCrdt::new(config, replica_id);
        
        // Set field values
        crdt.set_field("name", serde_json::Value::String("test".to_string())).unwrap();
        crdt.set_field("count", serde_json::Value::Number(serde_json::Number::from(42))).unwrap();
        
        // Get field values
        assert_eq!(crdt.get_field("name"), Some(&serde_json::Value::String("test".to_string())));
        assert_eq!(crdt.get_field("count"), Some(&serde_json::Value::Number(serde_json::Number::from(42))));
    }
    
    #[test]
    fn test_custom_crdt_merge() {
        let replica_id1 = ReplicaId::from(Uuid::new_v4());
        let replica_id2 = ReplicaId::from(Uuid::new_v4());
        
        let config = CrdtBuilder::new("TestCRDT".to_string())
            .add_field("name".to_string(), CrdtStrategy::Lww)
            .add_field("count".to_string(), CrdtStrategy::GCounter)
            .build();
        
        let mut crdt1 = CustomCrdt::new(config.clone(), replica_id1);
        let mut crdt2 = CustomCrdt::new(config, replica_id2);
        
        // Set different values with a small delay to ensure different timestamps
        crdt1.set_field("name", serde_json::Value::String("alice".to_string())).unwrap();
        crdt1.set_field("count", serde_json::Value::Number(serde_json::Number::from(10))).unwrap();
        
        // Small delay to ensure different timestamp
        std::thread::sleep(std::time::Duration::from_millis(1));
        
        crdt2.set_field("name", serde_json::Value::String("bob".to_string())).unwrap();
        crdt2.set_field("count", serde_json::Value::Number(serde_json::Number::from(20))).unwrap();
        
        // Merge crdt2 into crdt1
        crdt1.merge(&crdt2).unwrap();
        
        // Check merged values
        // Name should be "bob" (LWW with later timestamp)
        assert_eq!(crdt1.get_field("name"), Some(&serde_json::Value::String("bob".to_string())));
        // Count should be 20 (GCounter takes max)
        assert_eq!(crdt1.get_field("count"), Some(&serde_json::Value::Number(serde_json::Number::from(20))));
    }
    
    #[test]
    fn test_custom_crdt_conflict_detection() {
        let replica_id1 = ReplicaId::from(Uuid::new_v4());
        let replica_id2 = ReplicaId::from(Uuid::new_v4());
        
        let config = CrdtBuilder::new("TestCRDT".to_string())
            .add_field("name".to_string(), CrdtStrategy::Lww)
            .add_field("count".to_string(), CrdtStrategy::GCounter)
            .build();
        
        let mut crdt1 = CustomCrdt::new(config.clone(), replica_id1);
        let mut crdt2 = CustomCrdt::new(config, replica_id2);
        
        // Set same timestamp for LWW conflict
        crdt1.set_field("name", serde_json::Value::String("alice".to_string())).unwrap();
        crdt2.set_field("name", serde_json::Value::String("bob".to_string())).unwrap();
        
        // Manually set same timestamp to create conflict
        if let Some(field1) = crdt1.fields.get_mut("name") {
            field1.metadata.insert("timestamp".to_string(), serde_json::Value::Number(serde_json::Number::from(1000)));
        }
        if let Some(field2) = crdt2.fields.get_mut("name") {
            field2.metadata.insert("timestamp".to_string(), serde_json::Value::Number(serde_json::Number::from(1000)));
        }
        
        // Should detect conflict
        assert!(crdt1.has_conflict(&crdt2));
    }
    
    #[test]
    fn test_generic_field_merge_strategies() {
        // Test LWW merge
        let mut field1 = GenericCrdtField::new(
            "test".to_string(),
            serde_json::Value::String("alice".to_string()),
            CrdtStrategy::Lww,
        );
        let field2 = GenericCrdtField::new(
            "test".to_string(),
            serde_json::Value::String("bob".to_string()),
            CrdtStrategy::Lww,
        );
        
        // Set timestamps
        field1.metadata.insert("timestamp".to_string(), serde_json::Value::Number(serde_json::Number::from(1000)));
        let mut field2_with_timestamp = field2.clone();
        field2_with_timestamp.metadata.insert("timestamp".to_string(), serde_json::Value::Number(serde_json::Number::from(2000)));
        
        // Merge should take the later timestamp
        field1.merge(&field2_with_timestamp).unwrap();
        assert_eq!(field1.value, serde_json::Value::String("bob".to_string()));
        
        // Test GCounter merge
        let mut counter1 = GenericCrdtField::new(
            "count".to_string(),
            serde_json::Value::Number(serde_json::Number::from(10)),
            CrdtStrategy::GCounter,
        );
        let counter2 = GenericCrdtField::new(
            "count".to_string(),
            serde_json::Value::Number(serde_json::Number::from(20)),
            CrdtStrategy::GCounter,
        );
        
        counter1.merge(&counter2).unwrap();
        assert_eq!(counter1.value, serde_json::Value::Number(serde_json::Number::from(20)));
    }
    
    #[test]
    fn test_builder_error_handling() {
        let replica_id = ReplicaId::from(Uuid::new_v4());
        let config = CrdtBuilder::new("TestCRDT".to_string())
            .add_field("name".to_string(), CrdtStrategy::Lww)
            .build();
        
        let mut crdt = CustomCrdt::new(config, replica_id);
        
        // Test missing field error
        let result = crdt.set_field("nonexistent", serde_json::Value::String("test".to_string()));
        assert!(result.is_err());
        assert_eq!(result.unwrap_err(), BuilderError::MissingField("nonexistent".to_string()));
    }
}