rcp-tools-common 0.31.0

Internal library for RCP file operation tools - shared utilities and core operations (not intended for direct use)
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
use tracing::instrument;

/// Number of shards for the counter. More shards reduce contention but increase memory.
/// 64 shards × 128 bytes = 8KB per counter, which virtually eliminates contention.
const NUM_SHARDS: usize = 64;

/// Atomic counter padded to cache line size to prevent false sharing.
/// Each shard lives on its own cache line so concurrent updates from different
/// threads don't cause cache invalidation.
/// Uses 128B alignment to support both x86-64 (64B) and ARM (128B) cache lines.
#[repr(align(128))]
struct PaddedAtomicU64(std::sync::atomic::AtomicU64);

/// Global counter for assigning shard indices to threads.
/// Each thread gets a unique index (mod NUM_SHARDS) on first access.
static NEXT_SHARD_INDEX: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);

thread_local! {
    /// Per-thread shard index, assigned once on first access.
    /// Uses modulo to wrap around when more threads than shards.
    static MY_SHARD: usize =
        NEXT_SHARD_INDEX.fetch_add(1, std::sync::atomic::Ordering::Relaxed) % NUM_SHARDS;
}

/// Sharded atomic counter optimized for concurrent access from multiple threads.
///
/// Uses cache-line-padded shards to prevent false sharing. Each thread is assigned
/// a shard index, so updates from different threads typically hit different cache lines.
///
/// This design handles interleaved access to multiple counters efficiently - unlike
/// a single-slot cache approach, there's no "cache thrashing" when alternating between
/// counters.
///
/// # Memory
///
/// Each counter uses NUM_SHARDS × 128 bytes = 8KB (with 64 shards).
/// This is larger than a simple AtomicU64 but virtually eliminates contention.
pub struct TlsCounter {
    shards: [PaddedAtomicU64; NUM_SHARDS],
}

impl TlsCounter {
    #[must_use]
    pub fn new() -> Self {
        Self {
            shards: std::array::from_fn(|_| PaddedAtomicU64(std::sync::atomic::AtomicU64::new(0))),
        }
    }

    pub fn add(&self, value: u64) {
        let shard = MY_SHARD.with(|&s| s);
        self.shards[shard]
            .0
            .fetch_add(value, std::sync::atomic::Ordering::Relaxed);
    }

    pub fn inc(&self) {
        self.add(1);
    }

    pub fn get(&self) -> u64 {
        self.shards
            .iter()
            .map(|s| s.0.load(std::sync::atomic::Ordering::Relaxed))
            .sum()
    }
}

impl std::fmt::Debug for TlsCounter {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("TlsCounter")
            .field("value", &self.get())
            .finish()
    }
}

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

#[derive(Debug)]
pub struct ProgressCounter {
    started: TlsCounter,
    finished: TlsCounter,
}

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

pub struct ProgressGuard<'a> {
    progress: &'a ProgressCounter,
}

impl<'a> ProgressGuard<'a> {
    pub fn new(progress: &'a ProgressCounter) -> Self {
        progress.started.inc();
        Self { progress }
    }
}

impl Drop for ProgressGuard<'_> {
    fn drop(&mut self) {
        self.progress.finished.inc();
    }
}

pub struct Status {
    pub started: u64,
    pub finished: u64,
}

impl ProgressCounter {
    #[must_use]
    pub fn new() -> Self {
        Self {
            started: TlsCounter::new(),
            finished: TlsCounter::new(),
        }
    }

    pub fn guard(&self) -> ProgressGuard<'_> {
        ProgressGuard::new(self)
    }

    #[instrument]
    pub fn get(&self) -> Status {
        let mut status = Status {
            started: self.started.get(),
            finished: self.finished.get(),
        };
        if status.finished > status.started {
            tracing::debug!(
                "Progress inversion - started: {}, finished {}",
                status.started,
                status.finished
            );
            status.started = status.finished;
        }
        status
    }
}

pub struct Progress {
    pub ops: ProgressCounter,
    pub bytes_copied: TlsCounter,
    pub hard_links_created: TlsCounter,
    pub files_copied: TlsCounter,
    pub symlinks_created: TlsCounter,
    pub directories_created: TlsCounter,
    pub files_unchanged: TlsCounter,
    pub symlinks_unchanged: TlsCounter,
    pub directories_unchanged: TlsCounter,
    pub hard_links_unchanged: TlsCounter,
    pub files_removed: TlsCounter,
    pub symlinks_removed: TlsCounter,
    pub directories_removed: TlsCounter,
    pub bytes_removed: TlsCounter,
    pub files_skipped: TlsCounter,
    pub symlinks_skipped: TlsCounter,
    pub directories_skipped: TlsCounter,
    start_time: std::time::Instant,
}

