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

//! TimeSpec resolution to transaction group numbers.
//!
//! This module handles converting various time specifications (timestamps, datetime strings,
//! relative expressions, snapshot names) to concrete transaction group (TXG) numbers that
//! can be used to query historical filesystem state.

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

use super::types::{SnapshotInfo, TimeError, TimeSpec};

// ═══════════════════════════════════════════════════════════════════════════════
// CONSTANTS
// ═══════════════════════════════════════════════════════════════════════════════

/// Seconds per minute.
const SECS_PER_MINUTE: u64 = 60;
/// Seconds per hour.
const SECS_PER_HOUR: u64 = 3600;
/// Seconds per day.
const SECS_PER_DAY: u64 = 86400;
/// Seconds per week.
const SECS_PER_WEEK: u64 = 604800;

// ═══════════════════════════════════════════════════════════════════════════════
// TXG HISTORY
// ═══════════════════════════════════════════════════════════════════════════════

/// A record mapping a TXG to its creation timestamp.
#[derive(Debug, Clone, Copy)]
pub struct TxgTimestamp {
    /// Transaction group number.
    pub txg: u64,
    /// Unix timestamp when this TXG was synced.
    pub timestamp: u64,
}

/// History provider trait for TXG lookups.
///
/// This trait must be implemented by the filesystem to provide TXG history.
pub trait TxgHistoryProvider {
    /// Get the current TXG.
    fn current_txg(&self) -> u64;

    /// Get the current timestamp.
    fn current_timestamp(&self) -> u64;

    /// Get the minimum (oldest) available TXG.
    fn min_txg(&self) -> u64;

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

    /// Find the TXG that was active at a given timestamp.
    /// Returns the most recent TXG with timestamp <= target.
    fn timestamp_to_txg(&self, timestamp: u64) -> Option<u64>;

    /// Get TXG history entries for binary search.
    fn txg_history(&self) -> Vec<TxgTimestamp>;

    /// Look up a snapshot by name.
    fn lookup_snapshot(&self, name: &str) -> Option<SnapshotInfo>;

    /// List all snapshots.
    fn list_snapshots(&self) -> Vec<SnapshotInfo>;
}

// ═══════════════════════════════════════════════════════════════════════════════
// TIMESPEC RESOLVER
// ═══════════════════════════════════════════════════════════════════════════════

/// Resolver for converting TimeSpec to TXG numbers.
pub struct TimeSpecResolver<'a, P: TxgHistoryProvider> {
    provider: &'a P,
}

impl<'a, P: TxgHistoryProvider> TimeSpecResolver<'a, P> {
    /// Create a new resolver with the given history provider.
    pub fn new(provider: &'a P) -> Self {
        Self { provider }
    }

    /// Resolve a TimeSpec to a TXG number.
    pub fn resolve(&self, spec: &TimeSpec) -> Result<u64, TimeError> {
        match spec {
            TimeSpec::Txg(txg) => {
                // Validate TXG is in range
                if *txg < self.provider.min_txg() || *txg > self.provider.current_txg() {
                    return Err(TimeError::TxgNotFound(*txg));
                }
                Ok(*txg)
            }

            TimeSpec::Now => Ok(self.provider.current_txg()),

            TimeSpec::Timestamp(ts) => self.resolve_timestamp(*ts),

            TimeSpec::DateTime(s) => {
                let ts = parse_datetime(s)?;
                self.resolve_timestamp(ts)
            }

            TimeSpec::Relative(s) => {
                let offset = parse_relative_time(s)?;
                let now = self.provider.current_timestamp();
                let target = now.saturating_sub(offset);
                self.resolve_timestamp(target)
            }

            TimeSpec::Snapshot(name) => {
                let snap = self
                    .provider
                    .lookup_snapshot(name)
                    .ok_or_else(|| TimeError::SnapshotNotFound(name.clone()))?;
                Ok(snap.txg)
            }
        }
    }

    /// Resolve a timestamp to TXG using binary search.
    fn resolve_timestamp(&self, timestamp: u64) -> Result<u64, TimeError> {
        let history = self.provider.txg_history();

        if history.is_empty() {
            return Err(TimeError::NoHistory);
        }

        // Binary search for the TXG with the closest timestamp <= target
        let idx = binary_search_txg(&history, timestamp);

        if idx < history.len() {
            Ok(history[idx].txg)
        } else if !history.is_empty() {
            // Return the most recent if timestamp is in the future
            Ok(history[history.len() - 1].txg)
        } else {
            Err(TimeError::NoHistory)
        }
    }

