btctax-core 0.13.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
//! Full-return v1 **Form 8995** — the simplified §199A qualified-business-income deduction (SPEC §4.5).
//!
//! **Two QBI sources**, and the form adds their components:
//!   * the crypto **Schedule C trade or business** (Part I rows 1i–1v → lines 2/4/5), net of the
//!     §164(f) half-SE deduction. Added in P7, after the golden cross-check caught btctax handing a
//!     miner's 20% deduction back to the Treasury for nothing.
//!   * **§199A REIT/PTP dividends** (1099-DIV box 5 → lines 6/8/9).
//!
//! **Above the §199A(e)(2) threshold the simplified 8995 is unavailable** (the 8995-A phase-in is
//! unmodeled) — the caller REFUSES (`qbi_over_threshold`) rather than under-deduct. The REIT/PTP loss
//! carryforward (line 17) persists to next year (§4.5 write-back).
use crate::conventions::{round_dollar, Usd};
use crate::tax::tables::FullReturnParams;
use crate::tax::types::FilingStatus;
use rust_decimal_macros::dec;

/// §199A REIT/PTP-component rate (Form 8995 lines 9 & 14).
const QBI_RATE: Usd = dec!(0.20);

/// The simplified Form 8995 result: the QBI deduction (→ 1040 L13) + the REIT/PTP loss carryforward-out.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Qbi8995 {
    /// Form 8995 **line 15** → 1040 **L13** — the §199A qualified-business-income deduction (whole dollars).
    pub deduction: Usd,
    /// Form 8995 **line 17** — the qualified REIT-dividend / PTP-income LOSS carryforward to next year
    /// (a magnitude ≥ 0: the unused prior-year loss carryforward net of this year's REIT income).
    pub reit_ptp_carryforward_out: Usd,
}

/// Whether the return has ANY qualified business income: a crypto **Schedule C trade or business**, §199A
/// REIT dividends, or a prior-year REIT/PTP loss carryforward. When false there is no Form 8995 — no
/// deduction, and no above-threshold refuse.
pub fn has_qbi(business_qbi: Usd, reit_dividends: Usd, reit_ptp_carryforward_in: Usd) -> bool {
    business_qbi > Usd::ZERO || reit_dividends > Usd::ZERO || reit_ptp_carryforward_in > Usd::ZERO
}