impl Progress {
    #[must_use]
    pub fn new() -> Self {
        Self {
            ops: Default::default(),
            bytes_copied: Default::default(),
            hard_links_created: Default::default(),
            files_copied: Default::default(),
            symlinks_created: Default::default(),
            directories_created: Default::default(),
            files_unchanged: Default::default(),
            symlinks_unchanged: Default::default(),
            directories_unchanged: Default::default(),
            hard_links_unchanged: Default::default(),
            files_removed: Default::default(),
            symlinks_removed: Default::default(),
            directories_removed: Default::default(),
            bytes_removed: Default::default(),
            files_skipped: Default::default(),
            symlinks_skipped: Default::default(),
            directories_skipped: Default::default(),
            start_time: std::time::Instant::now(),
        }
    }

    pub fn get_duration(&self) -> std::time::Duration {
        self.start_time.elapsed()
    }
}

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

#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct SerializableProgress {
    pub ops_started: u64,
    pub ops_finished: u64,
    pub bytes_copied: u64,
    pub hard_links_created: u64,
    pub files_copied: u64,
    pub symlinks_created: u64,
    pub directories_created: u64,
    pub files_unchanged: u64,
    pub symlinks_unchanged: u64,
    pub directories_unchanged: u64,
    pub hard_links_unchanged: u64,
    pub files_removed: u64,
    pub symlinks_removed: u64,
    pub directories_removed: u64,
    pub bytes_removed: u64,
    pub files_skipped: u64,
    pub symlinks_skipped: u64,
    pub directories_skipped: u64,
    pub current_time: std::time::SystemTime,
}

impl Default for SerializableProgress {
    fn default() -> Self {
        Self {
            ops_started: 0,
            ops_finished: 0,
            bytes_copied: 0,
            hard_links_created: 0,
            files_copied: 0,
            symlinks_created: 0,
            directories_created: 0,
            files_unchanged: 0,
            symlinks_unchanged: 0,
            directories_unchanged: 0,
            hard_links_unchanged: 0,
            files_removed: 0,
            symlinks_removed: 0,
            directories_removed: 0,
            bytes_removed: 0,
            files_skipped: 0,
            symlinks_skipped: 0,
            directories_skipped: 0,
            current_time: std::time::SystemTime::now(),
        }
    }
}

impl From<&Progress> for SerializableProgress {
    /// Creates a `SerializableProgress` from a Progress, capturing the current time at the moment of conversion
    fn from(progress: &Progress) -> Self {
        Self {
            ops_started: progress.ops.started.get(),
            ops_finished: progress.ops.finished.get(),
            bytes_copied: progress.bytes_copied.get(),
            hard_links_created: progress.hard_links_created.get(),
            files_copied: progress.files_copied.get(),
            symlinks_created: progress.symlinks_created.get(),
            directories_created: progress.directories_created.get(),
            files_unchanged: progress.files_unchanged.get(),
            symlinks_unchanged: progress.symlinks_unchanged.get(),
            directories_unchanged: progress.directories_unchanged.get(),
            hard_links_unchanged: progress.hard_links_unchanged.get(),
            files_removed: progress.files_removed.get(),
            symlinks_removed: progress.symlinks_removed.get(),
            directories_removed: progress.directories_removed.get(),
            bytes_removed: progress.bytes_removed.get(),
            files_skipped: progress.files_skipped.get(),
            symlinks_skipped: progress.symlinks_skipped.get(),
            directories_skipped: progress.directories_skipped.get(),
            current_time: std::time::SystemTime::now(),
        }
    }
}

pub struct ProgressPrinter<'a> {
    progress: &'a Progress,
    last_ops: u64,
    last_bytes: u64,
    last_update: std::time::Instant,
}

impl<'a> ProgressPrinter<'a> {
    pub fn new(progress: &'a Progress) -> Self {
        Self {
            progress,
            last_ops: progress.ops.get().finished,
            last_bytes: progress.bytes_copied.get(),
            last_update: std::time::Instant::now(),
        }
    }

