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
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
// Copyright 2025 LunaOS Contributors
// SPDX-License-Identifier: Apache-2.0

//! Time-travel query types and AST definitions.
//!
//! This module defines the abstract syntax tree (AST) for time-travel queries,
//! enabling SQL-like syntax for querying filesystem state at any point in time.

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

// ═══════════════════════════════════════════════════════════════════════════════
// TIME SPECIFICATION
// ═══════════════════════════════════════════════════════════════════════════════

/// Time specification for historical queries.
///
/// Supports multiple ways to specify a point in time:
/// - Absolute Unix timestamp
/// - ISO 8601 datetime string
/// - Named snapshot
/// - Relative time (e.g., "1 hour ago")
/// - Transaction group number
#[derive(Debug, Clone, PartialEq)]
pub enum TimeSpec {
    /// Unix timestamp in seconds since epoch.
    Timestamp(u64),
    /// ISO 8601 datetime string (e.g., "2024-01-15 10:30:00").
    DateTime(String),
    /// Named snapshot (e.g., "daily-backup").
    Snapshot(String),
    /// Relative time expression (e.g., "1 hour ago", "yesterday").
    Relative(String),
    /// Transaction group number.
    Txg(u64),
    /// Current time (NOW).
    Now,
}

impl TimeSpec {
    /// Check if this is a relative time specification.
    pub fn is_relative(&self) -> bool {
        matches!(self, TimeSpec::Relative(_))
    }