/// Compute the simplified **Form 8995** QBI deduction (→ 1040 L13) — REIT/PTP path.
///
/// - `reit_dividends` = Σ 1099-DIV box 5 (§199A dividends), a magnitude ≥ 0.
/// - `reit_ptp_carryforward_in` = the prior-year REIT/PTP LOSS carryforward (magnitude ≥ 0; Form 8995
///   line 7 enters it as a loss, so it REDUCES line 8).
/// - `ti_before_qbi` = 1040 AGI − L12 (Form 8995 line 11).
/// - `net_capital_gain` = qualified dividends + net LTCG taxed at preferential rates (Form 8995 line 12).
///
/// The caller MUST have already refused when `ti_before_qbi` is above the §199A(e)(2) threshold with QBI
/// present ([`qbi_over_threshold`]) — the 8995-A phase-in is unmodeled.
pub fn compute_8995(
    business_qbi: Usd,
    reit_dividends: Usd,
    reit_ptp_carryforward_in: Usd,
    ti_before_qbi: Usd,
    net_capital_gain: Usd,
) -> Qbi8995 {
    // ── Lines 1–5 — the QUALIFIED BUSINESS component (the crypto Schedule C trade or business).
    //
    // ★ `business_qbi` is Schedule C's net profit REDUCED by the §164(f) deductible half of SE tax. The
    // Form 8995 instructions define QBI net of the deductible part of SE tax, self-employed health
    // insurance and self-employed retirement contributions — of which v1 models only the first (the other
    // two have no input). A crypto mining trade or business is a qualified trade or business (it is not an
    // SSTB), so its owner is entitled to this deduction, and omitting it OVERSTATED their tax by ~20% of
    // their business income. Found by the P7 independent-oracle cross-check.
    //
    // A Schedule C LOSS cannot reach here: it refuses upstream (`ScheduleCLoss`), so there is no negative
    // QBI and no QBI loss carryforward in v1 (Form 8995 lines 3 and 16 stay blank).
    let line5 = round_dollar(QBI_RATE * business_qbi.max(Usd::ZERO));

    // Line 8 — total qualified REIT dividends + PTP income (line 6 + line-7 loss, not below zero).
    let line8 = (reit_dividends - reit_ptp_carryforward_in).max(Usd::ZERO);
    // Line 9 — the REIT/PTP component = 20% of line 8.
    let line9 = round_dollar(QBI_RATE * line8);
    // Line 10 — the QBI deduction BEFORE the income limitation = line 5 + line 9. The two components ADD.
    let component = line5 + line9;
    // Line 13 — taxable income before QBI, less net capital gain (≥ 0).
    let line13 = (ti_before_qbi - net_capital_gain).max(Usd::ZERO);
    // Line 14 — income limit = 20% of line 13.
    let income_limit = round_dollar(QBI_RATE * line13);
    // Line 15 → 1040 L13 — the lesser of the component and the income limit.
    let deduction = component.min(income_limit);
    // Line 17 — the prior-year loss carryforward unused against this year's REIT income (magnitude).
    let reit_ptp_carryforward_out = (reit_ptp_carryforward_in - reit_dividends).max(Usd::ZERO);
    Qbi8995 {
        deduction,
        reit_ptp_carryforward_out,
    }
}

/// Whether QBI must be **refused**: there IS QBI (REIT dividends or a carryforward) AND the taxable
/// income before the QBI deduction exceeds the §199A(e)(2) threshold (at/below the threshold the
/// simplified Form 8995 applies; above it the 8995-A phase-in is required — unmodeled in v1, SPEC §4.5).
pub fn qbi_over_threshold(
    business_qbi: Usd,
    reit_dividends: Usd,
    reit_ptp_carryforward_in: Usd,
    ti_before_qbi: Usd,
    status: FilingStatus,
    params: &FullReturnParams,
) -> bool {
    // ★ Now that a Schedule C trade or business EARNS the deduction, it is also subject to the
    // §199A(e)(2) threshold: above it the simplified Form 8995 no longer applies (the W-2-wage / UBIA
    // limitations and the SSTB phase-in take over, which is Form 8995-A), and v1 REFUSES rather than
    // compute a deduction it cannot bound.
    has_qbi(business_qbi, reit_dividends, reit_ptp_carryforward_in)
        && ti_before_qbi > params.qbi_ti_threshold(status)
}

