ceres-core 0.4.0

Core types, harvesting logic, and services for Ceres
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
//! Sync service layer for portal synchronization logic.
//!
//! This module provides pure business logic for delta detection and sync statistics,
//! decoupled from I/O operations and CLI orchestration.

use std::sync::atomic::{AtomicUsize, Ordering};

/// Outcome of processing a single dataset during sync.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SyncOutcome {
    /// Dataset content hash matches existing - no changes needed
    Unchanged,
    /// Dataset content changed - embedding regenerated
    Updated,
    /// New dataset - first time seeing this dataset
    Created,
    /// Processing failed for this dataset
    Failed,
    /// Dataset skipped due to circuit breaker being open
    Skipped,
}

/// Statistics for a portal sync operation.
#[derive(Debug, Default, Clone, serde::Serialize, serde::Deserialize)]
pub struct SyncStats {
    pub unchanged: usize,
    pub updated: usize,
    pub created: usize,
    pub failed: usize,
    /// Number of datasets skipped due to circuit breaker being open.
    #[serde(default)]
    pub skipped: usize,
}

impl SyncStats {
    /// Creates a new empty stats tracker.
    pub fn new() -> Self {
        Self::default()
    }

    /// Records an outcome, incrementing the appropriate counter.
    pub fn record(&mut self, outcome: SyncOutcome) {
        match outcome {
            SyncOutcome::Unchanged => self.unchanged += 1,
            SyncOutcome::Updated => self.updated += 1,
            SyncOutcome::Created => self.created += 1,
            SyncOutcome::Failed => self.failed += 1,
            SyncOutcome::Skipped => self.skipped += 1,
        }
    }

    /// Returns the total number of processed datasets.
    pub fn total(&self) -> usize {
        self.unchanged + self.updated + self.created + self.failed + self.skipped
    }

    /// Returns the number of successfully processed datasets.
    pub fn successful(&self) -> usize {
        self.unchanged + self.updated + self.created
    }
}

// =============================================================================
// Sync Status and Result Types (for cancellation support)
// =============================================================================

/// Overall status of a sync operation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SyncStatus {
    /// Sync completed successfully with all datasets processed.
    Completed,
    /// Sync was cancelled but partial progress was saved.
    Cancelled,
}

impl SyncStatus {
    /// Returns the string representation for database storage.
    pub fn as_str(&self) -> &'static str {
        match self {
            SyncStatus::Completed => "completed",
            SyncStatus::Cancelled => "cancelled",
        }
    }

    /// Returns true if the sync was completed successfully.
    pub fn is_completed(&self) -> bool {
        matches!(self, SyncStatus::Completed)
    }

    /// Returns true if the sync was cancelled.
    pub fn is_cancelled(&self) -> bool {
        matches!(self, SyncStatus::Cancelled)
    }
}

/// Result of a sync operation including status and statistics.
#[derive(Debug, Clone)]
pub struct SyncResult {
    /// The final status of the sync operation.
    pub status: SyncStatus,
    /// Statistics about processed datasets.
    pub stats: SyncStats,
    /// Optional message providing context (e.g., cancellation reason).
    pub message: Option<String>,
}

impl SyncResult {
    /// Creates a completed sync result.
    pub fn completed(stats: SyncStats) -> Self {
        Self {
            status: SyncStatus::Completed,
            stats,
            message: None,
        }
    }

    /// Creates a cancelled sync result with partial statistics.
    pub fn cancelled(stats: SyncStats) -> Self {
        Self {
            status: SyncStatus::Cancelled,
            stats,
            message: Some("Operation cancelled - partial progress saved".to_string()),
        }
    }

    /// Returns true if the sync was fully successful.
    pub fn is_completed(&self) -> bool {
        self.status.is_completed()
    }

    /// Returns true if the sync was cancelled.
    pub fn is_cancelled(&self) -> bool {
        self.status.is_cancelled()
    }
}