    /// Validate that a TXG exists and has data.
    pub fn validate_txg(&self, txg: u64) -> Result<(), TimeError> {
        if txg < self.provider.min_txg() {
            return Err(TimeError::TxgNotFound(txg));
        }
        if txg > self.provider.current_txg() {
            return Err(TimeError::TxgNotFound(txg));
        }
        Ok(())
    }

    /// Get the timestamp for a resolved TXG.
    pub fn txg_timestamp(&self, txg: u64) -> Option<u64> {
        self.provider.txg_to_timestamp(txg)
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// BINARY SEARCH
// ═══════════════════════════════════════════════════════════════════════════════

/// Binary search for the TXG with timestamp <= target.
///
/// Returns the index of the last TXG whose timestamp is <= target timestamp.
fn binary_search_txg(history: &[TxgTimestamp], target: u64) -> usize {
    if history.is_empty() {
        return 0;
    }

    let mut left = 0;
    let mut right = history.len();

    while left < right {
        let mid = left + (right - left) / 2;

        if history[mid].timestamp <= target {
            left = mid + 1;
        } else {
            right = mid;
        }
    }

    // left now points to the first element > target, so left - 1 is the last <= target
    if left > 0 { left - 1 } else { 0 }
}

// ═══════════════════════════════════════════════════════════════════════════════
// DATETIME PARSING
// ═══════════════════════════════════════════════════════════════════════════════

/// Parse an ISO 8601 datetime string to Unix timestamp.
///
/// Supports formats:
/// - "2024-01-15" (date only, assumes 00:00:00 UTC)
/// - "2024-01-15 10:30:00" (date and time)
/// - "2024-01-15T10:30:00" (ISO 8601 with T separator)
/// - "2024-01-15T10:30:00Z" (with Z suffix)
fn parse_datetime(s: &str) -> Result<u64, TimeError> {
    let s = s.trim();

    // Remove trailing 'Z' if present
    let s = s.strip_suffix('Z').unwrap_or(s);
    let s = s.strip_suffix('z').unwrap_or(s);

    // Split into date and time parts
    let (date_part, time_part) = if s.contains('T') {
        let parts: Vec<&str> = s.splitn(2, 'T').collect();
        (parts[0], parts.get(1).copied())
    } else if s.contains(' ') {
        let parts: Vec<&str> = s.splitn(2, ' ').collect();
        (parts[0], parts.get(1).copied())
    } else {
        (s, None)
    };

    // Parse date: YYYY-MM-DD
    let date_parts: Vec<&str> = date_part.split('-').collect();
    if date_parts.len() != 3 {
        return Err(TimeError::InvalidTimeSpec(alloc::format!(
            "invalid date format: {}",
            s
        )));
    }

    let year: i32 = date_parts[0]
        .parse()
        .map_err(|_| TimeError::InvalidTimeSpec("invalid year".into()))?;
    let month: u32 = date_parts[1]
        .parse()
        .map_err(|_| TimeError::InvalidTimeSpec("invalid month".into()))?;
    let day: u32 = date_parts[2]
        .parse()
        .map_err(|_| TimeError::InvalidTimeSpec("invalid day".into()))?;

    // Validate ranges
    if !(1970..=2100).contains(&year) {
        return Err(TimeError::InvalidTimeSpec("year out of range".into()));
    }
    if !(1..=12).contains(&month) {
        return Err(TimeError::InvalidTimeSpec("month out of range".into()));
    }
    if !(1..=31).contains(&day) {
        return Err(TimeError::InvalidTimeSpec("day out of range".into()));
    }

    // Parse time if present: HH:MM:SS
    let (hour, minute, second) = if let Some(time) = time_part {
        let time_parts: Vec<&str> = time.split(':').collect();
        if time_parts.len() >= 2 {
            let h: u32 = time_parts[0]
                .parse()
                .map_err(|_| TimeError::InvalidTimeSpec("invalid hour".into()))?;
            let m: u32 = time_parts[1]
                .parse()
                .map_err(|_| TimeError::InvalidTimeSpec("invalid minute".into()))?;
            let s: u32 = time_parts.get(2).and_then(|s| s.parse().ok()).unwrap_or(0);

            if h > 23 || m > 59 || s > 59 {
                return Err(TimeError::InvalidTimeSpec("time out of range".into()));
            }

            (h, m, s)
        } else {
            (0, 0, 0)
        }
    } else {
        (0, 0, 0)
    };

    // Convert to Unix timestamp (simplified, assumes UTC)
    let timestamp = datetime_to_unix(year, month, day, hour, minute, second);

    Ok(timestamp)
}

/// Convert datetime components to Unix timestamp.
///
/// Simplified calculation assuming UTC. Uses the algorithm for calculating
/// days since epoch, then adds time components.
fn datetime_to_unix(year: i32, month: u32, day: u32, hour: u32, minute: u32, second: u32) -> u64 {
    // Days from epoch (1970-01-01) to the start of the given year
    let mut days = 0i64;

    // Add days for complete years
    for y in 1970..year {
        days += if is_leap_year(y) { 366 } else { 365 };
    }

    // If year is before 1970, subtract (not supported, but handle gracefully)
    if year < 1970 {
        return 0;
    }

    // Days in each month (non-leap year)
    let days_in_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

    // Add days for complete months
    for m in 1..month {
        days += days_in_month[(m - 1) as usize] as i64;
        if m == 2 && is_leap_year(year) {
            days += 1; // February in leap year
        }
    }

    // Add days in current month (day is 1-indexed)
    days += (day - 1) as i64;

    // Convert to seconds and add time
    let total_seconds =
        days * SECS_PER_DAY as i64 + hour as i64 * 3600 + minute as i64 * 60 + second as i64;

    total_seconds.max(0) as u64
}

/// Check if a year is a leap year.
fn is_leap_year(year: i32) -> bool {
    (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)
}

// ═══════════════════════════════════════════════════════════════════════════════
// RELATIVE TIME PARSING
// ═══════════════════════════════════════════════════════════════════════════════

/// Parse a relative time expression to seconds offset.
///
/// Supports:
/// - "N seconds ago", "N minutes ago", "N hours ago", "N days ago", "N weeks ago"
/// - "yesterday" (equivalent to "1 day ago")
/// - "today" (equivalent to "0 days ago")
fn parse_relative_time(s: &str) -> Result<u64, TimeError> {
    let s = s.trim().to_lowercase();

    // Handle special cases
    if s == "yesterday" {
        return Ok(SECS_PER_DAY);
    }
    if s == "today" || s == "now" {
        return Ok(0);
    }

    // Parse "N unit ago" format
    let parts: Vec<&str> = s.split_whitespace().collect();

    if parts.len() < 2 {
        return Err(TimeError::InvalidTimeSpec(alloc::format!(
            "invalid relative time: {}",
            s
        )));
    }

    // Check for "ago" suffix
    let has_ago = parts.last().is_some_and(|p| *p == "ago");
    let unit_idx = if has_ago && parts.len() >= 3 {
        parts.len() - 2
    } else {
        parts.len() - 1
    };

    // Parse number
    let number: u64 = parts[0]
        .parse()
        .map_err(|_| TimeError::InvalidTimeSpec(alloc::format!("invalid number: {}", parts[0])))?;

    // Parse unit
    let unit = if unit_idx < parts.len() {
        parts[unit_idx]
    } else {
        return Err(TimeError::InvalidTimeSpec("missing time unit".into()));
    };

    let multiplier = match unit {
        "second" | "seconds" | "sec" | "secs" | "s" => 1,
        "minute" | "minutes" | "min" | "mins" | "m" => SECS_PER_MINUTE,
        "hour" | "hours" | "hr" | "hrs" | "h" => SECS_PER_HOUR,
        "day" | "days" | "d" => SECS_PER_DAY,
        "week" | "weeks" | "w" => SECS_PER_WEEK,
        _ => {
            return Err(TimeError::InvalidTimeSpec(alloc::format!(
                "unknown time unit: {}",
                unit
            )));
        }
    };

    Ok(number * multiplier)
}

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

/// Simple in-memory implementation of TxgHistoryProvider for testing.
#[derive(Debug, Default)]
pub struct InMemoryTxgHistory {
    /// TXG history entries (must be sorted by txg).
    pub entries: Vec<TxgTimestamp>,
    /// Snapshot registry.
    pub snapshots: Vec<SnapshotInfo>,
    /// Current TXG.
    pub current_txg: u64,
    /// Current timestamp.
    pub current_timestamp: u64,
    /// Minimum available TXG.
    pub min_txg: u64,
}

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

    /// Add a TXG entry.
    pub fn add_txg(&mut self, txg: u64, timestamp: u64) {
        self.entries.push(TxgTimestamp { txg, timestamp });
        // Keep sorted
        self.entries.sort_by_key(|e| e.txg);
        if txg > self.current_txg {
            self.current_txg = txg;
            self.current_timestamp = timestamp;
        }
    }

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

impl TxgHistoryProvider for InMemoryTxgHistory {
    fn current_txg(&self) -> u64 {
        self.current_txg
    }

    fn current_timestamp(&self) -> u64 {
        self.current_timestamp
    }

    fn min_txg(&self) -> u64 {
        self.min_txg
    }

    fn txg_to_timestamp(&self, txg: u64) -> Option<u64> {
        self.entries
            .iter()
            .find(|e| e.txg == txg)
            .map(|e| e.timestamp)
    }

    fn timestamp_to_txg(&self, timestamp: u64) -> Option<u64> {
        let idx = binary_search_txg(&self.entries, timestamp);
        if idx < self.entries.len() {
            Some(self.entries[idx].txg)
        } else {
            None
        }
    }

    fn txg_history(&self) -> Vec<TxgTimestamp> {
        self.entries.clone()
    }

    fn lookup_snapshot(&self, name: &str) -> Option<SnapshotInfo> {
        self.snapshots.iter().find(|s| s.name == name).cloned()
    }

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

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

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

    fn create_test_history() -> InMemoryTxgHistory {
        let mut history = InMemoryTxgHistory::new();

        // Add some TXG entries spanning time
        // 2024-01-01 00:00:00 = 1704067200
        history.add_txg(100, 1704067200);
        // 2024-01-15 00:00:00 = 1705276800
        history.add_txg(200, 1705276800);
        // 2024-02-01 00:00:00 = 1706745600
        history.add_txg(300, 1706745600);
        // 2024-03-01 00:00:00 = 1709251200
        history.add_txg(400, 1709251200);
        // 2024-06-01 00:00:00 = 1717200000
        history.add_txg(500, 1717200000);

        history.min_txg = 100;

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

        history
    }

    #[test]
    fn test_resolve_txg() {
        let history = create_test_history();
        let resolver = TimeSpecResolver::new(&history);

        let spec = TimeSpec::Txg(300);
        assert_eq!(resolver.resolve(&spec).unwrap(), 300);
    }

    #[test]
    fn test_resolve_now() {
        let history = create_test_history();
        let resolver = TimeSpecResolver::new(&history);

        let spec = TimeSpec::Now;
        assert_eq!(resolver.resolve(&spec).unwrap(), 500);
    }

    #[test]
    fn test_resolve_timestamp() {
        let history = create_test_history();
        let resolver = TimeSpecResolver::new(&history);

        // Timestamp exactly matching TXG 200
        let spec = TimeSpec::Timestamp(1705276800);
        assert_eq!(resolver.resolve(&spec).unwrap(), 200);

        // Timestamp between TXG 200 and 300
        let spec = TimeSpec::Timestamp(1706000000);
        assert_eq!(resolver.resolve(&spec).unwrap(), 200);
    }

    #[test]
    fn test_resolve_snapshot() {
        let history = create_test_history();
        let resolver = TimeSpecResolver::new(&history);

        let spec = TimeSpec::Snapshot("daily-backup".into());
        assert_eq!(resolver.resolve(&spec).unwrap(), 200);
    }

    #[test]
    fn test_resolve_snapshot_not_found() {
        let history = create_test_history();
        let resolver = TimeSpecResolver::new(&history);

        let spec = TimeSpec::Snapshot("nonexistent".into());
        assert!(matches!(
            resolver.resolve(&spec),
            Err(TimeError::SnapshotNotFound(_))
        ));
    }

    #[test]
    fn test_parse_datetime_date_only() {
        // 2024-01-15 00:00:00 UTC
        let ts = parse_datetime("2024-01-15").unwrap();
        assert_eq!(ts, 1705276800);
    }

    #[test]
    fn test_parse_datetime_with_time() {
        // 2024-01-15 12:30:45 UTC
        let ts = parse_datetime("2024-01-15 12:30:45").unwrap();
        assert_eq!(ts, 1705276800 + 12 * 3600 + 30 * 60 + 45);
    }

    #[test]
    fn test_parse_datetime_iso8601() {
        let ts = parse_datetime("2024-01-15T12:30:45Z").unwrap();
        assert_eq!(ts, 1705276800 + 12 * 3600 + 30 * 60 + 45);
    }

    #[test]
    fn test_parse_relative_hours_ago() {
        let offset = parse_relative_time("3 hours ago").unwrap();
        assert_eq!(offset, 3 * SECS_PER_HOUR);
    }

    #[test]
    fn test_parse_relative_days_ago() {
        let offset = parse_relative_time("7 days ago").unwrap();
        assert_eq!(offset, 7 * SECS_PER_DAY);
    }

    #[test]
    fn test_parse_relative_yesterday() {
        let offset = parse_relative_time("yesterday").unwrap();
        assert_eq!(offset, SECS_PER_DAY);
    }

    #[test]
    fn test_parse_relative_minutes() {
        let offset = parse_relative_time("30 minutes ago").unwrap();
        assert_eq!(offset, 30 * SECS_PER_MINUTE);
    }

    #[test]
    fn test_parse_relative_weeks() {
        let offset = parse_relative_time("2 weeks ago").unwrap();
        assert_eq!(offset, 2 * SECS_PER_WEEK);
    }

    #[test]
    fn test_binary_search_exact_match() {
        let history = vec![
            TxgTimestamp {
                txg: 100,
                timestamp: 1000,
            },
            TxgTimestamp {
                txg: 200,
                timestamp: 2000,
            },
            TxgTimestamp {
                txg: 300,
                timestamp: 3000,
            },
        ];

        assert_eq!(binary_search_txg(&history, 2000), 1);
    }

    #[test]
    fn test_binary_search_between() {
        let history = vec![
            TxgTimestamp {
                txg: 100,
                timestamp: 1000,
            },
            TxgTimestamp {
                txg: 200,
                timestamp: 2000,
            },
            TxgTimestamp {
                txg: 300,
                timestamp: 3000,
            },
        ];

        // Between 1000 and 2000, should return index 0 (last <= 1500)
        assert_eq!(binary_search_txg(&history, 1500), 0);

        // Between 2000 and 3000, should return index 1 (last <= 2500)
        assert_eq!(binary_search_txg(&history, 2500), 1);
    }

    #[test]
    fn test_binary_search_before_first() {
        let history = vec![
            TxgTimestamp {
                txg: 100,
                timestamp: 1000,
            },
            TxgTimestamp {
                txg: 200,
                timestamp: 2000,
            },
        ];

        // Before first timestamp, return first entry
        assert_eq!(binary_search_txg(&history, 500), 0);
    }

    #[test]
    fn test_binary_search_after_last() {
        let history = vec![
            TxgTimestamp {
                txg: 100,
                timestamp: 1000,
            },
            TxgTimestamp {
                txg: 200,
                timestamp: 2000,
            },
        ];

        // After last timestamp, return last entry
        assert_eq!(binary_search_txg(&history, 3000), 1);
    }

    #[test]
    fn test_resolve_datetime() {
        let history = create_test_history();
        let resolver = TimeSpecResolver::new(&history);

        let spec = TimeSpec::DateTime("2024-01-15".into());
        assert_eq!(resolver.resolve(&spec).unwrap(), 200);
    }

    #[test]
    fn test_is_leap_year() {
        assert!(is_leap_year(2000)); // Divisible by 400
        assert!(is_leap_year(2024)); // Divisible by 4, not 100
        assert!(!is_leap_year(1900)); // Divisible by 100, not 400
        assert!(!is_leap_year(2023)); // Not divisible by 4
    }

    #[test]
    fn test_datetime_to_unix_epoch() {
        // 1970-01-01 00:00:00 should be 0
        assert_eq!(datetime_to_unix(1970, 1, 1, 0, 0, 0), 0);
    }

    #[test]
    fn test_datetime_to_unix_known_date() {
        // 2024-01-01 00:00:00 UTC = 1704067200
        let ts = datetime_to_unix(2024, 1, 1, 0, 0, 0);
        assert_eq!(ts, 1704067200);
    }

    #[test]
    fn test_invalid_datetime() {
        assert!(parse_datetime("not-a-date").is_err());
        assert!(parse_datetime("2024-13-01").is_err()); // Invalid month
        assert!(parse_datetime("2024-01-32").is_err()); // Invalid day
    }

    #[test]
    fn test_invalid_relative() {
        assert!(parse_relative_time("not relative").is_err());
        assert!(parse_relative_time("abc days ago").is_err());
    }

    #[test]
    fn test_txg_out_of_range() {
        let history = create_test_history();
        let resolver = TimeSpecResolver::new(&history);

        // TXG below minimum
        let spec = TimeSpec::Txg(50);
        assert!(matches!(
            resolver.resolve(&spec),
            Err(TimeError::TxgNotFound(50))
        ));

        // TXG above current
        let spec = TimeSpec::Txg(1000);
        assert!(matches!(
            resolver.resolve(&spec),
            Err(TimeError::TxgNotFound(1000))
        ));
    }
}