/// The printable **Form 8995 line chain** — whole dollars, cross-footing (SPEC §3.1). See
/// `other_taxes::Form8959Lines` for why the chain is derived in core and only transcribed by
/// `btctax-forms`.
///
/// **★ The Part I table (rows 1i–1v) carries the trade or business, and it MUST.** Line 2's own text is
/// "Total qualified business income or (loss). **Combine lines 1i through 1v, column (c)**" — a filed
/// form with a non-zero line 2 over an empty column totals nothing, and names no business for the
/// deduction it claims. v1 has exactly one trade or business (the crypto Schedule C), so row **1i**
/// carries it: (a) its description, (b) the filer's TIN (a sole proprietor's is their SSN — btctax has
/// no EIN input), (c) its QBI, which for one business IS line 2. [`Form8995Lines::business_name`] is
/// empty exactly when there is no Schedule C, and then the row stays blank and line 2 is zero.
///
/// Line 3 (a prior-year trade/business QBI loss carryforward) has no v1 input and stays blank: a
/// Schedule C LOSS refuses upstream, so v1 never carries one forward.
///
/// **★ Lines 3, 7, 16 and 17 are PARENTHESIZED boxes on the printed form: the parentheses supply the
/// minus sign, so the value written must be a POSITIVE MAGNITUDE.** Writing `-1234` renders as
/// `(-1,234)` — a positive number. Every one of these fields is a loss/carryforward, and every one is
/// stored here as a magnitude ≥ 0 for exactly that reason.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Form8995Lines {
    /// Part I row **1i column (a)** — the trade or business the deduction is claimed for. Empty exactly
    /// when there is no Schedule C, in which case the row stays blank and [`Self::line2`] is zero.
    ///
    /// Columns (b) and (c) of the row are NOT stored: (b) is the filer's SSN, which the form's identity
    /// header already carries, and (c) is `line2` itself — v1 has one business, so the column total IS
    /// the row. Storing them twice would let them disagree.
    pub business_name: String,
    /// L2 — total QBI from lines 1i–1v column (c) = the Schedule C profit net of the §164(f) half-SE
    /// deduction. Zero when there is no trade or business.
    pub line2: Usd,
    /// L4 — combine 2 and 3; if zero or less, `-0-`.
    pub line4: Usd,
    /// L5 — QBI component = 20% × line 4.
    pub line5: Usd,
    /// L6 — qualified REIT dividends + PTP income (Σ 1099-DIV box 5).
    pub line6: Usd,
    /// L7 — prior-year REIT/PTP **loss** carryforward. **Positive magnitude** (parenthesized box).
    pub line7: Usd,
    /// L8 — combine 6 and 7; if zero or less, `-0-`. (The line-7 loss REDUCES line 6.)
    pub line8: Usd,
    /// L9 — REIT/PTP component = 20% × line 8.
    pub line9: Usd,
    /// L10 — QBI deduction before the income limitation = line 5 + line 9.
    pub line10: Usd,
    /// L11 — taxable income before the QBI deduction (1040 AGI − L12).
    pub line11: Usd,
    /// L12 — net capital gain, increased by qualified dividends.
    pub line12: Usd,
    /// L13 — subtract 12 from 11; if zero or less, `-0-`.
    pub line13: Usd,
    /// L14 — income limitation = 20% × line 13.
    pub line14: Usd,
    /// L15 — the QBI deduction = the smaller of line 10 or line 14 → 1040 **L13**.
    pub line15: Usd,
    /// L16 — total qualified business (loss) carryforward = combine 2 and 3; if > 0, `-0-`. Always 0
    /// in v1. **Positive magnitude** (parenthesized box).
    pub line16: Usd,
    /// L17 — total REIT/PTP (loss) carryforward = combine 6 and 7; if > 0, `-0-`. Carries to next
    /// year. **Positive magnitude** (parenthesized box).
    pub line17: Usd,
}