/// Thread-safe wrapper for [`SyncStats`] using atomic counters.
///
/// This is useful for concurrent harvesting where multiple tasks
/// update statistics simultaneously without requiring a mutex.
///
/// # Example
///
/// ```
/// use ceres_core::sync::{AtomicSyncStats, SyncOutcome};
///
/// let stats = AtomicSyncStats::new();
///
/// // Can be safely called from multiple threads
/// stats.record(SyncOutcome::Created);
/// stats.record(SyncOutcome::Unchanged);
///
/// let snapshot = stats.to_stats();
/// assert_eq!(snapshot.created, 1);
/// assert_eq!(snapshot.unchanged, 1);
/// ```
pub struct AtomicSyncStats {
    unchanged: AtomicUsize,
    updated: AtomicUsize,
    created: AtomicUsize,
    failed: AtomicUsize,
    skipped: AtomicUsize,
}

impl AtomicSyncStats {
    /// Creates a new zeroed stats tracker.
    pub fn new() -> Self {
        Self {
            unchanged: AtomicUsize::new(0),
            updated: AtomicUsize::new(0),
            created: AtomicUsize::new(0),
            failed: AtomicUsize::new(0),
            skipped: AtomicUsize::new(0),
        }
    }

    /// Records an outcome, incrementing the appropriate counter atomically.
    pub fn record(&self, outcome: SyncOutcome) {
        match outcome {
            SyncOutcome::Unchanged => self.unchanged.fetch_add(1, Ordering::Relaxed),
            SyncOutcome::Updated => self.updated.fetch_add(1, Ordering::Relaxed),
            SyncOutcome::Created => self.created.fetch_add(1, Ordering::Relaxed),
            SyncOutcome::Failed => self.failed.fetch_add(1, Ordering::Relaxed),
            SyncOutcome::Skipped => self.skipped.fetch_add(1, Ordering::Relaxed),
        };
    }

    /// Converts atomic counters to a snapshot [`SyncStats`].
    pub fn to_stats(&self) -> SyncStats {
        SyncStats {
            unchanged: self.unchanged.load(Ordering::Relaxed),
            updated: self.updated.load(Ordering::Relaxed),
            created: self.created.load(Ordering::Relaxed),
            failed: self.failed.load(Ordering::Relaxed),
            skipped: self.skipped.load(Ordering::Relaxed),
        }
    }
}

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

/// Result of delta detection for a dataset.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ReprocessingDecision {
    /// The outcome classification for this dataset
    pub outcome: SyncOutcome,
    /// Human-readable reason for the decision
    pub reason: &'static str,
}

impl ReprocessingDecision {
    /// Returns true if this is a legacy record update (existing record without hash).
    pub fn is_legacy(&self) -> bool {
        self.reason == "legacy record without hash"
    }
}

/// Trait for delta detection strategies.
///
/// Implementations determine whether a dataset needs reprocessing based on
/// its existing and new content hashes. This enables different strategies
/// such as content-hash comparison, always-reprocess, or timestamp-based detection.
pub trait DeltaDetector: Send + Sync + Clone {
    /// Determines if a dataset needs reprocessing.
    ///
    /// Implementations must only return `Created`, `Updated`, or `Unchanged` outcomes.
    /// `Failed` and `Skipped` are reserved for runtime errors in the harvest pipeline.
    ///
    /// # Arguments
    /// * `existing_hash` - The stored content hash lookup result:
    ///   - `None` — dataset not found in the store (new dataset)
    ///   - `Some(None)` — dataset exists but has no stored hash (legacy record)
    ///   - `Some(Some(hash))` — dataset exists with the given content hash
    /// * `new_hash` - The computed content hash from the portal data
    fn needs_reprocessing(
        &self,
        existing_hash: Option<&Option<String>>,
        new_hash: &str,
    ) -> ReprocessingDecision;
}

/// Default delta detector using content hash comparison.
///
/// Compares the stored content hash with the newly computed hash to determine
/// if a dataset's embedding needs to be regenerated.
#[derive(Debug, Clone, Default)]
pub struct ContentHashDetector;

