msy 0.4.5

Modern musl rsync alternative - Fast, parallel file synchronization
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
use crate::error::{Result, SyncError};
use serde::{Deserialize, Serialize};
use std::fs::File;
use std::io::{BufReader, BufWriter};
use std::path::{Path, PathBuf};
use std::time::SystemTime;

const STATE_FILE_NAME: &str = ".sy-state.json";
const STATE_VERSION: u32 = 1;

/// Resume state for interrupted sync operations
#[derive(Debug, Serialize, Deserialize)]
pub struct ResumeState {
	version: u32,
	source: PathBuf,
	destination: PathBuf,
	started_at: String,
	checkpoint_at: String,
	flags: SyncFlags,
	completed_files: Vec<CompletedFile>,
	total_files: usize,
	total_bytes_transferred: u64,
}

/// Sync flags that must match for resume compatibility
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct SyncFlags {
	pub delete: bool,
	pub exclude: Vec<String>,
	pub min_size: Option<u64>,
	pub max_size: Option<u64>,
}

/// Information about a completed file transfer
#[derive(Debug, Serialize, Deserialize)]
pub struct CompletedFile {
	pub relative_path: PathBuf,
	pub action: String, // "create", "update", "delete"
	pub size: u64,
	pub checksum: String, // "xxhash3:..." format
	pub completed_at: String,
}

impl ResumeState {
	/// Create a new resume state
	pub fn new(source: PathBuf, destination: PathBuf, flags: SyncFlags, total_files: usize) -> Self {
		let now = format_timestamp(SystemTime::now());
		Self {
			version: STATE_VERSION,
			source,
			destination,
			started_at: now.clone(),
			checkpoint_at: now,
			flags,
			completed_files: Vec::new(),
			total_files,
			total_bytes_transferred: 0,
		}
	}

	/// Load resume state from destination directory
	pub fn load(destination: &Path) -> Result<Option<Self>> {
		let state_path = destination.join(STATE_FILE_NAME);

		if !state_path.exists() {
			return Ok(None);
		}

		tracing::debug!("Loading resume state from {}", state_path.display());

		let file = File::open(&state_path).map_err(|e| SyncError::Io(std::io::Error::new(e.kind(), format!("Failed to open state file: {}", e))))?;

		let reader = BufReader::new(file);
		let state: Self = match serde_json::from_reader(reader) {
			Ok(state) => state,
			Err(e) => {
				tracing::warn!("Failed to parse resume state (corrupted JSON): {}", e);
				tracing::info!("Deleting corrupted state file and starting fresh");
				Self::delete(destination)?;
				return Ok(None);
			}
		};

		// Verify state integrity
		if let Err(e) = state.verify_integrity() {
			tracing::warn!("Resume state failed integrity check: {}", e);
			tracing::info!("Deleting invalid state file and starting fresh");
			Self::delete(destination)?;
			return Ok(None);
		}

		Ok(Some(state))
	}

