rustledger 0.20.1

Drop-in replacement for Beancount. Pure Rust, 10-30x faster.
Documentation
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
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
//! Integration tests comparing rustledger against Python beancount.
//!
//! These tests verify that rustledger produces the same results as
//! the reference Python implementation.

mod common;

use std::path::{Path, PathBuf};
use std::process::Command;

use common::{project_root, test_fixtures_dir};

fn rledger_binary() -> Option<PathBuf> {
    // Use CARGO_BIN_EXE_rledger if available (set by cargo test)
    if let Ok(path) = std::env::var("CARGO_BIN_EXE_rledger") {
        return Some(PathBuf::from(path));
    }

    // Check target/release first (for --release and nix builds)
    let release = project_root().join("target/release/rledger");
    if release.exists() {
        return Some(release);
    }

    // Fall back to target/debug
    let debug = project_root().join("target/debug/rledger");
    if debug.exists() {
        return Some(debug);
    }

    // Binary not found
    None
}

/// Check if Python beancount is available.
fn python_beancount_available() -> bool {
    Command::new("bean-check")
        .arg("--version")
        .output()
        .is_ok_and(|o| o.status.success())
}

/// Run Python bean-check on a file.
fn python_bean_check(path: &Path) -> (bool, String) {
    let output = Command::new("bean-check")
        .arg(path)
        .output()
        .expect("Failed to run bean-check");

    let success = output.status.success();
    let stderr = String::from_utf8_lossy(&output.stderr).to_string();
    (success, stderr)
}

/// Run rledger check on a file.
fn rust_bean_check(path: &Path) -> Option<(bool, String)> {
    let binary = rledger_binary()?;
    let output = Command::new(binary)
        .args(["check", path.to_str().unwrap()])
        .output()
        .expect("Failed to run rledger check");

    let success = output.status.success();
    let combined = format!(
        "{}{}",
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr)
    );
    Some((success, combined))
}

#[test]
fn test_valid_ledger_parses_with_both() {
    if !python_beancount_available() {
        eprintln!("Skipping: Python beancount not available");
        return;
    }

    let path = test_fixtures_dir().join("valid-ledger.beancount");

    let (py_success, py_output) = python_bean_check(&path);
    let Some((rs_success, rs_output)) = rust_bean_check(&path) else {
        eprintln!("Skipping: rust bean-check binary not found");
        return;
    };

    assert!(
        py_success,
        "Python beancount failed on valid file: {py_output}"
    );
    assert!(
        rs_success,
        "Rust beancount failed on valid file: {rs_output}"
    );
}

#[test]
fn test_directive_count_matches() {
    let path = test_fixtures_dir().join("valid-ledger.beancount");

    // Parse with Rust and count
    let source = std::fs::read_to_string(&path).expect("Failed to read file");
    let result = rustledger_parser::parse(&source);

    // Count open directives
    let rs_open_count = result
        .directives
        .iter()
        .filter(|d| matches!(&d.value, rustledger_core::Directive::Open(_)))
        .count();

    // We expect 11 open directives
    assert_eq!(rs_open_count, 11, "Expected 11 open directives");

    // Count transactions
    let rs_txn_count = result
        .directives
        .iter()
        .filter(|d| matches!(&d.value, rustledger_core::Directive::Transaction(_)))
        .count();

    // We expect 8 transactions
    assert_eq!(rs_txn_count, 8, "Expected 8 transactions");

    // Verify no parse errors
    assert!(
        result.errors.is_empty(),
        "Unexpected parse errors: {:?}",
        result.errors
    );
}

