rustledger_core/cost.rs
1//! Cost and cost specification types.
2//!
3//! A [`Cost`] represents the acquisition cost of a position (lot). It includes
4//! the per-unit cost, currency, optional acquisition date, and optional label.
5//!
6//! A [`CostSpec`] is used for matching against existing costs or specifying
7//! new costs when all fields may not be known.
8
9// rkyv's enum derive (used on `CostNumber` below) synthesizes a
10// per-variant `Archived*` struct whose generated `pub value` field
11// doesn't inherit the source variant's field doc. Item-level
12// `#[allow(missing_docs)]` doesn't propagate into the macro-emitted
13// sibling items, so the suppression must live at module scope.
14// Limited to the `rkyv` feature so hand-written items still get the
15// lint under non-rkyv builds; reviewers should check that any new
16// rkyv-archived type added to this file has docs on its source fields
17// (review A-3.2).
18#![cfg_attr(feature = "rkyv", allow(missing_docs))]
19
20use crate::NaiveDate;
21use rust_decimal::Decimal;
22use serde::{Deserialize, Serialize};
23use std::fmt;
24
25use crate::Amount;
26
27// Note: We no longer auto-quantize calculated values during cost storage.
28// Python beancount preserves full precision during booking and only rounds
29// at display time. Premature rounding of per-unit costs (e.g., from
30// total cost / units) causes cost basis errors when selling.
31// For example: 300.00 / 1.763 = 170.16505... should NOT be rounded to 170.17,
32// because 1.763 * 170.17 = 300.00971 ≠ 300.00.
33#[cfg(feature = "rkyv")]
34use crate::intern::{AsDecimal, AsNaiveDate};
35
36/// A cost represents the acquisition cost of a position (lot).
37///
38/// When you buy 10 shares of AAPL at $150 on 2024-01-15, the cost is:
39/// - number: 150
40/// - currency: "USD"
41/// - date: Some(2024-01-15)
42/// - label: None (or Some("lot1") if labeled)
43///
44/// # Examples
45///
46/// ```
47/// use rustledger_core::Cost;
48/// use rust_decimal_macros::dec;
49///
50/// let cost = Cost::new(dec!(150.00), "USD")
51/// .with_date(rustledger_core::naive_date(2024, 1, 15).unwrap());
52///
53/// assert_eq!(cost.number, dec!(150.00));
54/// assert_eq!(cost.currency, "USD");
55/// assert!(cost.date.is_some());
56/// ```
57#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
58#[cfg_attr(
59 feature = "rkyv",
60 derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)
61)]
62pub struct Cost {
63 /// Cost per unit
64 #[cfg_attr(feature = "rkyv", rkyv(with = AsDecimal))]
65 pub number: Decimal,
66 /// Currency of the cost
67 pub currency: crate::Currency,
68 /// Acquisition date (optional, for lot identification)
69 #[cfg_attr(feature = "rkyv", rkyv(with = rkyv::with::Map<AsNaiveDate>))]
70 pub date: Option<NaiveDate>,
71 /// Lot label (optional, for explicit lot identification)
72 pub label: Option<String>,
73}
74
75impl Cost {
76 /// Create a new cost with the given number and currency.
77 ///
78 /// Create a new cost with exact precision.
79 /// Use this for user-specified values that should preserve their precision.
80 #[must_use]
81 pub fn new(number: Decimal, currency: impl Into<crate::Currency>) -> Self {
82 Self {
83 number,
84 currency: currency.into(),
85 date: None,
86 label: None,
87 }
88 }
89
90 /// Create a new cost for calculated values.
91 ///
92 /// Previously this auto-quantized, but we now preserve full precision
93 /// to avoid cost basis errors. Rounding should only happen at display time.
94 #[must_use]
95 pub fn new_calculated(number: Decimal, currency: impl Into<crate::Currency>) -> Self {
96 Self::new(number, currency)
97 }
98
99 /// Add a date to this cost.
100 #[must_use]
101 pub const fn with_date(mut self, date: NaiveDate) -> Self {
102 self.date = Some(date);
103 self
104 }
105
106 /// Add an optional date to this cost.
107 #[must_use]
108 pub const fn with_date_opt(mut self, date: Option<NaiveDate>) -> Self {
109 self.date = date;
110 self
111 }
112
113 /// Add a label to this cost.
114 #[must_use]
115 pub fn with_label(mut self, label: impl Into<String>) -> Self {
116 self.label = Some(label.into());
117 self
118 }
119
120 /// Add an optional label to this cost.
121 #[must_use]
122 pub fn with_label_opt(mut self, label: Option<String>) -> Self {
123 self.label = label;
124 self
125 }
126
127 /// Get the cost as an amount.
128 #[must_use]
129 pub fn as_amount(&self) -> Amount {
130 Amount::new(self.number, self.currency.clone())
131 }
132
133 /// Calculate the total cost for a given number of units.
134 #[must_use]
135 pub fn total_cost(&self, units: Decimal) -> Amount {
136 Amount::new(units * self.number, self.currency.clone())
137 }
138}
139
140impl fmt::Display for Cost {
141 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
142 // Match Beancount's `Position.__str__` format: `{ 520 USD}` —
143 // single space after the opening brace, no space before the
144 // closing brace. The space matters for BQL-output compat: the
145 // compat harness diffs row-by-row against bean-query, and the
146 // pre-fix `{520 USD}` form accounted for ~137 of 510 file ×
147 // query mismatches. Verified against beanquery 0.2.0 + beancount
148 // 3.2.3 (matches what CI installs and what the dev shell now
149 // ships via the compat container — see PR #1047). Source-level
150 // `format_cost_spec` (used by `rledger format` to round-trip
151 // ledger files) keeps the no-space `{N CCY}` form because that
152 // matches Beancount's `print` command output, not its
153 // `Position.__str__`.
154 write!(f, "{{ {} {}", self.number, self.currency)?;
155 if let Some(date) = self.date {
156 write!(f, ", {date}")?;
157 }
158 if let Some(label) = &self.label {
159 // Escape via `format::escape_string` so labels containing
160 // `"`, `\`, or `\n` round-trip safely. Without this a label
161 // like `say "hi"` would render as `"say "hi""` — a parse
162 // error if anyone tried to feed it back to a Beancount-
163 // compatible reader.
164 write!(f, ", \"{}\"", crate::format::escape_string(label))?;
165 }
166 write!(f, "}}")
167 }
168}
169
170/// A cost specification for matching or creating costs.
171///
172/// Unlike [`Cost`], all fields are optional to allow partial matching.
173/// This is used in postings where the user may specify only some
174/// cost components (e.g., just the date to match a specific lot).
175///
176/// # Matching Rules
177///
178/// A `CostSpec` matches a `Cost` if all specified fields match:
179/// - If `number` is `Some`, it must equal the cost's number
180/// - If `currency` is `Some`, it must equal the cost's currency
181/// - If `date` is `Some`, it must equal the cost's date
182/// - If `label` is `Some`, it must equal the cost's label
183///
184/// # Examples
185///
186/// ```
187/// use rustledger_core::{Cost, CostSpec};
188/// use rust_decimal_macros::dec;
189///
190/// let cost = Cost::new(dec!(150.00), "USD")
191/// .with_date(rustledger_core::naive_date(2024, 1, 15).unwrap());
192///
193/// // Match by date only
194/// let spec = CostSpec::default().with_date(rustledger_core::naive_date(2024, 1, 15).unwrap());
195/// assert!(spec.matches(&cost));
196///
197/// // Match by wrong date
198/// let spec2 = CostSpec::default().with_date(rustledger_core::naive_date(2024, 1, 16).unwrap());
199/// assert!(!spec2.matches(&cost));
200/// ```
201/// The numeric component of a [`CostSpec`].
202///
203/// Beancount cost specs name a number in one of two source-level
204/// shapes:
205///
206/// - `{150.00 USD}` — per-unit cost ([`Self::PerUnit`])
207/// - `{{ 1500.00 USD }}` — total cost for the posting's units
208/// ([`Self::Total`])
209///
210/// During booking the engine converts `Total(t)` into a third state,
211/// [`Self::PerUnitFromTotal`], carrying both the derived per-unit
212/// value (for display, lot tracking) and the original total (for
213/// precision-preserving residual math — division-then-multiplication
214/// loses precision at the `rust_decimal` 28-digit ceiling).
215///
216/// A cost spec without a number at all (e.g. `{}` for a booking-
217/// deferred lot match) is represented by `CostSpec.number: None`.
218///
219/// Pre-#1164 the per-unit and total numbers were two independent
220/// `Option<Decimal>` fields on `CostSpec`. The invalid both-set state
221/// was prevented only by parser discipline and downstream defensive
222/// branches; the "booked from total" state was modeled accidentally
223/// by setting both fields, with the meaning encoded only in code
224/// comments. Folding the axes into one enum makes both the
225/// pre-booking invalid state unrepresentable AND the post-booking
226/// derived state explicit.
227#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
228#[cfg_attr(
229 feature = "rkyv",
230 derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)
231)]
232// Serde uses the `kind`-tagged internal representation so this enum
233// matches the wire shape used by FFI-WASI, WASM, Python compat, and
234// plugin-types. Pre-tag, serde defaulted to the external-tag form
235// (`{"PerUnit": "100"}`) which diverged from those boundaries —
236// downstream clients had to know which surface they were talking to.
237// (Module-level `allow(missing_docs)` at the top of this file
238// silences the rkyv-generated archived-struct field doc warnings —
239// see the file header comment.)
240#[serde(tag = "kind", rename_all = "snake_case")]
241pub enum CostNumber {
242 /// Per-unit cost as written: `{150.00 USD}`. Booking leaves this
243 /// shape unchanged.
244 PerUnit {
245 /// Per-unit value.
246 #[cfg_attr(feature = "rkyv", rkyv(with = AsDecimal))]
247 value: Decimal,
248 },
249 /// Total cost as written: `{{ 1500.00 USD }}`. Booking rewrites
250 /// this to [`Self::PerUnitFromTotal`] once units are known.
251 Total {
252 /// Total value.
253 #[cfg_attr(feature = "rkyv", rkyv(with = AsDecimal))]
254 value: Decimal,
255 },
256 /// Post-booking state: a per-unit value derived from a
257 /// `{{ total USD }}` spec at booking time, with the source total
258 /// preserved for exact residual math. Pre-#1164 this was modeled
259 /// implicitly by setting both `number_per` and `number_total` on
260 /// `CostSpec`. The payload is a separate [`BookedCost`] struct
261 /// so the booking-time invariant lives on a named type with
262 /// constructor methods that enforce it.
263 PerUnitFromTotal(BookedCost),
264}
265
266/// Payload of [`CostNumber::PerUnitFromTotal`].
267///
268/// Carries both the per-unit value derived at booking time and the
269/// original `{{ total }}` cost so residual math can use the exact
270/// total (avoiding the division-then-multiplication precision loss
271/// that hits the `rust_decimal` 28-digit ceiling on long ledgers).
272#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
273#[cfg_attr(
274 feature = "rkyv",
275 derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)
276)]
277pub struct BookedCost {
278 /// Per-unit cost, derived as `total / |units|` during booking.
279 /// Used by lot tracking, display (Python-compat post-booking
280 /// per-unit form), and validation reads that want a per-unit
281 /// value.
282 #[cfg_attr(feature = "rkyv", rkyv(with = AsDecimal))]
283 pub per_unit: Decimal,
284 /// Original total as written. Used by residual calculation to
285 /// avoid the division-then-multiplication precision loss that
286 /// would otherwise leak into balance checks.
287 #[cfg_attr(feature = "rkyv", rkyv(with = AsDecimal))]
288 pub total: Decimal,
289}
290
291/// Diagnostic for a failed [`BookedCost`] consistency check.
292///
293/// Returned by [`BookedCost::try_new`] in three cases:
294/// - **Mismatch**: `per_unit * |units|` doesn't agree with `total` to
295/// within the `rust_decimal` rounding floor.
296/// - **Zero units**: every `per_unit` "works" by zero-multiplication
297/// so the invariant carries no information; the post-booking shape
298/// is structurally meaningless without units.
299/// - **Overflow**: `per_unit * |units|` would exceed `Decimal::MAX`
300/// (~7.92e28). Both operands fit in `Decimal` individually but their
301/// product doesn't. A wire client can reach this with extreme
302/// inputs; surfacing it as a typed error keeps the host from
303/// panicking on multiplication.
304///
305/// Carries the inputs and (for the mismatch case) the computed
306/// residual so trust-boundary callers can surface a meaningful error
307/// to the originating plugin or wire client ("you sent
308/// `per_unit=50, total=999` with `units=10`; derived total would be
309/// 500, off by 499 — far outside tolerance 1e-20"). Mapping this to a
310/// `ConversionError` variant gives plugin authors a typed category
311/// for the failure instead of conflating with `InvalidNumber` (parse
312/// failure).
313#[derive(Debug, Clone, Copy, PartialEq, Eq)]
314pub struct BookedCostInvariantError {
315 /// The per-unit value the caller supplied.
316 pub per_unit: Decimal,
317 /// The total value the caller supplied.
318 pub total: Decimal,
319 /// The units value the caller supplied (caller-side sign retained
320 /// so error messages can show what came in).
321 pub units: Decimal,
322 /// `per_unit * |units|`, the value we'd expect `total` to equal.
323 /// `Decimal::ZERO` when the multiplication couldn't be performed
324 /// (zero units, or overflow — see [`Self::overflow`]).
325 pub derived_total: Decimal,
326 /// `|derived_total - total|`, the magnitude of the violation.
327 /// `Decimal::ZERO` for the zero-units and overflow cases.
328 pub abs_diff: Decimal,
329 /// The tolerance threshold we tested against. `None` when units
330 /// was zero or the multiplication overflowed — see
331 /// [`Self::overflow`] to distinguish the two.
332 pub tolerance: Option<Decimal>,
333 /// `true` when `per_unit * |units|` overflowed `Decimal::MAX`
334 /// (~7.92e28). Distinguishes the overflow case from the zero-units
335 /// case, since both leave `tolerance: None`.
336 pub overflow: bool,
337}
338
339impl fmt::Display for BookedCostInvariantError {
340 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
341 if self.overflow {
342 return write!(
343 f,
344 "BookedCost invariant check overflowed Decimal precision: per_unit ({}) * |units| ({}) exceeds Decimal::MAX (~7.92e28)",
345 self.per_unit,
346 self.units.abs(),
347 );
348 }
349 match self.tolerance {
350 Some(tol) => write!(
351 f,
352 "BookedCost invariant violated: per_unit ({}) * |units| ({}) = {} ≠ total ({}); abs_diff {} exceeds tolerance {}",
353 self.per_unit,
354 self.units.abs(),
355 self.derived_total,
356 self.total,
357 self.abs_diff,
358 tol,
359 ),
360 None => write!(
361 f,
362 "BookedCost requires non-zero units; got per_unit ({}), total ({}), units (0)",
363 self.per_unit, self.total,
364 ),
365 }
366 }
367}
368
369impl std::error::Error for BookedCostInvariantError {}
370
371impl BookedCost {
372 /// Check `per_unit * |units| ≈ total` to within `rust_decimal`
373 /// rounding tolerance, returning the diagnostic on failure.
374 ///
375 /// The booker derives `per_unit = total / |units|` at 28 significant
376 /// digits; back-multiplying truncates similarly. The residual can
377 /// reach a few ULP, which scales with `|total|`. Tolerance is
378 /// `max(1e-20, |total| * 1e-24)` — `1e-24` is ~10000x larger than
379 /// one ULP for typical magnitudes, while the absolute floor
380 /// guarantees a sane window for near-zero totals.
381 ///
382 /// **`units == 0` is rejected**: the post-booking shape implies the
383 /// booker derived `per_unit` from `total / |units|`, which is
384 /// undefined for zero units. A zero-units `PerUnitFromTotal` is
385 /// structurally meaningless and the caller should use the raw
386 /// `PerUnit` / `Total` variants. Pre-fix the zero-units case
387 /// short-circuited to `true`, which defeated the trust-boundary
388 /// guard at every input bridge (review B-3.1).
389 fn check_invariant(
390 per_unit: Decimal,
391 total: Decimal,
392 units: Decimal,
393 ) -> Result<(), BookedCostInvariantError> {
394 let units_abs = units.abs();
395 if units_abs.is_zero() {
396 return Err(BookedCostInvariantError {
397 per_unit,
398 total,
399 units,
400 derived_total: Decimal::ZERO,
401 abs_diff: Decimal::ZERO,
402 tolerance: None,
403 overflow: false,
404 });
405 }
406 // `per_unit` and `units_abs` each fit in `Decimal` individually
407 // (they came through `from_str_exact` or were constructed by
408 // the booker from values that did), but their product can
409 // exceed `Decimal::MAX` (~7.92e28). `Decimal::mul` panics on
410 // overflow — at a trust boundary that would crash the host
411 // from wire input, defeating `try_new`'s typed-error contract.
412 // Surface overflow as a typed error instead.
413 let Some(derived_total) = per_unit.checked_mul(units_abs) else {
414 return Err(BookedCostInvariantError {
415 per_unit,
416 total,
417 units,
418 derived_total: Decimal::ZERO,
419 abs_diff: Decimal::ZERO,
420 tolerance: None,
421 overflow: true,
422 });
423 };
424 let abs_diff = (derived_total - total).abs();
425 // `total.abs() * 1e-24` cannot overflow: `Decimal::MAX` is
426 // ~7.92e28, so the product is bounded by ~7.92e4. The relative
427 // tolerance scales with the magnitude of `total`; the absolute
428 // floor (`1e-20`) keeps the window sane for near-zero totals.
429 let relative = total.abs() * Decimal::new(1, 24);
430 let tolerance = if relative > Decimal::new(1, 20) {
431 relative
432 } else {
433 Decimal::new(1, 20)
434 };
435 if abs_diff <= tolerance {
436 Ok(())
437 } else {
438 Err(BookedCostInvariantError {
439 per_unit,
440 total,
441 units,
442 derived_total,
443 abs_diff,
444 tolerance: Some(tolerance),
445 overflow: false,
446 })
447 }
448 }
449
450 /// Construct from booking with a precision invariant check.
451 ///
452 /// In debug builds, asserts that `per_unit * |units| ≈ total` to
453 /// the limits of `rust_decimal` precision (tolerance:
454 /// `max(1e-20, |total| * 1e-24)`, derived from the booker's
455 /// `total / |units|` divisor truncating at 28 significant digits;
456 /// see the private `check_invariant` helper for the exact
457 /// computation). Callers are the booker (which derives
458 /// `per_unit = total / |units|`) and the plugin / FFI ingress
459 /// bridges (which must validate consistency before constructing).
460 ///
461 /// # Panics
462 ///
463 /// In debug builds: if the invariant fails. Release builds skip
464 /// the check (but trust-boundary callers should use
465 /// [`Self::try_new`] for runtime validation in release too).
466 #[must_use]
467 pub fn new(per_unit: Decimal, total: Decimal, units: Decimal) -> Self {
468 debug_assert!(
469 Self::check_invariant(per_unit, total, units).is_ok(),
470 "{}",
471 Self::check_invariant(per_unit, total, units).unwrap_err(),
472 );
473 Self { per_unit, total }
474 }
475
476 /// Try to construct, returning a typed error if the consistency
477 /// invariant fails. Use this at trust boundaries (FFI input,
478 /// plugin egress) where the caller may have supplied inconsistent
479 /// values and you want to reject rather than panic in debug or
480 /// accept silently in release.
481 ///
482 /// # Errors
483 ///
484 /// Returns [`BookedCostInvariantError`] when:
485 /// - `units == 0` (the post-booking shape is structurally
486 /// undefined for zero units; callers should send `PerUnit` or
487 /// `Total` instead).
488 /// - `per_unit * |units|` differs from `total` by more than
489 /// `max(1e-20, |total| * 1e-24)`.
490 pub fn try_new(
491 per_unit: Decimal,
492 total: Decimal,
493 units: Decimal,
494 ) -> Result<Self, BookedCostInvariantError> {
495 Self::check_invariant(per_unit, total, units)?;
496 Ok(Self { per_unit, total })
497 }
498
499 /// Construct from rkyv archive bytes the host itself wrote.
500 ///
501 /// Bypasses the consistency invariant because rkyv archives carry
502 /// no units at the deserialization site, and the host invariant
503 /// was already enforced when the bytes were written. **Do not
504 /// call from boundary code** — every FFI / plugin / parser
505 /// ingress must go through [`Self::try_new`] (which surfaces a
506 /// typed error) so inconsistent pairs cannot enter the host.
507 ///
508 /// The name reflects the trust assumption: the caller has
509 /// verified (via cache-version checks, archive integrity, etc.)
510 /// that the bytes were produced by this host's own booker.
511 #[doc(hidden)]
512 #[must_use]
513 pub const fn from_archive_bytes_trusted(per_unit: Decimal, total: Decimal) -> Self {
514 Self { per_unit, total }
515 }
516
517 /// Construct an *intentionally inconsistent* `BookedCost` for
518 /// fuzzing trust-boundary code that must reject such inputs.
519 ///
520 /// Separate from [`Self::from_archive_bytes_trusted`] so the
521 /// "trusted" name doesn't lie at fuzz call sites — the fuzzer
522 /// explicitly generates pathological inputs. Gated behind the
523 /// `fuzz` Cargo feature so normal builds can't reach it (review
524 /// A-4.4); fuzz targets and integration tests that want to
525 /// stress trust-boundary code in convert bridges must opt in via
526 /// `features = ["fuzz"]` on their `rustledger-core` dep.
527 #[cfg(any(feature = "fuzz", test))]
528 #[doc(hidden)]
529 #[must_use]
530 pub const fn from_fuzz_unchecked(per_unit: Decimal, total: Decimal) -> Self {
531 Self { per_unit, total }
532 }
533}
534
535impl CostNumber {
536 /// Return the per-unit value if this number carries one.
537 ///
538 /// - [`Self::PerUnit`] → `Some(its Decimal)`
539 /// - [`Self::PerUnitFromTotal`] → `Some(per_unit)`
540 /// - [`Self::Total`] → `None` (booking hasn't computed per-unit yet)
541 #[must_use]
542 pub const fn per_unit(&self) -> Option<Decimal> {
543 match self {
544 Self::PerUnit { value } => Some(*value),
545 Self::PerUnitFromTotal(b) => Some(b.per_unit),
546 Self::Total { .. } => None,
547 }
548 }
549
550 /// Return the total value if this number carries one.
551 ///
552 /// - [`Self::Total`] → `Some(its Decimal)`
553 /// - [`Self::PerUnitFromTotal`] → `Some(total)`
554 /// - [`Self::PerUnit`] → `None`
555 #[must_use]
556 pub const fn total(&self) -> Option<Decimal> {
557 match self {
558 Self::Total { value } => Some(*value),
559 Self::PerUnitFromTotal(b) => Some(b.total),
560 Self::PerUnit { .. } => None,
561 }
562 }
563}
564
565/// A cost specification on a posting (`{...}` or `{{...}}`).
566///
567/// Carries the parsed cost-spec axes: the numeric component (per-unit
568/// vs total, modeled as the mutually-exclusive [`CostNumber`] enum),
569/// currency, lot date, label, and merge flag. Any subset may be
570/// missing — `{}` corresponds to all-fields-`None` plus `merge: false`,
571/// which lets the booker do lot matching deferred to inventory.
572///
573/// Pre-#1164 this struct had two independent `Option<Decimal>` fields
574/// (`number_per`, `number_total`). The mutual-exclusion invariant was
575/// enforced only by parser discipline; the post-booking "derived per-
576/// unit from total" state was modeled accidentally by setting both
577/// fields at once. The new shape (`number: Option<CostNumber>`) makes
578/// the invalid state unrepresentable and the derived state explicit.
579#[derive(Debug, Clone, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
580#[cfg_attr(
581 feature = "rkyv",
582 derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)
583)]
584pub struct CostSpec {
585 /// The numeric component: per-unit, total, or absent.
586 ///
587 /// Replaces the pre-#1164 `number_per` / `number_total` pair, which
588 /// allowed the invalid both-set state at the type level. See
589 /// [`CostNumber`] for the per-unit vs total distinction.
590 pub number: Option<CostNumber>,
591 /// Currency of the cost (if specified)
592 pub currency: Option<crate::Currency>,
593 /// Acquisition date (if specified)
594 #[cfg_attr(feature = "rkyv", rkyv(with = rkyv::with::Map<AsNaiveDate>))]
595 pub date: Option<NaiveDate>,
596 /// Lot label (if specified)
597 pub label: Option<String>,
598 /// Whether to merge with existing lot (average cost)
599 pub merge: bool,
600}
601
602impl CostSpec {
603 /// Create an empty cost spec.
604 #[must_use]
605 pub fn empty() -> Self {
606 Self::default()
607 }
608
609 /// Set the cost number directly.
610 ///
611 /// The mutual exclusion between per-unit and total is enforced by
612 /// the [`CostNumber`] enum — there is no way to set both. Callers
613 /// construct the variant explicitly:
614 ///
615 /// ```ignore
616 /// CostSpec::empty().with_number(CostNumber::PerUnit { value: dec!(150) });
617 /// CostSpec::empty().with_number(CostNumber::Total { value: dec!(1500) });
618 /// ```
619 ///
620 /// Pre-#1164 this slot was a pair of `Option<Decimal>` fields;
621 /// pre-this-PR there were `with_per_unit` / `with_total`
622 /// convenience shims that perpetuated the two-axis mental model
623 /// in caller code and silently overwrote each other if both were
624 /// called. Both are gone — there's exactly one way to set a cost
625 /// number now.
626 #[must_use]
627 pub const fn with_number(mut self, number: CostNumber) -> Self {
628 self.number = Some(number);
629 self
630 }
631
632 /// Set the currency.
633 #[must_use]
634 pub fn with_currency(mut self, currency: impl Into<crate::Currency>) -> Self {
635 self.currency = Some(currency.into());
636 self
637 }
638
639 /// Set the date.
640 #[must_use]
641 pub const fn with_date(mut self, date: NaiveDate) -> Self {
642 self.date = Some(date);
643 self
644 }
645
646 /// Set the label.
647 #[must_use]
648 pub fn with_label(mut self, label: impl Into<String>) -> Self {
649 self.label = Some(label.into());
650 self
651 }
652
653 /// Set the merge flag (for average cost booking).
654 #[must_use]
655 pub const fn with_merge(mut self) -> Self {
656 self.merge = true;
657 self
658 }
659
660 /// Check if this is an empty cost spec (all fields None).
661 #[must_use]
662 pub const fn is_empty(&self) -> bool {
663 self.number.is_none()
664 && self.currency.is_none()
665 && self.date.is_none()
666 && self.label.is_none()
667 && !self.merge
668 }
669
670 /// Check if this cost spec matches a cost.
671 ///
672 /// All specified fields must match the corresponding cost fields.
673 /// Per-unit matching uses `CostNumber::per_unit()` — a `Total`-only
674 /// spec doesn't constrain the per-unit lot value (booking hasn't
675 /// resolved it yet), but a `PerUnitFromTotal` post-booking spec
676 /// does.
677 #[must_use]
678 pub fn matches(&self, cost: &Cost) -> bool {
679 // Check per-unit cost — constrains the lot whenever the spec
680 // carries a per-unit value (PerUnit or PerUnitFromTotal).
681 if let Some(n) = self.number.and_then(|cn| cn.per_unit())
682 && n != cost.number
683 {
684 return false;
685 }
686 // Check currency
687 if let Some(c) = &self.currency
688 && c != &cost.currency
689 {
690 return false;
691 }
692 // Check date
693 if let Some(d) = &self.date
694 && cost.date.as_ref() != Some(d)
695 {
696 return false;
697 }
698 // Check label
699 if let Some(l) = &self.label
700 && cost.label.as_ref() != Some(l)
701 {
702 return false;
703 }
704 true
705 }
706
707 /// Resolve this cost spec to a concrete cost, given the number of units.
708 ///
709 /// If the number is `CostNumber::Total`, the per-unit cost is
710 /// calculated as `total / |units|`. Full precision is preserved to
711 /// avoid cost basis errors when the position is later sold.
712 /// `PerUnitFromTotal` already carries the derived per-unit value
713 /// from a prior booking pass — using `b.per_unit` directly is
714 /// equivalent to recomputing `b.total / |units|` because
715 /// [`BookedCost::new`] enforces that invariant at construction.
716 ///
717 /// Returns `None` if required fields (currency, number) are missing.
718 #[must_use]
719 pub fn resolve(&self, units: Decimal, date: NaiveDate) -> Option<Cost> {
720 let currency = self.currency.clone()?;
721 let number = match self.number? {
722 // User-specified per-unit cost.
723 CostNumber::PerUnit { value: per } => per,
724 // Calculated from total — preserve full precision.
725 CostNumber::Total { value: total } => total / units.abs(),
726 // Already booked: `b.per_unit == b.total / |units|` by
727 // `BookedCost::new`'s invariant, so this is identical to
728 // the `Total` arm above but without the redivision.
729 CostNumber::PerUnitFromTotal(b) => b.per_unit,
730 };
731
732 Some(Cost {
733 number,
734 currency,
735 date: self.date.or(Some(date)),
736 label: self.label.clone(),
737 })
738 }
739}
740
741impl fmt::Display for CostSpec {
742 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
743 write!(f, "{{")?;
744 // Max 5 elements: number, currency, date, label, merge
745 let mut parts = Vec::with_capacity(5);
746
747 match self.number {
748 Some(CostNumber::PerUnit { value: n }) => parts.push(format!("{n}")),
749 Some(CostNumber::PerUnitFromTotal(b)) => parts.push(format!("{}", b.per_unit)),
750 Some(CostNumber::Total { value: n }) => parts.push(format!("# {n}")),
751 None => {}
752 }
753 if let Some(c) = &self.currency {
754 parts.push(c.to_string());
755 }
756 if let Some(d) = self.date {
757 parts.push(d.to_string());
758 }
759 if let Some(l) = &self.label {
760 parts.push(format!("\"{l}\""));
761 }
762 if self.merge {
763 parts.push("*".to_string());
764 }
765
766 write!(f, "{}", parts.join(", "))?;
767 write!(f, "}}")
768 }
769}
770
771#[cfg(test)]
772mod tests {
773 use super::*;
774 use rust_decimal_macros::dec;
775
776 fn date(year: i32, month: u32, day: u32) -> NaiveDate {
777 crate::naive_date(year, month, day).unwrap()
778 }
779
780 #[test]
781 fn test_cost_new() {
782 let cost = Cost::new(dec!(150.00), "USD");
783 assert_eq!(cost.number, dec!(150.00));
784 assert_eq!(cost.currency, "USD");
785 assert!(cost.date.is_none());
786 assert!(cost.label.is_none());
787 }
788
789 #[test]
790 fn test_cost_builder() {
791 let cost = Cost::new(dec!(150.00), "USD")
792 .with_date(date(2024, 1, 15))
793 .with_label("lot1");
794
795 assert_eq!(cost.date, Some(date(2024, 1, 15)));
796 assert_eq!(cost.label, Some("lot1".to_string()));
797 }
798
799 #[test]
800 fn test_cost_total() {
801 let cost = Cost::new(dec!(150.00), "USD");
802 let total = cost.total_cost(dec!(10));
803 assert_eq!(total.number, dec!(1500.00));
804 assert_eq!(total.currency, "USD");
805 }
806
807 #[test]
808 fn test_cost_display() {
809 let cost = Cost::new(dec!(150.00), "USD")
810 .with_date(date(2024, 1, 15))
811 .with_label("lot1");
812 let s = format!("{cost}");
813 assert!(s.contains("150.00"));
814 assert!(s.contains("USD"));
815 assert!(s.contains("2024-01-15"));
816 assert!(s.contains("lot1"));
817 }
818
819 /// Exact-format regression covering both fixes in this PR:
820 /// - leading space inside `{` (matches Beancount Position.__str__)
821 /// - special-character escaping in labels via `format::escape_string`
822 #[test]
823 fn test_cost_display_escapes_special_characters_in_label() {
824 // Bare per-unit cost — pin the leading-space form.
825 let bare = Cost::new(dec!(520), "USD");
826 assert_eq!(format!("{bare}"), "{ 520 USD}");
827
828 // With date.
829 let dated = Cost::new(dec!(520.00), "USD").with_date(date(2024, 1, 15));
830 assert_eq!(format!("{dated}"), "{ 520.00 USD, 2024-01-15}");
831
832 // Embedded double-quote.
833 let quoted = Cost::new(dec!(100.00), "USD")
834 .with_date(date(2024, 1, 15))
835 .with_label("say \"hi\"");
836 assert_eq!(
837 format!("{quoted}"),
838 "{ 100.00 USD, 2024-01-15, \"say \\\"hi\\\"\"}"
839 );
840
841 // Embedded backslash.
842 let backslash = Cost::new(dec!(50.00), "USD").with_label("path\\to\\lot");
843 assert_eq!(
844 format!("{backslash}"),
845 "{ 50.00 USD, \"path\\\\to\\\\lot\"}"
846 );
847
848 // Embedded newline.
849 let newline = Cost::new(dec!(75.00), "USD").with_label("line1\nline2");
850 assert_eq!(format!("{newline}"), "{ 75.00 USD, \"line1\\nline2\"}");
851
852 // Plain label still works (no escaping changes for safe chars).
853 let plain = Cost::new(dec!(540.00), "USD")
854 .with_date(date(2024, 2, 15))
855 .with_label("lot-A");
856 assert_eq!(format!("{plain}"), "{ 540.00 USD, 2024-02-15, \"lot-A\"}");
857 }
858
859 #[test]
860 fn test_cost_spec_empty() {
861 let spec = CostSpec::empty();
862 assert!(spec.is_empty());
863 }
864
865 #[test]
866 fn test_cost_spec_matches() {
867 let cost = Cost::new(dec!(150.00), "USD")
868 .with_date(date(2024, 1, 15))
869 .with_label("lot1");
870
871 // Empty spec matches everything
872 assert!(CostSpec::empty().matches(&cost));
873
874 // Match by number
875 let spec = CostSpec::empty().with_number(crate::CostNumber::PerUnit {
876 value: dec!(150.00),
877 });
878 assert!(spec.matches(&cost));
879
880 // Wrong number
881 let spec = CostSpec::empty().with_number(crate::CostNumber::PerUnit {
882 value: dec!(160.00),
883 });
884 assert!(!spec.matches(&cost));
885
886 // Match by currency
887 let spec = CostSpec::empty().with_currency("USD");
888 assert!(spec.matches(&cost));
889
890 // Match by date
891 let spec = CostSpec::empty().with_date(date(2024, 1, 15));
892 assert!(spec.matches(&cost));
893
894 // Match by label
895 let spec = CostSpec::empty().with_label("lot1");
896 assert!(spec.matches(&cost));
897
898 // Match by all
899 let spec = CostSpec::empty()
900 .with_number(crate::CostNumber::PerUnit {
901 value: dec!(150.00),
902 })
903 .with_currency("USD")
904 .with_date(date(2024, 1, 15))
905 .with_label("lot1");
906 assert!(spec.matches(&cost));
907 }
908
909 #[test]
910 fn test_cost_spec_resolve() {
911 let spec = CostSpec::empty()
912 .with_number(crate::CostNumber::PerUnit {
913 value: dec!(150.00),
914 })
915 .with_currency("USD");
916
917 let cost = spec.resolve(dec!(10), date(2024, 1, 15)).unwrap();
918 assert_eq!(cost.number, dec!(150.00));
919 assert_eq!(cost.currency, "USD");
920 assert_eq!(cost.date, Some(date(2024, 1, 15)));
921 }
922
923 #[test]
924 fn test_cost_spec_resolve_total() {
925 let spec = CostSpec::empty()
926 .with_number(crate::CostNumber::Total {
927 value: dec!(1500.00),
928 })
929 .with_currency("USD");
930
931 let cost = spec.resolve(dec!(10), date(2024, 1, 15)).unwrap();
932 assert_eq!(cost.number, dec!(150.00)); // 1500 / 10
933 assert_eq!(cost.currency, "USD");
934 }
935
936 // ===== BookedCost / PerUnitFromTotal tests (#1164) =====
937
938 #[test]
939 fn booked_cost_new_accepts_consistent_pair() {
940 // 10 units of "300 total" → 30 per-unit. Constructor must
941 // accept; debug_assert sees per_unit * |units| == total.
942 let b = BookedCost::new(dec!(30), dec!(300), dec!(10));
943 assert_eq!(b.per_unit, dec!(30));
944 assert_eq!(b.total, dec!(300));
945 }
946
947 #[test]
948 fn booked_cost_new_accepts_negative_units() {
949 // Sales (negative units) still produce consistent
950 // PerUnitFromTotal: per_unit * |units| == total uses .abs().
951 let b = BookedCost::new(dec!(30), dec!(300), dec!(-10));
952 assert_eq!(b.per_unit, dec!(30));
953 }
954
955 #[test]
956 #[should_panic(expected = "BookedCost invariant violated")]
957 fn booked_cost_new_rejects_inconsistent_pair_in_debug() {
958 // per_unit (50) * |units| (10) = 500, NOT 300. Invariant must
959 // fire. Release builds would skip the check by design — this
960 // test verifies the debug-build safety net.
961 let _ = BookedCost::new(dec!(50), dec!(300), dec!(10));
962 }
963
964 #[test]
965 #[should_panic(expected = "requires non-zero units")]
966 fn booked_cost_new_rejects_zero_units_in_debug() {
967 // Post-A-3.5/B-3.1: zero units is structurally meaningless
968 // for the post-booking shape (every per_unit "works" by
969 // zero-multiplication). `new` debug-asserts and panics;
970 // `try_new` returns a typed error. The booker never
971 // constructs PerUnitFromTotal with zero units (see book.rs),
972 // so this only fires when boundary code forgets to validate.
973 let _ = BookedCost::new(dec!(7), dec!(99), dec!(0));
974 }
975
976 #[test]
977 fn booked_cost_from_archive_bytes_trusted_skips_invariant() {
978 // rkyv deserialization uses this when units aren't at hand.
979 // Constructs the inconsistent pair without panicking —
980 // verifying it's truly unchecked. Plugin / FFI ingress code
981 // must NOT use this path; they get `try_new`.
982 let b = BookedCost::from_archive_bytes_trusted(dec!(50), dec!(300));
983 assert_eq!(b.per_unit, dec!(50));
984 assert_eq!(b.total, dec!(300));
985 }
986
987 #[test]
988 fn booked_cost_from_fuzz_unchecked_skips_invariant() {
989 // Fuzz harness uses this to generate pathological inputs that
990 // stress trust-boundary code in convert bridges. Distinct
991 // from the archive constructor at the source level so grep
992 // can identify each kind of bypass.
993 let b = BookedCost::from_fuzz_unchecked(dec!(999999), dec!(0.01));
994 assert_eq!(b.per_unit, dec!(999999));
995 assert_eq!(b.total, dec!(0.01));
996 }
997
998 #[test]
999 fn booked_cost_try_new_rejects_inconsistent_pair_with_diagnostic() {
1000 // Trust-boundary constructor must return a typed error for
1001 // inconsistent pairs. 10 units × 50/u = 500, not 999.
1002 let err = BookedCost::try_new(dec!(50), dec!(999), dec!(10))
1003 .expect_err("expected invariant error for inconsistent input");
1004 assert_eq!(err.per_unit, dec!(50));
1005 assert_eq!(err.total, dec!(999));
1006 assert_eq!(err.units, dec!(10));
1007 assert_eq!(err.derived_total, dec!(500));
1008 assert_eq!(err.abs_diff, dec!(499));
1009 assert!(err.tolerance.is_some(), "tolerance must be reported");
1010 assert!(!err.overflow, "this case is mismatch, not overflow");
1011
1012 // Display includes both supplied and derived values for
1013 // plugin-author diagnostics.
1014 let msg = format!("{err}");
1015 assert!(msg.contains("50") && msg.contains("999") && msg.contains("500"));
1016 }
1017
1018 #[test]
1019 fn booked_cost_try_new_rejects_zero_units() {
1020 // Pre-fix the zero-units case short-circuited to "valid",
1021 // defeating the trust-boundary guard at every input bridge
1022 // (review B-3.1). PerUnitFromTotal is structurally
1023 // meaningless for zero units — every per_unit "works" by
1024 // zero-multiplication. Reject explicitly with `tolerance:
1025 // None` so callers can distinguish this from a numeric
1026 // mismatch.
1027 let err = BookedCost::try_new(dec!(999999), dec!(0.01), dec!(0))
1028 .expect_err("zero units must be rejected, not silently accepted");
1029 assert!(err.tolerance.is_none(), "zero-units error has no tolerance");
1030 assert!(!err.overflow, "this is zero-units, not overflow");
1031 assert!(format!("{err}").contains("non-zero units"));
1032 }
1033
1034 #[test]
1035 fn booked_cost_try_new_accepts_consistent_pair() {
1036 let result = BookedCost::try_new(dec!(50), dec!(500), dec!(10));
1037 assert!(result.is_ok());
1038 }
1039
1040 #[test]
1041 #[should_panic(expected = "overflow")]
1042 fn booked_cost_new_panics_in_debug_on_overflow() {
1043 // `BookedCost::new` debug-asserts the invariant. Overflow
1044 // should reach the assertion via `check_invariant`'s Err, then
1045 // panic with a message that names the failure mode — same
1046 // contract as the existing zero-units / mismatch debug
1047 // asserts. Without this test, a future refactor of
1048 // `check_invariant`'s error path could swallow the overflow
1049 // case at the `new` call site (e.g. by short-circuiting to
1050 // Ok or by using a different Display) and the `new`-side
1051 // contract would degrade silently. Inputs: 5e15 × 5e15 →
1052 // 2.5e31, which exceeds Decimal::MAX (~7.92e28).
1053 let huge = Decimal::from_str_exact("5000000000000000").unwrap();
1054 let _ = BookedCost::new(huge, Decimal::from_str_exact("0.01").unwrap(), huge);
1055 }
1056
1057 #[test]
1058 fn booked_cost_try_new_surfaces_overflow_instead_of_panicking() {
1059 // Trust-boundary regression guard: a wire client can submit
1060 // per_unit and units that each fit in Decimal but whose product
1061 // exceeds Decimal::MAX (~7.92e28). Pre-fix `check_invariant`
1062 // used bare `*` and panicked the host on multiplication;
1063 // `try_new` now surfaces it as a typed error so FFI / plugin
1064 // bridges can map it to ConversionError and propagate to the
1065 // caller. Inputs: 5e15 × 5e15 = 2.5e31, well over Decimal::MAX.
1066 let per_unit = Decimal::from_str_exact("5000000000000000").unwrap();
1067 let units = Decimal::from_str_exact("5000000000000000").unwrap();
1068 let total = Decimal::from_str_exact("0.01").unwrap();
1069 let err = BookedCost::try_new(per_unit, total, units)
1070 .expect_err("overflow must surface as Err, not panic");
1071 assert!(err.overflow, "overflow flag must be set");
1072 assert!(
1073 err.tolerance.is_none(),
1074 "no tolerance comparison performed for overflow",
1075 );
1076 assert_eq!(err.derived_total, Decimal::ZERO);
1077 assert_eq!(err.abs_diff, Decimal::ZERO);
1078
1079 let msg = format!("{err}");
1080 assert!(
1081 msg.contains("overflow") || msg.contains("Decimal::MAX"),
1082 "error message must name the overflow condition, got: {msg}"
1083 );
1084 }
1085
1086 #[test]
1087 fn booked_cost_invariant_tolerates_rust_decimal_rounding() {
1088 // The booker computes per_unit = total / |units| at 28-digit
1089 // precision; back-multiplying truncates the same way. The
1090 // tolerance must accommodate the ULP-scale residual that real
1091 // ledgers exercise — the original tight 1e-20 floor fired
1092 // spuriously on cases like 300 / 1.763.
1093 let total = dec!(300);
1094 let units = dec!(1.763);
1095 let per_unit = total / units;
1096 // This must NOT panic.
1097 let _ = BookedCost::new(per_unit, total, units);
1098 }
1099
1100 #[test]
1101 fn cost_number_per_unit_accessor() {
1102 assert_eq!(
1103 CostNumber::PerUnit { value: dec!(150) }.per_unit(),
1104 Some(dec!(150))
1105 );
1106 assert_eq!(CostNumber::Total { value: dec!(1500) }.per_unit(), None);
1107 let b = BookedCost::new(dec!(30), dec!(300), dec!(10));
1108 assert_eq!(CostNumber::PerUnitFromTotal(b).per_unit(), Some(dec!(30)));
1109 }
1110
1111 #[test]
1112 fn cost_number_total_accessor() {
1113 assert_eq!(CostNumber::PerUnit { value: dec!(150) }.total(), None);
1114 assert_eq!(
1115 CostNumber::Total { value: dec!(1500) }.total(),
1116 Some(dec!(1500))
1117 );
1118 let b = BookedCost::new(dec!(30), dec!(300), dec!(10));
1119 assert_eq!(CostNumber::PerUnitFromTotal(b).total(), Some(dec!(300)));
1120 }
1121
1122 #[test]
1123 fn cost_spec_resolve_per_unit_from_total_uses_per_unit_directly() {
1124 // Verifies the documented optimization: by `BookedCost::new`'s
1125 // invariant, b.per_unit == b.total / |units|, so resolve()
1126 // returns b.per_unit without redivision. The result must equal
1127 // what the `Total` arm would have computed.
1128 let b = BookedCost::new(dec!(30), dec!(300), dec!(10));
1129 let spec = CostSpec::empty()
1130 .with_number(CostNumber::PerUnitFromTotal(b))
1131 .with_currency("USD");
1132
1133 let cost = spec.resolve(dec!(10), date(2024, 1, 15)).unwrap();
1134 assert_eq!(cost.number, dec!(30));
1135 assert_eq!(cost.currency, "USD");
1136
1137 // Same shape via raw Total → same number after division.
1138 let total_spec = CostSpec::empty()
1139 .with_number(crate::CostNumber::Total { value: dec!(300) })
1140 .with_currency("USD");
1141 let total_cost = total_spec.resolve(dec!(10), date(2024, 1, 15)).unwrap();
1142 assert_eq!(cost.number, total_cost.number);
1143 }
1144
1145 #[test]
1146 fn cost_spec_matches_per_unit_from_total() {
1147 // PerUnitFromTotal must match against a Cost by its per-unit
1148 // value (the lot's canonical number) — this is what lot
1149 // reduction code path needs.
1150 let cost = Cost::new(dec!(150.00), "USD")
1151 .with_date(date(2024, 1, 15))
1152 .with_label("lot1");
1153
1154 let b = BookedCost::new(dec!(150), dec!(300), dec!(2));
1155 let spec = CostSpec::empty().with_number(CostNumber::PerUnitFromTotal(b));
1156 assert!(spec.matches(&cost));
1157
1158 // Wrong per-unit: must not match.
1159 let wrong = BookedCost::new(dec!(160), dec!(320), dec!(2));
1160 let wrong_spec = CostSpec::empty().with_number(CostNumber::PerUnitFromTotal(wrong));
1161 assert!(!wrong_spec.matches(&cost));
1162 }
1163
1164 #[test]
1165 fn cost_number_serde_emits_kind_tagged_shape() {
1166 // The unified wire shape across plugin-types, FFI-WASI, WASM,
1167 // and Python compat is `{"kind": "per_unit", "value": "100"}`
1168 // etc. This test pins that crate::CostNumber serde
1169 // matches — silent drift here breaks every downstream client.
1170 let pu = CostNumber::PerUnit { value: dec!(100) };
1171 let json = serde_json::to_value(pu).unwrap();
1172 assert_eq!(json["kind"], "per_unit", "PerUnit must use kind tag");
1173
1174 let t = CostNumber::Total { value: dec!(1500) };
1175 let json = serde_json::to_value(t).unwrap();
1176 assert_eq!(json["kind"], "total");
1177
1178 let b = BookedCost::new(dec!(150), dec!(300), dec!(2));
1179 let puft = CostNumber::PerUnitFromTotal(b);
1180 let json = serde_json::to_value(puft).unwrap();
1181 assert_eq!(json["kind"], "per_unit_from_total");
1182 assert_eq!(json["per_unit"], "150");
1183 assert_eq!(json["total"], "300");
1184 }
1185
1186 #[test]
1187 fn cost_number_serde_round_trip() {
1188 // The cross-language wire contract is only honored if Rust
1189 // can also deserialize what it serialized. Pin the round-trip.
1190 for cn in [
1191 CostNumber::PerUnit { value: dec!(42) },
1192 CostNumber::Total { value: dec!(420) },
1193 CostNumber::PerUnitFromTotal(BookedCost::new(dec!(150), dec!(300), dec!(2))),
1194 ] {
1195 let json = serde_json::to_string(&cn).unwrap();
1196 let back: CostNumber = serde_json::from_str(&json).unwrap();
1197 assert_eq!(cn, back, "round trip lost data for {cn:?}");
1198 }
1199 }
1200
1201 #[cfg(feature = "rkyv")]
1202 #[test]
1203 fn cost_number_rkyv_round_trip_preserves_all_variants() {
1204 // Cache v8 docstring claims tuple→struct variant migration is
1205 // byte-compatible (review A-4.1). Verify by round-tripping
1206 // each variant through rkyv archive bytes — if the
1207 // serialize/deserialize pair loses info or panics, the cache
1208 // claim is wrong and v8 must bump to v9.
1209 for cn in [
1210 CostNumber::PerUnit { value: dec!(150) },
1211 CostNumber::Total { value: dec!(1500) },
1212 CostNumber::PerUnitFromTotal(BookedCost::new(dec!(30), dec!(300), dec!(10))),
1213 ] {
1214 let bytes = rkyv::to_bytes::<rkyv::rancor::Error>(&cn).unwrap();
1215 let back: CostNumber =
1216 rkyv::from_bytes::<CostNumber, rkyv::rancor::Error>(&bytes).unwrap();
1217 assert_eq!(cn, back, "rkyv round-trip lost data for variant {cn:?}");
1218 }
1219 }
1220
1221 #[cfg(feature = "rkyv")]
1222 #[test]
1223 fn cost_number_archived_bytes_snapshot() {
1224 // Layout snapshot: if rkyv's encoding ever changes (version
1225 // upgrade, attribute change, or accidental shape drift), this
1226 // test fires and CACHE_VERSION must bump (review A-4.1).
1227 // Each archived byte sequence is a fixed contract — any change
1228 // means existing cache files on user disks become invalid.
1229 let per_unit = CostNumber::PerUnit { value: dec!(150) };
1230 let per_unit_bytes = rkyv::to_bytes::<rkyv::rancor::Error>(&per_unit).unwrap();
1231 assert!(
1232 !per_unit_bytes.is_empty(),
1233 "PerUnit must serialize to non-empty bytes"
1234 );
1235
1236 let total = CostNumber::Total { value: dec!(1500) };
1237 let total_bytes = rkyv::to_bytes::<rkyv::rancor::Error>(&total).unwrap();
1238 assert!(!total_bytes.is_empty());
1239
1240 // Critical pin: PerUnit and Total of the same numeric value
1241 // serialize to different bytes (the discriminator must be
1242 // distinct). If they collide, the cache cannot distinguish
1243 // `{150 USD}` from `{{150 USD}}`.
1244 let pu_same = CostNumber::PerUnit { value: dec!(1500) };
1245 let pu_same_bytes = rkyv::to_bytes::<rkyv::rancor::Error>(&pu_same).unwrap();
1246 assert_ne!(
1247 total_bytes.as_ref(),
1248 pu_same_bytes.as_ref(),
1249 "PerUnit and Total of the same value must serialize distinctly"
1250 );
1251
1252 // PerUnitFromTotal must also be distinct from PerUnit-only.
1253 let booked = CostNumber::PerUnitFromTotal(BookedCost::new(dec!(150), dec!(300), dec!(2)));
1254 let booked_bytes = rkyv::to_bytes::<rkyv::rancor::Error>(&booked).unwrap();
1255 let pu_only = CostNumber::PerUnit { value: dec!(150) };
1256 let pu_only_bytes = rkyv::to_bytes::<rkyv::rancor::Error>(&pu_only).unwrap();
1257 assert_ne!(
1258 booked_bytes.as_ref(),
1259 pu_only_bytes.as_ref(),
1260 "PerUnitFromTotal and PerUnit must serialize distinctly (preserved total is load-bearing)"
1261 );
1262 }
1263
1264 // Frozen byte fixtures for the v8 cache layout live alongside
1265 // CACHE_VERSION in `rustledger-loader::cache::tests` so the
1266 // version constant and the on-disk byte layout sit in one place
1267 // — see `cost_number_archived_bytes_match_v8_fixtures` there.
1268
1269 #[test]
1270 fn cost_spec_display_renders_per_unit_from_total_as_per_unit() {
1271 // Python-beancount compat: post-booking display uses per-unit
1272 // form even though source was `{{...}}`. This pins the
1273 // documented format-amount.rs behavior.
1274 let b = BookedCost::new(dec!(150), dec!(300), dec!(2));
1275 let spec = CostSpec::empty()
1276 .with_number(CostNumber::PerUnitFromTotal(b))
1277 .with_currency("USD");
1278 let s = format!("{spec}");
1279 // Per-unit form: just the per_unit value, not `# total`.
1280 assert!(s.contains("150"), "expected per-unit 150 in {s}");
1281 assert!(!s.contains("# 300"), "must NOT render as `# total` ({s})");
1282 }
1283}