	/// Verify the integrity of this resume state
	fn verify_integrity(&self) -> Result<()> {
		// Check version is supported
		if self.version != STATE_VERSION {
			return Err(SyncError::Io(std::io::Error::new(
				std::io::ErrorKind::InvalidData,
				format!("Unsupported state version: expected {}, got {}", STATE_VERSION, self.version),
			)));
		}

		// Check paths are absolute
		if !self.source.is_absolute() {
			return Err(SyncError::Io(std::io::Error::new(
				std::io::ErrorKind::InvalidData,
				format!("Source path is not absolute: {}", self.source.display()),
			)));
		}

		if !self.destination.is_absolute() {
			return Err(SyncError::Io(std::io::Error::new(
				std::io::ErrorKind::InvalidData,
				format!("Destination path is not absolute: {}", self.destination.display()),
			)));
		}

		// Parse and validate timestamps
		let started_at = chrono::DateTime::parse_from_rfc3339(&self.started_at)
			.map_err(|e| SyncError::Io(std::io::Error::new(std::io::ErrorKind::InvalidData, format!("Invalid started_at timestamp: {}", e))))?;

		let checkpoint_at = chrono::DateTime::parse_from_rfc3339(&self.checkpoint_at)
			.map_err(|e| SyncError::Io(std::io::Error::new(std::io::ErrorKind::InvalidData, format!("Invalid checkpoint_at timestamp: {}", e))))?;

		// Check timestamps are reasonable (not in the future + reasonable window)
		let now = chrono::Utc::now();
		if started_at > now {
			return Err(SyncError::Io(std::io::Error::new(std::io::ErrorKind::InvalidData, "Started timestamp is in the future")));
		}

		if checkpoint_at > now {
			return Err(SyncError::Io(std::io::Error::new(std::io::ErrorKind::InvalidData, "Checkpoint timestamp is in the future")));
		}

		// Check checkpoint is not before start
		if checkpoint_at < started_at {
			return Err(SyncError::Io(std::io::Error::new(std::io::ErrorKind::InvalidData, "Checkpoint timestamp is before start timestamp")));
		}

		// Check completed files count doesn't exceed total
		if self.completed_files.len() > self.total_files {
			return Err(SyncError::Io(std::io::Error::new(
				std::io::ErrorKind::InvalidData,
				format!("Completed files ({}) exceeds total files ({})", self.completed_files.len(), self.total_files),
			)));
		}

		// Validate completed file entries
		for file in &self.completed_files {
			// Check action is valid
			match file.action.as_str() {
				"create" | "update" | "delete" => {}
				_ => {
					return Err(SyncError::Io(std::io::Error::new(std::io::ErrorKind::InvalidData, format!("Invalid file action: {}", file.action))));
				}
			}

			// Parse completed_at timestamp
			chrono::DateTime::parse_from_rfc3339(&file.completed_at)
				.map_err(|e| SyncError::Io(std::io::Error::new(std::io::ErrorKind::InvalidData, format!("Invalid completed_at timestamp for file: {}", e))))?;
		}

		Ok(())
	}

	/// Save resume state to destination directory (atomic)
	#[allow(dead_code)] // Public API for manual state saving
	pub fn save(&self, destination: &Path) -> Result<()> {
		let state_path = destination.join(STATE_FILE_NAME);
		let temp_path = destination.join(format!("{}.tmp", STATE_FILE_NAME));

		tracing::trace!("Saving resume state to {}", state_path.display());

		// Write to temporary file
		let file = File::create(&temp_path).map_err(|e| SyncError::Io(std::io::Error::new(e.kind(), format!("Failed to create temp state file: {}", e))))?;

		let writer = BufWriter::new(file);
		serde_json::to_writer_pretty(writer, self).map_err(|e| SyncError::Io(std::io::Error::other(format!("Failed to write state file: {}", e))))?;

		// Atomic rename
		std::fs::rename(&temp_path, &state_path).map_err(|e| SyncError::Io(std::io::Error::new(e.kind(), format!("Failed to save state file: {}", e))))?;

		Ok(())
	}

	/// Delete resume state file
	pub fn delete(destination: &Path) -> Result<()> {
		let state_path = destination.join(STATE_FILE_NAME);

		if state_path.exists() {
			tracing::debug!("Deleting resume state file");
			std::fs::remove_file(&state_path).map_err(|e| SyncError::Io(std::io::Error::new(e.kind(), format!("Failed to delete state file: {}", e))))?;
		}

		Ok(())
	}

	/// Check if this state is compatible with current sync flags
	pub fn is_compatible_with(&self, current_flags: &SyncFlags) -> bool {
		// Flags must match exactly for safe resume
		self.flags == *current_flags
	}

	/// Add a completed file to the state
	#[allow(dead_code)] // Public API for state management
	pub fn add_completed_file(&mut self, file: CompletedFile, bytes_transferred: u64) {
		self.completed_files.push(file);
		self.total_bytes_transferred += bytes_transferred;
		// Update checkpoint timestamp whenever we modify state
		self.checkpoint_at = format_timestamp(SystemTime::now());
	}

	/// Get the set of completed file paths for quick lookup
	pub fn completed_paths(&self) -> std::collections::HashSet<PathBuf> {
		self.completed_files.iter().map(|f| f.relative_path.clone()).collect()
	}