#[test]
fn test_error_detection_consistency() {
    if !python_beancount_available() {
        eprintln!("Skipping: Python beancount not available");
        return;
    }

    // Create a file with a known error (duplicate open)
    let content = r#"
option "title" "Error Test"

2020-01-01 open Assets:Bank
2020-01-01 open Assets:Bank  ; Duplicate!

2020-01-15 * "Test"
  Assets:Bank  100 USD
  Equity:Opening
"#;

    let temp_dir = std::env::temp_dir();
    let temp_file = temp_dir.join("error-test.beancount");
    std::fs::write(&temp_file, content).expect("Failed to write temp file");

    let (py_success, _py_output) = python_bean_check(&temp_file);
    let Some((rs_success, _rs_output)) = rust_bean_check(&temp_file) else {
        eprintln!("Skipping: rust bean-check binary not found");
        return;
    };

    // Both should report errors
    assert!(!py_success, "Python should detect duplicate open error");
    assert!(!rs_success, "Rust should detect duplicate open error");

    std::fs::remove_file(&temp_file).ok();
}

#[test]
fn test_balance_assertion_consistency() {
    if !python_beancount_available() {
        eprintln!("Skipping: Python beancount not available");
        return;
    }

    // File with failing balance assertion
    let content = r#"
option "title" "Balance Test"

2020-01-01 open Assets:Bank USD
2020-01-01 open Equity:Opening

2020-01-01 * "Opening"
  Assets:Bank  1000 USD
  Equity:Opening

2020-01-15 balance Assets:Bank  500 USD  ; Wrong amount!
"#;

    let temp_dir = std::env::temp_dir();
    let temp_file = temp_dir.join("balance-test.beancount");
    std::fs::write(&temp_file, content).expect("Failed to write temp file");

    let (py_success, _) = python_bean_check(&temp_file);
    let Some((rs_success, _)) = rust_bean_check(&temp_file) else {
        eprintln!("Skipping: rust bean-check binary not found");
        return;
    };

    // Both should fail on balance assertion
    assert!(
        !py_success,
        "Python should detect balance assertion failure"
    );
    assert!(!rs_success, "Rust should detect balance assertion failure");

    std::fs::remove_file(&temp_file).ok();
}

#[test]
fn test_currency_constraint_consistency() {
    if !python_beancount_available() {
        eprintln!("Skipping: Python beancount not available");
        return;
    }

    // File with currency constraint violation
    let content = r#"
option "title" "Currency Test"

2020-01-01 open Assets:USDOnly USD
2020-01-01 open Equity:Opening

2020-01-01 * "Wrong currency"
  Assets:USDOnly  100 EUR  ; EUR not allowed!
  Equity:Opening
"#;

    let temp_dir = std::env::temp_dir();
    let temp_file = temp_dir.join("currency-test.beancount");
    std::fs::write(&temp_file, content).expect("Failed to write temp file");

    let (py_success, _) = python_bean_check(&temp_file);
    let Some((rs_success, _)) = rust_bean_check(&temp_file) else {
        eprintln!("Skipping: rust bean-check binary not found");
        return;
    };

    // Both should fail on currency constraint
    assert!(
        !py_success,
        "Python should detect currency constraint violation"
    );
    assert!(
        !rs_success,
        "Rust should detect currency constraint violation"
    );

    std::fs::remove_file(&temp_file).ok();
}

#[test]
fn test_account_lifecycle_consistency() {
    if !python_beancount_available() {
        eprintln!("Skipping: Python beancount not available");
        return;
    }

    // File with account used before open
    let content = r#"
option "title" "Lifecycle Test"

2020-01-01 open Equity:Opening

; Use account before it's opened
2020-01-15 * "Too early"
  Assets:Bank  100 USD
  Equity:Opening

2020-02-01 open Assets:Bank USD
"#;

    let temp_dir = std::env::temp_dir();
    let temp_file = temp_dir.join("lifecycle-test.beancount");
    std::fs::write(&temp_file, content).expect("Failed to write temp file");

    let (py_success, _) = python_bean_check(&temp_file);
    let Some((rs_success, _)) = rust_bean_check(&temp_file) else {
        eprintln!("Skipping: rust bean-check binary not found");
        return;
    };

    // Both should fail
    assert!(!py_success, "Python should detect account used before open");
    assert!(!rs_success, "Rust should detect account used before open");

    std::fs::remove_file(&temp_file).ok();
}

