btctax-core 0.14.0

Offline US Bitcoin tax engine — per-lot cost basis, realized gains, and IRS-form projection (part of btctax).
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
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
//! Sub-project C, Task 4 — Mode-1 optimizer `optimize_year` KATs.
//!
//! The headline guarantee: the optimizer's `optimized_tax` equals an INDEPENDENT exhaustive brute-force
//! oracle (`oracle_min_total`) on small whole-lot fixtures, AND beats the named naive baseline. The oracle
//! enumerates every whole-lot subset assignment per disposal and scores each through B's
//! `score_assignment` — it shares NO code with the optimizer's candidate generators / contention logic, so
//! agreement proves optimality, not self-consistency.
//!
//! All fixtures are synthetic (privacy — no real reads); exact Decimal, no float (NFR5); two calls are
//! byte-identical (NFR4). Federal-only.
use btctax_core::conventions::Usd;
use btctax_core::event::*;
use btctax_core::identity::*;
use btctax_core::optimize::{optimize_year, score_assignment, ApproxReason};
use btctax_core::price::{PriceProvider, StaticPrices};
use btctax_core::project::{LotMethod, ProjectionConfig};
use btctax_core::tax::tables::{
    LtcgBreakpoints, OrdinaryBracket, OrdinarySchedule, TaxTable, TaxTables,
};
use btctax_core::tax::types::{Carryforward, FilingStatus, TaxOutcome, TaxProfile};
use rust_decimal_macros::dec;
use std::collections::{BTreeMap, BTreeSet};
use time::macros::{datetime, offset};

const LOT: i64 = 100_000_000; // one whole BTC per lot

// ── synthetic table + profile (Single; 32% band starts at $90k so a $100k profile is marginal-32%) ───
struct OneTable(TaxTable);
impl TaxTables for OneTable {
    fn table_for(&self, year: i32) -> Option<&TaxTable> {
        (year == self.0.year).then_some(&self.0)
    }
}
fn synth(year: i32) -> OneTable {
    let mut ordinary = BTreeMap::new();
    ordinary.insert(
        FilingStatus::Single,
        OrdinarySchedule {
            brackets: vec![
                OrdinaryBracket {
                    lower: dec!(0),
                    rate: dec!(0.10),
                },
                OrdinaryBracket {
                    lower: dec!(50000),
                    rate: dec!(0.22),
                },
                OrdinaryBracket {
                    lower: dec!(90000),
                    rate: dec!(0.32),
                },
            ],
        },
    );
    let mut ltcg = BTreeMap::new();
    ltcg.insert(
        FilingStatus::Single,
        LtcgBreakpoints {
            max_zero: dec!(40000),
            max_fifteen: dec!(400000),
        },
    );
    OneTable(TaxTable {
        year,
        source: "SYNTHETIC",
        ordinary,
        ltcg,
        gift_annual_exclusion: dec!(19000),
        ss_wage_base: dec!(176100),
        gift_lifetime_exclusion: dec!(13_990_000),
    })
}
/// Single filer; ordinary == MAGI so a chosen ordinary income places the marginal rate AND keeps MAGI
/// below the $200k NIIT threshold for the small crypto gains in these KATs.
fn profile(ordinary: Usd) -> TaxProfile {
    TaxProfile {
        filing_status: FilingStatus::Single,
        ordinary_taxable_income: ordinary,
        magi_excluding_crypto: ordinary,
        qualified_dividends_and_other_pref_income: dec!(0),
        other_net_capital_gain: dec!(0),
        capital_loss_carryforward_in: Carryforward {
            short: dec!(0),
            long: dec!(0),
        },
        w2_ss_wages: dec!(0),
        w2_medicare_wages: dec!(0),
        schedule_c_expenses: dec!(0),
    }
}

// ── event / id builders ──────────────────────────────────────────────────────────────────────────
fn cold() -> WalletId {
    WalletId::SelfCustody {
        label: "cold".into(),
    }
}
fn wallet(label: &str) -> WalletId {
    WalletId::SelfCustody {
        label: label.into(),
    }
}
fn eid(rf: &str) -> EventId {
    EventId::import(Source::Swan, SourceRef::new(rf))
}
fn lid(rf: &str) -> LotId {
    LotId {
        origin_event_id: eid(rf),
        split_sequence: 0,
    }
}
fn pick(rf: &str, sat: i64) -> LotPick {
    LotPick { lot: lid(rf), sat }
}
fn ev(rf: &str, ts: time::OffsetDateTime, w: WalletId, p: EventPayload) -> LedgerEvent {
    LedgerEvent {
        id: eid(rf),
        utc_timestamp: ts,
        original_tz: offset!(+00:00),
        wallet: Some(w),
        payload: p,
    }
}
fn buy(rf: &str, ts: time::OffsetDateTime, w: WalletId, sat: i64, cost: Usd) -> LedgerEvent {
    ev(
        rf,
        ts,
        w,
        EventPayload::Acquire(Acquire {
            sat,
            usd_cost: cost,
            fee_usd: dec!(0),
            basis_source: BasisSource::ExchangeProvided,
        }),
    )
}
fn sell(rf: &str, ts: time::OffsetDateTime, w: WalletId, sat: i64, proceeds: Usd) -> LedgerEvent {
    ev(
        rf,
        ts,
        w,
        EventPayload::Dispose(Dispose {
            sat,
            usd_proceeds: proceeds,
            fee_usd: dec!(0),
            kind: DisposeKind::Sell,
        }),
    )
}
/// A standing-order `MethodElection` (decision event; wallet None). `effective_from` 2025-01-01 binds all
/// post-2025 disposals to `method` — used to make the BASELINE a naive HIFO/LIFO pick.
fn method_election(seq: u64, ts: time::OffsetDateTime, method: LotMethod) -> LedgerEvent {
    LedgerEvent {
        id: EventId::decision(seq),
        utc_timestamp: ts,
        original_tz: offset!(+00:00),
        wallet: None,
        payload: EventPayload::MethodElection(MethodElection {
            effective_from: time::macros::date!(2025 - 01 - 01),
            method,
            wallet: None,
        }),
    }
}
fn cfg() -> ProjectionConfig {
    ProjectionConfig::default() // FIFO default, TreatmentC
}
fn made() -> time::Date {
    time::macros::date!(2026 - 07 - 01)
}
fn no_attest() -> BTreeSet<EventId> {
    BTreeSet::new()
}