impl DeltaDetector for ContentHashDetector {
    fn needs_reprocessing(
        &self,
        existing_hash: Option<&Option<String>>,
        new_hash: &str,
    ) -> ReprocessingDecision {
        match existing_hash {
            Some(Some(hash)) if hash == new_hash => {
                // Hash matches - content unchanged
                ReprocessingDecision {
                    outcome: SyncOutcome::Unchanged,
                    reason: "content hash matches",
                }
            }
            Some(Some(_)) => {
                // Hash exists but differs - content updated
                ReprocessingDecision {
                    outcome: SyncOutcome::Updated,
                    reason: "content hash changed",
                }
            }
            Some(None) => {
                // Exists but no hash (legacy data) - treat as update
                ReprocessingDecision {
                    outcome: SyncOutcome::Updated,
                    reason: "legacy record without hash",
                }
            }
            None => {
                // Not in existing data - new dataset
                ReprocessingDecision {
                    outcome: SyncOutcome::Created,
                    reason: "new dataset",
                }
            }
        }
    }
}

/// Delta detector that always triggers reprocessing.
///
/// Useful for full rebuilds where all embeddings should be regenerated
/// regardless of content changes.
#[derive(Debug, Clone, Default)]
pub struct AlwaysReprocessDetector;

impl DeltaDetector for AlwaysReprocessDetector {
    fn needs_reprocessing(
        &self,
        existing_hash: Option<&Option<String>>,
        _new_hash: &str,
    ) -> ReprocessingDecision {
        match existing_hash {
            Some(_) => ReprocessingDecision {
                outcome: SyncOutcome::Updated,
                reason: "always reprocess strategy",
            },
            None => ReprocessingDecision {
                outcome: SyncOutcome::Created,
                reason: "new dataset",
            },
        }
    }
}

/// Determines if a dataset needs reprocessing based on content hash comparison.
///
/// This is a convenience wrapper around [`ContentHashDetector`].
///
/// # Arguments
/// * `existing_hash` - The stored content hash for this dataset (None if new dataset)
/// * `new_hash` - The computed content hash from the portal data
///
/// # Returns
/// A `ReprocessingDecision` indicating whether embedding regeneration is needed
/// and the classification of this sync operation.
pub fn needs_reprocessing(
    existing_hash: Option<&Option<String>>,
    new_hash: &str,
) -> ReprocessingDecision {
    ContentHashDetector.needs_reprocessing(existing_hash, new_hash)
}

// =============================================================================
// Batch Harvest Types
// =============================================================================

/// Result of harvesting a single portal in batch mode.
#[derive(Debug, Clone)]
pub struct PortalHarvestResult {
    /// Portal name identifier.
    pub portal_name: String,
    /// Portal URL.
    pub portal_url: String,
    /// Sync statistics for this portal.
    pub stats: SyncStats,
    /// Error message if harvest failed, None if successful.
    pub error: Option<String>,
}

impl PortalHarvestResult {
    /// Creates a successful harvest result.
    pub fn success(name: String, url: String, stats: SyncStats) -> Self {
        Self {
            portal_name: name,
            portal_url: url,
            stats,
            error: None,
        }
    }

    /// Creates a failed harvest result.
    pub fn failure(name: String, url: String, error: String) -> Self {
        Self {
            portal_name: name,
            portal_url: url,
            stats: SyncStats::default(),
            error: Some(error),
        }
    }

    /// Returns true if the harvest was successful.
    pub fn is_success(&self) -> bool {
        self.error.is_none()
    }
}

/// Aggregated results from batch harvesting multiple portals.
#[derive(Debug, Clone, Default)]
pub struct BatchHarvestSummary {
    /// Results for each portal.
    pub results: Vec<PortalHarvestResult>,
}

impl BatchHarvestSummary {
    /// Creates a new empty summary.
    pub fn new() -> Self {
        Self::default()
    }

    /// Adds a portal harvest result.
    pub fn add(&mut self, result: PortalHarvestResult) {
        self.results.push(result);
    }

    /// Returns the count of successful harvests.
    pub fn successful_count(&self) -> usize {
        self.results.iter().filter(|r| r.is_success()).count()
    }

    /// Returns the count of failed harvests.
    pub fn failed_count(&self) -> usize {
        self.results.iter().filter(|r| !r.is_success()).count()
    }

    /// Returns the total number of datasets across all successful portals.
    pub fn total_datasets(&self) -> usize {
        self.results.iter().map(|r| r.stats.total()).sum()
    }