#[test]
fn test_transaction_not_balanced_consistency() {
    if !python_beancount_available() {
        eprintln!("Skipping: Python beancount not available");
        return;
    }

    // File with unbalanced transaction
    let content = r#"
option "title" "Unbalanced Test"

2020-01-01 open Assets:Bank USD
2020-01-01 open Expenses:Food USD

2020-01-15 * "Unbalanced"
  Assets:Bank     -100 USD
  Expenses:Food     50 USD  ; Should be 100 to balance
"#;

    let temp_dir = std::env::temp_dir();
    let temp_file = temp_dir.join("unbalanced-test.beancount");
    std::fs::write(&temp_file, content).expect("Failed to write temp file");

    let (py_success, _) = python_bean_check(&temp_file);
    let Some((rs_success, _)) = rust_bean_check(&temp_file) else {
        eprintln!("Skipping: rust bean-check binary not found");
        return;
    };

    // Both should fail on unbalanced transaction
    assert!(!py_success, "Python should detect unbalanced transaction");
    assert!(!rs_success, "Rust should detect unbalanced transaction");

    std::fs::remove_file(&temp_file).ok();
}

#[test]
fn test_pad_directive_consistency() {
    if !python_beancount_available() {
        eprintln!("Skipping: Python beancount not available");
        return;
    }

    // File with pad directive
    let content = r#"
option "title" "Pad Test"

2020-01-01 open Assets:Bank USD
2020-01-01 open Equity:Opening USD

2020-01-01 pad Assets:Bank Equity:Opening
2020-01-15 balance Assets:Bank 1000 USD
"#;

    let temp_dir = std::env::temp_dir();
    let temp_file = temp_dir.join("pad-test.beancount");
    std::fs::write(&temp_file, content).expect("Failed to write temp file");

    let (py_success, py_output) = python_bean_check(&temp_file);
    let Some((rs_success, rs_output)) = rust_bean_check(&temp_file) else {
        eprintln!("Skipping: rust bean-check binary not found");
        return;
    };

    // Both should succeed
    assert!(
        py_success,
        "Python should handle pad directive: {py_output}"
    );
    assert!(rs_success, "Rust should handle pad directive: {rs_output}");

    std::fs::remove_file(&temp_file).ok();
}

#[test]
fn test_price_directive_consistency() {
    if !python_beancount_available() {
        eprintln!("Skipping: Python beancount not available");
        return;
    }

    // File with price directives
    let content = r#"
option "title" "Price Test"

2020-01-01 open Assets:Stock AAPL
2020-01-01 open Assets:Cash USD
2020-01-01 commodity AAPL
2020-01-01 commodity USD

2020-01-15 price AAPL 150 USD
2020-06-15 price AAPL 200 USD

2020-01-15 * "Buy stock"
  Assets:Stock   10 AAPL {150 USD}
  Assets:Cash   -1500 USD
"#;

    let temp_dir = std::env::temp_dir();
    let temp_file = temp_dir.join("price-test.beancount");
    std::fs::write(&temp_file, content).expect("Failed to write temp file");

    let (py_success, py_output) = python_bean_check(&temp_file);
    let Some((rs_success, rs_output)) = rust_bean_check(&temp_file) else {
        eprintln!("Skipping: rust bean-check binary not found");
        return;
    };

    // Both should succeed
    assert!(
        py_success,
        "Python should handle price directive: {py_output}"
    );
    assert!(
        rs_success,
        "Rust should handle price directive: {rs_output}"
    );

    std::fs::remove_file(&temp_file).ok();
}