/// Reconstruct the optimizer's chosen assignment from the proposal (disposal → proposed picks), so we can
/// re-score it (e.g. to read `loss_deduction`).
fn assignment_of(p: &btctax_core::optimize::OptimizeProposal) -> BTreeMap<EventId, Vec<LotPick>> {
    p.per_disposal
        .iter()
        .map(|d| (d.disposal.clone(), d.proposed_selection.clone()))
        .collect()
}

/// `(disposal, its available (lot, sat) universe, need)` — one oracle input row per disposal.
type OracleDisposal = (EventId, Vec<(LotId, i64)>, i64);

/// INDEPENDENT exhaustive oracle: for each disposal enumerate ALL whole-lot subsets of its available lots
/// summing to `need`, take the cartesian product, score each via `score_assignment`, return the min total.
/// Infeasible cross-disposal combinations self-eliminate (`NotComputable` → skipped). No optimizer code.
fn oracle_min_total(
    events: &[LedgerEvent],
    prices: &dyn PriceProvider,
    config: &ProjectionConfig,
    year: i32,
    prof: Option<&TaxProfile>,
    tables: &dyn TaxTables,
    per_disposal: &[OracleDisposal],
) -> Usd {
    let mut per: Vec<Vec<Vec<LotPick>>> = Vec::new();
    for (_id, lots, need) in per_disposal {
        let n = lots.len();
        let mut subs: Vec<Vec<LotPick>> = Vec::new();
        for mask in 0u32..(1u32 << n) {
            let mut v = Vec::new();
            let mut sum = 0i64;
            for (i, (lot, sat)) in lots.iter().enumerate() {
                if mask & (1 << i) != 0 {
                    v.push(LotPick {
                        lot: lot.clone(),
                        sat: *sat,
                    });
                    sum += *sat;
                }
            }
            if sum == *need {
                v.sort_by(|a, b| a.lot.cmp(&b.lot));
                subs.push(v);
            }
        }
        per.push(subs);
    }
    let mut assigns: Vec<BTreeMap<EventId, Vec<LotPick>>> = vec![BTreeMap::new()];
    for (di, subs) in per.iter().enumerate() {
        let id = &per_disposal[di].0;
        let mut next = Vec::new();
        for a in &assigns {
            for s in subs {
                let mut a2 = a.clone();
                a2.insert(id.clone(), s.clone());
                next.push(a2);
            }
        }
        assigns = next;
    }
    let mut best: Option<Usd> = None;
    for a in &assigns {
        if let TaxOutcome::Computed(r) =
            score_assignment(events, prices, config, year, prof, tables, a)
        {
            let t = r.total_federal_tax_attributable;
            best = Some(best.map_or(t, |b| b.min(t)));
        }
    }
    best.expect("oracle: at least one feasible assignment")
}

// ── (a) HIFO-beats-FIFO ────────────────────────────────────────────────────────────────────────────

/// One wallet, two long-term lots (low-basis old, high-basis newer), one all-LT sell. FIFO baseline picks
/// the low-basis lot (max gain); the optimum picks the high-basis lot. Both LT → pure basis minimisation.
#[test]
fn hifo_beats_fifo_matches_oracle() {
    let events = vec![
        // [reconcile-defaults] pin the BASELINE to FIFO (default is now HIFO) so this FIFO-vs-HIFO KAT holds.
        method_election(1, datetime!(2025-01-01 00:00:00 UTC), LotMethod::Fifo),
        buy(
            "LB",
            datetime!(2025-01-02 00:00:00 UTC),
            cold(),
            LOT,
            dec!(1000),
        ),
        buy(
            "HB",
            datetime!(2025-02-02 00:00:00 UTC),
            cold(),
            LOT,
            dec!(5000),
        ),
        sell(
            "D",
            datetime!(2026-06-01 00:00:00 UTC),
            cold(),
            LOT,
            dec!(10000),
        ),
    ];
    let prices = StaticPrices::default();
    let tables = synth(2026);
    let prof = profile(dec!(100000));
    let p = optimize_year(
        &events,
        &prices,
        &cfg(),
        2026,
        Some(&prof),
        &tables,
        &no_attest(),
        made(),
    )
    .expect("computable");

    let oracle = oracle_min_total(
        &events,
        &prices,
        &cfg(),
        2026,
        Some(&prof),
        &tables,
        &[(eid("D"), vec![(lid("LB"), LOT), (lid("HB"), LOT)], LOT)],
    );
    assert_eq!(p.optimized_tax, oracle, "optimizer == independent oracle");
    assert_eq!(p.optimized_tax, dec!(750.00)); // $5,000 LT gain @ 15%
    assert_eq!(p.baseline_tax, dec!(1350.00)); // FIFO: $9,000 LT gain @ 15%
    assert!(p.optimized_tax < p.baseline_tax);
    assert!(p.delta <= dec!(0));
    assert_eq!(p.delta, dec!(-600.00));
    assert!(!p.approximate);
    assert_eq!(p.approx_reason, None);
    assert_eq!(p.per_disposal.len(), 1);
    assert_eq!(p.per_disposal[0].proposed_selection, vec![pick("HB", LOT)]);
    assert_eq!(p.per_disposal[0].current_selection, vec![pick("LB", LOT)]);
}