/// Derive the printed Form 8995 chain from the same inputs as [`compute_8995`].
///
/// Returns `None` when there is no QBI at all ([`has_qbi`] is false) — no REIT dividends and no
/// prior-year carryforward means no Form 8995, no deduction, and nothing to carry forward.
///
/// The caller MUST already have refused when [`qbi_over_threshold`] (the 8995-A phase-in is
/// unmodeled), exactly as for [`compute_8995`].
///
/// Note the printed line 15 is `min(printed line 10, printed line 14)` — each rounded at its own
/// line — so it can differ by a dollar from `compute_8995`'s `deduction`, which rounds only the 20%
/// products. That is the SPEC §3.1 round-all-amounts election, not a defect: the printed form
/// cross-foots against itself, which is what gets filed.
pub fn form_8995_lines(
    business_name: &str,
    business_qbi: Usd,
    reit_dividends: Usd,
    reit_ptp_carryforward_in: Usd,
    ti_before_qbi: Usd,
    net_capital_gain: Usd,
) -> Option<Form8995Lines> {
    if !has_qbi(business_qbi, reit_dividends, reit_ptp_carryforward_in) {
        return None;
    }
    // Part I — the trade-or-business QBI (the crypto Schedule C), net of the §164(f) half-SE deduction.
    // Line 3 (prior-year QBI loss carryforward) stays BLANK: a Schedule C loss refuses upstream, so v1
    // never carries one.
    let line2 = round_dollar(business_qbi.max(Usd::ZERO));
    let line4 = line2;
    let line5 = round_dollar(QBI_RATE * line4);

    // Part I (cont.) — the REIT/PTP component. Line 7 is a positive magnitude that REDUCES line 6.
    let line6 = round_dollar(reit_dividends);
    let line7 = round_dollar(reit_ptp_carryforward_in);
    let line8 = (line6 - line7).max(Usd::ZERO);
    let line9 = round_dollar(QBI_RATE * line8);
    let line10 = line5 + line9;

    // Part II — the taxable-income limitation.
    let line11 = round_dollar(ti_before_qbi);
    let line12 = round_dollar(net_capital_gain);
    let line13 = (line11 - line12).max(Usd::ZERO);
    let line14 = round_dollar(QBI_RATE * line13);
    let line15 = line10.min(line14);

    // Carryforwards out. Both are magnitudes: the form's parentheses supply the sign.
    let line16 = Usd::ZERO; // combine 2 and 3 (= 0); "if greater than zero, enter -0-"
    let line17 = (line7 - line6).max(Usd::ZERO); // the prior-year loss unused against this year's REIT

    Some(Form8995Lines {
        // Row 1i(a). Blank when there is no trade or business — line 2 is then zero and the
        // form's column total has nothing to total.
        business_name: if business_qbi > Usd::ZERO {
            business_name.to_string()
        } else {
            String::new()
        },
        line2,
        line4,
        line5,
        line6,
        line7,
        line8,
        line9,
        line10,
        line11,
        line12,
        line13,
        line14,
        line15,
        line16,
        line17,
    })
}

#[cfg(test)]
mod tests {

    /// ★ **§199A on Schedule C — the deduction the P7 oracle proved we were giving away.**
    ///
    /// A crypto MINING trade or business is a qualified trade or business (not an SSTB), so its owner is
    /// entitled to a §199A deduction of 20% of QBI. btctax v1 originally computed the deduction for REIT
    /// dividends ONLY, silently overstating a miner's tax by ~20% of their business income. The PSL
    /// Tax-Calculator applies it; the golden cross-check exposed the gap; the user's call is to follow the
    /// law ("20% is way too much to give away for free").
    ///
    /// **QBI is the Schedule C net profit REDUCED by the §164(f) deductible half of SE tax** (Form 8995
    /// instructions: QBI is net of the deductible part of SE tax, SE health insurance and SE retirement
    /// contributions — of which v1 models only the first). The oracle independently confirms the rule:
    /// $60,000 profit − $4,239 half-SE = $55,761 of QBI ⇒ a $11,152 deduction, to the dollar.
    #[test]
    fn schedule_c_business_income_earns_the_199a_deduction_net_of_the_half_se_deduction() {
        // The deep/02 Ex.2 shape: $60k of mining, $40k of wages.
        let qbi = dec!(60000) - dec!(4239); // Sch C net − the §164(f) half-SE deduction
        let r = compute_8995(qbi, Usd::ZERO, Usd::ZERO, dec!(95761), Usd::ZERO);

        assert_eq!(
            r.deduction,
            dec!(11152),
            "20% × $55,761 of QBI — the figure the independent oracle computes"
        );
    }