#[test]
fn test_pushtag_poptag_consistency() {
    if !python_beancount_available() {
        eprintln!("Skipping: Python beancount not available");
        return;
    }

    // File with pushtag/poptag
    let content = r#"
option "title" "Tag Test"

2020-01-01 open Assets:Bank USD
2020-01-01 open Expenses:Food USD

pushtag #trip

2020-01-15 * "Lunch" #extra
  Expenses:Food    20 USD
  Assets:Bank

2020-01-16 * "Dinner"
  Expenses:Food    50 USD
  Assets:Bank

poptag #trip

2020-01-20 * "Home food"
  Expenses:Food    10 USD
  Assets:Bank
"#;

    let temp_dir = std::env::temp_dir();
    let temp_file = temp_dir.join("pushtag-test.beancount");
    std::fs::write(&temp_file, content).expect("Failed to write temp file");

    let (py_success, py_output) = python_bean_check(&temp_file);
    let Some((rs_success, rs_output)) = rust_bean_check(&temp_file) else {
        eprintln!("Skipping: rust bean-check binary not found");
        return;
    };

    // Both should succeed
    assert!(
        py_success,
        "Python should handle pushtag/poptag: {py_output}"
    );
    assert!(rs_success, "Rust should handle pushtag/poptag: {rs_output}");

    std::fs::remove_file(&temp_file).ok();
}

#[test]
fn test_arithmetic_expressions_consistency() {
    if !python_beancount_available() {
        eprintln!("Skipping: Python beancount not available");
        return;
    }

    // File with arithmetic expressions in amounts
    let content = r#"
option "title" "Arithmetic Test"

2020-01-01 open Assets:Bank USD
2020-01-01 open Expenses:Food USD

2020-01-15 * "Split dinner"
  Expenses:Food    120 / 3 USD  ; 40 USD
  Assets:Bank      -40 USD

2020-01-16 * "Group lunch"
  Expenses:Food    15 + 10 USD  ; 25 USD
  Assets:Bank      -25 USD

2020-01-17 * "Multiplied"
  Expenses:Food    10 * 5 USD   ; 50 USD
  Assets:Bank      -50 USD
"#;

    let temp_dir = std::env::temp_dir();
    let temp_file = temp_dir.join("arithmetic-test.beancount");
    std::fs::write(&temp_file, content).expect("Failed to write temp file");

    let (py_success, py_output) = python_bean_check(&temp_file);
    let Some((rs_success, rs_output)) = rust_bean_check(&temp_file) else {
        eprintln!("Skipping: rust bean-check binary not found");
        return;
    };

    // Both should succeed
    assert!(
        py_success,
        "Python should handle arithmetic expressions: {py_output}"
    );
    assert!(
        rs_success,
        "Rust should handle arithmetic expressions: {rs_output}"
    );

    std::fs::remove_file(&temp_file).ok();
}

#[test]
fn test_metadata_consistency() {
    if !python_beancount_available() {
        eprintln!("Skipping: Python beancount not available");
        return;
    }

    // File with metadata
    let content = r#"
option "title" "Metadata Test"

2020-01-01 open Assets:Bank USD
  description: "Main checking account"
  bank: "First National"

2020-01-01 open Expenses:Food USD

2020-01-15 * "Restaurant" ^link-001
  document: "receipts/lunch.pdf"
  Expenses:Food    50 USD
    vendor: "Joe's Diner"
  Assets:Bank     -50 USD
"#;

    let temp_dir = std::env::temp_dir();
    let temp_file = temp_dir.join("metadata-test.beancount");
    std::fs::write(&temp_file, content).expect("Failed to write temp file");

    let (py_success, py_output) = python_bean_check(&temp_file);
    let Some((rs_success, rs_output)) = rust_bean_check(&temp_file) else {
        eprintln!("Skipping: rust bean-check binary not found");
        return;
    };

    // Both should succeed
    assert!(py_success, "Python should handle metadata: {py_output}");
    assert!(rs_success, "Rust should handle metadata: {rs_output}");

    std::fs::remove_file(&temp_file).ok();
}