// ── (b) Rate-awareness: naive-HIFO LOSES to a long-term pick ─────────────────────────────────────────

/// A short-term HIGH-basis lot vs a long-term LOWER-basis lot, with the ordinary marginal rate (32%) far
/// above the 15% LT rate. Naive HIFO takes the ST high-basis lot (smaller gain, ordinary rate); the true
/// optimum takes the LT lot (slightly larger gain, 15%) for a STRICTLY lower total tax. Baseline is a HIFO
/// standing order, so the optimizer is shown overriding the in-force basis-greedy method.
#[test]
fn rate_aware_naive_hifo_loses_to_long_term() {
    let events = vec![
        method_election(1, datetime!(2025-01-01 00:00:00 UTC), LotMethod::Hifo),
        buy(
            "LT_LB",
            datetime!(2025-01-02 00:00:00 UTC),
            cold(),
            LOT,
            dec!(9000),
        ),
        buy(
            "ST_HB",
            datetime!(2026-05-01 00:00:00 UTC),
            cold(),
            LOT,
            dec!(9500),
        ),
        sell(
            "D",
            datetime!(2026-06-01 00:00:00 UTC),
            cold(),
            LOT,
            dec!(10000),
        ),
    ];
    let prices = StaticPrices::default();
    let tables = synth(2026);
    let prof = profile(dec!(100000));
    let p = optimize_year(
        &events,
        &prices,
        &cfg(),
        2026,
        Some(&prof),
        &tables,
        &no_attest(),
        made(),
    )
    .expect("computable");

    let oracle = oracle_min_total(
        &events,
        &prices,
        &cfg(),
        2026,
        Some(&prof),
        &tables,
        &[(
            eid("D"),
            vec![(lid("LT_LB"), LOT), (lid("ST_HB"), LOT)],
            LOT,
        )],
    );
    // The naive basis-greedy (all-HIFO) pick = the ST high-basis lot.
    let all_hifo = btreemap_assign(&[(eid("D"), vec![pick("ST_HB", LOT)])]);
    let TaxOutcome::Computed(hifo) = score_assignment(
        &events,
        &prices,
        &cfg(),
        2026,
        Some(&prof),
        &tables,
        &all_hifo,
    ) else {
        panic!("HIFO pick computable");
    };

    assert_eq!(p.optimized_tax, oracle, "optimizer == independent oracle");
    assert_eq!(p.optimized_tax, dec!(150.00)); // $1,000 LT gain @ 15%
    assert_eq!(hifo.total_federal_tax_attributable, dec!(160.00)); // $500 ST gain @ 32%
    assert!(
        p.optimized_tax < hifo.total_federal_tax_attributable,
        "rate-aware optimum strictly beats naive HIFO ({} !< {})",
        p.optimized_tax,
        hifo.total_federal_tax_attributable
    );
    assert_eq!(p.baseline_tax, dec!(160.00)); // HIFO standing order == naive-HIFO
    assert!(p.delta <= dec!(0));
    assert_eq!(
        p.per_disposal[0].proposed_selection,
        vec![pick("LT_LB", LOT)]
    );
    assert!(!p.approximate);
}

fn btreemap_assign(entries: &[(EventId, Vec<LotPick>)]) -> BTreeMap<EventId, Vec<LotPick>> {
    entries.iter().cloned().collect()
}

// ── (d) Loss-harvest within the $3k limit (R0-I3: assert only what the single-year objective pins) ───