    pub fn print(&mut self) -> anyhow::Result<String> {
        let time_now = std::time::Instant::now();
        let ops = self.progress.ops.get();
        let total_duration_secs = self.progress.get_duration().as_secs_f64();
        let curr_duration_secs = (time_now - self.last_update).as_secs_f64();
        let average_ops_rate = ops.finished as f64 / total_duration_secs;
        let current_ops_rate = (ops.finished - self.last_ops) as f64 / curr_duration_secs;
        let bytes = self.progress.bytes_copied.get();
        let average_bytes_rate = bytes as f64 / total_duration_secs;
        let current_bytes_rate = (bytes - self.last_bytes) as f64 / curr_duration_secs;
        // update self
        self.last_ops = ops.finished;
        self.last_bytes = bytes;
        self.last_update = time_now;
        // nice to have: convert to a table
        Ok(format!(
            "---------------------\n\
            OPS:\n\
            pending: {:>10}\n\
            average: {:>10.2} items/s\n\
            current: {:>10.2} items/s\n\
            -----------------------\n\
            COPIED:\n\
            average: {:>10}/s\n\
            current: {:>10}/s\n\
            bytes:   {:>10}\n\
            files:       {:>10}\n\
            symlinks:    {:>10}\n\
            directories: {:>10}\n\
            hard-links:  {:>10}\n\
            -----------------------\n\
            UNCHANGED:\n\
            files:       {:>10}\n\
            symlinks:    {:>10}\n\
            directories: {:>10}\n\
            hard-links:  {:>10}\n\
            -----------------------\n\
            REMOVED:\n\
            bytes:       {:>10}\n\
            files:       {:>10}\n\
            symlinks:    {:>10}\n\
            directories: {:>10}\n\
            -----------------------\n\
            SKIPPED:\n\
            files:       {:>10}\n\
            symlinks:    {:>10}\n\
            directories: {:>10}",
            ops.started - ops.finished, // pending
            average_ops_rate,
            current_ops_rate,
            // copy
            bytesize::ByteSize(average_bytes_rate as u64),
            bytesize::ByteSize(current_bytes_rate as u64),
            bytesize::ByteSize(self.progress.bytes_copied.get()),
            self.progress.files_copied.get(),
            self.progress.symlinks_created.get(),
            self.progress.directories_created.get(),
            self.progress.hard_links_created.get(),
            // unchanged
            self.progress.files_unchanged.get(),
            self.progress.symlinks_unchanged.get(),
            self.progress.directories_unchanged.get(),
            self.progress.hard_links_unchanged.get(),
            // remove
            bytesize::ByteSize(self.progress.bytes_removed.get()),
            self.progress.files_removed.get(),
            self.progress.symlinks_removed.get(),
            self.progress.directories_removed.get(),
            // skipped
            self.progress.files_skipped.get(),
            self.progress.symlinks_skipped.get(),
            self.progress.directories_skipped.get(),
        ))
    }
}

pub struct RcpdProgressPrinter {
    start_time: std::time::Instant,
    last_source_ops: u64,
    last_source_bytes: u64,
    last_source_files: u64,
    last_dest_ops: u64,
    last_dest_bytes: u64,
    last_update: std::time::Instant,
}

impl RcpdProgressPrinter {
    #[must_use]
    pub fn new() -> Self {
        let now = std::time::Instant::now();
        Self {
            start_time: now,
            last_source_ops: 0,
            last_source_bytes: 0,
            last_source_files: 0,
            last_dest_ops: 0,
            last_dest_bytes: 0,
            last_update: now,
        }
    }

    fn calculate_current_rate(&self, current: u64, last: u64, duration_secs: f64) -> f64 {
        if duration_secs > 0.0 {
            (current - last) as f64 / duration_secs
        } else {
            0.0
        }
    }

    fn calculate_average_rate(&self, total: u64, total_duration_secs: f64) -> f64 {
        if total_duration_secs > 0.0 {
            total as f64 / total_duration_secs
        } else {
            0.0
        }
    }