#[test]
fn test_cost_and_price_annotations() {
    if !python_beancount_available() {
        eprintln!("Skipping: Python beancount not available");
        return;
    }

    // File with various cost and price annotations
    let content = r#"
option "title" "Cost/Price Test"
option "operating_currency" "USD"

2020-01-01 open Assets:Stock AAPL
2020-01-01 open Assets:Cash USD
2020-01-01 open Income:Gains USD
2020-01-01 commodity AAPL
2020-01-01 commodity USD

; Buy with cost
2020-01-15 * "Buy stock"
  Assets:Stock   10 AAPL {150 USD}
  Assets:Cash   -1500 USD

; Sell with cost and price annotation
2020-06-15 * "Sell stock"
  Assets:Stock   -5 AAPL {150 USD} @ 200 USD
  Assets:Cash    1000 USD
  Income:Gains   -250 USD
"#;

    let temp_dir = std::env::temp_dir();
    let temp_file = temp_dir.join("cost-price-test.beancount");
    std::fs::write(&temp_file, content).expect("Failed to write temp file");

    let (py_success, py_output) = python_bean_check(&temp_file);
    let Some((rs_success, rs_output)) = rust_bean_check(&temp_file) else {
        eprintln!("Skipping: rust bean-check binary not found");
        return;
    };

    // Both should succeed
    assert!(py_success, "Python should handle cost/price: {py_output}");
    assert!(rs_success, "Rust should handle cost/price: {rs_output}");

    std::fs::remove_file(&temp_file).ok();
}

#[test]
fn test_event_and_query_directives() {
    if !python_beancount_available() {
        eprintln!("Skipping: Python beancount not available");
        return;
    }

    // File with event and query directives
    let content = r#"
option "title" "Event/Query Test"

2020-01-01 open Assets:Bank USD
2020-01-01 open Expenses:Travel USD

2020-01-15 event "location" "New York"
2020-02-01 event "location" "Los Angeles"

2020-06-01 query "travel_expenses" "
  SELECT account, sum(position)
  WHERE account ~ 'Expenses:Travel'
  GROUP BY account
"

2020-01-20 * "Travel expense"
  Expenses:Travel   200 USD
  Assets:Bank
"#;

    let temp_dir = std::env::temp_dir();
    let temp_file = temp_dir.join("event-query-test.beancount");
    std::fs::write(&temp_file, content).expect("Failed to write temp file");

    let (py_success, py_output) = python_bean_check(&temp_file);
    let Some((rs_success, rs_output)) = rust_bean_check(&temp_file) else {
        eprintln!("Skipping: rust bean-check binary not found");
        return;
    };

    // Both should succeed
    assert!(py_success, "Python should handle event/query: {py_output}");
    assert!(rs_success, "Rust should handle event/query: {rs_output}");

    std::fs::remove_file(&temp_file).ok();
}

#[test]
fn test_note_directive() {
    if !python_beancount_available() {
        eprintln!("Skipping: Python beancount not available");
        return;
    }

    // File with note directive
    let content = r#"
option "title" "Note Test"

2020-01-01 open Assets:Bank USD
2020-01-01 open Equity:Opening

2020-01-15 note Assets:Bank "Changed account number"
2020-06-01 note Assets:Bank "Switched to online banking"

2020-01-20 * "Deposit"
  Assets:Bank    1000 USD
  Equity:Opening
"#;

    let temp_dir = std::env::temp_dir();
    let temp_file = temp_dir.join("note-test.beancount");
    std::fs::write(&temp_file, content).expect("Failed to write temp file");

    let (py_success, py_output) = python_bean_check(&temp_file);
    let Some((rs_success, rs_output)) = rust_bean_check(&temp_file) else {
        eprintln!("Skipping: rust bean-check binary not found");
        return;
    };

    // Both should succeed
    assert!(
        py_success,
        "Python should handle note directive: {py_output}"
    );
    assert!(rs_success, "Rust should handle note directive: {rs_output}");

    std::fs::remove_file(&temp_file).ok();
}

/// Path to beancount's canonical example.beancount file.
fn beancount_example_file() -> PathBuf {
    project_root().join("tests/fixtures/examples/example.beancount")
}

#[test]
fn test_beancount_canonical_example() {
    // This is beancount's official example.beancount file.
    // It should parse and validate without errors in rustledger.
    let path = beancount_example_file();

    if !path.exists() {
        eprintln!("Skipping: tests/fixtures/examples/example.beancount not found");
        return;
    }

    let Some((rs_success, rs_output)) = rust_bean_check(&path) else {
        eprintln!("Skipping: rust bean-check binary not found");
        return;
    };

    assert!(
        rs_success,
        "Rust should validate beancount's canonical example.beancount without errors: {rs_output}"
    );
}

