lcpfs 2026.1.102

LCP File System - A ZFS-inspired copy-on-write filesystem for Rust
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
// Copyright 2025 LunaOS Contributors
// SPDX-License-Identifier: Apache-2.0

//! Version history tracking for files.
//!
//! This module provides the ability to list all historical versions of a file,
//! showing when it was created, modified, and what snapshots contain it.

use alloc::string::String;
use alloc::vec::Vec;

use super::types::{ChangeType, FileVersion, SnapshotInfo, TimeError};
use super::walker::{HistoricalEntry, HistoricalTreeProvider};

// ═══════════════════════════════════════════════════════════════════════════════
// VERSION HISTORY PROVIDER
// ═══════════════════════════════════════════════════════════════════════════════

/// Trait for accessing file version history.
///
/// This trait must be implemented to track changes to files across TXGs.
pub trait VersionHistoryProvider: HistoricalTreeProvider {
    /// Get all TXGs where a file at the given path was modified.
    fn file_txg_history(&self, path: &str) -> Result<Vec<u64>, TimeError>;

    /// Get all snapshots.
    fn all_snapshots(&self) -> Vec<SnapshotInfo>;

    /// Get the timestamp for a TXG.
    fn txg_timestamp(&self, txg: u64) -> Option<u64>;
}

// ═══════════════════════════════════════════════════════════════════════════════
// VERSION HISTORY ENGINE
// ═══════════════════════════════════════════════════════════════════════════════

/// Engine for computing file version history.
pub struct VersionHistory<'a, P: VersionHistoryProvider> {
    provider: &'a P,
}

impl<'a, P: VersionHistoryProvider> VersionHistory<'a, P> {
    /// Create a new version history engine.
    pub fn new(provider: &'a P) -> Self {
        Self { provider }
    }

    /// Get all versions of a file.
    pub fn get_versions(
        &self,
        path: &str,
        limit: Option<usize>,
    ) -> Result<Vec<FileVersion>, TimeError> {
        // Get all TXGs where file changed
        let txgs = self.provider.file_txg_history(path)?;

        if txgs.is_empty() {
            return Err(TimeError::PathNotFound(path.into()));
        }

        // Get all snapshots for lookup
        let snapshots = self.provider.all_snapshots();

        let mut versions = Vec::new();
        let mut prev_checksum: Option<[u64; 4]> = None;

        for txg in &txgs {
            // Get the file state at this TXG
            let entry = self.provider.lookup_at_txg(path, *txg)?;

            // Determine change type
            let change_type = if prev_checksum.is_none() {
                ChangeType::Created
            } else if prev_checksum != Some(entry.checksum) {
                ChangeType::Modified
            } else {
                ChangeType::MetadataChanged
            };

            prev_checksum = Some(entry.checksum);

            // Find snapshot containing this TXG
            let snapshot_name = snapshots
                .iter()
                .find(|s| s.txg == *txg)
                .map(|s| s.name.clone());

            // Get timestamp
            let timestamp = self.provider.txg_timestamp(*txg).unwrap_or(0);

            versions.push(FileVersion {
                txg: *txg,
                timestamp,
                snapshot_name,
                size: entry.size,
                checksum: entry.checksum,
                change_type,
            });
        }

        // Sort by TXG descending (most recent first)
        versions.sort_by(|a, b| b.txg.cmp(&a.txg));

        // Apply limit
        if let Some(limit) = limit {
            versions.truncate(limit);
        }

        Ok(versions)
    }

    /// Get the version of a file at a specific TXG.
    pub fn get_version_at(&self, path: &str, txg: u64) -> Result<FileVersion, TimeError> {
        let entry = self.provider.lookup_at_txg(path, txg)?;

        // Get all TXGs to determine change type
        let txgs = self.provider.file_txg_history(path)?;

        // Find previous TXG
        let prev_txg = txgs.iter().filter(|t| **t < txg).max();

        let change_type = if prev_txg.is_none() {
            ChangeType::Created
        } else if let Some(pt) = prev_txg {
            let prev_entry = self.provider.lookup_at_txg(path, *pt)?;
            if prev_entry.checksum != entry.checksum {
                ChangeType::Modified
            } else {
                ChangeType::MetadataChanged
            }
        } else {
            ChangeType::Created
        };

        // Find snapshot
        let snapshots = self.provider.all_snapshots();
        let snapshot_name = snapshots
            .iter()
            .find(|s| s.txg == txg)
            .map(|s| s.name.clone());

        let timestamp = self.provider.txg_timestamp(txg).unwrap_or(0);

        Ok(FileVersion {
            txg,
            timestamp,
            snapshot_name,
            size: entry.size,
            checksum: entry.checksum,
            change_type,
        })
    }