    pub fn print(
        &mut self,
        source_progress: &SerializableProgress,
        dest_progress: &SerializableProgress,
    ) -> anyhow::Result<String> {
        let time_now = std::time::Instant::now();
        let total_duration_secs = (time_now - self.start_time).as_secs_f64();
        let curr_duration_secs = (time_now - self.last_update).as_secs_f64();
        // source current rates
        let source_ops_rate_curr = self.calculate_current_rate(
            source_progress.ops_finished,
            self.last_source_ops,
            curr_duration_secs,
        );
        let source_bytes_rate_curr = self.calculate_current_rate(
            source_progress.bytes_copied,
            self.last_source_bytes,
            curr_duration_secs,
        );
        let source_files_rate_curr = self.calculate_current_rate(
            source_progress.files_copied,
            self.last_source_files,
            curr_duration_secs,
        );
        // source average rates
        let source_ops_rate_avg =
            self.calculate_average_rate(source_progress.ops_finished, total_duration_secs);
        let source_bytes_rate_avg =
            self.calculate_average_rate(source_progress.bytes_copied, total_duration_secs);
        let source_files_rate_avg =
            self.calculate_average_rate(source_progress.files_copied, total_duration_secs);
        // destination current rates
        let dest_ops_rate_curr = self.calculate_current_rate(
            dest_progress.ops_finished,
            self.last_dest_ops,
            curr_duration_secs,
        );
        let dest_bytes_rate_curr = self.calculate_current_rate(
            dest_progress.bytes_copied,
            self.last_dest_bytes,
            curr_duration_secs,
        );
        // destination average rates
        let dest_ops_rate_avg =
            self.calculate_average_rate(dest_progress.ops_finished, total_duration_secs);
        let dest_bytes_rate_avg =
            self.calculate_average_rate(dest_progress.bytes_copied, total_duration_secs);
        // update last values
        self.last_source_ops = source_progress.ops_finished;
        self.last_source_bytes = source_progress.bytes_copied;
        self.last_source_files = source_progress.files_copied;
        self.last_dest_ops = dest_progress.ops_finished;
        self.last_dest_bytes = dest_progress.bytes_copied;
        self.last_update = time_now;
        Ok(format!(
            "==== SOURCE =======\n\
            OPS:\n\
            pending: {:>10}\n\
            average: {:>10.2} items/s\n\
            current: {:>10.2} items/s\n\
            ---------------------\n\
            COPIED:\n\
            average: {:>10}/s\n\
            current: {:>10}/s\n\
            bytes:   {:>10}\n\
            files:       {:>10}\n\
            ---------------------\n\
            FILES:\n\
            average: {:>10.2} files/s\n\
            current: {:>10.2} files/s\n\
            ---------------------\n\
            SKIPPED:\n\
            files:       {:>10}\n\
            symlinks:    {:>10}\n\
            directories: {:>10}\n\
            ==== DESTINATION ====\n\
            OPS:\n\
            pending: {:>10}\n\
            average: {:>10.2} items/s\n\
            current: {:>10.2} items/s\n\
            ---------------------\n\
            COPIED:\n\
            average: {:>10}/s\n\
            current: {:>10}/s\n\
            bytes:   {:>10}\n\
            files:       {:>10}\n\
            symlinks:    {:>10}\n\
            directories: {:>10}\n\
            hard-links:  {:>10}\n\
            ---------------------\n\
            UNCHANGED:\n\
            files:       {:>10}\n\
            symlinks:    {:>10}\n\
            directories: {:>10}\n\
            hard-links:  {:>10}\n\
            ---------------------\n\
            REMOVED:\n\
            bytes:       {:>10}\n\
            files:       {:>10}\n\
            symlinks:    {:>10}\n\
            directories: {:>10}",
            // source section
            source_progress.ops_started - source_progress.ops_finished, // pending
            source_ops_rate_avg,
            source_ops_rate_curr,
            bytesize::ByteSize(source_bytes_rate_avg as u64),
            bytesize::ByteSize(source_bytes_rate_curr as u64),
            bytesize::ByteSize(source_progress.bytes_copied),
            source_progress.files_copied,
            source_files_rate_avg,
            source_files_rate_curr,
            // source skipped
            source_progress.files_skipped,
            source_progress.symlinks_skipped,
            source_progress.directories_skipped,
            // destination section
            dest_progress.ops_started - dest_progress.ops_finished, // pending
            dest_ops_rate_avg,
            dest_ops_rate_curr,
            bytesize::ByteSize(dest_bytes_rate_avg as u64),
            bytesize::ByteSize(dest_bytes_rate_curr as u64),
            bytesize::ByteSize(dest_progress.bytes_copied),
            // destination detailed stats
            dest_progress.files_copied,
            dest_progress.symlinks_created,
            dest_progress.directories_created,
            dest_progress.hard_links_created,
            // unchanged
            dest_progress.files_unchanged,
            dest_progress.symlinks_unchanged,
            dest_progress.directories_unchanged,
            dest_progress.hard_links_unchanged,
            // removed
            bytesize::ByteSize(dest_progress.bytes_removed),
            dest_progress.files_removed,
            dest_progress.symlinks_removed,
            dest_progress.directories_removed,
        ))
    }
}

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