    /// Returns the total number of portals processed.
    pub fn total_portals(&self) -> usize {
        self.results.len()
    }
}

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

    #[test]
    fn test_sync_stats_default() {
        let stats = SyncStats::new();
        assert_eq!(stats.unchanged, 0);
        assert_eq!(stats.updated, 0);
        assert_eq!(stats.created, 0);
        assert_eq!(stats.failed, 0);
        assert_eq!(stats.skipped, 0);
    }

    #[test]
    fn test_sync_stats_record() {
        let mut stats = SyncStats::new();
        stats.record(SyncOutcome::Unchanged);
        stats.record(SyncOutcome::Updated);
        stats.record(SyncOutcome::Created);
        stats.record(SyncOutcome::Failed);
        stats.record(SyncOutcome::Skipped);

        assert_eq!(stats.unchanged, 1);
        assert_eq!(stats.updated, 1);
        assert_eq!(stats.created, 1);
        assert_eq!(stats.failed, 1);
        assert_eq!(stats.skipped, 1);
    }

    #[test]
    fn test_sync_stats_total() {
        let mut stats = SyncStats::new();
        stats.unchanged = 10;
        stats.updated = 5;
        stats.created = 3;
        stats.failed = 2;
        stats.skipped = 1;

        assert_eq!(stats.total(), 21);
    }

    #[test]
    fn test_sync_stats_successful() {
        let mut stats = SyncStats::new();
        stats.unchanged = 10;
        stats.updated = 5;
        stats.created = 3;
        stats.failed = 2;
        stats.skipped = 1;

        // successful does not include failed or skipped
        assert_eq!(stats.successful(), 18);
    }

    #[test]
    fn test_needs_reprocessing_unchanged() {
        let hash = "abc123".to_string();
        let existing = Some(Some(hash.clone()));
        let decision = needs_reprocessing(existing.as_ref(), &hash);

        assert_eq!(decision.outcome, SyncOutcome::Unchanged);
        assert_eq!(decision.reason, "content hash matches");
    }

    #[test]
    fn test_needs_reprocessing_updated() {
        let old_hash = "abc123".to_string();
        let new_hash = "def456";
        let existing = Some(Some(old_hash));
        let decision = needs_reprocessing(existing.as_ref(), new_hash);

        assert_eq!(decision.outcome, SyncOutcome::Updated);
        assert_eq!(decision.reason, "content hash changed");
    }

    #[test]
    fn test_needs_reprocessing_legacy() {
        let existing: Option<Option<String>> = Some(None);
        let decision = needs_reprocessing(existing.as_ref(), "new_hash");

        assert_eq!(decision.outcome, SyncOutcome::Updated);
        assert_eq!(decision.reason, "legacy record without hash");
    }

    #[test]
    fn test_needs_reprocessing_new() {
        let decision = needs_reprocessing(None, "new_hash");

        assert_eq!(decision.outcome, SyncOutcome::Created);
        assert_eq!(decision.reason, "new dataset");
    }

    #[test]
    fn test_is_legacy_true() {
        let existing: Option<Option<String>> = Some(None);
        let decision = needs_reprocessing(existing.as_ref(), "new_hash");

        assert!(decision.is_legacy());
    }

    #[test]
    fn test_is_legacy_false() {
        let decision = needs_reprocessing(None, "new_hash");
        assert!(!decision.is_legacy());

        let hash = "abc123".to_string();
        let existing = Some(Some(hash.clone()));
        let decision = needs_reprocessing(existing.as_ref(), &hash);
        assert!(!decision.is_legacy());
    }

    // =========================================================================
    // PortalHarvestResult tests
    // =========================================================================

    #[test]
    fn test_portal_harvest_result_success() {
        let stats = SyncStats {
            unchanged: 5,
            updated: 3,
            created: 2,
            failed: 0,
            skipped: 0,
        };
        let result = PortalHarvestResult::success(
            "test".to_string(),
            "https://example.com".to_string(),
            stats,
        );
        assert!(result.is_success());
        assert!(result.error.is_none());
        assert_eq!(result.stats.total(), 10);
        assert_eq!(result.portal_name, "test");
        assert_eq!(result.portal_url, "https://example.com");
    }

    #[test]
    fn test_portal_harvest_result_failure() {
        let result = PortalHarvestResult::failure(
            "test".to_string(),
            "https://example.com".to_string(),
            "Connection timeout".to_string(),
        );
        assert!(!result.is_success());
        assert_eq!(result.error, Some("Connection timeout".to_string()));
        assert_eq!(result.stats.total(), 0);
    }

    // =========================================================================
    // BatchHarvestSummary tests
    // =========================================================================

    #[test]
    fn test_batch_harvest_summary_empty() {
        let summary = BatchHarvestSummary::new();
        assert_eq!(summary.successful_count(), 0);
        assert_eq!(summary.failed_count(), 0);
        assert_eq!(summary.total_datasets(), 0);
        assert_eq!(summary.total_portals(), 0);
    }

    #[test]
    fn test_batch_harvest_summary_mixed_results() {
        let mut summary = BatchHarvestSummary::new();

        let stats1 = SyncStats {
            unchanged: 10,
            updated: 5,
            created: 3,
            failed: 2,
            skipped: 0,
        };
        summary.add(PortalHarvestResult::success(
            "a".into(),
            "https://a.com".into(),
            stats1,
        ));

        summary.add(PortalHarvestResult::failure(
            "b".into(),
            "https://b.com".into(),
            "error".into(),
        ));

        let stats2 = SyncStats {
            unchanged: 20,
            updated: 0,
            created: 0,
            failed: 0,
            skipped: 0,
        };
        summary.add(PortalHarvestResult::success(
            "c".into(),
            "https://c.com".into(),
            stats2,
        ));

        assert_eq!(summary.total_portals(), 3);
        assert_eq!(summary.successful_count(), 2);
        assert_eq!(summary.failed_count(), 1);
        assert_eq!(summary.total_datasets(), 40); // 20 + 20 + 0 (failed portal has 0)
    }

    #[test]
    fn test_batch_harvest_summary_all_successful() {
        let mut summary = BatchHarvestSummary::new();

        let stats = SyncStats {
            unchanged: 5,
            updated: 0,
            created: 5,
            failed: 0,
            skipped: 0,
        };
        summary.add(PortalHarvestResult::success(
            "portal1".into(),
            "https://portal1.com".into(),
            stats,
        ));

        assert_eq!(summary.successful_count(), 1);
        assert_eq!(summary.failed_count(), 0);
        assert_eq!(summary.total_datasets(), 10);
    }

    #[test]
    fn test_batch_harvest_summary_all_failed() {
        let mut summary = BatchHarvestSummary::new();

        summary.add(PortalHarvestResult::failure(
            "portal1".into(),
            "https://portal1.com".into(),
            "error1".into(),
        ));
        summary.add(PortalHarvestResult::failure(
            "portal2".into(),
            "https://portal2.com".into(),
            "error2".into(),
        ));

        assert_eq!(summary.successful_count(), 0);
        assert_eq!(summary.failed_count(), 2);
        assert_eq!(summary.total_datasets(), 0);
        assert_eq!(summary.total_portals(), 2);
    }

    // =========================================================================
    // AtomicSyncStats tests
    // =========================================================================

    #[test]
    fn test_atomic_sync_stats_new() {
        let stats = AtomicSyncStats::new();
        let result = stats.to_stats();
        assert_eq!(result.unchanged, 0);
        assert_eq!(result.updated, 0);
        assert_eq!(result.created, 0);
        assert_eq!(result.failed, 0);
        assert_eq!(result.skipped, 0);
    }

    #[test]
    fn test_atomic_sync_stats_record() {
        let stats = AtomicSyncStats::new();
        stats.record(SyncOutcome::Unchanged);
        stats.record(SyncOutcome::Updated);
        stats.record(SyncOutcome::Created);
        stats.record(SyncOutcome::Failed);
        stats.record(SyncOutcome::Skipped);

        let result = stats.to_stats();
        assert_eq!(result.unchanged, 1);
        assert_eq!(result.updated, 1);
        assert_eq!(result.created, 1);
        assert_eq!(result.failed, 1);
        assert_eq!(result.skipped, 1);
    }

    #[test]
    fn test_atomic_sync_stats_multiple_records() {
        let stats = AtomicSyncStats::new();
        for _ in 0..10 {
            stats.record(SyncOutcome::Unchanged);
        }
        for _ in 0..5 {
            stats.record(SyncOutcome::Updated);
        }

        let result = stats.to_stats();
        assert_eq!(result.unchanged, 10);
        assert_eq!(result.updated, 5);
        assert_eq!(result.total(), 15);
        assert_eq!(result.successful(), 15);
    }

    #[test]
    fn test_atomic_sync_stats_default() {
        let stats = AtomicSyncStats::default();
        let result = stats.to_stats();
        assert_eq!(result.total(), 0);
    }

    // =========================================================================
    // SyncStatus tests
    // =========================================================================

    #[test]
    fn test_sync_status_completed() {
        let status = SyncStatus::Completed;
        assert_eq!(status.as_str(), "completed");
        assert!(status.is_completed());
        assert!(!status.is_cancelled());
    }

    #[test]
    fn test_sync_status_cancelled() {
        let status = SyncStatus::Cancelled;
        assert_eq!(status.as_str(), "cancelled");
        assert!(!status.is_completed());
        assert!(status.is_cancelled());
    }

    // =========================================================================
    // SyncResult tests
    // =========================================================================

    #[test]
    fn test_sync_result_completed() {
        let stats = SyncStats {
            unchanged: 10,
            updated: 5,
            created: 3,
            failed: 0,
            skipped: 0,
        };
        let result = SyncResult::completed(stats);
        assert!(result.is_completed());
        assert!(!result.is_cancelled());
        assert!(result.message.is_none());
        assert_eq!(result.stats.total(), 18);
    }

    #[test]
    fn test_sync_result_cancelled() {
        let stats = SyncStats {
            unchanged: 5,
            updated: 2,
            created: 1,
            failed: 0,
            skipped: 0,
        };
        let result = SyncResult::cancelled(stats);
        assert!(!result.is_completed());
        assert!(result.is_cancelled());
        assert!(result.message.is_some());
        assert!(result.message.unwrap().contains("cancelled"));
        assert_eq!(result.stats.total(), 8);
    }

    // =========================================================================
    // DeltaDetector trait tests
    // =========================================================================

    #[test]
    fn test_content_hash_detector_unchanged() {
        let detector = ContentHashDetector;
        let hash = "abc123".to_string();
        let existing = Some(Some(hash.clone()));
        let decision = detector.needs_reprocessing(existing.as_ref(), &hash);

        assert_eq!(decision.outcome, SyncOutcome::Unchanged);
    }

    #[test]
    fn test_content_hash_detector_updated() {
        let detector = ContentHashDetector;
        let existing = Some(Some("old_hash".to_string()));
        let decision = detector.needs_reprocessing(existing.as_ref(), "new_hash");

        assert_eq!(decision.outcome, SyncOutcome::Updated);
    }

    #[test]
    fn test_content_hash_detector_new() {
        let detector = ContentHashDetector;
        let decision = detector.needs_reprocessing(None, "new_hash");

        assert_eq!(decision.outcome, SyncOutcome::Created);
    }

    #[test]
    fn test_always_reprocess_detector_existing() {
        let detector = AlwaysReprocessDetector;
        let hash = "abc123".to_string();
        let existing = Some(Some(hash.clone()));
        let decision = detector.needs_reprocessing(existing.as_ref(), &hash);

        assert_eq!(decision.outcome, SyncOutcome::Updated);
        assert_eq!(decision.reason, "always reprocess strategy");
    }

    #[test]
    fn test_always_reprocess_detector_new() {
        let detector = AlwaysReprocessDetector;
        let decision = detector.needs_reprocessing(None, "new_hash");

        assert_eq!(decision.outcome, SyncOutcome::Created);
        assert_eq!(decision.reason, "new dataset");
    }

    #[test]
    fn test_always_reprocess_detector_legacy() {
        let detector = AlwaysReprocessDetector;
        let existing: Option<Option<String>> = Some(None);
        let decision = detector.needs_reprocessing(existing.as_ref(), "new_hash");

        assert_eq!(decision.outcome, SyncOutcome::Updated);
        assert_eq!(decision.reason, "always reprocess strategy");
    }
}