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

//! Data lineage types and structures.
//!
//! This module defines the core types for tracking data provenance
//! and lineage in LCPFS.

use alloc::string::{String, ToString};
use alloc::vec::Vec;
use core::fmt;

// ═══════════════════════════════════════════════════════════════════════════════
// LINEAGE NODE
// ═══════════════════════════════════════════════════════════════════════════════

/// A node in the lineage graph representing a data object version.
#[derive(Debug, Clone)]
pub struct LineageNode {
    /// Unique node ID.
    pub id: u64,
    /// Object ID (e.g., inode number).
    pub object_id: u64,
    /// Version number.
    pub version: u64,
    /// File path.
    pub path: String,
    /// Content checksum (256-bit as 4 x u64).
    pub checksum: [u64; 4],
    /// Creation timestamp (nanoseconds).
    pub created: u64,
    /// Creator identifier (username, process, etc.).
    pub creator: String,
    /// Dataset containing this object.
    pub dataset: String,
    /// Size in bytes.
    pub size: u64,
    /// Optional metadata.
    pub metadata: Option<String>,
}

impl LineageNode {
    /// Create a new lineage node.
    pub fn new(
        id: u64,
        object_id: u64,
        version: u64,
        path: &str,
        checksum: [u64; 4],
        created: u64,
        creator: &str,
        dataset: &str,
    ) -> Self {
        Self {
            id,
            object_id,
            version,
            path: path.to_string(),
            checksum,
            created,
            creator: creator.to_string(),
            dataset: dataset.to_string(),
            size: 0,
            metadata: None,
        }
    }

    /// Set the size.
    pub fn with_size(mut self, size: u64) -> Self {
        self.size = size;
        self
    }

    /// Set metadata.
    pub fn with_metadata(mut self, metadata: &str) -> Self {
        self.metadata = Some(metadata.to_string());
        self
    }

    /// Get checksum as hex string.
    pub fn checksum_hex(&self) -> String {
        alloc::format!(
            "{:016x}{:016x}{:016x}{:016x}",
            self.checksum[0],
            self.checksum[1],
            self.checksum[2],
            self.checksum[3]
        )
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// LINEAGE RELATION
// ═══════════════════════════════════════════════════════════════════════════════

/// Type of relationship between lineage nodes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum LineageRelation {
    /// Direct copy of source.
    Copy = 1,
    /// Derived from source (transformation applied).
    Derived = 2,
    /// Merged from multiple sources.
    Merged = 3,
    /// Imported from external source.
    Import = 4,
    /// Updated version of source.
    Updated = 5,
    /// Snapshot of source.
    Snapshot = 6,
    /// Clone of source.
    Clone = 7,
    /// Renamed from source.
    Renamed = 8,
}

impl LineageRelation {
    /// Convert from u8.
    pub fn from_u8(val: u8) -> Option<Self> {
        match val {
            1 => Some(Self::Copy),
            2 => Some(Self::Derived),
            3 => Some(Self::Merged),
            4 => Some(Self::Import),
            5 => Some(Self::Updated),
            6 => Some(Self::Snapshot),
            7 => Some(Self::Clone),
            8 => Some(Self::Renamed),
            _ => None,
        }
    }

    /// Get relation name.
    pub fn name(&self) -> &'static str {
        match self {
            Self::Copy => "copy",
            Self::Derived => "derived",
            Self::Merged => "merged",
            Self::Import => "import",
            Self::Updated => "updated",
            Self::Snapshot => "snapshot",
            Self::Clone => "clone",
            Self::Renamed => "renamed",
        }
    }
}

impl fmt::Display for LineageRelation {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.name())
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// LINEAGE EDGE
// ═══════════════════════════════════════════════════════════════════════════════

/// An edge in the lineage graph connecting two nodes.
#[derive(Debug, Clone)]
pub struct LineageEdge {
    /// Source node ID.
    pub source: u64,
    /// Target node ID.
    pub target: u64,
    /// Type of relationship.
    pub relation: LineageRelation,
    /// Optional transformation description.
    pub transform: Option<String>,
    /// Timestamp of the edge creation.
    pub timestamp: u64,
    /// Weight/importance (for analysis).
    pub weight: f32,
}