#[test]
fn test_beancount_canonical_example_matches_python() {
    if !python_beancount_available() {
        eprintln!("Skipping: Python beancount not available");
        return;
    }

    let path = beancount_example_file();

    if !path.exists() {
        eprintln!("Skipping: tests/fixtures/examples/example.beancount not found");
        return;
    }

    let (py_success, py_output) = python_bean_check(&path);
    let Some((rs_success, rs_output)) = rust_bean_check(&path) else {
        eprintln!("Skipping: rust bean-check binary not found");
        return;
    };

    assert!(
        py_success,
        "Python beancount should pass on its own example.beancount: {py_output}"
    );
    assert!(
        rs_success,
        "Rust should match Python on example.beancount: {rs_output}"
    );
}

#[test]
fn test_query_filename_lineno_columns_resolve() {
    // Regression: `SELECT filename, lineno` used to return NULL from the CLI
    // because the query command built the executor without a source map.
    let Some(binary) = rledger_binary() else {
        eprintln!("Skipping: rledger binary not found");
        return;
    };
    // Transaction header is on line 3 (two opens precede it); its postings are
    // on lines 4 (Assets:Cash) and 5 (Equity:O).
    let content = "2020-01-01 open Assets:Cash USD\n\
                   2020-01-01 open Equity:O USD\n\
                   2020-02-01 * \"p\"\n  \
                     Assets:Cash  10.00 USD\n  \
                     Equity:O\n";
    // Unique temp file (auto-removed on drop) to avoid cross-run collisions.
    let mut tmp = tempfile::Builder::new()
        .suffix(".beancount")
        .tempfile()
        .expect("create temp file");
    std::io::Write::write_all(&mut tmp, content.as_bytes()).expect("write temp file");

    let output = Command::new(binary)
        .arg("query")
        .arg(tmp.path())
        .arg("SELECT filename, lineno WHERE flag = \"*\"")
        .output()
        .expect("run rledger query");
    let stdout = String::from_utf8_lossy(&output.stdout);

    assert!(
        output.status.success(),
        "query should succeed; stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    // filename resolves to the real path (was empty/NULL before the fix).
    assert!(
        stdout.contains(".beancount"),
        "expected the source filename in output, got:\n{stdout}"
    );
    // lineno resolves per-posting: the Assets:Cash posting is on line 4 (was the
    // transaction's line 3 before per-posting resolution).
    assert!(
        stdout
            .lines()
            .any(|l| l.contains(".beancount") && l.trim_end().ends_with('4')),
        "expected lineno 4 on the first posting's row, got:\n{stdout}"
    );
}

#[test]
fn test_query_print_outputs_directives() {
    // Regression: PRINT returned 0 rows from the CLI after the executor switched
    // to new_with_sources (execute_print didn't fall back to spanned_directives).
    let Some(binary) = rledger_binary() else {
        eprintln!("Skipping: rledger binary not found");
        return;
    };
    let content = "2020-01-01 open Assets:Cash USD\n\
                   2020-01-01 open Equity:O USD\n\
                   2020-02-01 * \"p\"\n  \
                     Assets:Cash  10.00 USD\n  \
                     Equity:O\n";
    // Unique temp file (auto-removed on drop) to avoid cross-run collisions.
    let mut tmp = tempfile::Builder::new()
        .suffix(".beancount")
        .tempfile()
        .expect("create temp file");
    std::io::Write::write_all(&mut tmp, content.as_bytes()).expect("write temp file");

    let output = Command::new(binary)
        .arg("query")
        .arg(tmp.path())
        .arg("PRINT")
        .output()
        .expect("run rledger query PRINT");
    let stdout = String::from_utf8_lossy(&output.stdout);

    assert!(
        output.status.success(),
        "PRINT should succeed; stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    // PRINT must emit the directives (was empty before the fix).
    assert!(
        stdout.contains("open Assets:Cash"),
        "PRINT should emit directives, got:\n{stdout}"
    );
}