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