/// A forced gain disposal (wallet `g`) + a wallet (`h`) holding loss lots of different magnitudes. The
/// single-year objective is carryforward-blind: once a pick offsets all gains AND takes the $3,000 §1211
/// cap, any EXTRA realized loss only grows the carryforward — the objective is identical. So "harvest
/// exactly enough" and "over-harvest" TIE; we assert ONLY (a) optimizer == oracle and < baseline, and
/// (b) the in-year `loss_deduction == $3,000` — NOT a carryforward split.
#[test]
fn loss_harvest_within_3k_limit() {
    let g = wallet("g");
    let h = wallet("h");
    let events = vec![
        // [reconcile-defaults] pin the BASELINE to FIFO (default is now HIFO) so the harvest beats it.
        method_election(1, datetime!(2025-01-01 00:00:00 UTC), LotMethod::Fifo),
        buy(
            "GLO",
            datetime!(2026-05-01 00:00:00 UTC),
            g.clone(),
            LOT,
            dec!(1000),
        ),
        // FIFO-first loss lot is INSUFFICIENT (only $4k loss); the better picks come later in time.
        buy(
            "HB3",
            datetime!(2026-05-01 00:00:00 UTC),
            h.clone(),
            LOT,
            dec!(5000),
        ),
        buy(
            "HB1",
            datetime!(2026-05-02 00:00:00 UTC),
            h.clone(),
            LOT,
            dec!(9000),
        ),
        buy(
            "HB2",
            datetime!(2026-05-03 00:00:00 UTC),
            h.clone(),
            LOT,
            dec!(11000),
        ),
        sell(
            "DG",
            datetime!(2026-06-01 00:00:00 UTC),
            g.clone(),
            LOT,
            dec!(6000),
        ), // +$5,000 ST gain
        sell(
            "DL",
            datetime!(2026-06-01 00:00:00 UTC),
            h.clone(),
            LOT,
            dec!(1000),
        ), // a loss lot
    ];
    let prices = StaticPrices::default();
    let tables = synth(2026);
    let prof = profile(dec!(100000));
    let p = optimize_year(
        &events,
        &prices,
        &cfg(),
        2026,
        Some(&prof),
        &tables,
        &no_attest(),
        made(),
    )
    .expect("computable");

    let oracle = oracle_min_total(
        &events,
        &prices,
        &cfg(),
        2026,
        Some(&prof),
        &tables,
        &[
            (eid("DG"), vec![(lid("GLO"), LOT)], LOT),
            (
                eid("DL"),
                vec![(lid("HB1"), LOT), (lid("HB2"), LOT), (lid("HB3"), LOT)],
                LOT,
            ),
        ],
    );
    assert_eq!(p.optimized_tax, oracle, "optimizer == independent oracle");
    assert!(
        p.optimized_tax < p.baseline_tax,
        "harvest beats the FIFO baseline"
    );
    assert!(p.delta < dec!(0));
    assert!(!p.approximate);

    // (b) the in-year loss_deduction is pinned at the $3,000 §1211 cap (gains fully offset + cap taken).
    let best = assignment_of(&p);
    let TaxOutcome::Computed(r) =
        score_assignment(&events, &prices, &cfg(), 2026, Some(&prof), &tables, &best)
    else {
        panic!("best assignment computable");
    };
    assert_eq!(r.loss_deduction, dec!(3000.00));
}

// ── Per-wallet constraint (§1.1012-1(j)) ─────────────────────────────────────────────────────────────

/// The globally cheapest lot lives in ANOTHER wallet; cross-account identification is forbidden, so the
/// optimum is the oracle restricted to the disposal's OWN wallet and the cross-wallet lot never appears.
#[test]
fn per_wallet_constraint_respected() {
    let hot = wallet("hot");
    let events = vec![
        // [reconcile-defaults] pin the BASELINE to FIFO (default is now HIFO) so FIFO baseline = CL_LOW.
        method_election(1, datetime!(2025-01-01 00:00:00 UTC), LotMethod::Fifo),
        buy(
            "CL_LOW",
            datetime!(2026-05-01 00:00:00 UTC),
            cold(),
            LOT,
            dec!(1000),
        ),
        buy(
            "CL_HIGH",
            datetime!(2026-05-02 00:00:00 UTC),
            cold(),
            LOT,
            dec!(8000),
        ),
        buy(
            "HL_SUPER",
            datetime!(2026-05-01 00:00:00 UTC),
            hot.clone(),
            LOT,
            dec!(9500),
        ),
        sell(
            "DC",
            datetime!(2026-06-01 00:00:00 UTC),
            cold(),
            LOT,
            dec!(10000),
        ),
    ];
    let prices = StaticPrices::default();
    let tables = synth(2026);
    let prof = profile(dec!(100000));
    let p = optimize_year(
        &events,
        &prices,
        &cfg(),
        2026,
        Some(&prof),
        &tables,
        &no_attest(),
        made(),
    )
    .expect("computable");

    // oracle restricted to cold's own wallet lots only.
    let oracle = oracle_min_total(
        &events,
        &prices,
        &cfg(),
        2026,
        Some(&prof),
        &tables,
        &[(
            eid("DC"),
            vec![(lid("CL_LOW"), LOT), (lid("CL_HIGH"), LOT)],
            LOT,
        )],
    );
    assert_eq!(p.optimized_tax, oracle);
    assert_eq!(p.optimized_tax, dec!(640.00)); // $2,000 ST gain @ 32%
    assert!(p.optimized_tax < p.baseline_tax); // FIFO baseline = CL_LOW ($9,000 gain)
    assert_eq!(
        p.per_disposal[0].proposed_selection,
        vec![pick("CL_HIGH", LOT)]
    );
    // the cross-wallet lot is NEVER selected.
    for d in &p.per_disposal {
        assert!(
            d.proposed_selection
                .iter()
                .all(|pk| pk.lot != lid("HL_SUPER")),
            "cross-wallet lot must never appear in a proposed selection"
        );
    }
    assert!(!p.approximate);
}

// ── (c) Contended same-wallet sells across an ST/LT crossover ────────────────────────────────────────