    /// Check if this is a snapshot reference.
    pub fn is_snapshot(&self) -> bool {
        matches!(self, TimeSpec::Snapshot(_))
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// QUERY AST
// ═══════════════════════════════════════════════════════════════════════════════

/// Time-travel query abstract syntax tree.
#[derive(Debug, Clone, PartialEq)]
pub enum TimeQuery {
    /// SELECT query for point-in-time state.
    ///
    /// Example: `SELECT path, size FROM /data AS OF '2024-01-15'`
    Select {
        /// Columns to retrieve (empty = all).
        columns: Vec<Column>,
        /// Path to query.
        path: String,
        /// Point in time.
        time: TimeSpec,
        /// Optional filter condition.
        filter: Option<Filter>,
        /// Result limit.
        limit: Option<usize>,
        /// Order by clause.
        order_by: Option<OrderBy>,
    },

    /// DIFF query between two points in time.
    ///
    /// Example: `DIFF /data BETWEEN '2024-01-01' AND '2024-06-01'`
    Diff {
        /// Path to diff.
        path: String,
        /// Start time.
        from: TimeSpec,
        /// End time.
        to: TimeSpec,
        /// Filter for change types.
        change_types: Option<Vec<ChangeType>>,
    },

    /// VERSIONS query to list all versions of a file.
    ///
    /// Example: `VERSIONS /data/config.yaml LIMIT 100`
    Versions {
        /// Path to the file.
        path: String,
        /// Maximum versions to return.
        limit: Option<usize>,
    },

    /// RESTORE command to restore file to previous state.
    ///
    /// Example: `RESTORE /data/file.txt TO '2024-03-15'`
    Restore {
        /// Path to restore.
        path: String,
        /// Target time to restore to.
        time: TimeSpec,
        /// Destination path (if different from source).
        dest_path: Option<String>,
    },

    /// SHOW SNAPSHOTS query.
    ///
    /// Example: `SHOW SNAPSHOTS FOR /data`
    ShowSnapshots {
        /// Dataset path.
        path: String,
    },

    /// COUNT query for statistics.
    ///
    /// Example: `SELECT COUNT(*), SUM(size) FROM /data AS OF '2024-01-15'`
    Aggregate {
        /// Aggregate functions.
        functions: Vec<AggregateFunc>,
        /// Path to query.
        path: String,
        /// Point in time.
        time: TimeSpec,
        /// Optional filter.
        filter: Option<Filter>,
    },
}

/// Column specification for SELECT queries.
#[derive(Debug, Clone, PartialEq)]
pub enum Column {
    /// All columns (*).
    All,
    /// Specific column by name.
    Named(String),
    /// Column with alias.
    Aliased {
        /// Column name.
        name: String,
        /// Alias for the column.
        alias: String,
    },
}

impl Column {
    /// Get the column name.
    pub fn name(&self) -> &str {
        match self {
            Column::All => "*",
            Column::Named(n) => n,
            Column::Aliased { name, .. } => name,
        }
    }
}

/// Aggregate function.
#[derive(Debug, Clone, PartialEq)]
pub enum AggregateFunc {
    /// COUNT(*) or COUNT(column).
    Count(Option<String>),
    /// SUM(column).
    Sum(String),
    /// AVG(column).
    Avg(String),
    /// MIN(column).
    Min(String),
    /// MAX(column).
    Max(String),
}

/// Order by specification.
#[derive(Debug, Clone, PartialEq)]
pub struct OrderBy {
    /// Column to order by.
    pub column: String,
    /// Ascending or descending.
    pub ascending: bool,
}

// ═══════════════════════════════════════════════════════════════════════════════
// FILTER CONDITIONS
// ═══════════════════════════════════════════════════════════════════════════════

/// Filter condition for queries.
#[derive(Debug, Clone, PartialEq)]
pub enum Filter {
    /// Equality comparison.
    Eq {
        /// Column name.
        column: String,
        /// Value to compare.
        value: Value,
    },
    /// Not equal comparison.
    Ne {
        /// Column name.
        column: String,
        /// Value to compare.
        value: Value,
    },
    /// Less than.
    Lt {
        /// Column name.
        column: String,
        /// Value to compare.
        value: Value,
    },
    /// Less than or equal.
    Le {
        /// Column name.
        column: String,
        /// Value to compare.
        value: Value,
    },
    /// Greater than.
    Gt {
        /// Column name.
        column: String,
        /// Value to compare.
        value: Value,
    },
    /// Greater than or equal.
    Ge {
        /// Column name.
        column: String,
        /// Value to compare.
        value: Value,
    },
    /// LIKE pattern match.
    Like {
        /// Column name.
        column: String,
        /// Pattern to match.
        pattern: String,
    },
    /// IN list.
    In {
        /// Column name.
        column: String,
        /// Values to check.
        values: Vec<Value>,
    },
    /// BETWEEN range.
    Between {
        /// Column name.
        column: String,
        /// Lower bound.
        low: Value,
        /// Upper bound.
        high: Value,
    },
    /// IS NULL check.
    IsNull {
        /// Column name.
        column: String,
    },
    /// IS NOT NULL check.
    IsNotNull {
        /// Column name.
        column: String,
    },
    /// AND combination.
    And(Box<Filter>, Box<Filter>),
    /// OR combination.
    Or(Box<Filter>, Box<Filter>),
    /// NOT negation.
    Not(Box<Filter>),
}

impl Filter {
    /// Create an AND filter.
    pub fn and(self, other: Filter) -> Filter {
        Filter::And(Box::new(self), Box::new(other))
    }

    /// Create an OR filter.
    pub fn or(self, other: Filter) -> Filter {
        Filter::Or(Box::new(self), Box::new(other))
    }

    /// Create a NOT filter.
    pub fn not(self) -> Filter {
        Filter::Not(Box::new(self))
    }
}

/// Value type for filter comparisons.
#[derive(Debug, Clone, PartialEq)]
pub enum Value {
    /// String value.
    String(String),
    /// Integer value.
    Integer(i64),
    /// Unsigned integer.
    Unsigned(u64),
    /// Boolean value.
    Bool(bool),
    /// Null value.
    Null,
}

impl Value {
    /// Try to get as string.
    pub fn as_str(&self) -> Option<&str> {
        match self {
            Value::String(s) => Some(s),
            _ => None,
        }
    }

    /// Try to get as i64.
    pub fn as_i64(&self) -> Option<i64> {
        match self {
            Value::Integer(n) => Some(*n),
            Value::Unsigned(n) => i64::try_from(*n).ok(),
            _ => None,
        }
    }

    /// Try to get as u64.
    pub fn as_u64(&self) -> Option<u64> {
        match self {
            Value::Unsigned(n) => Some(*n),
            Value::Integer(n) => u64::try_from(*n).ok(),
            _ => None,
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// CHANGE TYPES
// ═══════════════════════════════════════════════════════════════════════════════

/// Type of change detected in diff.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ChangeType {
    /// File was created.
    Created,
    /// File was modified.
    Modified,
    /// File was deleted.
    Deleted,
    /// File was renamed.
    Renamed {
        /// Previous path.
        old_path: String,
    },
    /// File metadata changed (permissions, etc.).
    MetadataChanged,
}

impl ChangeType {
    /// Get the change type name.
    pub fn name(&self) -> &'static str {
        match self {
            ChangeType::Created => "created",
            ChangeType::Modified => "modified",
            ChangeType::Deleted => "deleted",
            ChangeType::Renamed { .. } => "renamed",
            ChangeType::MetadataChanged => "metadata_changed",
        }
    }

    /// Parse from string.
    pub fn from_str(s: &str) -> Option<Self> {
        match s.to_lowercase().as_str() {
            "created" | "create" | "new" => Some(ChangeType::Created),
            "modified" | "modify" | "changed" => Some(ChangeType::Modified),
            "deleted" | "delete" | "removed" => Some(ChangeType::Deleted),
            "renamed" | "rename" | "moved" => Some(ChangeType::Renamed {
                old_path: String::new(),
            }),
            "metadata" | "metadata_changed" => Some(ChangeType::MetadataChanged),
            _ => None,
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// QUERY RESULTS
// ═══════════════════════════════════════════════════════════════════════════════

/// Result of a time-travel query.
#[derive(Debug, Clone)]
pub enum QueryResult {
    /// Rows from SELECT query.
    Rows(Vec<QueryRow>),
    /// Diff entries.
    Diffs(Vec<DiffEntry>),
    /// File versions.
    Versions(Vec<FileVersion>),
    /// Snapshot list.
    Snapshots(Vec<SnapshotInfo>),
    /// Aggregate results.
    Aggregate(AggregateResult),
    /// Restore completed.
    Restored {
        /// Restored path.
        path: String,
        /// TXG restored from.
        txg: u64,
    },
    /// Empty result.
    Empty,
}

impl QueryResult {
    /// Get the number of results.
    pub fn len(&self) -> usize {
        match self {
            QueryResult::Rows(rows) => rows.len(),
            QueryResult::Diffs(diffs) => diffs.len(),
            QueryResult::Versions(versions) => versions.len(),
            QueryResult::Snapshots(snaps) => snaps.len(),
            QueryResult::Aggregate(_) => 1,
            QueryResult::Restored { .. } => 1,
            QueryResult::Empty => 0,
        }
    }

    /// Check if empty.
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }
}

/// A row from a SELECT query.
#[derive(Debug, Clone)]
pub struct QueryRow {
    /// File path.
    pub path: String,
    /// Object ID.
    pub object_id: u64,
    /// File size in bytes.
    pub size: u64,
    /// Modification time (Unix timestamp).
    pub mtime: u64,
    /// Creation time (Unix timestamp).
    pub ctime: u64,
    /// Access time (Unix timestamp).
    pub atime: u64,
    /// File mode/permissions.
    pub mode: u32,
    /// Owner UID.
    pub uid: u32,
    /// Owner GID.
    pub gid: u32,
    /// Transaction group when this version was created.
    pub txg: u64,
    /// File type.
    pub file_type: FileType,
    /// Checksum.
    pub checksum: [u64; 4],
}

/// File type enumeration.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FileType {
    /// Regular file.
    Regular,
    /// Directory.
    Directory,
    /// Symbolic link.
    Symlink,
    /// Block device.
    BlockDevice,
    /// Character device.
    CharDevice,
    /// Named pipe (FIFO).
    Fifo,
    /// Socket.
    Socket,
}

impl FileType {
    /// Get the file type name.
    pub fn name(&self) -> &'static str {
        match self {
            FileType::Regular => "file",
            FileType::Directory => "directory",
            FileType::Symlink => "symlink",
            FileType::BlockDevice => "block",
            FileType::CharDevice => "char",
            FileType::Fifo => "fifo",
            FileType::Socket => "socket",
        }
    }
}

/// Entry from a DIFF query.
#[derive(Debug, Clone)]
pub struct DiffEntry {
    /// File path.
    pub path: String,
    /// Type of change.
    pub change_type: ChangeType,
    /// Old size (if existed before).
    pub old_size: Option<u64>,
    /// New size (if exists after).
    pub new_size: Option<u64>,
    /// Old checksum.
    pub old_checksum: Option<[u64; 4]>,
    /// New checksum.
    pub new_checksum: Option<[u64; 4]>,
    /// Old modification time.
    pub old_mtime: Option<u64>,
    /// New modification time.
    pub new_mtime: Option<u64>,
    /// TXG of the change.
    pub txg: u64,
}

/// File version entry.
#[derive(Debug, Clone)]
pub struct FileVersion {
    /// Transaction group.
    pub txg: u64,
    /// Timestamp when this version was created.
    pub timestamp: u64,
    /// Snapshot name if this version is in a snapshot.
    pub snapshot_name: Option<String>,
    /// File size at this version.
    pub size: u64,
    /// Checksum at this version.
    pub checksum: [u64; 4],
    /// Type of change that created this version.
    pub change_type: ChangeType,
}

/// Snapshot information.
#[derive(Debug, Clone)]
pub struct SnapshotInfo {
    /// Snapshot name.
    pub name: String,
    /// Creation timestamp.
    pub creation_time: u64,
    /// Transaction group.
    pub txg: u64,
    /// Referenced bytes.
    pub referenced: u64,
    /// Used bytes (exclusive to this snapshot).
    pub used: u64,
}

/// Aggregate query result.
#[derive(Debug, Clone)]
pub struct AggregateResult {
    /// COUNT result.
    pub count: Option<u64>,
    /// SUM result.
    pub sum: Option<u64>,
    /// AVG result.
    pub avg: Option<f64>,
    /// MIN result.
    pub min: Option<u64>,
    /// MAX result.
    pub max: Option<u64>,
}

// ═══════════════════════════════════════════════════════════════════════════════
// ERRORS
// ═══════════════════════════════════════════════════════════════════════════════

/// Errors from time-travel operations.
#[derive(Debug, Clone)]
pub enum TimeError {
    /// Query parse error.
    ParseError(String),
    /// Invalid time specification.
    InvalidTimeSpec(String),
    /// Snapshot not found.
    SnapshotNotFound(String),
    /// Path not found.
    PathNotFound(String),
    /// TXG not found or out of range.
    TxgNotFound(u64),
    /// No historical data available.
    NoHistory,
    /// Dataset not found.
    DatasetNotFound(String),
    /// Permission denied.
    PermissionDenied,
    /// IO error.
    IoError(String),
    /// Feature not supported.
    NotSupported(String),
}

impl core::fmt::Display for TimeError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            TimeError::ParseError(msg) => write!(f, "parse error: {}", msg),
            TimeError::InvalidTimeSpec(msg) => write!(f, "invalid time specification: {}", msg),
            TimeError::SnapshotNotFound(name) => write!(f, "snapshot not found: {}", name),
            TimeError::PathNotFound(path) => write!(f, "path not found: {}", path),
            TimeError::TxgNotFound(txg) => write!(f, "TXG {} not found", txg),
            TimeError::NoHistory => write!(f, "no historical data available"),
            TimeError::DatasetNotFound(name) => write!(f, "dataset not found: {}", name),
            TimeError::PermissionDenied => write!(f, "permission denied"),
            TimeError::IoError(msg) => write!(f, "IO error: {}", msg),
            TimeError::NotSupported(msg) => write!(f, "not supported: {}", msg),
        }
    }
}

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

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

    #[test]
    fn test_time_spec_variants() {
        let ts = TimeSpec::Timestamp(1704067200);
        assert!(!ts.is_relative());
        assert!(!ts.is_snapshot());

        let rel = TimeSpec::Relative("1 hour ago".into());
        assert!(rel.is_relative());

        let snap = TimeSpec::Snapshot("daily-backup".into());
        assert!(snap.is_snapshot());
    }

    #[test]
    fn test_change_type_from_str() {
        assert_eq!(ChangeType::from_str("created"), Some(ChangeType::Created));
        assert_eq!(ChangeType::from_str("MODIFIED"), Some(ChangeType::Modified));
        assert_eq!(ChangeType::from_str("deleted"), Some(ChangeType::Deleted));
        assert_eq!(ChangeType::from_str("invalid"), None);
    }

    #[test]
    fn test_filter_combinators() {
        let f1 = Filter::Eq {
            column: "size".into(),
            value: Value::Unsigned(100),
        };
        let f2 = Filter::Eq {
            column: "type".into(),
            value: Value::String("file".into()),
        };

        let combined = f1.clone().and(f2.clone());
        assert!(matches!(combined, Filter::And(_, _)));

        let either = f1.clone().or(f2);
        assert!(matches!(either, Filter::Or(_, _)));

        let negated = f1.not();
        assert!(matches!(negated, Filter::Not(_)));
    }

    #[test]
    fn test_value_conversions() {
        let s = Value::String("test".into());
        assert_eq!(s.as_str(), Some("test"));
        assert_eq!(s.as_i64(), None);

        let n = Value::Integer(42);
        assert_eq!(n.as_i64(), Some(42));
        assert_eq!(n.as_u64(), Some(42));

        let u = Value::Unsigned(100);
        assert_eq!(u.as_u64(), Some(100));
    }

    #[test]
    fn test_query_result_len() {
        let empty = QueryResult::Empty;
        assert!(empty.is_empty());

        let rows = QueryResult::Rows(vec![QueryRow {
            path: "/test".into(),
            object_id: 1,
            size: 100,
            mtime: 0,
            ctime: 0,
            atime: 0,
            mode: 0o644,
            uid: 0,
            gid: 0,
            txg: 1,
            file_type: FileType::Regular,
            checksum: [0; 4],
        }]);
        assert_eq!(rows.len(), 1);
    }
}