	/// Get progress information
	pub fn progress(&self) -> (usize, usize) {
		(self.completed_files.len(), self.total_files)
	}
}

/// Format a timestamp for serialization (ISO 8601)
pub fn format_timestamp(time: SystemTime) -> String {
	let datetime: chrono::DateTime<chrono::Utc> = time.into();
	datetime.to_rfc3339()
}

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

	/// Create platform-appropriate absolute paths for testing
	fn test_absolute_paths() -> (PathBuf, PathBuf) {
		// Use temp directories which are guaranteed to be absolute on all platforms
		let src_temp = tempdir().unwrap();
		let dst_temp = tempdir().unwrap();
		(src_temp.path().to_path_buf(), dst_temp.path().to_path_buf())
	}

	#[test]
	fn test_resume_state_save_load() {
		let temp_dir = tempdir().unwrap();
		let dest = temp_dir.path();
		let (src, dst) = test_absolute_paths();

		let flags = SyncFlags { delete: true, exclude: vec!["*.log".to_string()], min_size: Some(1024), max_size: None };

		let mut state = ResumeState::new(src, dst, flags.clone(), 100);

		state.add_completed_file(
			CompletedFile {
				relative_path: PathBuf::from("file1.txt"),
				action: "create".to_string(),
				size: 1234,
				checksum: "xxhash3:abc123".to_string(),
				completed_at: format_timestamp(SystemTime::now()),
			},
			1234,
		);

		// Save
		state.save(dest).unwrap();

		// Load
		let loaded = ResumeState::load(dest).unwrap();
		assert!(loaded.is_some());
		let loaded = loaded.unwrap();

		assert_eq!(loaded.version, STATE_VERSION);
		assert_eq!(loaded.total_files, 100);
		assert_eq!(loaded.completed_files.len(), 1);
		assert_eq!(loaded.total_bytes_transferred, 1234);
		assert!(loaded.is_compatible_with(&flags));
	}

	#[test]
	fn test_resume_state_compatibility() {
		let flags1 = SyncFlags { delete: true, exclude: vec!["*.log".to_string()], min_size: Some(1024), max_size: None };

		let flags2 = SyncFlags {
			delete: false, // Different!
			exclude: vec!["*.log".to_string()],
			min_size: Some(1024),
			max_size: None,
		};

		let state = ResumeState::new(PathBuf::from("/src"), PathBuf::from("/dst"), flags1.clone(), 100);

		assert!(state.is_compatible_with(&flags1));
		assert!(!state.is_compatible_with(&flags2));
	}

	#[test]
	fn test_resume_state_delete() {
		let temp_dir = tempdir().unwrap();
		let dest = temp_dir.path();
		let (src, dst) = test_absolute_paths();

		let flags = SyncFlags { delete: false, exclude: Vec::new(), min_size: None, max_size: None };

		let state = ResumeState::new(src, dst, flags, 10);

		state.save(dest).unwrap();
		assert!(dest.join(STATE_FILE_NAME).exists());

		ResumeState::delete(dest).unwrap();
		assert!(!dest.join(STATE_FILE_NAME).exists());
	}

	#[test]
	fn test_completed_paths() {
		let flags = SyncFlags { delete: false, exclude: Vec::new(), min_size: None, max_size: None };

		let mut state = ResumeState::new(PathBuf::from("/src"), PathBuf::from("/dst"), flags, 10);

		state.add_completed_file(
			CompletedFile {
				relative_path: PathBuf::from("file1.txt"),
				action: "create".to_string(),
				size: 100,
				checksum: "xxhash3:abc".to_string(),
				completed_at: format_timestamp(SystemTime::now()),
			},
			100,
		);

		state.add_completed_file(
			CompletedFile {
				relative_path: PathBuf::from("file2.txt"),
				action: "update".to_string(),
				size: 200,
				checksum: "xxhash3:def".to_string(),
				completed_at: format_timestamp(SystemTime::now()),
			},
			200,
		);

		let paths = state.completed_paths();
		assert_eq!(paths.len(), 2);
		assert!(paths.contains(&PathBuf::from("file1.txt")));
		assert!(paths.contains(&PathBuf::from("file2.txt")));
	}

	#[test]
	fn test_corrupted_json_auto_deleted() {
		let temp_dir = tempdir().unwrap();
		let dest = temp_dir.path();
		let state_path = dest.join(STATE_FILE_NAME);

		// Write corrupted JSON
		std::fs::write(&state_path, "{ invalid json }").unwrap();
		assert!(state_path.exists());

		// Load should return None and delete the file
		let loaded = ResumeState::load(dest).unwrap();
		assert!(loaded.is_none());
		assert!(!state_path.exists());
	}

	#[test]
	fn test_invalid_version_auto_deleted() {
		let temp_dir = tempdir().unwrap();
		let dest = temp_dir.path();
		let (src, dst) = test_absolute_paths();
		let state_path = dest.join(STATE_FILE_NAME);

		// Write state with invalid version
		let invalid_state = serde_json::json!({
			"version": 999,
			"source": src,
			"destination": dst,
			"started_at": "2025-01-01T00:00:00Z",
			"checkpoint_at": "2025-01-01T00:00:00Z",
			"flags": {
				"delete": false,
				"exclude": [],
				"min_size": null,
				"max_size": null
			},
			"completed_files": [],
			"total_files": 10,
			"total_bytes_transferred": 0
		});
		std::fs::write(&state_path, serde_json::to_string(&invalid_state).unwrap()).unwrap();
		assert!(state_path.exists());

		// Load should return None and delete the file
		let loaded = ResumeState::load(dest).unwrap();
		assert!(loaded.is_none());
		assert!(!state_path.exists());
	}

	#[test]
	fn test_relative_paths_rejected() {
		let temp_dir = tempdir().unwrap();
		let dest = temp_dir.path();
		let (_, dst) = test_absolute_paths();
		let state_path = dest.join(STATE_FILE_NAME);

		// Write state with relative source path
		let invalid_state = serde_json::json!({
			"version": STATE_VERSION,
			"source": "relative/path",  // Relative!
			"destination": dst,
			"started_at": "2025-01-01T00:00:00Z",
			"checkpoint_at": "2025-01-01T00:00:00Z",
			"flags": {
				"delete": false,
				"exclude": [],
				"min_size": null,
				"max_size": null
			},
			"completed_files": [],
			"total_files": 10,
			"total_bytes_transferred": 0
		});
		std::fs::write(&state_path, serde_json::to_string(&invalid_state).unwrap()).unwrap();

		// Load should reject and delete
		let loaded = ResumeState::load(dest).unwrap();
		assert!(loaded.is_none());
		assert!(!state_path.exists());
	}

	#[test]
	fn test_future_timestamp_rejected() {
		let temp_dir = tempdir().unwrap();
		let dest = temp_dir.path();
		let (src, dst) = test_absolute_paths();
		let state_path = dest.join(STATE_FILE_NAME);

		// Write state with future timestamp
		let future = chrono::Utc::now() + chrono::Duration::days(1);
		let invalid_state = serde_json::json!({
			"version": STATE_VERSION,
			"source": src,
			"destination": dst,
			"started_at": future.to_rfc3339(),  // Future!
			"checkpoint_at": future.to_rfc3339(),
			"flags": {
				"delete": false,
				"exclude": [],
				"min_size": null,
				"max_size": null
			},
			"completed_files": [],
			"total_files": 10,
			"total_bytes_transferred": 0
		});
		std::fs::write(&state_path, serde_json::to_string(&invalid_state).unwrap()).unwrap();

		// Load should reject and delete
		let loaded = ResumeState::load(dest).unwrap();
		assert!(loaded.is_none());
		assert!(!state_path.exists());
	}

	#[test]
	fn test_checkpoint_before_start_rejected() {
		let temp_dir = tempdir().unwrap();
		let dest = temp_dir.path();
		let (src, dst) = test_absolute_paths();
		let state_path = dest.join(STATE_FILE_NAME);

		let start = chrono::Utc::now();
		let checkpoint = start - chrono::Duration::hours(1); // Before start!

		let invalid_state = serde_json::json!({
			"version": STATE_VERSION,
			"source": src,
			"destination": dst,
			"started_at": start.to_rfc3339(),
			"checkpoint_at": checkpoint.to_rfc3339(),
			"flags": {
				"delete": false,
				"exclude": [],
				"min_size": null,
				"max_size": null
			},
			"completed_files": [],
			"total_files": 10,
			"total_bytes_transferred": 0
		});
		std::fs::write(&state_path, serde_json::to_string(&invalid_state).unwrap()).unwrap();

		// Load should reject and delete
		let loaded = ResumeState::load(dest).unwrap();
		assert!(loaded.is_none());
		assert!(!state_path.exists());
	}

	#[test]
	fn test_completed_exceeds_total_rejected() {
		let temp_dir = tempdir().unwrap();
		let dest = temp_dir.path();
		let (src, dst) = test_absolute_paths();
		let state_path = dest.join(STATE_FILE_NAME);

		let now = chrono::Utc::now();
		let invalid_state = serde_json::json!({
			"version": STATE_VERSION,
			"source": src,
			"destination": dst,
			"started_at": now.to_rfc3339(),
			"checkpoint_at": now.to_rfc3339(),
			"flags": {
				"delete": false,
				"exclude": [],
				"min_size": null,
				"max_size": null
			},
			"completed_files": [
				{
					"relative_path": "file1.txt",
					"action": "create",
					"size": 100,
					"checksum": "xxhash3:abc",
					"completed_at": now.to_rfc3339()
				},
				{
					"relative_path": "file2.txt",
					"action": "create",
					"size": 200,
					"checksum": "xxhash3:def",
					"completed_at": now.to_rfc3339()
				}
			],
			"total_files": 1,  // Only 1 but 2 completed!
			"total_bytes_transferred": 300
		});
		std::fs::write(&state_path, serde_json::to_string(&invalid_state).unwrap()).unwrap();

		// Load should reject and delete
		let loaded = ResumeState::load(dest).unwrap();
		assert!(loaded.is_none());
		assert!(!state_path.exists());
	}

	#[test]
	fn test_invalid_file_action_rejected() {
		let temp_dir = tempdir().unwrap();
		let dest = temp_dir.path();
		let (src, dst) = test_absolute_paths();
		let state_path = dest.join(STATE_FILE_NAME);

		let now = chrono::Utc::now();
		let invalid_state = serde_json::json!({
			"version": STATE_VERSION,
			"source": src,
			"destination": dst,
			"started_at": now.to_rfc3339(),
			"checkpoint_at": now.to_rfc3339(),
			"flags": {
				"delete": false,
				"exclude": [],
				"min_size": null,
				"max_size": null
			},
			"completed_files": [
				{
					"relative_path": "file1.txt",
					"action": "invalid_action",  // Invalid!
					"size": 100,
					"checksum": "xxhash3:abc",
					"completed_at": now.to_rfc3339()
				}
			],
			"total_files": 10,
			"total_bytes_transferred": 100
		});
		std::fs::write(&state_path, serde_json::to_string(&invalid_state).unwrap()).unwrap();

		// Load should reject and delete
		let loaded = ResumeState::load(dest).unwrap();
		assert!(loaded.is_none());
		assert!(!state_path.exists());
	}

	#[test]
	fn test_valid_state_passes_integrity_check() {
		let temp_dir = tempdir().unwrap();
		let dest = temp_dir.path();
		let (src, dst) = test_absolute_paths();

		let flags = SyncFlags { delete: false, exclude: Vec::new(), min_size: None, max_size: None };

		let mut state = ResumeState::new(src, dst, flags, 10);

		state.add_completed_file(
			CompletedFile {
				relative_path: PathBuf::from("file1.txt"),
				action: "create".to_string(),
				size: 100,
				checksum: "xxhash3:abc".to_string(),
				completed_at: format_timestamp(SystemTime::now()),
			},
			100,
		);

		// Save and reload
		state.save(dest).unwrap();
		let loaded = ResumeState::load(dest).unwrap();

		// Should successfully load
		assert!(loaded.is_some());
		let loaded = loaded.unwrap();
		assert_eq!(loaded.completed_files.len(), 1);
	}

	// === Additional Edge Case Tests ===

	#[test]
	fn test_corrupted_json_deleted() {
		let temp_dir = tempdir().unwrap();
		let dest = temp_dir.path();

		// Create corrupted JSON file
		let state_path = dest.join(".sy-state.json");
		std::fs::write(&state_path, "{ corrupted json }}}}").unwrap();

		// Should handle corruption gracefully
		let loaded = ResumeState::load(dest).unwrap();
		assert!(loaded.is_none(), "Corrupted state should be rejected");
		assert!(!state_path.exists(), "Corrupted state should be deleted");
	}

	#[test]
	fn test_empty_state_file() {
		let temp_dir = tempdir().unwrap();
		let dest = temp_dir.path();

		// Create empty state file
		let state_path = dest.join(".sy-state.json");
		std::fs::write(&state_path, "").unwrap();

		// Should handle empty file gracefully
		let loaded = ResumeState::load(dest).unwrap();
		assert!(loaded.is_none(), "Empty state should be rejected");
		assert!(!state_path.exists(), "Empty state should be deleted");
	}

	#[test]
	fn test_state_with_missing_version() {
		let temp_dir = tempdir().unwrap();
		let dest = temp_dir.path();
		let (src, dst) = test_absolute_paths();

		let state_path = dest.join(".sy-state.json");

		// Create state without version field
		let invalid_state = serde_json::json!({
			"source": src,
			"destination": dst,
			"started_at": format_timestamp(SystemTime::now()),
			"flags": {
				"delete": false,
				"exclude": [],
				"min_size": null,
				"max_size": null
			},
			"completed_files": [],
			"total_files": 0,
			"total_bytes_transferred": 0
		});
		std::fs::write(&state_path, serde_json::to_string(&invalid_state).unwrap()).unwrap();

		// Should fail to deserialize and delete
		let loaded = ResumeState::load(dest).unwrap();
		assert!(loaded.is_none());
		assert!(!state_path.exists());
	}

	#[test]
	fn test_flag_change_delete_added() {
		let temp_dir = tempdir().unwrap();
		let dest = temp_dir.path();
		let (src, dst) = test_absolute_paths();

		let original_flags = SyncFlags { delete: false, exclude: Vec::new(), min_size: None, max_size: None };

		let state = ResumeState::new(src, dst, original_flags.clone(), 10);
		state.save(dest).unwrap();

		// Try to resume with delete flag changed
		let new_flags = SyncFlags {
			delete: true, // Changed!
			exclude: Vec::new(),
			min_size: None,
			max_size: None,
		};

		let loaded = ResumeState::load(dest).unwrap().unwrap();
		assert!(!loaded.is_compatible_with(&new_flags), "Should detect delete flag change");
	}

	#[test]
	fn test_flag_change_exclude_added() {
		let temp_dir = tempdir().unwrap();
		let dest = temp_dir.path();
		let (src, dst) = test_absolute_paths();

		let original_flags = SyncFlags { delete: false, exclude: Vec::new(), min_size: None, max_size: None };

		let state = ResumeState::new(src, dst, original_flags.clone(), 10);
		state.save(dest).unwrap();

		// Try to resume with exclude patterns added
		let new_flags = SyncFlags {
			delete: false,
			exclude: vec!["*.tmp".to_string()], // Added!
			min_size: None,
			max_size: None,
		};

		let loaded = ResumeState::load(dest).unwrap().unwrap();
		assert!(!loaded.is_compatible_with(&new_flags), "Should detect exclude pattern change");
	}

	#[test]
	fn test_flag_change_size_filters() {
		let temp_dir = tempdir().unwrap();
		let dest = temp_dir.path();
		let (src, dst) = test_absolute_paths();

		let original_flags = SyncFlags { delete: false, exclude: Vec::new(), min_size: None, max_size: None };

		let state = ResumeState::new(src, dst, original_flags.clone(), 10);
		state.save(dest).unwrap();

		// Try to resume with size filters changed
		let new_flags = SyncFlags {
			delete: false,
			exclude: Vec::new(),
			min_size: Some(1024),     // Added!
			max_size: Some(10485760), // Added!
		};

		let loaded = ResumeState::load(dest).unwrap().unwrap();
		assert!(!loaded.is_compatible_with(&new_flags), "Should detect size filter change");
	}

	#[test]
	fn test_multiple_resume_cycles() {
		let temp_dir = tempdir().unwrap();
		let dest = temp_dir.path();
		let (src, dst) = test_absolute_paths();

		let flags = SyncFlags { delete: false, exclude: Vec::new(), min_size: None, max_size: None };

		// First cycle: save with 3 files
		let mut state = ResumeState::new(src, dst, flags.clone(), 10);

		for i in 0..3 {
			state.add_completed_file(
				CompletedFile {
					relative_path: PathBuf::from(format!("file{}.txt", i)),
					action: "create".to_string(),
					size: 100 * (i + 1) as u64,
					checksum: format!("xxhash3:abc{}", i),
					completed_at: format_timestamp(SystemTime::now()),
				},
				100 * (i + 1) as u64,
			);
		}
		state.save(dest).unwrap();

		// Second cycle: load and add more files
		let mut state = ResumeState::load(dest).unwrap().unwrap();
		assert_eq!(state.completed_files.len(), 3);

		for i in 3..6 {
			state.add_completed_file(
				CompletedFile {
					relative_path: PathBuf::from(format!("file{}.txt", i)),
					action: "create".to_string(),
					size: 100 * (i + 1) as u64,
					checksum: format!("xxhash3:abc{}", i),
					completed_at: format_timestamp(SystemTime::now()),
				},
				100 * (i + 1) as u64,
			);
		}
		state.save(dest).unwrap();

		// Third cycle: verify all files preserved
		let state = ResumeState::load(dest).unwrap().unwrap();
		assert_eq!(state.completed_files.len(), 6);
		assert_eq!(state.total_bytes_transferred, 2100); // 100+200+300+400+500+600
	}

	#[test]
	fn test_progress_tracking_accuracy() {
		let temp_dir = tempdir().unwrap();
		let _dest = temp_dir.path();

		let flags = SyncFlags { delete: false, exclude: Vec::new(), min_size: None, max_size: None };

		let mut state = ResumeState::new(
			PathBuf::from("/src"),
			PathBuf::from("/dst"),
			flags,
			100, // Total files
		);

		// Add 30 completed files
		for i in 0..30 {
			state.add_completed_file(
				CompletedFile {
					relative_path: PathBuf::from(format!("file{}.txt", i)),
					action: "create".to_string(),
					size: 1000,
					checksum: format!("xxhash3:abc{}", i),
					completed_at: format_timestamp(SystemTime::now()),
				},
				1000,
			);
		}

		let (completed, total) = state.progress();
		assert_eq!(completed, 30);
		assert_eq!(total, 100);
		assert_eq!(state.total_bytes_transferred, 30000);
	}

	#[test]
	fn test_state_with_large_number_of_files() {
		let temp_dir = tempdir().unwrap();
		let dest = temp_dir.path();
		let (src, dst) = test_absolute_paths();

		let flags = SyncFlags { delete: false, exclude: Vec::new(), min_size: None, max_size: None };

		let mut state = ResumeState::new(src, dst, flags, 10000);

		// Add 1000 completed files
		for i in 0..1000 {
			state.add_completed_file(
				CompletedFile {
					relative_path: PathBuf::from(format!("file{:04}.txt", i)),
					action: "create".to_string(),
					size: 1024,
					checksum: format!("xxhash3:hash{}", i),
					completed_at: format_timestamp(SystemTime::now()),
				},
				1024,
			);
		}

		// Save and reload
		state.save(dest).unwrap();
		let loaded = ResumeState::load(dest).unwrap().unwrap();

		assert_eq!(loaded.completed_files.len(), 1000);
		assert_eq!(loaded.total_bytes_transferred, 1024 * 1000);
	}

	#[test]
	fn test_delete_nonexistent_state() {
		let temp_dir = tempdir().unwrap();
		let dest = temp_dir.path();

		// Try to delete state that doesn't exist
		let result = ResumeState::delete(dest);

		// Should succeed (idempotent)
		assert!(result.is_ok(), "Deleting nonexistent state should succeed");
	}
}