    /// Count total versions of a file.
    pub fn count_versions(&self, path: &str) -> Result<usize, TimeError> {
        let txgs = self.provider.file_txg_history(path)?;
        Ok(txgs.len())
    }

    /// Get the first (creation) version of a file.
    pub fn get_first_version(&self, path: &str) -> Result<FileVersion, TimeError> {
        let txgs = self.provider.file_txg_history(path)?;

        let first_txg = txgs
            .iter()
            .min()
            .ok_or_else(|| TimeError::PathNotFound(path.into()))?;

        let entry = self.provider.lookup_at_txg(path, *first_txg)?;

        let snapshots = self.provider.all_snapshots();
        let snapshot_name = snapshots
            .iter()
            .find(|s| s.txg == *first_txg)
            .map(|s| s.name.clone());

        let timestamp = self.provider.txg_timestamp(*first_txg).unwrap_or(0);

        Ok(FileVersion {
            txg: *first_txg,
            timestamp,
            snapshot_name,
            size: entry.size,
            checksum: entry.checksum,
            change_type: ChangeType::Created,
        })
    }

    /// Get the most recent version of a file.
    pub fn get_latest_version(&self, path: &str) -> Result<FileVersion, TimeError> {
        let txgs = self.provider.file_txg_history(path)?;

        let latest_txg = txgs
            .iter()
            .max()
            .ok_or_else(|| TimeError::PathNotFound(path.into()))?;

        self.get_version_at(path, *latest_txg)
    }

    /// Get versions within a time range.
    pub fn get_versions_between(
        &self,
        path: &str,
        from_txg: u64,
        to_txg: u64,
    ) -> Result<Vec<FileVersion>, TimeError> {
        let all_versions = self.get_versions(path, None)?;

        let filtered: Vec<_> = all_versions
            .into_iter()
            .filter(|v| v.txg >= from_txg && v.txg <= to_txg)
            .collect();

        Ok(filtered)
    }

    /// Check if a file existed at a given TXG.
    pub fn existed_at(&self, path: &str, txg: u64) -> bool {
        self.provider.exists_at_txg(path, txg)
    }