#[cfg(test)]
mod tests {
    use super::*;
    use crate::remote_tracing::TracingMessage;
    use anyhow::Result;

    #[test]
    fn basic_counting() -> Result<()> {
        let tls_counter = TlsCounter::new();
        for _ in 0..10 {
            tls_counter.inc();
        }
        assert!(tls_counter.get() == 10);
        Ok(())
    }

    #[test]
    fn threaded_counting() -> Result<()> {
        let tls_counter = TlsCounter::new();
        std::thread::scope(|scope| {
            let mut handles = Vec::new();
            for _ in 0..10 {
                handles.push(scope.spawn(|| {
                    for _ in 0..100 {
                        tls_counter.inc();
                    }
                }));
            }
        });
        assert!(tls_counter.get() == 1000);
        Ok(())
    }

    #[test]
    fn basic_guard() -> Result<()> {
        let tls_progress = ProgressCounter::new();
        let _guard = tls_progress.guard();
        Ok(())
    }

    #[test]
    fn test_serializable_progress() -> Result<()> {
        let progress = Progress::new();

        // Add some test data
        progress.files_copied.inc();
        progress.bytes_copied.add(1024);
        progress.directories_created.add(2);

        // Test conversion to serializable format
        let serializable = SerializableProgress::from(&progress);
        assert_eq!(serializable.files_copied, 1);
        assert_eq!(serializable.bytes_copied, 1024);
        assert_eq!(serializable.directories_created, 2);

        // Test that we can create a TracingMessage with progress
        let _tracing_msg = TracingMessage::Progress(serializable);

        Ok(())
    }

    #[test]
    fn test_rcpd_progress_printer() -> Result<()> {
        let mut printer = RcpdProgressPrinter::new();

        // Create test progress data
        let source_progress = SerializableProgress {
            ops_started: 100,
            ops_finished: 80,
            bytes_copied: 1024,
            files_copied: 5,
            files_skipped: 3,
            symlinks_skipped: 1,
            directories_skipped: 2,
            ..Default::default()
        };

        let dest_progress = SerializableProgress {
            ops_started: 80,
            ops_finished: 70,
            bytes_copied: 1024,
            files_copied: 8,
            symlinks_created: 2,
            directories_created: 1,
            ..Default::default()
        };

        // Test that print returns a formatted string
        let output = printer.print(&source_progress, &dest_progress)?;
        assert!(output.contains("SOURCE"));
        assert!(output.contains("DESTINATION"));
        assert!(output.contains("OPS:"));
        assert!(output.contains("pending:"));
        assert!(output.contains("20")); // source pending ops (100-80)
        assert!(output.contains("10")); // dest pending ops (80-70)
        let mut sections = output.split("==== DESTINATION ====");
        let source_section = sections.next().unwrap();
        let dest_section = sections.next().unwrap_or("");
        let source_files_line = source_section
            .lines()
            .find(|line| line.trim_start().starts_with("files:"))
            .expect("source files line missing");
        assert!(source_files_line.trim_start().ends_with("5"));
        assert!(!source_files_line.contains('.'));
        let dest_files_line = dest_section
            .lines()
            .find(|line| line.trim_start().starts_with("files:"))
            .expect("dest files line missing");
        assert!(dest_files_line.trim_start().ends_with("8"));
        assert!(!dest_files_line.contains('.'));
        // verify SKIPPED section appears in source
        assert!(source_section.contains("SKIPPED:"));
        let skipped_section = source_section
            .split("SKIPPED:")
            .nth(1)
            .expect("SKIPPED section missing in source");
        let skipped_lines: Vec<&str> = skipped_section.lines().collect();
        let skipped_files_line = skipped_lines
            .iter()
            .find(|line| line.trim_start().starts_with("files:"))
            .expect("skipped files line missing");
        assert!(skipped_files_line.trim_start().ends_with("3"));
        let skipped_symlinks_line = skipped_lines
            .iter()
            .find(|line| line.trim_start().starts_with("symlinks:"))
            .expect("skipped symlinks line missing");
        assert!(skipped_symlinks_line.trim_start().ends_with("1"));
        let skipped_dirs_line = skipped_lines
            .iter()
            .find(|line| line.trim_start().starts_with("directories:"))
            .expect("skipped directories line missing");
        assert!(skipped_dirs_line.trim_start().ends_with("2"));

        Ok(())
    }