impl LineageEdge {
    /// Create a new lineage edge.
    pub fn new(source: u64, target: u64, relation: LineageRelation) -> Self {
        Self {
            source,
            target,
            relation,
            transform: None,
            timestamp: 0,
            weight: 1.0,
        }
    }

    /// Set the transformation description.
    pub fn with_transform(mut self, transform: &str) -> Self {
        self.transform = Some(transform.to_string());
        self
    }

    /// Set the timestamp.
    pub fn with_timestamp(mut self, timestamp: u64) -> Self {
        self.timestamp = timestamp;
        self
    }

    /// Set the weight.
    pub fn with_weight(mut self, weight: f32) -> Self {
        self.weight = weight;
        self
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// LINEAGE GRAPH
// ═══════════════════════════════════════════════════════════════════════════════

/// A subgraph of lineage (for query results).
#[derive(Debug, Clone, Default)]
pub struct LineageGraph {
    /// Nodes in the subgraph.
    pub nodes: Vec<LineageNode>,
    /// Edges in the subgraph.
    pub edges: Vec<LineageEdge>,
    /// Root node ID (if applicable).
    pub root: Option<u64>,
    /// Maximum depth from root.
    pub max_depth: usize,
}

impl LineageGraph {
    /// Create an empty graph.
    pub fn new() -> Self {
        Self::default()
    }

    /// Create a graph with a root.
    pub fn with_root(root: u64) -> Self {
        Self {
            root: Some(root),
            ..Default::default()
        }
    }

    /// Add a node.
    pub fn add_node(&mut self, node: LineageNode) {
        self.nodes.push(node);
    }

    /// Add an edge.
    pub fn add_edge(&mut self, edge: LineageEdge) {
        self.edges.push(edge);
    }

    /// Get node count.
    pub fn node_count(&self) -> usize {
        self.nodes.len()
    }

    /// Get edge count.
    pub fn edge_count(&self) -> usize {
        self.edges.len()
    }

    /// Find a node by ID.
    pub fn find_node(&self, id: u64) -> Option<&LineageNode> {
        self.nodes.iter().find(|n| n.id == id)
    }

    /// Get edges from a node.
    pub fn edges_from(&self, node_id: u64) -> Vec<&LineageEdge> {
        self.edges.iter().filter(|e| e.source == node_id).collect()
    }

    /// Get edges to a node.
    pub fn edges_to(&self, node_id: u64) -> Vec<&LineageEdge> {
        self.edges.iter().filter(|e| e.target == node_id).collect()
    }

    /// Export to DOT format for GraphViz visualization.
    pub fn to_dot(&self) -> String {
        let mut dot = String::from("digraph lineage {\n");
        dot.push_str("    rankdir=TB;\n");
        dot.push_str("    node [shape=box];\n\n");

        // Add nodes
        for node in &self.nodes {
            let label = alloc::format!(
                "{}\\nv{}\\n{}",
                node.path.split('/').next_back().unwrap_or(&node.path),
                node.version,
                &node.checksum_hex()[..8]
            );
            dot.push_str(&alloc::format!("    n{} [label=\"{}\"];\n", node.id, label));
        }

        dot.push('\n');

        // Add edges
        for edge in &self.edges {
            let style = match edge.relation {
                LineageRelation::Copy => "style=dashed",
                LineageRelation::Merged => "style=bold",
                LineageRelation::Import => "style=dotted",
                _ => "",
            };
            let label = match &edge.transform {
                Some(t) => alloc::format!("label=\"{}\"", t),
                None => alloc::format!("label=\"{}\"", edge.relation),
            };
            dot.push_str(&alloc::format!(
                "    n{} -> n{} [{}{}];\n",
                edge.source,
                edge.target,
                label,
                if style.is_empty() {
                    String::new()
                } else {
                    alloc::format!(",{}", style)
                }
            ));
        }

        dot.push_str("}\n");
        dot
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// LINEAGE QUERY
// ═══════════════════════════════════════════════════════════════════════════════

/// Query for searching lineage nodes.
#[derive(Debug, Clone, Default)]
pub struct LineageQuery {
    /// Filter by dataset.
    pub dataset: Option<String>,
    /// Filter by path pattern (glob).
    pub path_pattern: Option<String>,
    /// Filter by creator.
    pub creator: Option<String>,
    /// Filter by minimum creation time.
    pub created_after: Option<u64>,
    /// Filter by maximum creation time.
    pub created_before: Option<u64>,
    /// Filter by checksum.
    pub checksum: Option<[u64; 4]>,
    /// Maximum number of results.
    pub limit: Option<usize>,
    /// Offset for pagination.
    pub offset: Option<usize>,
}

impl LineageQuery {
    /// Create a new empty query.
    pub fn new() -> Self {
        Self::default()
    }

    /// Filter by dataset.
    pub fn dataset(mut self, dataset: &str) -> Self {
        self.dataset = Some(dataset.to_string());
        self
    }

    /// Filter by path pattern.
    pub fn path(mut self, pattern: &str) -> Self {
        self.path_pattern = Some(pattern.to_string());
        self
    }

    /// Filter by creator.
    pub fn creator(mut self, creator: &str) -> Self {
        self.creator = Some(creator.to_string());
        self
    }

    /// Filter by creation time range.
    pub fn created_between(mut self, after: u64, before: u64) -> Self {
        self.created_after = Some(after);
        self.created_before = Some(before);
        self
    }

    /// Limit results.
    pub fn limit(mut self, limit: usize) -> Self {
        self.limit = Some(limit);
        self
    }

    /// Offset results.
    pub fn offset(mut self, offset: usize) -> Self {
        self.offset = Some(offset);
        self
    }

    /// Check if a node matches this query.
    pub fn matches(&self, node: &LineageNode) -> bool {
        if let Some(ref ds) = self.dataset {
            if &node.dataset != ds {
                return false;
            }
        }

        if let Some(ref pattern) = self.path_pattern {
            if !path_matches(pattern, &node.path) {
                return false;
            }
        }

        if let Some(ref creator) = self.creator {
            if &node.creator != creator {
                return false;
            }
        }

        if let Some(after) = self.created_after {
            if node.created < after {
                return false;
            }
        }

        if let Some(before) = self.created_before {
            if node.created > before {
                return false;
            }
        }

        if let Some(checksum) = self.checksum {
            if node.checksum != checksum {
                return false;
            }
        }

        true
    }
}

/// Simple path pattern matching (supports * and ?).
fn path_matches(pattern: &str, path: &str) -> bool {
    if pattern.is_empty() {
        return path.is_empty();
    }
    if pattern == "*" {
        return true;
    }

    // Simple implementation: just check contains for now
    if pattern.starts_with('*') && pattern.ends_with('*') {
        let inner = pattern
            .strip_prefix('*')
            .and_then(|s| s.strip_suffix('*'))
            .unwrap_or("");
        return path.contains(inner);
    }

    if let Some(suffix) = pattern.strip_prefix('*') {
        return path.ends_with(suffix);
    }

    if let Some(prefix) = pattern.strip_suffix('*') {
        return path.starts_with(prefix);
    }

    path == pattern
}

// ═══════════════════════════════════════════════════════════════════════════════
// ERROR TYPES
// ═══════════════════════════════════════════════════════════════════════════════

/// Lineage error.
#[derive(Debug, Clone)]
pub enum LineageError {
    /// Node not found.
    NodeNotFound(u64),
    /// Edge already exists.
    EdgeExists {
        /// Source node.
        source: u64,
        /// Target node.
        target: u64,
    },
    /// Cycle detected.
    CycleDetected {
        /// Nodes in the cycle.
        path: Vec<u64>,
    },
    /// Invalid relation.
    InvalidRelation(String),
    /// Storage error.
    StorageError(String),
}

impl fmt::Display for LineageError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::NodeNotFound(id) => write!(f, "node not found: {}", id),
            Self::EdgeExists { source, target } => {
                write!(f, "edge already exists: {} -> {}", source, target)
            }
            Self::CycleDetected { path } => {
                write!(f, "cycle detected: {:?}", path)
            }
            Self::InvalidRelation(msg) => write!(f, "invalid relation: {}", msg),
            Self::StorageError(msg) => write!(f, "storage error: {}", msg),
        }
    }
}

/// Lineage result type.
pub type LineageResult<T> = Result<T, LineageError>;

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

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