/// Two same-wallet sells D1 (earlier) and D2 (later) in 2026, with lot `P` ST at D1's date but LT at D2's.
/// Under the LIFO standing order the baseline puts `P` at D1 (ST/ordinary). The true optimum REASSIGNS
/// `P` to D2 (LT/15%) and `R` to D1 — a JOINT sequence the independent per-disposal product cannot reach.
/// Within `GROUP_COMBO_BOUND` the optimizer finds it and `approximate == false`; the oracle enumerates the
/// JOINT space and agrees.
#[test]
fn contended_st_lt_crossover_finds_joint_optimum() {
    let events = vec![
        method_election(1, datetime!(2025-01-01 00:00:00 UTC), LotMethod::Lifo),
        buy(
            "R",
            datetime!(2025-05-01 00:00:00 UTC),
            cold(),
            LOT,
            dec!(5000),
        ),
        buy(
            "P",
            datetime!(2025-06-15 00:00:00 UTC),
            cold(),
            LOT,
            dec!(5000),
        ),
        sell(
            "D1",
            datetime!(2026-06-01 00:00:00 UTC),
            cold(),
            LOT,
            dec!(10000),
        ),
        sell(
            "D2",
            datetime!(2026-06-20 00:00:00 UTC),
            cold(),
            LOT,
            dec!(10000),
        ),
    ];
    let prices = StaticPrices::default();
    let tables = synth(2026);
    let prof = profile(dec!(100000));
    let p = optimize_year(
        &events,
        &prices,
        &cfg(),
        2026,
        Some(&prof),
        &tables,
        &no_attest(),
        made(),
    )
    .expect("computable");

    // Oracle over the JOINT whole-lot space: both disposals may draw R or P (both acquired before both).
    let oracle = oracle_min_total(
        &events,
        &prices,
        &cfg(),
        2026,
        Some(&prof),
        &tables,
        &[
            (eid("D1"), vec![(lid("R"), LOT), (lid("P"), LOT)], LOT),
            (eid("D2"), vec![(lid("R"), LOT), (lid("P"), LOT)], LOT),
        ],
    );
    assert_eq!(p.optimized_tax, oracle, "optimizer == JOINT oracle");
    assert_eq!(p.optimized_tax, dec!(1500.00)); // both LT: $10,000 @ 15%
    assert_eq!(p.baseline_tax, dec!(2350.00)); // LIFO: $5k ST @ 32% + $5k LT @ 15% = $1,600 + $750
    assert!(
        p.optimized_tax < p.baseline_tax,
        "the joint reassignment beats the (best-independent) baseline"
    );
    assert!(p.delta <= dec!(0));
    assert!(!p.approximate, "contention jointly enumerated within bound");
    assert_eq!(p.approx_reason, None);
    // D1 took the LT lot R; D2 took P (LT at D2's date).
    let by: BTreeMap<&EventId, &Vec<LotPick>> = p
        .per_disposal
        .iter()
        .map(|d| (&d.disposal, &d.proposed_selection))
        .collect();
    assert_eq!(by[&eid("D1")], &vec![pick("R", LOT)]);
    assert_eq!(by[&eid("D2")], &vec![pick("P", LOT)]);
}

/// Variant forcing the contended group PAST `GROUP_COMBO_BOUND` (4 same-wallet sells over a 10-lot pool:
/// 10·9·8·7 = 5040 > 4096). The proposal is flagged `approximate = true, ContentionUnenumerated`, and the
/// baseline-seed still guarantees `delta ≤ 0`.
#[test]
fn contended_beyond_bound_flags_unenumerated() {
    let mut events: Vec<LedgerEvent> = (0..10)
        .map(|i| {
            buy(
                &format!("L{i:02}"),
                datetime!(2026-05-01 00:00:00 UTC),
                cold(),
                LOT,
                dec!(5000),
            )
        })
        .collect();
    for (k, d) in [
        datetime!(2026-06-01 00:00:00 UTC),
        datetime!(2026-06-02 00:00:00 UTC),
        datetime!(2026-06-03 00:00:00 UTC),
        datetime!(2026-06-04 00:00:00 UTC),
    ]
    .into_iter()
    .enumerate()
    {
        events.push(sell(&format!("D{k}"), d, cold(), LOT, dec!(10000)));
    }
    let prices = StaticPrices::default();
    let tables = synth(2026);
    let prof = profile(dec!(100000));
    let p = optimize_year(
        &events,
        &prices,
        &cfg(),
        2026,
        Some(&prof),
        &tables,
        &no_attest(),
        made(),
    )
    .expect("computable");

    assert!(p.approximate);
    match p.approx_reason {
        Some(ApproxReason::ContentionUnenumerated { contended, .. }) => {
            assert_eq!(contended, 4, "all four contended disposals counted");
        }
        other => panic!("expected ContentionUnenumerated, got {other:?}"),
    }
    assert!(p.delta <= dec!(0)); // equal-basis lots ⇒ delta == 0
}

// ── approximate honesty: ComboCapExceeded (coordinate-descent fallback) ──────────────────────────────

/// Two wallets, each a 5-of-10-lot sell: product = C(10,5)² = 252² = 63,504 > MAX_COMBOS → baseline-seeded
/// coordinate descent. `approximate = true, ComboCapExceeded`, and `delta ≤ 0`.
#[test]
fn combo_cap_exceeded_falls_back_baseline_seeded() {
    let a = wallet("a");
    let b = wallet("b");
    let mut events: Vec<LedgerEvent> = Vec::new();
    for i in 0..10 {
        events.push(buy(
            &format!("A{i:02}"),
            datetime!(2026-05-01 00:00:00 UTC),
            a.clone(),
            LOT,
            dec!(5000),
        ));
        events.push(buy(
            &format!("B{i:02}"),
            datetime!(2026-05-01 00:00:00 UTC),
            b.clone(),
            LOT,
            dec!(5000),
        ));
    }
    events.push(sell(
        "DA",
        datetime!(2026-06-01 00:00:00 UTC),
        a.clone(),
        5 * LOT,
        dec!(50000),
    ));
    events.push(sell(
        "DB",
        datetime!(2026-06-01 00:00:00 UTC),
        b.clone(),
        5 * LOT,
        dec!(50000),
    ));
    let prices = StaticPrices::default();
    let tables = synth(2026);
    let prof = profile(dec!(100000));
    let p = optimize_year(
        &events,
        &prices,
        &cfg(),
        2026,
        Some(&prof),
        &tables,
        &no_attest(),
        made(),
    )
    .expect("computable");

    assert!(p.approximate);
    assert_eq!(
        p.approx_reason,
        Some(ApproxReason::ComboCapExceeded {
            combos: 63_504,
            cap: 50_000
        })
    );
    assert!(p.delta <= dec!(0)); // equal-basis ⇒ delta == 0; never worse than baseline
}