    #[test]
    fn interleaved_counter_access() -> Result<()> {
        // test that interleaved access to multiple counters works correctly
        // (this was problematic with the old single-slot cache design)
        let counter_a = TlsCounter::new();
        let counter_b = TlsCounter::new();
        let counter_c = TlsCounter::new();
        for i in 0..100 {
            counter_a.add(1);
            counter_b.add(2);
            counter_c.add(3);
            // verify intermediate values are correct
            if i % 10 == 0 {
                assert_eq!(counter_a.get(), i + 1);
                assert_eq!(counter_b.get(), (i + 1) * 2);
                assert_eq!(counter_c.get(), (i + 1) * 3);
            }
        }
        // verify final counts
        assert_eq!(counter_a.get(), 100);
        assert_eq!(counter_b.get(), 200);
        assert_eq!(counter_c.get(), 300);
        Ok(())
    }

    #[test]
    fn concurrent_multi_counter_access() -> Result<()> {
        // test concurrent access with multiple threads each using multiple counters
        let counter_a = std::sync::Arc::new(TlsCounter::new());
        let counter_b = std::sync::Arc::new(TlsCounter::new());
        const THREADS: usize = 4;
        const ITERATIONS: u64 = 1000;
        let handles: Vec<_> = (0..THREADS)
            .map(|_| {
                let ca = counter_a.clone();
                let cb = counter_b.clone();
                std::thread::spawn(move || {
                    for _ in 0..ITERATIONS {
                        ca.add(1);
                        cb.add(2);
                    }
                })
            })
            .collect();
        for h in handles {
            h.join().unwrap();
        }
        // verify totals are correct (no lost increments)
        assert_eq!(counter_a.get(), THREADS as u64 * ITERATIONS);
        assert_eq!(counter_b.get(), THREADS as u64 * ITERATIONS * 2);
        Ok(())
    }

    #[test]
    fn repeated_counter_access() -> Result<()> {
        // test that repeated access to the same counter works correctly
        let counter = TlsCounter::new();
        for i in 1..=1000 {
            counter.add(1);
            assert_eq!(counter.get(), i);
        }
        Ok(())
    }

    #[test]
    fn sharding_distributes_across_threads() -> Result<()> {
        // test that different threads get assigned to different shards
        // and that all increments are correctly counted
        let counter = std::sync::Arc::new(TlsCounter::new());
        const THREADS: usize = 16;
        const ITERATIONS: u64 = 100;
        let handles: Vec<_> = (0..THREADS)
            .map(|_| {
                let c = counter.clone();
                std::thread::spawn(move || {
                    for _ in 0..ITERATIONS {
                        c.inc();
                    }
                })
            })
            .collect();
        for h in handles {
            h.join().unwrap();
        }
        assert_eq!(counter.get(), THREADS as u64 * ITERATIONS);
        Ok(())
    }

    #[test]
    fn sharding_handles_more_threads_than_shards() -> Result<()> {
        // test that shard assignment wraps correctly when threads > NUM_SHARDS
        let counter = std::sync::Arc::new(TlsCounter::new());
        const THREADS: usize = 128; // 2x NUM_SHARDS to force wrap-around
        const ITERATIONS: u64 = 100;
        let handles: Vec<_> = (0..THREADS)
            .map(|_| {
                let c = counter.clone();
                std::thread::spawn(move || {
                    for _ in 0..ITERATIONS {
                        c.inc();
                    }
                })
            })
            .collect();
        for h in handles {
            h.join().unwrap();
        }
        assert_eq!(counter.get(), THREADS as u64 * ITERATIONS);
        Ok(())
    }

    #[test]
    fn counter_independence() -> Result<()> {
        // test that multiple counters are completely independent
        let counters: Vec<_> = (0..10).map(|_| TlsCounter::new()).collect();
        for (i, counter) in counters.iter().enumerate() {
            counter.add((i + 1) as u64 * 100);
        }
        for (i, counter) in counters.iter().enumerate() {
            assert_eq!(counter.get(), (i + 1) as u64 * 100);
        }
        Ok(())
    }
}