    #[test]
    fn test_lineage_node() {
        let node = LineageNode::new(
            1,
            100,
            1,
            "/data/file.txt",
            [0x1234, 0x5678, 0x9abc, 0xdef0],
            1000,
            "user1",
            "pool/data",
        );

        assert_eq!(node.id, 1);
        assert_eq!(node.object_id, 100);
        assert_eq!(node.path, "/data/file.txt");
        assert!(node.checksum_hex().contains("1234"));
    }

    #[test]
    fn test_lineage_relation() {
        assert_eq!(LineageRelation::Copy.name(), "copy");
        assert_eq!(LineageRelation::from_u8(1), Some(LineageRelation::Copy));
        assert_eq!(LineageRelation::from_u8(99), None);
    }

    #[test]
    fn test_lineage_edge() {
        let edge = LineageEdge::new(1, 2, LineageRelation::Derived)
            .with_transform("gzip")
            .with_timestamp(1000);

        assert_eq!(edge.source, 1);
        assert_eq!(edge.target, 2);
        assert_eq!(edge.transform, Some("gzip".into()));
    }

    #[test]
    fn test_lineage_graph() {
        let mut graph = LineageGraph::with_root(1);

        graph.add_node(LineageNode::new(1, 1, 1, "/a", [0; 4], 0, "user", "ds"));
        graph.add_node(LineageNode::new(2, 2, 1, "/b", [0; 4], 0, "user", "ds"));
        graph.add_edge(LineageEdge::new(1, 2, LineageRelation::Copy));

        assert_eq!(graph.node_count(), 2);
        assert_eq!(graph.edge_count(), 1);
        assert!(graph.find_node(1).is_some());
        assert_eq!(graph.edges_from(1).len(), 1);
        assert_eq!(graph.edges_to(2).len(), 1);
    }