// ── approximate honesty: PoolHeuristic (incomplete vertex subset) both ways ──────────────────────────

/// A single disposal over a `> LOT_ENUM_BOUND` (20-lot) pool: `candidate_selections` returns the heuristic
/// INCOMPLETE subset, so the overall product is small yet the result is NOT a proven global minimum.
/// `approximate = true, PoolHeuristic { lots: 20, bound: 12 }`, `delta ≤ 0`.
#[test]
fn pool_heuristic_disclosed_above_bound() {
    let mut events: Vec<LedgerEvent> = (0..20)
        .map(|i| {
            buy(
                &format!("L{i:02}"),
                datetime!(2026-05-01 00:00:00 UTC),
                cold(),
                LOT,
                dec!(5000),
            )
        })
        .collect();
    events.push(sell(
        "D",
        datetime!(2026-06-01 00:00:00 UTC),
        cold(),
        2 * LOT,
        dec!(20000),
    ));
    let prices = StaticPrices::default();
    let tables = synth(2026);
    let prof = profile(dec!(100000));
    let p = optimize_year(
        &events,
        &prices,
        &cfg(),
        2026,
        Some(&prof),
        &tables,
        &no_attest(),
        made(),
    )
    .expect("computable");

    assert!(p.approximate);
    assert_eq!(
        p.approx_reason,
        Some(ApproxReason::PoolHeuristic {
            lots: 20,
            bound: 12
        })
    );
    assert!(p.delta <= dec!(0));
}

/// Mirror: a `≤ LOT_ENUM_BOUND` (12-lot) pool with a small product → fully enumerated ⇒ proven global
/// minimum ⇒ `approximate == false, approx_reason == None`. Together with the above this pins
/// `approximate == false ⇔ fully-enumerated-global`.
#[test]
fn small_pool_is_not_approximate() {
    let mut events: Vec<LedgerEvent> = (0..12)
        .map(|i| {
            buy(
                &format!("L{i:02}"),
                datetime!(2026-05-01 00:00:00 UTC),
                cold(),
                LOT,
                dec!(5000),
            )
        })
        .collect();
    events.push(sell(
        "D",
        datetime!(2026-06-01 00:00:00 UTC),
        cold(),
        2 * LOT,
        dec!(20000),
    ));
    let prices = StaticPrices::default();
    let tables = synth(2026);
    let prof = profile(dec!(100000));
    let p = optimize_year(
        &events,
        &prices,
        &cfg(),
        2026,
        Some(&prof),
        &tables,
        &no_attest(),
        made(),
    )
    .expect("computable");

    assert!(!p.approximate);
    assert_eq!(p.approx_reason, None);
    assert!(p.delta <= dec!(0));
}

// ── refusals ─────────────────────────────────────────────────────────────────────────────────────

#[test]
fn refuses_pre_2025_year() {
    let events = vec![
        buy(
            "LB",
            datetime!(2025-01-02 00:00:00 UTC),
            cold(),
            LOT,
            dec!(1000),
        ),
        sell(
            "D",
            datetime!(2026-06-01 00:00:00 UTC),
            cold(),
            LOT,
            dec!(10000),
        ),
    ];
    let prices = StaticPrices::default();
    let tables = synth(2024);
    let prof = profile(dec!(100000));
    let err = optimize_year(
        &events,
        &prices,
        &cfg(),
        2024,
        Some(&prof),
        &tables,
        &no_attest(),
        made(),
    )
    .unwrap_err();
    assert_eq!(
        err,
        btctax_core::optimize::OptimizeError::PreTransitionYear(2024)
    );
}

#[test]
fn refuses_year_with_no_disposals() {
    let events = vec![buy(
        "LB",
        datetime!(2026-01-02 00:00:00 UTC),
        cold(),
        LOT,
        dec!(1000),
    )];
    let prices = StaticPrices::default();
    let tables = synth(2026);
    let prof = profile(dec!(100000));
    let err = optimize_year(
        &events,
        &prices,
        &cfg(),
        2026,
        Some(&prof),
        &tables,
        &no_attest(),
        made(),
    )
    .unwrap_err();
    assert_eq!(err, btctax_core::optimize::OptimizeError::NoDisposals);
}

#[test]
fn refuses_year_not_computable_missing_profile() {
    let events = vec![
        buy(
            "LB",
            datetime!(2025-01-02 00:00:00 UTC),
            cold(),
            LOT,
            dec!(1000),
        ),
        sell(
            "D",
            datetime!(2026-06-01 00:00:00 UTC),
            cold(),
            LOT,
            dec!(10000),
        ),
    ];
    let prices = StaticPrices::default();
    let tables = synth(2026);
    // No profile → B refuses (TaxProfileMissing, Hard) → optimizer returns YearNotComputable (I6).
    let err = optimize_year(
        &events,
        &prices,
        &cfg(),
        2026,
        None,
        &tables,
        &no_attest(),
        made(),
    )
    .unwrap_err();
    assert!(matches!(
        err,
        btctax_core::optimize::OptimizeError::YearNotComputable(_)
    ));
}