    /// The §199A(b)(3) INCOME LIMITATION still binds: the deduction is the LESSER of 20% of QBI and 20% of
    /// (taxable income − net capital gain). A business owner whose taxable income is mostly preferential
    /// gain cannot deduct against income taxed at capital-gain rates.
    #[test]
    fn the_199a_deduction_is_capped_by_the_income_limitation() {
        // $50,000 of QBI (⇒ a $10,000 component), but only $12,000 of ordinary taxable income.
        let r = compute_8995(dec!(50000), Usd::ZERO, Usd::ZERO, dec!(60000), dec!(48000));

        // Line 13 = 60,000 − 48,000 = 12,000 ⇒ line 14 = 20% × 12,000 = 2,400 < the 10,000 component.
        assert_eq!(
            r.deduction,
            dec!(2400),
            "the income limitation binds — the deduction cannot exceed 20% of NON-preferential income"
        );
    }

    /// Both components ADD: a filer with a business AND REIT dividends gets 20% of each (Form 8995 line
    /// 10 = line 5 + line 9).
    #[test]
    fn the_business_and_reit_components_add() {
        let r = compute_8995(dec!(50000), dec!(10000), Usd::ZERO, dec!(200000), Usd::ZERO);
        assert_eq!(
            r.deduction,
            dec!(12000),
            "20% × 50,000 (business) + 20% × 10,000 (REIT) = 10,000 + 2,000"
        );
    }
    use super::*;
    use std::collections::BTreeMap;

    fn params() -> FullReturnParams {
        let mut std_deduction = BTreeMap::new();
        for s in [
            FilingStatus::Single,
            FilingStatus::Mfj,
            FilingStatus::Mfs,
            FilingStatus::HoH,
        ] {
            std_deduction.insert(s, dec!(14600));
        }
        FullReturnParams {
            year: 2024,
            std_deduction,
            std_aged_blind_married: dec!(1550),
            std_aged_blind_unmarried: dec!(1950),
            dependent_std_floor: dec!(1300),
            dependent_std_earned_addon: dec!(450),
            salt_cap: dec!(10000),
            kiddie_unearned_threshold: dec!(2600),
            elective_deferral_limit: dec!(23000),
            ftc_ceiling: dec!(300),
            qbi_ti_threshold_unmarried: dec!(191950),
            qbi_ti_threshold_married: dec!(383900),
            student_loan_phaseout_unmarried: (dec!(80000), dec!(95000)),
            student_loan_phaseout_married: (dec!(165000), dec!(195000)),
            amt: crate::tax::tables::AmtParams {
                exemption_single_hoh: dec!(85700),
                exemption_mfj_qss: dec!(133300),
                exemption_mfs: dec!(66650),
                phaseout_start_single_hoh_mfs: dec!(609350),
                phaseout_start_mfj_qss: dec!(1218700),
                breakpoint_28pct: dec!(232600),
                breakpoint_28pct_mfs: dec!(116300),
            },
        }
    }

    /// KAT-16 (QBI): REIT box5 × 20% when the income limit does NOT bind. $10,000 REIT dividends →
    /// line 9 = $2,000; income limit 20% × ($100,000 − $5,000 net cap gain) = $19,000 → L13 = $2,000.
    #[test]
    fn reit_component_when_income_limit_slack() {
        let r = compute_8995(
            Usd::ZERO, /* no business QBI */
            dec!(10000),
            Usd::ZERO,
            dec!(100000),
            dec!(5000),
        );
        assert_eq!(r.deduction, dec!(2000));
        assert_eq!(r.reit_ptp_carryforward_out, Usd::ZERO);
    }

    /// The TI-before-QBI income limit (line 14) binds when it is smaller than the REIT component.
    /// $10,000 REIT → component $2,000; TI-before-QBI $6,000, no net cap gain → limit 20%×6,000 = $1,200.
    #[test]
    fn income_limit_binds_below_component() {
        let r = compute_8995(
            Usd::ZERO, /* no business QBI */
            dec!(10000),
            Usd::ZERO,
            dec!(6000),
            Usd::ZERO,
        );
        assert_eq!(r.deduction, dec!(1200));
    }