    #[test]
    fn test_to_dot() {
        let mut graph = LineageGraph::new();
        graph.add_node(LineageNode::new(1, 1, 1, "/a.txt", [0; 4], 0, "user", "ds"));
        graph.add_node(LineageNode::new(2, 2, 1, "/b.txt", [0; 4], 0, "user", "ds"));
        graph.add_edge(LineageEdge::new(1, 2, LineageRelation::Copy));

        let dot = graph.to_dot();
        assert!(dot.contains("digraph"));
        assert!(dot.contains("n1"));
        assert!(dot.contains("n2"));
        assert!(dot.contains("->"));
    }

    #[test]
    fn test_lineage_query() {
        let query = LineageQuery::new()
            .dataset("pool/data")
            .creator("user1")
            .limit(10);

        let node = LineageNode::new(1, 1, 1, "/file.txt", [0; 4], 1000, "user1", "pool/data");
        assert!(query.matches(&node));

        let other = LineageNode::new(2, 2, 1, "/file.txt", [0; 4], 1000, "user2", "pool/data");
        assert!(!query.matches(&other));
    }

    #[test]
    fn test_path_matches() {
        assert!(path_matches("*.txt", "/file.txt"));
        assert!(path_matches("/data/*", "/data/file"));
        assert!(path_matches("*file*", "/path/to/file.txt"));
        assert!(path_matches("*", "/anything"));
        assert!(!path_matches("*.txt", "/file.csv"));
    }

    #[test]
    fn test_error_display() {
        let err = LineageError::NodeNotFound(123);
        assert!(err.to_string().contains("123"));
    }
}