    /// Get versions that are captured in snapshots.
    pub fn get_snapshot_versions(&self, path: &str) -> Result<Vec<FileVersion>, TimeError> {
        let versions = self.get_versions(path, None)?;

        let snapshot_versions: Vec<_> = versions
            .into_iter()
            .filter(|v| v.snapshot_name.is_some())
            .collect();

        Ok(snapshot_versions)
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// VERSION COMPARISON
// ═══════════════════════════════════════════════════════════════════════════════

/// Result of comparing two versions.
#[derive(Debug, Clone)]
pub struct VersionComparison {
    /// First version.
    pub version1: FileVersion,
    /// Second version.
    pub version2: FileVersion,
    /// Size difference (positive = grew, negative = shrunk).
    pub size_delta: i64,
    /// Checksum changed.
    pub content_changed: bool,
    /// Number of TXGs between versions.
    pub txg_delta: u64,
    /// Time between versions in seconds.
    pub time_delta: u64,
}

impl<'a, P: VersionHistoryProvider> VersionHistory<'a, P> {
    /// Compare two versions of a file.
    pub fn compare_versions(
        &self,
        path: &str,
        txg1: u64,
        txg2: u64,
    ) -> Result<VersionComparison, TimeError> {
        let v1 = self.get_version_at(path, txg1)?;
        let v2 = self.get_version_at(path, txg2)?;

        let size_delta = v2.size as i64 - v1.size as i64;
        let content_changed = v1.checksum != v2.checksum;
        let txg_delta = txg2.abs_diff(txg1);
        let time_delta = v2.timestamp.abs_diff(v1.timestamp);

        Ok(VersionComparison {
            version1: v1,
            version2: v2,
            size_delta,
            content_changed,
            txg_delta,
            time_delta,
        })
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// IN-MEMORY HISTORY PROVIDER (FOR TESTING)
// ═══════════════════════════════════════════════════════════════════════════════

use super::walker::InMemoryTreeProvider;

/// Extended in-memory provider with version history.
#[derive(Debug, Default)]
pub struct InMemoryVersionProvider {
    /// Base tree provider.
    pub tree: InMemoryTreeProvider,
    /// Snapshots.
    pub snapshots: Vec<SnapshotInfo>,
    /// TXG to timestamp mapping.
    pub txg_timestamps: Vec<(u64, u64)>,
}

impl InMemoryVersionProvider {
    /// Create a new provider.
    pub fn new() -> Self {
        Self::default()
    }

    /// Add a snapshot.
    pub fn add_snapshot(&mut self, info: SnapshotInfo) {
        self.snapshots.push(info);
    }

    /// Add TXG timestamp.
    pub fn add_txg_timestamp(&mut self, txg: u64, timestamp: u64) {
        self.txg_timestamps.push((txg, timestamp));
    }

    /// Add an entry.
    pub fn add_entry(&mut self, txg: u64, entry: HistoricalEntry) {
        self.tree.add_entry(txg, entry);
    }
}

impl HistoricalTreeProvider for InMemoryVersionProvider {
    fn root_at_txg(&self, txg: u64) -> Result<HistoricalEntry, TimeError> {
        self.tree.root_at_txg(txg)
    }

    fn lookup_at_txg(&self, path: &str, txg: u64) -> Result<HistoricalEntry, TimeError> {
        self.tree.lookup_at_txg(path, txg)
    }

    fn readdir_at_txg(&self, path: &str, txg: u64) -> Result<Vec<HistoricalEntry>, TimeError> {
        self.tree.readdir_at_txg(path, txg)
    }

    fn lookup_by_id_at_txg(&self, object_id: u64, txg: u64) -> Result<HistoricalEntry, TimeError> {
        self.tree.lookup_by_id_at_txg(object_id, txg)
    }

    fn exists_at_txg(&self, path: &str, txg: u64) -> bool {
        self.tree.exists_at_txg(path, txg)
    }

    fn readlink_at_txg(&self, path: &str, txg: u64) -> Result<String, TimeError> {
        self.tree.readlink_at_txg(path, txg)
    }
}

impl VersionHistoryProvider for InMemoryVersionProvider {
    fn file_txg_history(&self, path: &str) -> Result<Vec<u64>, TimeError> {
        // Collect all TXGs where this file appears
        let txgs: Vec<u64> = self
            .tree
            .entries
            .iter()
            .filter(|(_, e)| e.path == path)
            .map(|(txg, _)| *txg)
            .collect();

        if txgs.is_empty() {
            return Err(TimeError::PathNotFound(path.into()));
        }

        Ok(txgs)
    }

    fn all_snapshots(&self) -> Vec<SnapshotInfo> {
        self.snapshots.clone()
    }

    fn txg_timestamp(&self, txg: u64) -> Option<u64> {
        self.txg_timestamps
            .iter()
            .find(|(t, _)| *t == txg)
            .map(|(_, ts)| *ts)
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// TESTS
// ═══════════════════════════════════════════════════════════════════════════════

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

    fn create_entry(
        path: &str,
        name: &str,
        size: u64,
        txg: u64,
        checksum: [u64; 4],
    ) -> HistoricalEntry {
        HistoricalEntry {
            name: name.into(),
            path: path.into(),
            object_id: path.len() as u64,
            parent_id: 1,
            file_type: FileType::Regular,
            size,
            mode: 0o644,
            uid: 1000,
            gid: 1000,
            atime: txg * 1000,
            mtime: txg * 1000,
            ctime: txg * 1000,
            txg,
            checksum,
            nlinks: 1,
            blocks: size.div_ceil(512),
            generation: txg,
        }
    }

    fn create_test_provider() -> InMemoryVersionProvider {
        let mut provider = InMemoryVersionProvider::new();

        // Add file versions at different TXGs
        provider.add_entry(
            100,
            create_entry("/data/file.txt", "file.txt", 100, 100, [1; 4]),
        );
        provider.add_entry(
            200,
            create_entry("/data/file.txt", "file.txt", 150, 200, [2; 4]),
        );
        provider.add_entry(
            300,
            create_entry("/data/file.txt", "file.txt", 200, 300, [3; 4]),
        );

        // Add timestamps
        provider.add_txg_timestamp(100, 1704067200); // 2024-01-01
        provider.add_txg_timestamp(200, 1705276800); // 2024-01-15
        provider.add_txg_timestamp(300, 1706486400); // 2024-01-29

        // Add a snapshot at TXG 200
        provider.add_snapshot(SnapshotInfo {
            name: "weekly-backup".into(),
            creation_time: 1705276800,
            txg: 200,
            referenced: 1024 * 1024,
            used: 512 * 1024,
        });

        provider
    }

    #[test]
    fn test_get_versions() {
        let provider = create_test_provider();
        let history = VersionHistory::new(&provider);

        let versions = history.get_versions("/data/file.txt", None).unwrap();

        assert_eq!(versions.len(), 3);
        // Should be sorted by TXG descending
        assert_eq!(versions[0].txg, 300);
        assert_eq!(versions[1].txg, 200);
        assert_eq!(versions[2].txg, 100);
    }

    #[test]
    fn test_get_versions_with_limit() {
        let provider = create_test_provider();
        let history = VersionHistory::new(&provider);

        let versions = history.get_versions("/data/file.txt", Some(2)).unwrap();
        assert_eq!(versions.len(), 2);
    }

    #[test]
    fn test_version_change_types() {
        let provider = create_test_provider();
        let history = VersionHistory::new(&provider);

        let versions = history.get_versions("/data/file.txt", None).unwrap();

        // First version should be Created
        let first = versions.iter().find(|v| v.txg == 100).unwrap();
        assert!(matches!(first.change_type, ChangeType::Created));

        // Later versions should be Modified (checksum changed)
        let second = versions.iter().find(|v| v.txg == 200).unwrap();
        assert!(matches!(second.change_type, ChangeType::Modified));
    }

    #[test]
    fn test_snapshot_in_versions() {
        let provider = create_test_provider();
        let history = VersionHistory::new(&provider);

        let versions = history.get_versions("/data/file.txt", None).unwrap();

        // TXG 200 should have snapshot name
        let v200 = versions.iter().find(|v| v.txg == 200).unwrap();
        assert_eq!(v200.snapshot_name, Some("weekly-backup".into()));

        // Others should not
        let v100 = versions.iter().find(|v| v.txg == 100).unwrap();
        assert_eq!(v100.snapshot_name, None);
    }

    #[test]
    fn test_get_first_version() {
        let provider = create_test_provider();
        let history = VersionHistory::new(&provider);

        let first = history.get_first_version("/data/file.txt").unwrap();
        assert_eq!(first.txg, 100);
        assert!(matches!(first.change_type, ChangeType::Created));
    }

    #[test]
    fn test_get_latest_version() {
        let provider = create_test_provider();
        let history = VersionHistory::new(&provider);

        let latest = history.get_latest_version("/data/file.txt").unwrap();
        assert_eq!(latest.txg, 300);
        assert_eq!(latest.size, 200);
    }

    #[test]
    fn test_count_versions() {
        let provider = create_test_provider();
        let history = VersionHistory::new(&provider);

        let count = history.count_versions("/data/file.txt").unwrap();
        assert_eq!(count, 3);
    }

    #[test]
    fn test_versions_between() {
        let provider = create_test_provider();
        let history = VersionHistory::new(&provider);

        let versions = history
            .get_versions_between("/data/file.txt", 150, 250)
            .unwrap();

        assert_eq!(versions.len(), 1);
        assert_eq!(versions[0].txg, 200);
    }

    #[test]
    fn test_existed_at() {
        let provider = create_test_provider();
        let history = VersionHistory::new(&provider);

        assert!(history.existed_at("/data/file.txt", 100));
        assert!(history.existed_at("/data/file.txt", 200));
        assert!(!history.existed_at("/data/file.txt", 50)); // Before creation
    }

    #[test]
    fn test_snapshot_versions() {
        let provider = create_test_provider();
        let history = VersionHistory::new(&provider);

        let snap_versions = history.get_snapshot_versions("/data/file.txt").unwrap();

        assert_eq!(snap_versions.len(), 1);
        assert_eq!(snap_versions[0].txg, 200);
    }

    #[test]
    fn test_compare_versions() {
        let provider = create_test_provider();
        let history = VersionHistory::new(&provider);

        let cmp = history
            .compare_versions("/data/file.txt", 100, 300)
            .unwrap();

        assert_eq!(cmp.version1.txg, 100);
        assert_eq!(cmp.version2.txg, 300);
        assert_eq!(cmp.size_delta, 100); // 200 - 100
        assert!(cmp.content_changed);
        assert_eq!(cmp.txg_delta, 200);
    }

    #[test]
    fn test_file_not_found() {
        let provider = create_test_provider();
        let history = VersionHistory::new(&provider);

        let result = history.get_versions("/nonexistent", None);
        assert!(matches!(result, Err(TimeError::PathNotFound(_))));
    }
}