    /// Net capital gain (qualified dividends + preferential LTCG) is SUBTRACTED from the income-limit
    /// base (line 13): a return that is all preferential income gets a $0 QBI income limit.
    #[test]
    fn net_capital_gain_reduces_the_income_limit() {
        // TI-before-QBI $50,000 all of which is net capital gain → line 13 = 0 → limit 0 → L13 = 0.
        let r = compute_8995(
            Usd::ZERO, /* no business QBI */
            dec!(10000),
            Usd::ZERO,
            dec!(50000),
            dec!(50000),
        );
        assert_eq!(r.deduction, Usd::ZERO);
    }

    /// A prior-year REIT/PTP loss carryforward reduces this year's line 8 and, if it exceeds this year's
    /// REIT income, produces a fresh loss carryforward-out (Form 8995 line 17, a magnitude).
    #[test]
    fn loss_carryforward_in_reduces_income_and_carries_out() {
        // $4,000 REIT − $10,000 prior loss → line 8 = 0 → deduction 0; $6,000 loss carries out.
        let r = compute_8995(
            Usd::ZERO, /* no business QBI */
            dec!(4000),
            dec!(10000),
            dec!(100000),
            Usd::ZERO,
        );
        assert_eq!(r.deduction, Usd::ZERO);
        assert_eq!(r.reit_ptp_carryforward_out, dec!(6000));
    }

    /// No REIT dividends and no carryforward ⇒ no QBI at all: no deduction, no carryforward, not "over".
    #[test]
    fn no_qbi_when_no_reit() {
        assert!(!has_qbi(Usd::ZERO, Usd::ZERO, Usd::ZERO));
        let r = compute_8995(
            Usd::ZERO, /* no business QBI */
            Usd::ZERO,
            Usd::ZERO,
            dec!(500000),
            Usd::ZERO,
        );
        assert_eq!(r.deduction, Usd::ZERO);
        assert_eq!(r.reit_ptp_carryforward_out, Usd::ZERO);
        // Even far above the threshold, no QBI ⇒ no refuse.
        assert!(!qbi_over_threshold(
            Usd::ZERO,
            Usd::ZERO,
            Usd::ZERO,
            dec!(500000),
            FilingStatus::Single,
            &params()
        ));
    }

    /// §199A(e)(2) refuse: with QBI present, TI-before-QBI ABOVE the threshold refuses (8995-A unmodeled);
    /// AT the threshold is fine (simplified 8995 applies). MFJ uses the doubled threshold; QSS the base.
    #[test]
    fn over_threshold_refuse_boundary() {
        let p = params();
        // Single: $191,951 > $191,950 → refuse; exactly $191,950 → OK.
        assert!(qbi_over_threshold(
            Usd::ZERO,
            dec!(1000),
            Usd::ZERO,
            dec!(191951),
            FilingStatus::Single,
            &p
        ));
        assert!(!qbi_over_threshold(
            Usd::ZERO,
            dec!(1000),
            Usd::ZERO,
            dec!(191950),
            FilingStatus::Single,
            &p
        ));
        // MFJ threshold is $383,900: $300,000 OK, $400,000 refuses.
        assert!(!qbi_over_threshold(
            Usd::ZERO,
            dec!(1000),
            Usd::ZERO,
            dec!(300000),
            FilingStatus::Mfj,
            &p
        ));
        assert!(qbi_over_threshold(
            Usd::ZERO,
            dec!(1000),
            Usd::ZERO,
            dec!(400000),
            FilingStatus::Mfj,
            &p
        ));
        // QSS is NOT a joint return → uses the $191,950 base (refuses at $300,000, unlike MFJ).
        assert!(qbi_over_threshold(
            Usd::ZERO,
            dec!(1000),
            Usd::ZERO,
            dec!(300000),
            FilingStatus::Qss,
            &p
        ));
        // A carryforward alone (no current REIT) is still QBI for the refuse trigger.
        assert!(qbi_over_threshold(
            Usd::ZERO,
            Usd::ZERO,
            dec!(5000),
            dec!(200000),
            FilingStatus::Single,
            &p
        ));
    }