// ── determinism + tie-break ─────────────────────────────────────────────────────────────────────────

#[test]
fn optimize_year_is_deterministic() {
    let events = vec![
        buy(
            "LB",
            datetime!(2025-01-02 00:00:00 UTC),
            cold(),
            LOT,
            dec!(1000),
        ),
        buy(
            "HB",
            datetime!(2025-02-02 00:00:00 UTC),
            cold(),
            LOT,
            dec!(5000),
        ),
        sell(
            "D",
            datetime!(2026-06-01 00:00:00 UTC),
            cold(),
            LOT,
            dec!(10000),
        ),
    ];
    let prices = StaticPrices::default();
    let tables = synth(2026);
    let prof = profile(dec!(100000));
    let run = || {
        optimize_year(
            &events,
            &prices,
            &cfg(),
            2026,
            Some(&prof),
            &tables,
            &no_attest(),
            made(),
        )
        .unwrap()
    };
    assert_eq!(run(), run(), "byte-identical OptimizeProposal across calls");
}

/// All-equal-tax tie: two equal-basis lots, one sell. C-M1: STRICT-ONLY eviction keeps the baseline
/// → proposed == current at delta == 0 (no divergent pick, no churn).
/// FIFO baseline picks lot "A" (acquired 2025-01-02, earlier than "B" at 2025-02-02).
#[test]
fn tie_exact_baseline_kept_proposed_equals_current() {
    let events = vec![
        buy(
            "A",
            datetime!(2025-01-02 00:00:00 UTC),
            cold(),
            LOT,
            dec!(5000),
        ),
        buy(
            "B",
            datetime!(2025-02-02 00:00:00 UTC),
            cold(),
            LOT,
            dec!(5000),
        ),
        sell(
            "D",
            datetime!(2026-06-01 00:00:00 UTC),
            cold(),
            LOT,
            dec!(10000),
        ),
    ];
    let prices = StaticPrices::default();
    let tables = synth(2026);
    let prof = profile(dec!(100000));
    let p = optimize_year(
        &events,
        &prices,
        &cfg(),
        2026,
        Some(&prof),
        &tables,
        &no_attest(),
        made(),
    )
    .expect("computable");

    // Equal basis ⇒ identical tax ⇒ delta == 0. C-M1 strict-only tie-break: the baseline is kept
    // → proposed == current (no divergent pick, no churn). FIFO baseline picks lot "A" (acquired first).
    assert_eq!(p.delta, dec!(0));
    assert_eq!(
        p.per_disposal[0].proposed_selection, p.per_disposal[0].current_selection,
        "exact tie: baseline kept → proposed == current (no divergent pick)"
    );
    // For this fixture, FIFO picks "A" (earliest acquired); confirm the baseline selection is "A".
    assert_eq!(
        p.per_disposal[0].current_selection,
        vec![pick("A", LOT)],
        "FIFO baseline picks lot A (earlier acquisition date)"
    );
}

/// C-M1 regression: exact-tie tie-break KEEPS the baseline even when a lex-SMALLER non-baseline
/// candidate exists. Under the OLD `total == best_total && assign < best_assign` lex rule, the
/// lex-smaller candidate would EVICT the baseline → `proposed != current` at `delta == 0` (churn).
/// Under the NEW strict-only rule (`total < best_total`), the baseline is kept on every tie →
/// `proposed == current` → no churn, no `--attest` prompt, no needless divergent `LotSelection`.
///
/// Fixture: lot "B" acquired FIRST (2025-01-02) → FIFO picks "B" as baseline. Lot "A" acquired
/// second (2025-02-02) → lid("A") < lid("B") lex-wise (string "A" < "B"). Equal basis ⇒ tie on tax.
/// Old behavior: assign {D:[pick("A", ...)]} < assign {D:[pick("B", ...)]} on tie → proposed="A" ≠ current="B".
/// New behavior: strict only → baseline {D:[pick("B", ...)]} kept → proposed == current == [pick("B", ...)].
#[test]
fn tie_exact_baseline_kept_when_lex_smaller_is_not_baseline() {
    // "B" is the FIFO-first lot (earlier acquired); "A" is lex-smaller (lid("A") < lid("B")).
    let events = vec![
        buy(
            "B", // acquired first → FIFO baseline picks "B"
            datetime!(2025-01-02 00:00:00 UTC),
            cold(),
            LOT,
            dec!(5000), // equal basis
        ),
        buy(
            "A", // acquired second, lex-smaller (lid("A") < lid("B"))
            datetime!(2025-02-02 00:00:00 UTC),
            cold(),
            LOT,
            dec!(5000), // equal basis → same tax on either pick
        ),
        sell(
            "D",
            datetime!(2026-06-01 00:00:00 UTC),
            cold(),
            LOT,
            dec!(10000),
        ),
    ];
    let prices = StaticPrices::default();
    let tables = synth(2026);
    let prof = profile(dec!(100000));
    let p = optimize_year(
        &events,
        &prices,
        &cfg(),
        2026,
        Some(&prof),
        &tables,
        &no_attest(),
        made(),
    )
    .expect("computable");

    // Delta is exactly 0 (tied candidates — neither strictly improves).
    assert_eq!(p.delta, dec!(0), "delta must be 0 on an exact tie");
    // C-M1: baseline kept → proposed == current == [pick("B", ...)] (FIFO picks "B" first).
    assert_eq!(
        p.per_disposal[0].proposed_selection, p.per_disposal[0].current_selection,
        "C-M1: proposed must equal current on an exact tie (baseline kept, no churn)"
    );
    // Explicitly confirm the baseline is lot "B" (FIFO picks the earlier lot).
    assert_eq!(
        p.per_disposal[0].current_selection,
        vec![pick("B", LOT)],
        "FIFO baseline picks lot B (earlier acquisition date 2025-01-02)"
    );
    // Confirm lid("A") < lid("B") so the old lex rule WOULD have diverged (regression guard).
    assert!(
        lid("A") < lid("B"),
        "lot-id A must be lex-smaller than B for this to be a meaningful C-M1 regression KAT"
    );
}

