Skip to main content

rustledger_loader/
cache.rs

1//! Binary cache for parsed ledgers.
2//!
3//! This module provides a caching layer that can dramatically speed up
4//! subsequent loads of unchanged beancount files by serializing the parsed
5//! directives to a binary format using rkyv.
6//!
7//! # How it works
8//!
9//! 1. When loading a file, compute a hash of all source files
10//! 2. Check if a cache file exists with a matching hash
11//! 3. If yes, deserialize and return immediately (typically <1ms)
12//! 4. If no, parse normally, serialize to cache, and return
13//!
14//! # Cache location
15//!
16//! Cache files are stored alongside the main ledger file with a `.cache` extension.
17//! For example, `ledger.beancount` would have cache at `ledger.beancount.cache`.
18
19use crate::Options;
20use rust_decimal::Decimal;
21use rustledger_core::Directive;
22use rustledger_core::intern::StringInterner;
23use rustledger_parser::Spanned;
24use sha2::{Digest, Sha256};
25use std::fs;
26use std::io::{Read, Write};
27use std::path::{Path, PathBuf};
28use std::str::FromStr;
29
30/// Cached plugin information.
31#[derive(Debug, Clone, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)]
32pub struct CachedPlugin {
33    /// Plugin module name.
34    pub name: String,
35    /// Optional configuration string.
36    pub config: Option<String>,
37    /// Whether the `python:` prefix was used to force Python execution.
38    pub force_python: bool,
39}
40
41/// Cached options - a serializable subset of Options.
42///
43/// Excludes parsing-time fields like `set_options` and `warnings`.
44/// These fields mirror the Options struct and inherit their meaning.
45#[derive(Debug, Clone, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)]
46#[allow(missing_docs)]
47pub struct CachedOptions {
48    pub title: Option<String>,
49    pub filename: Option<String>,
50    pub operating_currency: Vec<String>,
51    pub name_assets: String,
52    pub name_liabilities: String,
53    pub name_equity: String,
54    pub name_income: String,
55    pub name_expenses: String,
56    pub account_rounding: Option<String>,
57    pub account_previous_balances: String,
58    pub account_previous_earnings: String,
59    pub account_previous_conversions: String,
60    pub account_current_earnings: String,
61    pub account_current_conversions: Option<String>,
62    pub account_unrealized_gains: Option<String>,
63    pub conversion_currency: Option<String>,
64    /// Stored as (currency, `tolerance_string`) pairs since Decimal needs special handling
65    pub inferred_tolerance_default: Vec<(String, String)>,
66    pub inferred_tolerance_multiplier: String,
67    pub infer_tolerance_from_cost: bool,
68    pub use_legacy_fixed_tolerances: bool,
69    pub experiment_explicit_tolerances: bool,
70    pub booking_method: String,
71    pub render_commas: bool,
72    pub allow_pipe_separator: bool,
73    pub long_string_maxlines: u32,
74    pub documents: Vec<String>,
75    pub custom: Vec<(String, String)>,
76}
77
78impl From<&Options> for CachedOptions {
79    fn from(opts: &Options) -> Self {
80        Self {
81            title: opts.title.clone(),
82            filename: opts.filename.clone(),
83            operating_currency: opts.operating_currency.clone(),
84            name_assets: opts.name_assets.clone(),
85            name_liabilities: opts.name_liabilities.clone(),
86            name_equity: opts.name_equity.clone(),
87            name_income: opts.name_income.clone(),
88            name_expenses: opts.name_expenses.clone(),
89            account_rounding: opts.account_rounding.clone(),
90            account_previous_balances: opts.account_previous_balances.clone(),
91            account_previous_earnings: opts.account_previous_earnings.clone(),
92            account_previous_conversions: opts.account_previous_conversions.clone(),
93            account_current_earnings: opts.account_current_earnings.clone(),
94            account_current_conversions: opts.account_current_conversions.clone(),
95            account_unrealized_gains: opts.account_unrealized_gains.clone(),
96            conversion_currency: opts.conversion_currency.clone(),
97            inferred_tolerance_default: opts
98                .inferred_tolerance_default
99                .iter()
100                .map(|(k, v)| (k.clone(), v.to_string()))
101                .collect(),
102            inferred_tolerance_multiplier: opts.inferred_tolerance_multiplier.to_string(),
103            infer_tolerance_from_cost: opts.infer_tolerance_from_cost,
104            use_legacy_fixed_tolerances: opts.use_legacy_fixed_tolerances,
105            experiment_explicit_tolerances: opts.experiment_explicit_tolerances,
106            booking_method: opts.booking_method.clone(),
107            render_commas: opts.render_commas,
108            allow_pipe_separator: opts.allow_pipe_separator,
109            long_string_maxlines: opts.long_string_maxlines,
110            documents: opts.documents.clone(),
111            custom: opts
112                .custom
113                .iter()
114                .map(|(k, v)| (k.clone(), v.clone()))
115                .collect(),
116        }
117    }
118}
119
120impl From<CachedOptions> for Options {
121    fn from(cached: CachedOptions) -> Self {
122        let mut opts = Self::new();
123        opts.title = cached.title;
124        opts.filename = cached.filename;
125        opts.operating_currency = cached.operating_currency;
126        opts.name_assets = cached.name_assets;
127        opts.name_liabilities = cached.name_liabilities;
128        opts.name_equity = cached.name_equity;
129        opts.name_income = cached.name_income;
130        opts.name_expenses = cached.name_expenses;
131        opts.account_rounding = cached.account_rounding;
132        opts.account_previous_balances = cached.account_previous_balances;
133        opts.account_previous_earnings = cached.account_previous_earnings;
134        opts.account_previous_conversions = cached.account_previous_conversions;
135        opts.account_current_earnings = cached.account_current_earnings;
136        opts.account_current_conversions = cached.account_current_conversions;
137        opts.account_unrealized_gains = cached.account_unrealized_gains;
138        opts.conversion_currency = cached.conversion_currency;
139        opts.inferred_tolerance_default = cached
140            .inferred_tolerance_default
141            .into_iter()
142            .filter_map(|(k, v)| Decimal::from_str(&v).ok().map(|d| (k, d)))
143            .collect();
144        opts.inferred_tolerance_multiplier =
145            Decimal::from_str(&cached.inferred_tolerance_multiplier)
146                .unwrap_or_else(|_| Decimal::new(5, 1));
147        opts.infer_tolerance_from_cost = cached.infer_tolerance_from_cost;
148        opts.use_legacy_fixed_tolerances = cached.use_legacy_fixed_tolerances;
149        opts.experiment_explicit_tolerances = cached.experiment_explicit_tolerances;
150        opts.booking_method = cached.booking_method;
151        opts.render_commas = cached.render_commas;
152        opts.allow_pipe_separator = cached.allow_pipe_separator;
153        opts.long_string_maxlines = cached.long_string_maxlines;
154        opts.documents = cached.documents;
155        opts.custom = cached.custom.into_iter().collect();
156        opts
157    }
158}
159
160/// Complete cache entry containing all data needed to restore a `LoadResult`.
161#[derive(Debug, Clone, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)]
162pub struct CacheEntry {
163    /// All parsed directives.
164    pub directives: Vec<Spanned<Directive>>,
165    /// Parsed options.
166    pub options: CachedOptions,
167    /// Plugin declarations.
168    pub plugins: Vec<CachedPlugin>,
169    /// All files that were loaded (as strings, for serialization).
170    pub files: Vec<String>,
171}
172
173impl CacheEntry {
174    /// Get files as `PathBuf` references.
175    pub fn file_paths(&self) -> Vec<PathBuf> {
176        self.files.iter().map(PathBuf::from).collect()
177    }
178}
179
180/// Magic bytes to identify cache files.
181const CACHE_MAGIC: &[u8; 8] = b"RLEDGER\0";
182
183/// Cache version - increment when format changes.
184/// v1: Initial release with string-based Decimal/NaiveDate
185/// v2: Binary Decimal (16 bytes) and `NaiveDate` (i32 days)
186/// v3: Fixed account type defaults in `CachedOptions`
187const CACHE_VERSION: u32 = 3;
188
189/// Cache header stored at the start of cache files.
190#[derive(Debug, Clone)]
191struct CacheHeader {
192    /// Magic bytes for identification.
193    magic: [u8; 8],
194    /// Cache format version.
195    version: u32,
196    /// SHA-256 hash of source files.
197    hash: [u8; 32],
198    /// Length of the serialized data.
199    data_len: u64,
200}
201
202impl CacheHeader {
203    const SIZE: usize = 8 + 4 + 32 + 8;
204
205    fn to_bytes(&self) -> [u8; Self::SIZE] {
206        let mut buf = [0u8; Self::SIZE];
207        buf[0..8].copy_from_slice(&self.magic);
208        buf[8..12].copy_from_slice(&self.version.to_le_bytes());
209        buf[12..44].copy_from_slice(&self.hash);
210        buf[44..52].copy_from_slice(&self.data_len.to_le_bytes());
211        buf
212    }
213
214    fn from_bytes(bytes: &[u8]) -> Option<Self> {
215        if bytes.len() < Self::SIZE {
216            return None;
217        }
218
219        let mut magic = [0u8; 8];
220        magic.copy_from_slice(&bytes[0..8]);
221
222        let version = u32::from_le_bytes(bytes[8..12].try_into().ok()?);
223
224        let mut hash = [0u8; 32];
225        hash.copy_from_slice(&bytes[12..44]);
226
227        let data_len = u64::from_le_bytes(bytes[44..52].try_into().ok()?);
228
229        Some(Self {
230            magic,
231            version,
232            hash,
233            data_len,
234        })
235    }
236}
237
238/// Compute a hash of the given files and their modification times.
239fn compute_hash(files: &[&Path]) -> [u8; 32] {
240    let mut hasher = Sha256::new();
241
242    for file in files {
243        // Hash the file path
244        hasher.update(file.to_string_lossy().as_bytes());
245
246        // Hash the modification time
247        if let Ok(metadata) = fs::metadata(file) {
248            if let Ok(mtime) = metadata.modified()
249                && let Ok(duration) = mtime.duration_since(std::time::UNIX_EPOCH)
250            {
251                hasher.update(duration.as_secs().to_le_bytes());
252                hasher.update(duration.subsec_nanos().to_le_bytes());
253            }
254            // Hash the file size
255            hasher.update(metadata.len().to_le_bytes());
256        }
257    }
258
259    hasher.finalize().into()
260}
261
262/// Get the cache file path for a given source file.
263fn cache_path(source: &Path) -> std::path::PathBuf {
264    let mut path = source.to_path_buf();
265    let name = path.file_name().map_or_else(
266        || "ledger.cache".to_string(),
267        |n| format!("{}.cache", n.to_string_lossy()),
268    );
269    path.set_file_name(name);
270    path
271}
272
273/// Try to load a cache entry from disk.
274///
275/// Returns `Some(CacheEntry)` if cache is valid and file hashes match,
276/// `None` if cache is missing, invalid, or outdated.
277pub fn load_cache_entry(main_file: &Path) -> Option<CacheEntry> {
278    let cache_file = cache_path(main_file);
279    let mut file = fs::File::open(&cache_file).ok()?;
280
281    // Read header
282    let mut header_bytes = [0u8; CacheHeader::SIZE];
283    file.read_exact(&mut header_bytes).ok()?;
284    let header = CacheHeader::from_bytes(&header_bytes)?;
285
286    // Validate magic and version
287    if header.magic != *CACHE_MAGIC {
288        return None;
289    }
290    if header.version != CACHE_VERSION {
291        return None;
292    }
293
294    // Read data
295    let mut data = vec![0u8; header.data_len as usize];
296    file.read_exact(&mut data).ok()?;
297
298    // Deserialize
299    let entry: CacheEntry = rkyv::from_bytes::<CacheEntry, rkyv::rancor::Error>(&data).ok()?;
300
301    // Validate hash against the files stored in the cache
302    let file_paths = entry.file_paths();
303    let file_refs: Vec<&Path> = file_paths.iter().map(PathBuf::as_path).collect();
304    let expected_hash = compute_hash(&file_refs);
305    if header.hash != expected_hash {
306        return None;
307    }
308
309    Some(entry)
310}
311
312/// Save a cache entry to disk.
313pub fn save_cache_entry(main_file: &Path, entry: &CacheEntry) -> Result<(), std::io::Error> {
314    let cache_file = cache_path(main_file);
315
316    // Compute hash from the files in the entry
317    let file_paths = entry.file_paths();
318    let file_refs: Vec<&Path> = file_paths.iter().map(PathBuf::as_path).collect();
319    let hash = compute_hash(&file_refs);
320
321    // Serialize
322    let data = rkyv::to_bytes::<rkyv::rancor::Error>(entry)
323        .map(|v| v.to_vec())
324        .map_err(|e| std::io::Error::other(e.to_string()))?;
325
326    // Write header + data
327    let header = CacheHeader {
328        magic: *CACHE_MAGIC,
329        version: CACHE_VERSION,
330        hash,
331        data_len: data.len() as u64,
332    };
333
334    let mut file = fs::File::create(&cache_file)?;
335    file.write_all(&header.to_bytes())?;
336    file.write_all(&data)?;
337
338    Ok(())
339}
340
341/// Serialize directives to bytes using rkyv (for benchmarking).
342#[cfg(test)]
343fn serialize_directives(directives: &Vec<Spanned<Directive>>) -> Result<Vec<u8>, std::io::Error> {
344    rkyv::to_bytes::<rkyv::rancor::Error>(directives)
345        .map(|v| v.to_vec())
346        .map_err(|e| std::io::Error::other(e.to_string()))
347}
348
349/// Deserialize directives from bytes using rkyv (for benchmarking).
350#[cfg(test)]
351fn deserialize_directives(data: &[u8]) -> Option<Vec<Spanned<Directive>>> {
352    rkyv::from_bytes::<Vec<Spanned<Directive>>, rkyv::rancor::Error>(data).ok()
353}
354
355/// Invalidate the cache for a file.
356pub fn invalidate_cache(main_file: &Path) {
357    let cache_file = cache_path(main_file);
358    let _ = fs::remove_file(cache_file);
359}
360
361/// Re-intern all strings in directives to deduplicate memory.
362///
363/// After deserializing from cache, strings are not interned (each is a separate
364/// allocation). This function walks through all directives and re-interns account
365/// names and currencies using a shared `StringInterner`, deduplicating identical
366/// strings to save memory.
367///
368/// Returns the number of strings that were deduplicated (i.e., strings that
369/// were found to already exist in the interner).
370pub fn reintern_directives(directives: &mut [Spanned<Directive>]) -> usize {
371    use rustledger_core::intern::InternedStr;
372    use rustledger_core::{IncompleteAmount, PriceAnnotation};
373
374    // Intern a single string (defined before use to satisfy clippy)
375    fn do_intern(s: &mut InternedStr, interner: &mut StringInterner) -> bool {
376        let already_exists = interner.contains(s.as_str());
377        *s = interner.intern(s.as_str());
378        already_exists
379    }
380
381    let mut interner = StringInterner::with_capacity(1024);
382    let mut dedup_count = 0;
383
384    for spanned in directives.iter_mut() {
385        match &mut spanned.value {
386            Directive::Transaction(txn) => {
387                for posting in &mut txn.postings {
388                    if do_intern(&mut posting.account, &mut interner) {
389                        dedup_count += 1;
390                    }
391                    // Units
392                    if let Some(ref mut units) = posting.units {
393                        match units {
394                            IncompleteAmount::Complete(amt) => {
395                                if do_intern(&mut amt.currency, &mut interner) {
396                                    dedup_count += 1;
397                                }
398                            }
399                            IncompleteAmount::CurrencyOnly(cur) => {
400                                if do_intern(cur, &mut interner) {
401                                    dedup_count += 1;
402                                }
403                            }
404                            IncompleteAmount::NumberOnly(_) => {}
405                        }
406                    }
407                    // Cost spec
408                    if let Some(ref mut cost) = posting.cost
409                        && let Some(ref mut cur) = cost.currency
410                        && do_intern(cur, &mut interner)
411                    {
412                        dedup_count += 1;
413                    }
414                    // Price annotation
415                    if let Some(ref mut price) = posting.price {
416                        match price {
417                            PriceAnnotation::Unit(amt) | PriceAnnotation::Total(amt) => {
418                                if do_intern(&mut amt.currency, &mut interner) {
419                                    dedup_count += 1;
420                                }
421                            }
422                            PriceAnnotation::UnitIncomplete(inc)
423                            | PriceAnnotation::TotalIncomplete(inc) => match inc {
424                                IncompleteAmount::Complete(amt) => {
425                                    if do_intern(&mut amt.currency, &mut interner) {
426                                        dedup_count += 1;
427                                    }
428                                }
429                                IncompleteAmount::CurrencyOnly(cur) => {
430                                    if do_intern(cur, &mut interner) {
431                                        dedup_count += 1;
432                                    }
433                                }
434                                IncompleteAmount::NumberOnly(_) => {}
435                            },
436                            PriceAnnotation::UnitEmpty | PriceAnnotation::TotalEmpty => {}
437                        }
438                    }
439                }
440            }
441            Directive::Balance(bal) => {
442                if do_intern(&mut bal.account, &mut interner) {
443                    dedup_count += 1;
444                }
445                if do_intern(&mut bal.amount.currency, &mut interner) {
446                    dedup_count += 1;
447                }
448            }
449            Directive::Open(open) => {
450                if do_intern(&mut open.account, &mut interner) {
451                    dedup_count += 1;
452                }
453                for cur in &mut open.currencies {
454                    if do_intern(cur, &mut interner) {
455                        dedup_count += 1;
456                    }
457                }
458            }
459            Directive::Close(close) => {
460                if do_intern(&mut close.account, &mut interner) {
461                    dedup_count += 1;
462                }
463            }
464            Directive::Commodity(comm) => {
465                if do_intern(&mut comm.currency, &mut interner) {
466                    dedup_count += 1;
467                }
468            }
469            Directive::Pad(pad) => {
470                if do_intern(&mut pad.account, &mut interner) {
471                    dedup_count += 1;
472                }
473                if do_intern(&mut pad.source_account, &mut interner) {
474                    dedup_count += 1;
475                }
476            }
477            Directive::Note(note) => {
478                if do_intern(&mut note.account, &mut interner) {
479                    dedup_count += 1;
480                }
481            }
482            Directive::Document(doc) => {
483                if do_intern(&mut doc.account, &mut interner) {
484                    dedup_count += 1;
485                }
486            }
487            Directive::Price(price) => {
488                if do_intern(&mut price.currency, &mut interner) {
489                    dedup_count += 1;
490                }
491                if do_intern(&mut price.amount.currency, &mut interner) {
492                    dedup_count += 1;
493                }
494            }
495            Directive::Event(_) | Directive::Query(_) | Directive::Custom(_) => {
496                // These don't contain InternedStr fields
497            }
498        }
499    }
500
501    dedup_count
502}
503
504#[cfg(test)]
505mod tests {
506    use super::*;
507    use chrono::NaiveDate;
508    use rust_decimal_macros::dec;
509    use rustledger_core::{Amount, Posting, Transaction};
510    use rustledger_parser::Span;
511
512    #[test]
513    fn test_cache_header_roundtrip() {
514        let header = CacheHeader {
515            magic: *CACHE_MAGIC,
516            version: CACHE_VERSION,
517            hash: [42u8; 32],
518            data_len: 12345,
519        };
520
521        let bytes = header.to_bytes();
522        let parsed = CacheHeader::from_bytes(&bytes).unwrap();
523
524        assert_eq!(parsed.magic, header.magic);
525        assert_eq!(parsed.version, header.version);
526        assert_eq!(parsed.hash, header.hash);
527        assert_eq!(parsed.data_len, header.data_len);
528    }
529
530    #[test]
531    fn test_compute_hash_deterministic() {
532        let files: Vec<&Path> = vec![];
533        let hash1 = compute_hash(&files);
534        let hash2 = compute_hash(&files);
535        assert_eq!(hash1, hash2);
536    }
537
538    #[test]
539    fn test_serialize_deserialize_roundtrip() {
540        let date = NaiveDate::from_ymd_opt(2024, 1, 15).unwrap();
541
542        let txn = Transaction::new(date, "Test transaction")
543            .with_payee("Test Payee")
544            .with_posting(Posting::new(
545                "Expenses:Test",
546                Amount::new(dec!(100.00), "USD"),
547            ))
548            .with_posting(Posting::auto("Assets:Checking"));
549
550        let directives = vec![Spanned::new(Directive::Transaction(txn), Span::new(0, 100))];
551
552        // Serialize
553        let serialized = serialize_directives(&directives).expect("serialization failed");
554
555        // Deserialize
556        let deserialized = deserialize_directives(&serialized).expect("deserialization failed");
557
558        // Verify roundtrip
559        assert_eq!(directives.len(), deserialized.len());
560        let orig_txn = directives[0].value.as_transaction().unwrap();
561        let deser_txn = deserialized[0].value.as_transaction().unwrap();
562
563        assert_eq!(orig_txn.date, deser_txn.date);
564        assert_eq!(orig_txn.payee, deser_txn.payee);
565        assert_eq!(orig_txn.narration, deser_txn.narration);
566        assert_eq!(orig_txn.postings.len(), deser_txn.postings.len());
567
568        // Check first posting
569        assert_eq!(orig_txn.postings[0].account, deser_txn.postings[0].account);
570        assert_eq!(orig_txn.postings[0].units, deser_txn.postings[0].units);
571    }
572
573    #[test]
574    #[ignore = "manual benchmark - run with: cargo test -p rustledger-loader --release -- --ignored --nocapture"]
575    fn bench_cache_performance() {
576        // Generate test directives
577        let date = NaiveDate::from_ymd_opt(2024, 1, 15).unwrap();
578        let mut directives = Vec::with_capacity(10000);
579
580        for i in 0..10000 {
581            let txn = Transaction::new(date, format!("Transaction {i}"))
582                .with_payee("Store")
583                .with_posting(Posting::new(
584                    "Expenses:Food",
585                    Amount::new(dec!(25.00), "USD"),
586                ))
587                .with_posting(Posting::auto("Assets:Checking"));
588
589            directives.push(Spanned::new(Directive::Transaction(txn), Span::new(0, 100)));
590        }
591
592        println!("\n=== Cache Benchmark (10,000 directives) ===");
593
594        // Benchmark serialization
595        let start = std::time::Instant::now();
596        let serialized = serialize_directives(&directives).unwrap();
597        let serialize_time = start.elapsed();
598        println!(
599            "Serialize: {:?} ({:.2} MB)",
600            serialize_time,
601            serialized.len() as f64 / 1_000_000.0
602        );
603
604        // Benchmark deserialization
605        let start = std::time::Instant::now();
606        let deserialized = deserialize_directives(&serialized).unwrap();
607        let deserialize_time = start.elapsed();
608        println!("Deserialize: {deserialize_time:?}");
609
610        assert_eq!(directives.len(), deserialized.len());
611
612        println!(
613            "\nSpeedup potential: If parsing takes 100ms, cache load would be {:.1}x faster",
614            100.0 / deserialize_time.as_millis() as f64
615        );
616    }
617
618    #[test]
619    fn test_cache_path() {
620        let source = Path::new("/tmp/ledger.beancount");
621        let cache = cache_path(source);
622        assert_eq!(cache, Path::new("/tmp/ledger.beancount.cache"));
623
624        let source2 = Path::new("relative/path/my.beancount");
625        let cache2 = cache_path(source2);
626        assert_eq!(cache2, Path::new("relative/path/my.beancount.cache"));
627    }
628
629    #[test]
630    fn test_save_load_cache_entry_roundtrip() {
631        use std::io::Write;
632
633        // Create a temp directory
634        let temp_dir = std::env::temp_dir().join("rustledger_cache_test");
635        let _ = fs::create_dir_all(&temp_dir);
636
637        // Create a temp beancount file
638        let beancount_file = temp_dir.join("test.beancount");
639        let mut f = fs::File::create(&beancount_file).unwrap();
640        writeln!(f, "2024-01-01 open Assets:Test").unwrap();
641        drop(f);
642
643        // Create a cache entry
644        let date = NaiveDate::from_ymd_opt(2024, 1, 15).unwrap();
645        let txn = Transaction::new(date, "Test").with_posting(Posting::auto("Assets:Test"));
646        let directives = vec![Spanned::new(Directive::Transaction(txn), Span::new(0, 50))];
647
648        let entry = CacheEntry {
649            directives,
650            options: CachedOptions::from(&Options::new()),
651            plugins: vec![CachedPlugin {
652                name: "test_plugin".to_string(),
653                config: Some("config".to_string()),
654                force_python: false,
655            }],
656            files: vec![beancount_file.to_string_lossy().to_string()],
657        };
658
659        // Save cache
660        save_cache_entry(&beancount_file, &entry).expect("save failed");
661
662        // Load cache
663        let loaded = load_cache_entry(&beancount_file).expect("load failed");
664
665        // Verify
666        assert_eq!(loaded.directives.len(), entry.directives.len());
667        assert_eq!(loaded.plugins.len(), 1);
668        assert_eq!(loaded.plugins[0].name, "test_plugin");
669        assert_eq!(loaded.plugins[0].config, Some("config".to_string()));
670        assert_eq!(loaded.files.len(), 1);
671
672        // Cleanup
673        let _ = fs::remove_file(&beancount_file);
674        let _ = fs::remove_file(cache_path(&beancount_file));
675        let _ = fs::remove_dir(&temp_dir);
676    }
677
678    #[test]
679    fn test_invalidate_cache() {
680        use std::io::Write;
681
682        let temp_dir = std::env::temp_dir().join("rustledger_invalidate_test");
683        let _ = fs::create_dir_all(&temp_dir);
684
685        let beancount_file = temp_dir.join("test.beancount");
686        let mut f = fs::File::create(&beancount_file).unwrap();
687        writeln!(f, "2024-01-01 open Assets:Test").unwrap();
688        drop(f);
689
690        // Create and save a cache
691        let entry = CacheEntry {
692            directives: vec![],
693            options: CachedOptions::from(&Options::new()),
694            plugins: vec![],
695            files: vec![beancount_file.to_string_lossy().to_string()],
696        };
697        save_cache_entry(&beancount_file, &entry).unwrap();
698
699        // Verify cache exists
700        assert!(cache_path(&beancount_file).exists());
701
702        // Invalidate
703        invalidate_cache(&beancount_file);
704
705        // Verify cache is gone
706        assert!(!cache_path(&beancount_file).exists());
707
708        // Cleanup
709        let _ = fs::remove_file(&beancount_file);
710        let _ = fs::remove_dir(&temp_dir);
711    }
712
713    #[test]
714    fn test_load_cache_missing_file() {
715        let missing = Path::new("/nonexistent/path/to/file.beancount");
716        assert!(load_cache_entry(missing).is_none());
717    }
718
719    #[test]
720    fn test_load_cache_invalid_magic() {
721        use std::io::Write;
722
723        let temp_dir = std::env::temp_dir().join("rustledger_magic_test");
724        let _ = fs::create_dir_all(&temp_dir);
725
726        let cache_file = temp_dir.join("test.beancount.cache");
727        let mut f = fs::File::create(&cache_file).unwrap();
728        // Write invalid magic
729        f.write_all(b"INVALID\0").unwrap();
730        f.write_all(&[0u8; CacheHeader::SIZE - 8]).unwrap();
731        drop(f);
732
733        let beancount_file = temp_dir.join("test.beancount");
734        assert!(load_cache_entry(&beancount_file).is_none());
735
736        // Cleanup
737        let _ = fs::remove_file(&cache_file);
738        let _ = fs::remove_dir(&temp_dir);
739    }
740
741    #[test]
742    fn test_reintern_directives_deduplication() {
743        let date = NaiveDate::from_ymd_opt(2024, 1, 15).unwrap();
744
745        // Create multiple transactions with the same account
746        let mut directives = vec![];
747        for i in 0..5 {
748            let txn = Transaction::new(date, format!("Txn {i}"))
749                .with_posting(Posting::new(
750                    "Expenses:Food",
751                    Amount::new(dec!(10.00), "USD"),
752                ))
753                .with_posting(Posting::auto("Assets:Checking"));
754            directives.push(Spanned::new(Directive::Transaction(txn), Span::new(0, 50)));
755        }
756
757        // Re-intern should deduplicate the repeated account names and currencies
758        let dedup_count = reintern_directives(&mut directives);
759
760        // We should have deduplicated:
761        // - "Expenses:Food" appears 5 times but only first is new (4 dedup)
762        // - "USD" appears 5 times but only first is new (4 dedup)
763        // - "Assets:Checking" appears 5 times but only first is new (4 dedup)
764        // Total: 12 deduplications
765        assert_eq!(dedup_count, 12);
766    }
767
768    #[test]
769    fn test_cached_options_roundtrip() {
770        let mut opts = Options::new();
771        opts.title = Some("Test Ledger".to_string());
772        opts.operating_currency = vec!["USD".to_string(), "EUR".to_string()];
773        opts.render_commas = true;
774
775        let cached = CachedOptions::from(&opts);
776        let restored: Options = cached.into();
777
778        assert_eq!(restored.title, Some("Test Ledger".to_string()));
779        assert_eq!(restored.operating_currency, vec!["USD", "EUR"]);
780        assert!(restored.render_commas);
781    }
782
783    #[test]
784    fn test_cache_entry_file_paths() {
785        let entry = CacheEntry {
786            directives: vec![],
787            options: CachedOptions::from(&Options::new()),
788            plugins: vec![],
789            files: vec![
790                "/path/to/ledger.beancount".to_string(),
791                "/path/to/include.beancount".to_string(),
792            ],
793        };
794
795        let paths = entry.file_paths();
796        assert_eq!(paths.len(), 2);
797        assert_eq!(paths[0], PathBuf::from("/path/to/ledger.beancount"));
798        assert_eq!(paths[1], PathBuf::from("/path/to/include.beancount"));
799    }
800
801    #[test]
802    fn test_reintern_balance_directive() {
803        use rustledger_core::Balance;
804
805        let date = NaiveDate::from_ymd_opt(2024, 1, 15).unwrap();
806        let balance = Balance::new(date, "Assets:Checking", Amount::new(dec!(1000.00), "USD"));
807
808        let mut directives = vec![
809            Spanned::new(Directive::Balance(balance.clone()), Span::new(0, 50)),
810            Spanned::new(Directive::Balance(balance), Span::new(51, 100)),
811        ];
812
813        let dedup_count = reintern_directives(&mut directives);
814        // Second occurrence of "Assets:Checking" and "USD" should be deduplicated
815        assert_eq!(dedup_count, 2);
816    }
817
818    #[test]
819    fn test_reintern_open_close_directives() {
820        use rustledger_core::{Close, Open};
821
822        let date = NaiveDate::from_ymd_opt(2024, 1, 15).unwrap();
823        let open = Open::new(date, "Assets:Checking");
824        let close = Close::new(date, "Assets:Checking");
825
826        let mut directives = vec![
827            Spanned::new(Directive::Open(open), Span::new(0, 50)),
828            Spanned::new(Directive::Close(close), Span::new(51, 100)),
829        ];
830
831        let dedup_count = reintern_directives(&mut directives);
832        // Second "Assets:Checking" should be deduplicated
833        assert_eq!(dedup_count, 1);
834    }
835}