    /// Printed Form 8995 lines are `round_dollar` (half-up): a $2,502.50 REIT component rounds the 20%
    /// line to $501 (not the round-half-even $500) — the printed-line rounding policy (SPEC §3.1).
    #[test]
    fn component_line_rounds_half_up() {
        let r = compute_8995(
            Usd::ZERO, /* no business QBI */
            dec!(2502.50),
            Usd::ZERO,
            dec!(100000),
            Usd::ZERO,
        );
        // 20% × 2,502.50 = 500.50 → half-up 501 (income limit 20% × 100,000 = 20,000 does not bind).
        assert_eq!(r.deduction, dec!(501));
    }

    /// The printed Form 8995 chain for the ordinary v1 case: REIT dividends, no carryforward, income
    /// limit not binding. Part I's table is blank and lines 2/4/5 print as zero.
    #[test]
    fn form_8995_printed_chain_reit_only() {
        // $10,000 REIT dividends; TI-before-QBI $100,000; net capital gain $20,000.
        // line 9 = 20% × 10,000 = 2,000. line 13 = 80,000 → line 14 = 16,000. line 15 = min = 2,000.
        let l = form_8995_lines(
            "",
            Usd::ZERO,
            dec!(10000),
            Usd::ZERO,
            dec!(100000),
            dec!(20000),
        )
        .unwrap();
        assert_eq!(l.line2, Usd::ZERO);
        assert_eq!(l.line4, Usd::ZERO);
        assert_eq!(l.line5, Usd::ZERO);
        assert_eq!(l.line6, dec!(10000));
        assert_eq!(l.line7, Usd::ZERO);
        assert_eq!(l.line8, dec!(10000));
        assert_eq!(l.line9, dec!(2000));
        assert_eq!(l.line10, dec!(2000));
        assert_eq!(l.line11, dec!(100000));
        assert_eq!(l.line12, dec!(20000));
        assert_eq!(l.line13, dec!(80000));
        assert_eq!(l.line14, dec!(16000));
        assert_eq!(l.line15, dec!(2000)); // the component binds, not the income limit
        assert_eq!(l.line16, Usd::ZERO);
        assert_eq!(l.line17, Usd::ZERO);
    }

    /// The income limitation binds: line 15 takes line 14, not line 10.
    #[test]
    fn form_8995_printed_chain_income_limit_binds() {
        // TI-before-QBI 12,000 all of which is capital gain → line 13 = 0 → line 14 = 0 → no deduction.
        let l = form_8995_lines(
            "",
            Usd::ZERO,
            dec!(10000),
            Usd::ZERO,
            dec!(12000),
            dec!(12000),
        )
        .unwrap();
        assert_eq!(l.line10, dec!(2000)); // the component is there…
        assert_eq!(l.line13, Usd::ZERO);
        assert_eq!(l.line14, Usd::ZERO);
        assert_eq!(l.line15, Usd::ZERO); // …but the income limit wipes it out
    }