// ── delta ≤ 0 invariant: multi-leg disposal where baseline == best ─────────────────────────────────

/// Regression KAT for the "pro-rata remainder-cent" delta perturbation on a multi-leg disposal whose
/// legs span ST and LT terms and where the optimizer's best == baseline_assignment.
///
/// **Root-cause:** `baseline_selection` sorts picks by lot-id. When `optimize_year` re-folded the
/// chosen `best` assignment to get `optimized_tax`, it injected those lot-id-sorted picks via
/// `fold_with` → `consume_picks`. `make_disposal_legs` allocated proceeds pro-rata in that lot-id
/// order — but the ORIGINAL baseline fold used FIFO temporal order. For this fixture the two orderings
/// differ (ST lot has an alphabetically earlier source_ref than the LT lot), so the half-cent rounding
/// remainder shifts between legs:
///
///   FIFO (baseline): Z_LT (LT, older) gets round_cents($10.03 / 2) = $5.02 (second decimal 1 is odd
///   → ROUND_HALF_EVEN rounds UP), A_ST gets remainder $5.01.
///   Gains: LT $0.05, ST $0.01. Tax: pref($0.05@15%) + ord-delta($0.01@32%) = $0.01 + $0.00 = $0.01.
///
///   Lot-id re-fold (A_ST < Z_LT, so A_ST first): A_ST gets $5.02, Z_LT gets $5.01.
///   Gains: ST $0.02, LT $0.04. Tax: pref($0.04@15%) + ord-delta($0.02@32%) = $0.01 + $0.01 = $0.02.
///
/// The only feasible selection for the disposal (needs 2 BTC, pool has exactly 1 BTC per lot) is to
/// take both lots, so the optimizer finds no improvement: best == baseline. The old re-fold then
/// produced `optimized_tax = $0.02 > baseline_tax = $0.01` → `delta = +$0.01`, violating "ALWAYS ≤ 0".
///
/// **Fix:** `optimized_tax` and `delta` now use the search's tracked `best_total` (baseline-seeded, ≤
/// baseline by construction) instead of the re-fold's total. For this fixture `best_total` = $0.01 =
/// `baseline_tax` and `delta` = $0.00 ≤ 0.
#[test]
fn multileg_stlt_prorata_rounding_delta_le_zero() {
    // A_ST (source_ref "A_ST"): acquired recently → short-term at disposal.
    // Z_LT (source_ref "Z_LT"): acquired >1 yr ago → long-term at disposal.
    // lot-id order: "A_ST" < "Z_LT" (A < Z) ≠ FIFO order (Z_LT older → FIFO first).
    let events = vec![
        buy(
            "Z_LT",
            datetime!(2024-01-02 00:00:00 UTC), // LT: >1 yr before disposal
            cold(),
            LOT,
            dec!(4.97), // basis $4.97 → FIFO gain $5.02 − $4.97 = $0.05 LT
        ),
        buy(
            "A_ST",
            datetime!(2026-05-01 00:00:00 UTC), // ST: <1 yr before disposal
            cold(),
            LOT,
            dec!(5.00), // basis $5.00 → FIFO remainder gain $5.01 − $5.00 = $0.01 ST
        ),
        sell(
            "DISP",
            datetime!(2026-06-01 00:00:00 UTC),
            cold(),
            2 * LOT, // consumes BOTH lots → only 1 feasible selection
            // $10.03: round_cents($10.03 / 2) = round_cents($5.015) = $5.02
            // (second decimal 1 is odd → ROUND_HALF_EVEN rounds UP)
            dec!(10.03),
        ),
    ];
    let prices = StaticPrices::default();
    let tables = synth(2026);
    // ordinary = $100k (32% marginal bracket per synth) → a $0.01 ST gain shift causes
    // ordinary_tax_on to round from $17000.0032 ($0.00 delta) to $17000.0064 ($0.01 delta).
    let prof = profile(dec!(100000));
    let p = optimize_year(
        &events,
        &prices,
        &cfg(),
        2026,
        Some(&prof),
        &tables,
        &no_attest(),
        made(),
    )
    .expect("computable");

    // (1) The only feasible selection is both lots → optimizer finds no improvement: baseline == best.
    assert_eq!(
        p.per_disposal[0].proposed_selection, p.per_disposal[0].current_selection,
        "baseline == best: no strictly better selection exists"
    );
    // (2) delta ≤ 0 holds exactly (was +$0.01 under the old re-fold approach).
    assert!(
        p.delta <= dec!(0),
        "delta must be ≤ 0; got {} (invariant violation — re-fold perturbation bug)",
        p.delta
    );
    // (3) With no improvement found, optimized_tax == baseline_tax and delta == 0.
    assert_eq!(
        p.delta,
        dec!(0),
        "no improvement possible → delta is exactly 0"
    );
    assert_eq!(
        p.optimized_tax, p.baseline_tax,
        "optimized_tax must equal baseline_tax when best == baseline"
    );
}