    /// ★ **The parenthesized-box invariant.** Lines 3/7/16/17 are printed inside literal `(   )` on the
    /// form — the parentheses supply the minus sign — so the value must be a POSITIVE MAGNITUDE. A
    /// negative here renders as `(-1,234)`, i.e. a POSITIVE number on the filed form: a wrong return.
    /// A prior-year loss carryforward larger than this year's REIT income must therefore surface as a
    /// positive line 7 AND a positive line 17, never as a negative anything.
    #[test]
    fn form_8995_loss_carryforward_lines_are_positive_magnitudes() {
        // Prior-year REIT/PTP loss carryforward $15,000 against only $10,000 of REIT dividends.
        let l = form_8995_lines(
            "",
            Usd::ZERO,
            dec!(10000),
            dec!(15000),
            dec!(100000),
            Usd::ZERO,
        )
        .unwrap();
        assert_eq!(l.line6, dec!(10000));
        assert_eq!(l.line7, dec!(15000)); // POSITIVE magnitude, not −15,000
        assert_eq!(l.line8, Usd::ZERO); // 10,000 − 15,000, floored: no REIT income survives
        assert_eq!(l.line9, Usd::ZERO);
        assert_eq!(l.line15, Usd::ZERO); // no deduction this year
        assert_eq!(l.line17, dec!(5000)); // POSITIVE magnitude: 15,000 − 10,000 carries forward

        // Every parenthesized cell is non-negative, always. This is the invariant the filler relies on.
        for cell in [l.line7, l.line16, l.line17] {
            assert!(
                cell >= Usd::ZERO,
                "parenthesized cells are magnitudes: {cell}"
            );
        }
    }

    /// No REIT dividends and no carryforward ⇒ no Form 8995 at all.
    #[test]
    fn form_8995_absent_when_there_is_no_qbi() {
        assert!(
            form_8995_lines("", Usd::ZERO, Usd::ZERO, Usd::ZERO, dec!(100000), Usd::ZERO).is_none()
        );
        // …but a bare carryforward, with no REIT income this year, DOES produce the form (it must
        // carry the loss forward on line 17, or the carryforward is silently lost).
        let l = form_8995_lines(
            "",
            Usd::ZERO,
            Usd::ZERO,
            dec!(5000),
            dec!(100000),
            Usd::ZERO,
        )
        .unwrap();
        assert_eq!(l.line17, dec!(5000));
    }

    /// The printed chain cross-foots: every derived line re-derives from the OTHER printed cells.
    #[test]
    fn form_8995_printed_lines_cross_foot() {
        for (reit, cf_in, ti, ncg) in [
            (dec!(10000), Usd::ZERO, dec!(100000), dec!(20000)),
            (dec!(10000), dec!(15000), dec!(100000), Usd::ZERO),
            (dec!(2502.50), Usd::ZERO, dec!(80000.49), dec!(0.50)), // cents in, dollars out
            (dec!(10000), Usd::ZERO, dec!(12000), dec!(12000)),     // income limit binds
        ] {
            let l = form_8995_lines("", Usd::ZERO, reit, cf_in, ti, ncg).unwrap();
            assert_eq!(l.line4, l.line2, "L4 = 2 + 3 (3 blank)");
            assert_eq!(l.line5, round_dollar(QBI_RATE * l.line4), "L5 = 20% × 4");
            assert_eq!(
                l.line8,
                (l.line6 - l.line7).max(Usd::ZERO),
                "L8 = 6 + 7(loss), floored"
            );
            assert_eq!(l.line9, round_dollar(QBI_RATE * l.line8), "L9 = 20% × 8");
            assert_eq!(l.line10, l.line5 + l.line9, "L10 = 5 + 9");
            assert_eq!(
                l.line13,
                (l.line11 - l.line12).max(Usd::ZERO),
                "L13 = 11 − 12, floored"
            );
            assert_eq!(
                l.line14,
                round_dollar(QBI_RATE * l.line13),
                "L14 = 20% × 13"
            );
            assert_eq!(
                l.line15,
                l.line10.min(l.line14),
                "L15 = smaller of 10 or 14"
            );
            assert_eq!(
                l.line17,
                (l.line7 - l.line6).max(Usd::ZERO),
                "L17 = 6 + 7, if > 0 then -0-"
            );
            for cell in [
                l.line2, l.line4, l.line5, l.line6, l.line7, l.line8, l.line9, l.line10, l.line11,
                l.line12, l.line13, l.line14, l.line15, l.line16, l.line17,
            ] {
                assert_eq!(
                    cell.fract(),
                    Usd::ZERO,
                    "printed cells are whole dollars: {cell}"
                );
            }
        }
    }
}